Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
Bedrock Mission!

Learn more

View all

Sign in to view all badges

Uploading Files into the JCR with a Swing Application

Avatar

Employee

We've created a simple Swing JAR executable that calls a Sling Servlet, thanks to Scott MacDonald AEM Community Manager. The executable JAR is here:

Dropbox - Executable JAR

Here is the source code for the Swing JAR, with comments:

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.SwingUtilities;

import org.apache.http.client.methods.*;

/*

* Posts a file to an AEM Sling Servlet

*/

public class PostFile extends JPanel

        implements ActionListener {

    static private final String newline = "\n";

    JButton postButton, clearButton;

    JTextArea log;

    JTextField hostField;

    JTextField path;

    JFileChooser fc;

    static  String aemURL;

    JTextField queryField;

    JComboBox patternList;

    int m_stars = -1;

    String[] mimeType = {

            "text/javascript",

            "text/css",

            "text/plain",

    };

    public PostFile() {

        super(new BorderLayout());

        //Create the log first, because the action listeners

        //need to refer to it.

        log = new JTextArea(5,20);

        log.setMargin(new Insets(5,5,5,5));

        log.setEditable(false);

        JScrollPane logScrollPane = new JScrollPane(log);

        //Create a file chooser

        fc = new JFileChooser();

        //Create the post button.

        postButton = new JButton("Post File...",

                createImageIcon("images/Open16.gif"));

        postButton.addActionListener(this);

        //Create the clear button.

        clearButton = new JButton("Clear...",

                createImageIcon("images/Save16.gif"));

        clearButton.addActionListener(this);

        //For layout purposes, put the buttons in a separate panel

        JPanel buttonPanel = new JPanel(); //use FlowLayout

        buttonPanel.setLayout(new GridLayout(5, 2));

        buttonPanel.add(new JLabel("Enter the AEM URL: "));

        buttonPanel.add(hostField = new JTextField());

        hostField.setText("http://localhost:4502"); // Set default for AEM URL

        buttonPanel.add(new JLabel("Enter the AEM Path: "));

        buttonPanel.add(path = new JTextField());

        path.setText("/apps/slingSevletApp/components/clientlibs"); // Set default for AEM URL

        buttonPanel.add(new JLabel("File MIME type: "));

        buttonPanel.add(patternList = new JComboBox(mimeType));

        buttonPanel.add(postButton);

        buttonPanel.add(clearButton);

        //Add the buttons and the log to this panel.

        add(buttonPanel, BorderLayout.PAGE_START);

        add(logScrollPane, BorderLayout.CENTER);

    }

    public void actionPerformed(ActionEvent e) {

        //Handle open button action.

        if (e.getSource() == postButton) {

            int returnVal = fc.showOpenDialog(PostFile.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();

                //Get the path & server value

                String myPath = path.getText();

                String aemUrl = hostField.getText();

                String mimeType =(String) patternList.getSelectedItem() ;

                //This is where a real application would open the file.

                postAEM(file, aemUrl, myPath, mimeType);

                log.append("Successfully posted " + file.getName() + " to "+myPath +"." + newline);

            } else {

                log.append("Open command cancelled by user." + newline);

            }

            log.setCaretPosition(log.getDocument().getLength());

            //Handle clear button action.

        } else if (e.getSource() == clearButton) {

            log.setText("");

        }

    }

    /** Returns an ImageIcon, or null if the path was invalid. */

    protected static ImageIcon createImageIcon(String path) {

        java.net.URL imgURL = PostFile.class.getResource(path);

        if (imgURL != null) {

            return new ImageIcon(imgURL);

        } else {

            System.err.println("Couldn't find file: " + path);

            return null;

        }

    }

    /**

     * Create the GUI and show it.  For thread safety,

     * this method should be invoked from the

     * event dispatch thread.

     */

    private static void createAndShowGUI() {

        //Create and set up the window.

        JFrame frame = new JFrame("AEM File Uploader");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.

        frame.add(new PostFile());

        //Display the window.

        frame.pack();

        frame.setVisible(true);

    }

    //Posts the selected file to AEM

    private static void postAEM(File file, String host, String path, String mimeType)

    {

        try {

            String aemPostUrl = host+"/bin/upfile";

            HttpPost post = new HttpPost(aemPostUrl);

            org.apache.http.entity.mime.MultipartEntity entity = new org.apache.http.entity.mime.MultipartEntity ();

            byte[] b = new byte[(int)file.length()];

            org.apache.http.entity.mime.content.FileBody fileBody = new org.apache.http.entity.mime.content.FileBody(file, mimeType) ;

            org.apache.http.entity.mime.content.StringBody imageTitle = new org.apache.http.entity.mime.content.StringBody(path);

            entity.addPart("imageTitle", imageTitle);

            entity.addPart("image", fileBody);

            post.setEntity(entity);

            org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();

            org.apache.http.HttpResponse response = null;

            response = client.execute(post);

            System.out.println("Done") ;

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                //Turn off metal's use of bold fonts

                UIManager.put("swing.boldMetal", Boolean.FALSE);

                createAndShowGUI();

            }

        });

    }

}

0 Replies