Search in sources :

Example 6 with ErrorResponse

use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse in project SEPA by arces-wot.

the class Dashboard method initialize.

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    namespacesDM = new DefaultTableModel(0, 0) {

        /**
         */
        private static final long serialVersionUID = 6788045463932990156L;

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    namespacesDM.setColumnIdentifiers(namespacesHeader);
    propertiesDM = new DefaultTableModel(0, 0) {

        /**
         */
        private static final long serialVersionUID = -5161490469556412655L;

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    propertiesDM.setColumnIdentifiers(propertiesHeader);
    frmSepaDashboard = new JFrame();
    frmSepaDashboard.setTitle(versionLabel);
    frmSepaDashboard.setBounds(100, 100, 925, 768);
    frmSepaDashboard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 925, 0 };
    gridBagLayout.rowHeights = new int[] { 78, 651, 39, 0 };
    gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gridBagLayout.rowWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE };
    frmSepaDashboard.getContentPane().setLayout(gridBagLayout);
    JPanel configuration = new JPanel();
    GridBagConstraints gbc_configuration = new GridBagConstraints();
    gbc_configuration.insets = new Insets(0, 0, 5, 0);
    gbc_configuration.fill = GridBagConstraints.BOTH;
    gbc_configuration.gridx = 0;
    gbc_configuration.gridy = 0;
    frmSepaDashboard.getContentPane().add(configuration, gbc_configuration);
    configuration.setBorder(new TitledBorder(null, "Configuration", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    GridBagLayout gbl_configuration = new GridBagLayout();
    gbl_configuration.columnWidths = new int[] { 46, 45, 31, 20, 0, 24, 0, 0, 0, 0, 0, 0, 37, 0 };
    gbl_configuration.rowHeights = new int[] { 9, -25, 0 };
    gbl_configuration.columnWeights = new double[] { 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, Double.MIN_VALUE };
    gbl_configuration.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
    configuration.setLayout(gbl_configuration);
    JLabel label1 = new JLabel("URL:");
    label1.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_label1 = new GridBagConstraints();
    gbc_label1.anchor = GridBagConstraints.EAST;
    gbc_label1.insets = new Insets(0, 0, 5, 5);
    gbc_label1.gridx = 0;
    gbc_label1.gridy = 0;
    configuration.add(label1, gbc_label1);
    JButton btnLoadXmlProfile = new JButton("Load SAP profile");
    btnLoadXmlProfile.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // String path = appProperties.getProperty("path");
            final JFileChooser fc = new JFileChooser(appProperties.getProperty("appProfile"));
            // final JFileChooser fc = new
            // JFileChooser("/Users/luca/Documents/SEPAProject/WOTDemo/tools/");
            DashboardFileFilter filter = new DashboardFileFilter("JSON SAP Profile (.jsap)", ".jsap");
            fc.setFileFilter(filter);
            int returnVal = fc.showOpenDialog(frmSepaDashboard);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                String fileName = fc.getSelectedFile().getPath();
                if (loadSAP(fileName)) {
                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream("dashboard.properties");
                    } catch (FileNotFoundException e3) {
                        logger.error(e3.getMessage());
                        return;
                    }
                    appProperties = new Properties();
                    appProperties.put("appProfile", fileName);
                    try {
                        appProperties.store(out, "Dashboard properties");
                    } catch (IOException e1) {
                        logger.error(e1.getMessage());
                    }
                    try {
                        out.close();
                    } catch (IOException e2) {
                        logger.error(e2.getMessage());
                    }
                }
            }
        }
    });
    labelUrl = new JLabel("---");
    GridBagConstraints gbc_labelUrl = new GridBagConstraints();
    gbc_labelUrl.anchor = GridBagConstraints.WEST;
    gbc_labelUrl.insets = new Insets(0, 0, 5, 5);
    gbc_labelUrl.gridx = 1;
    gbc_labelUrl.gridy = 0;
    configuration.add(labelUrl, gbc_labelUrl);
    JLabel label2 = new JLabel("http:");
    label2.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_label2 = new GridBagConstraints();
    gbc_label2.insets = new Insets(0, 0, 5, 5);
    gbc_label2.gridx = 2;
    gbc_label2.gridy = 0;
    configuration.add(label2, gbc_label2);
    labelHttpPort = new JLabel("---");
    GridBagConstraints gbc_labelHttpPort = new GridBagConstraints();
    gbc_labelHttpPort.anchor = GridBagConstraints.WEST;
    gbc_labelHttpPort.insets = new Insets(0, 0, 5, 5);
    gbc_labelHttpPort.gridx = 3;
    gbc_labelHttpPort.gridy = 0;
    configuration.add(labelHttpPort, gbc_labelHttpPort);
    JLabel lblWs = new JLabel("ws:");
    lblWs.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_lblWs = new GridBagConstraints();
    gbc_lblWs.insets = new Insets(0, 0, 5, 5);
    gbc_lblWs.gridx = 4;
    gbc_lblWs.gridy = 0;
    configuration.add(lblWs, gbc_lblWs);
    labelWsPort = new JLabel("---");
    GridBagConstraints gbc_labelWsPort = new GridBagConstraints();
    gbc_labelWsPort.anchor = GridBagConstraints.WEST;
    gbc_labelWsPort.insets = new Insets(0, 0, 5, 5);
    gbc_labelWsPort.gridx = 5;
    gbc_labelWsPort.gridy = 0;
    configuration.add(labelWsPort, gbc_labelWsPort);
    JLabel lblUpdate = new JLabel("update:");
    lblUpdate.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_lblUpdate = new GridBagConstraints();
    gbc_lblUpdate.insets = new Insets(0, 0, 5, 5);
    gbc_lblUpdate.gridx = 6;
    gbc_lblUpdate.gridy = 0;
    configuration.add(lblUpdate, gbc_lblUpdate);
    labelUpdatePath = new JLabel("---");
    GridBagConstraints gbc_labelUpdatepath = new GridBagConstraints();
    gbc_labelUpdatepath.anchor = GridBagConstraints.WEST;
    gbc_labelUpdatepath.insets = new Insets(0, 0, 5, 5);
    gbc_labelUpdatepath.gridx = 7;
    gbc_labelUpdatepath.gridy = 0;
    configuration.add(labelUpdatePath, gbc_labelUpdatepath);
    JLabel lblQuery = new JLabel("query:");
    lblQuery.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_lblQuery = new GridBagConstraints();
    gbc_lblQuery.insets = new Insets(0, 0, 5, 5);
    gbc_lblQuery.gridx = 8;
    gbc_lblQuery.gridy = 0;
    configuration.add(lblQuery, gbc_lblQuery);
    labelQueryPath = new JLabel("---");
    GridBagConstraints gbc_labelQueryPath = new GridBagConstraints();
    gbc_labelQueryPath.anchor = GridBagConstraints.WEST;
    gbc_labelQueryPath.insets = new Insets(0, 0, 5, 5);
    gbc_labelQueryPath.gridx = 9;
    gbc_labelQueryPath.gridy = 0;
    configuration.add(labelQueryPath, gbc_labelQueryPath);
    JLabel lblSubscribe = new JLabel("subscribe:");
    lblSubscribe.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_lblSubscribe = new GridBagConstraints();
    gbc_lblSubscribe.insets = new Insets(0, 0, 5, 5);
    gbc_lblSubscribe.gridx = 10;
    gbc_lblSubscribe.gridy = 0;
    configuration.add(lblSubscribe, gbc_lblSubscribe);
    labelSubscribePath = new JLabel("---");
    GridBagConstraints gbc_labelSubscribePath = new GridBagConstraints();
    gbc_labelSubscribePath.anchor = GridBagConstraints.WEST;
    gbc_labelSubscribePath.insets = new Insets(0, 0, 5, 5);
    gbc_labelSubscribePath.gridx = 11;
    gbc_labelSubscribePath.gridy = 0;
    configuration.add(labelSubscribePath, gbc_labelSubscribePath);
    GridBagConstraints gbc_btnLoadXmlProfile = new GridBagConstraints();
    gbc_btnLoadXmlProfile.insets = new Insets(0, 0, 5, 0);
    gbc_btnLoadXmlProfile.anchor = GridBagConstraints.NORTHEAST;
    gbc_btnLoadXmlProfile.gridx = 12;
    gbc_btnLoadXmlProfile.gridy = 0;
    configuration.add(btnLoadXmlProfile, gbc_btnLoadXmlProfile);
    JLabel label3 = new JLabel("https:");
    label3.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_label3 = new GridBagConstraints();
    gbc_label3.insets = new Insets(0, 0, 0, 5);
    gbc_label3.gridx = 2;
    gbc_label3.gridy = 1;
    configuration.add(label3, gbc_label3);
    labelHttpsPort = new JLabel("---");
    GridBagConstraints gbc_labelHttpsPort = new GridBagConstraints();
    gbc_labelHttpsPort.anchor = GridBagConstraints.WEST;
    gbc_labelHttpsPort.insets = new Insets(0, 0, 0, 5);
    gbc_labelHttpsPort.gridx = 3;
    gbc_labelHttpsPort.gridy = 1;
    configuration.add(labelHttpsPort, gbc_labelHttpsPort);
    JLabel lblWss = new JLabel("wss:");
    lblWss.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_lblWss = new GridBagConstraints();
    gbc_lblWss.insets = new Insets(0, 0, 0, 5);
    gbc_lblWss.gridx = 4;
    gbc_lblWss.gridy = 1;
    configuration.add(lblWss, gbc_lblWss);
    labelWssPort = new JLabel("---");
    GridBagConstraints gbc_labelWssPort = new GridBagConstraints();
    gbc_labelWssPort.anchor = GridBagConstraints.WEST;
    gbc_labelWssPort.insets = new Insets(0, 0, 0, 5);
    gbc_labelWssPort.gridx = 5;
    gbc_labelWssPort.gridy = 1;
    configuration.add(labelWssPort, gbc_labelWssPort);
    JLabel lblNewLabel = new JLabel("secure:");
    lblNewLabel.setFont(new Font("Lucida Grande", Font.BOLD, 13));
    GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
    gbc_lblNewLabel.insets = new Insets(0, 0, 0, 5);
    gbc_lblNewLabel.gridx = 6;
    gbc_lblNewLabel.gridy = 1;
    configuration.add(lblNewLabel, gbc_lblNewLabel);
    labelSecurePath = new JLabel("---");
    GridBagConstraints gbc_labelSecurePath = new GridBagConstraints();
    gbc_labelSecurePath.anchor = GridBagConstraints.WEST;
    gbc_labelSecurePath.insets = new Insets(0, 0, 0, 5);
    gbc_labelSecurePath.gridx = 7;
    gbc_labelSecurePath.gridy = 1;
    configuration.add(labelSecurePath, gbc_labelSecurePath);
    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    GridBagConstraints gbc_tabbedPane = new GridBagConstraints();
    gbc_tabbedPane.insets = new Insets(0, 0, 5, 0);
    gbc_tabbedPane.fill = GridBagConstraints.BOTH;
    gbc_tabbedPane.gridx = 0;
    gbc_tabbedPane.gridy = 1;
    frmSepaDashboard.getContentPane().add(tabbedPane, gbc_tabbedPane);
    JPanel primitives = new JPanel();
    tabbedPane.addTab("Primitives", null, primitives, null);
    primitives.setBorder(new TitledBorder(null, "Primitives", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    GridBagLayout gbl_primitives = new GridBagLayout();
    gbl_primitives.columnWidths = new int[] { 684, 0, 0 };
    gbl_primitives.rowHeights = new int[] { 114, 115, 0, 0, 0 };
    gbl_primitives.columnWeights = new double[] { 1.0, 1.0, Double.MIN_VALUE };
    gbl_primitives.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE };
    primitives.setLayout(gbl_primitives);
    JSplitPane splitPanel_Update = new JSplitPane();
    splitPanel_Update.setResizeWeight(0.5);
    GridBagConstraints gbc_splitPanel_Update = new GridBagConstraints();
    gbc_splitPanel_Update.insets = new Insets(0, 0, 5, 5);
    gbc_splitPanel_Update.fill = GridBagConstraints.BOTH;
    gbc_splitPanel_Update.gridx = 0;
    gbc_splitPanel_Update.gridy = 0;
    primitives.add(splitPanel_Update, gbc_splitPanel_Update);
    JPanel panel_4 = new JPanel();
    splitPanel_Update.setLeftComponent(panel_4);
    GridBagLayout gbl_panel_4 = new GridBagLayout();
    gbl_panel_4.columnWidths = new int[] { 66, 0 };
    gbl_panel_4.rowHeights = new int[] { 17, 75, 0 };
    gbl_panel_4.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gbl_panel_4.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
    panel_4.setLayout(gbl_panel_4);
    JLabel lblUpdates = new JLabel("UPDATEs");
    GridBagConstraints gbc_lblUpdates = new GridBagConstraints();
    gbc_lblUpdates.anchor = GridBagConstraints.NORTH;
    gbc_lblUpdates.insets = new Insets(0, 0, 5, 0);
    gbc_lblUpdates.gridx = 0;
    gbc_lblUpdates.gridy = 0;
    panel_4.add(lblUpdates, gbc_lblUpdates);
    lblUpdates.setFont(new Font("Lucida Grande", Font.BOLD, 14));
    JScrollPane scrollPane = new JScrollPane();
    GridBagConstraints gbc_scrollPane = new GridBagConstraints();
    gbc_scrollPane.fill = GridBagConstraints.BOTH;
    gbc_scrollPane.gridx = 0;
    gbc_scrollPane.gridy = 1;
    panel_4.add(scrollPane, gbc_scrollPane);
    updatesList = new JList<String>(updateListDM);
    scrollPane.setViewportView(updatesList);
    updatesList.addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (updatesList.getSelectedIndex() != -1) {
                    String sparql = appProfile.update(updatesList.getSelectedValue());
                    sparql = sparql.replaceFirst("\n", "");
                    sparql = sparql.replaceAll("\t", "");
                    sparql = sparql.trim();
                    SPARQLUpdate.setText(sparql);
                    Bindings bindings = appProfile.updateBindings(updatesList.getSelectedValue());
                    updateForcedBindingsDM.clearBindings();
                    if (bindings == null)
                        return;
                    for (String var : bindings.getVariables()) {
                        updateForcedBindingsDM.addBindings(var, bindings.isLiteral(var));
                    }
                }
            }
        }
    });
    updatesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JPanel panel_5 = new JPanel();
    splitPanel_Update.setRightComponent(panel_5);
    GridBagLayout gbl_panel_5 = new GridBagLayout();
    gbl_panel_5.columnWidths = new int[] { 101, 0 };
    gbl_panel_5.rowHeights = new int[] { 16, 0, 0 };
    gbl_panel_5.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gbl_panel_5.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
    panel_5.setLayout(gbl_panel_5);
    JLabel lblForcedBindings = new JLabel("Forced bindings");
    GridBagConstraints gbc_lblForcedBindings = new GridBagConstraints();
    gbc_lblForcedBindings.anchor = GridBagConstraints.NORTH;
    gbc_lblForcedBindings.insets = new Insets(0, 0, 5, 0);
    gbc_lblForcedBindings.gridx = 0;
    gbc_lblForcedBindings.gridy = 0;
    panel_5.add(lblForcedBindings, gbc_lblForcedBindings);
    JScrollPane scrollPane_2 = new JScrollPane();
    GridBagConstraints gbc_scrollPane_2 = new GridBagConstraints();
    gbc_scrollPane_2.fill = GridBagConstraints.BOTH;
    gbc_scrollPane_2.gridx = 0;
    gbc_scrollPane_2.gridy = 1;
    panel_5.add(scrollPane_2, gbc_scrollPane_2);
    updateForcedBindings = new JTable(updateForcedBindingsDM);
    scrollPane_2.setViewportView(updateForcedBindings);
    JSplitPane splitPanel_Subscribe = new JSplitPane();
    GridBagConstraints gbc_splitPanel_Subscribe = new GridBagConstraints();
    gbc_splitPanel_Subscribe.insets = new Insets(0, 0, 5, 0);
    gbc_splitPanel_Subscribe.fill = GridBagConstraints.BOTH;
    gbc_splitPanel_Subscribe.gridx = 1;
    gbc_splitPanel_Subscribe.gridy = 0;
    primitives.add(splitPanel_Subscribe, gbc_splitPanel_Subscribe);
    JPanel panel_6 = new JPanel();
    splitPanel_Subscribe.setLeftComponent(panel_6);
    GridBagLayout gbl_panel_6 = new GridBagLayout();
    gbl_panel_6.columnWidths = new int[] { 193, 0 };
    gbl_panel_6.rowHeights = new int[] { 17, 72, 0 };
    gbl_panel_6.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gbl_panel_6.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
    panel_6.setLayout(gbl_panel_6);
    JLabel lblSubscribes = new JLabel("SUBSCRIBEs");
    GridBagConstraints gbc_lblSubscribes = new GridBagConstraints();
    gbc_lblSubscribes.anchor = GridBagConstraints.NORTH;
    gbc_lblSubscribes.insets = new Insets(0, 0, 5, 0);
    gbc_lblSubscribes.gridx = 0;
    gbc_lblSubscribes.gridy = 0;
    panel_6.add(lblSubscribes, gbc_lblSubscribes);
    lblSubscribes.setFont(new Font("Lucida Grande", Font.BOLD, 14));
    JScrollPane scrollPane_3 = new JScrollPane();
    GridBagConstraints gbc_scrollPane_3 = new GridBagConstraints();
    gbc_scrollPane_3.fill = GridBagConstraints.BOTH;
    gbc_scrollPane_3.gridx = 0;
    gbc_scrollPane_3.gridy = 1;
    panel_6.add(scrollPane_3, gbc_scrollPane_3);
    subscribesList = new JList<String>(subscribeListDM);
    subscribesList.addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting() == false) {
                if (subscribesList.getSelectedIndex() != -1) {
                    String sparql = appProfile.subscribe(subscribesList.getSelectedValue());
                    sparql = sparql.replaceFirst("\n", "");
                    sparql = sparql.replaceAll("\t", "");
                    sparql = sparql.trim();
                    SPARQLSubscribe.setText(sparql);
                }
                Bindings bindings = appProfile.subscribeBindings(subscribesList.getSelectedValue());
                subscribeForcedBindingsDM.clearBindings();
                if (bindings == null)
                    return;
                for (String var : bindings.getVariables()) {
                    subscribeForcedBindingsDM.addBindings(var, bindings.isLiteral(var));
                }
            }
        }
    });
    scrollPane_3.setViewportView(subscribesList);
    subscribesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JPanel panel_7 = new JPanel();
    splitPanel_Subscribe.setRightComponent(panel_7);
    GridBagLayout gbl_panel_7 = new GridBagLayout();
    gbl_panel_7.columnWidths = new int[] { 454, 0 };
    gbl_panel_7.rowHeights = new int[] { 16, 126, 0 };
    gbl_panel_7.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    gbl_panel_7.rowWeights = new double[] { 0.0, 1.0, Double.MIN_VALUE };
    panel_7.setLayout(gbl_panel_7);
    JLabel lblForcedBindings_1 = new JLabel("Forced bindings");
    GridBagConstraints gbc_lblForcedBindings_1 = new GridBagConstraints();
    gbc_lblForcedBindings_1.anchor = GridBagConstraints.NORTH;
    gbc_lblForcedBindings_1.insets = new Insets(0, 0, 5, 0);
    gbc_lblForcedBindings_1.gridx = 0;
    gbc_lblForcedBindings_1.gridy = 0;
    panel_7.add(lblForcedBindings_1, gbc_lblForcedBindings_1);
    JScrollPane scrollPane_1 = new JScrollPane();
    GridBagConstraints gbc_scrollPane_1 = new GridBagConstraints();
    gbc_scrollPane_1.fill = GridBagConstraints.BOTH;
    gbc_scrollPane_1.gridx = 0;
    gbc_scrollPane_1.gridy = 1;
    panel_7.add(scrollPane_1, gbc_scrollPane_1);
    subscribeForcedBindings = new JTable(subscribeForcedBindingsDM);
    scrollPane_1.setViewportView(subscribeForcedBindings);
    JScrollPane scrollPane_Update = new JScrollPane();
    GridBagConstraints gbc_scrollPane_Update = new GridBagConstraints();
    gbc_scrollPane_Update.fill = GridBagConstraints.BOTH;
    gbc_scrollPane_Update.insets = new Insets(0, 0, 5, 5);
    gbc_scrollPane_Update.gridx = 0;
    gbc_scrollPane_Update.gridy = 1;
    primitives.add(scrollPane_Update, gbc_scrollPane_Update);
    SPARQLUpdate = new JTextArea();
    scrollPane_Update.setViewportView(SPARQLUpdate);
    SPARQLUpdate.setLineWrap(true);
    btnUpdate = new JButton("UPDATE");
    btnUpdate.setEnabled(false);
    btnUpdate.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Bindings forced = new Bindings();
            for (int index = 0; index < updateForcedBindingsDM.getRowCount(); index++) {
                String value = (String) updateForcedBindingsDM.getValueAt(index, 1);
                String var = (String) updateForcedBindingsDM.getValueAt(index, 0);
                boolean literal = (boolean) updateForcedBindingsDM.getValueAt(index, 2);
                if (value.equals("")) {
                    lblInfo.setText("Please specify binding value: " + var);
                    lblInfo.setToolTipText("Please specify binding value: " + var);
                    return;
                }
                if (literal)
                    forced.addBinding(var, new RDFTermLiteral(value));
                else
                    forced.addBinding(var, new RDFTermURI(value));
            }
            String update = SPARQLUpdate.getText().replaceAll("[\n\t]", "");
            long start = System.currentTimeMillis();
            Response result = sepaClient.update(update, forced);
            long stop = System.currentTimeMillis();
            String status = "DONE";
            if (result.isError()) {
                status = "FAILED " + ((ErrorResponse) result).getErrorMessage();
            }
            lblInfo.setText("UPDATE (" + (stop - start) + " ms): " + status);
            lblInfo.setToolTipText("UPDATE (" + (stop - start) + " ms): " + status);
        }
    });
    JScrollPane scrollPane_Subscribe = new JScrollPane();
    GridBagConstraints gbc_scrollPane_Subscribe = new GridBagConstraints();
    gbc_scrollPane_Subscribe.fill = GridBagConstraints.BOTH;
    gbc_scrollPane_Subscribe.insets = new Insets(0, 0, 5, 0);
    gbc_scrollPane_Subscribe.gridx = 1;
    gbc_scrollPane_Subscribe.gridy = 1;
    primitives.add(scrollPane_Subscribe, gbc_scrollPane_Subscribe);
    SPARQLSubscribe = new JTextArea();
    scrollPane_Subscribe.setViewportView(SPARQLSubscribe);
    SPARQLSubscribe.setLineWrap(true);
    GridBagConstraints gbc_btnUpdate = new GridBagConstraints();
    gbc_btnUpdate.insets = new Insets(0, 0, 5, 5);
    gbc_btnUpdate.gridx = 0;
    gbc_btnUpdate.gridy = 2;
    primitives.add(btnUpdate, gbc_btnUpdate);
    JPanel panel = new JPanel();
    GridBagConstraints gbc_panel = new GridBagConstraints();
    gbc_panel.insets = new Insets(0, 0, 5, 0);
    gbc_panel.fill = GridBagConstraints.BOTH;
    gbc_panel.gridx = 1;
    gbc_panel.gridy = 2;
    primitives.add(panel, gbc_panel);
    GridBagLayout gbl_panel = new GridBagLayout();
    gbl_panel.columnWidths = new int[] { 0, 0, 0 };
    gbl_panel.rowHeights = new int[] { 0, 0 };
    gbl_panel.columnWeights = new double[] { 1.0, 1.0, Double.MIN_VALUE };
    gbl_panel.rowWeights = new double[] { 1.0, Double.MIN_VALUE };
    panel.setLayout(gbl_panel);
    btnQuery = new JButton("QUERY");
    btnQuery.setEnabled(false);
    btnQuery.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Bindings forced = new Bindings();
            for (int index = 0; index < subscribeForcedBindings.getRowCount(); index++) {
                String value = (String) subscribeForcedBindings.getValueAt(index, 1);
                boolean literal = (boolean) subscribeForcedBindings.getValueAt(index, 2);
                String var = (String) subscribeForcedBindings.getValueAt(index, 0);
                if (value.equals("")) {
                    lblInfo.setText("Please specify binding value: " + var);
                    lblInfo.setToolTipText("Please specify binding value: " + var);
                    return;
                }
                if (literal)
                    forced.addBinding(var, new RDFTermLiteral(value));
                else
                    forced.addBinding(var, new RDFTermURI(value));
            }
            String query = SPARQLSubscribe.getText().replaceAll("[\n\t]", "");
            lblInfo.setText("Running query...");
            long start = System.currentTimeMillis();
            response = sepaClient.query(query, forced);
            long stop = System.currentTimeMillis();
            String status = "DONE";
            if (response.isError()) {
                status = "FAILED " + ((ErrorResponse) response).getErrorMessage();
            } else {
                bindingsDM.clear();
                BindingsResults ret = ((QueryResponse) response).getBindingsResults();
                bindingsDM.setAddedResults(ret, null);
                status = " " + ret.size() + " bindings results";
            }
            lblInfo.setText("QUERY (" + (stop - start) + " ms) :" + status);
            lblInfo.setToolTipText("QUERY (" + (stop - start) + " ms) :" + status);
        }
    });
    GridBagConstraints gbc_btnQuery = new GridBagConstraints();
    gbc_btnQuery.insets = new Insets(0, 0, 0, 5);
    gbc_btnQuery.gridx = 0;
    gbc_btnQuery.gridy = 0;
    panel.add(btnQuery, gbc_btnQuery);
    btnSubscribe = new JButton("SUBSCRIBE");
    btnSubscribe.setEnabled(false);
    btnSubscribe.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (btnSubscribe.getText().equals("SUBSCRIBE")) {
                Bindings forced = new Bindings();
                for (int index = 0; index < subscribeForcedBindings.getRowCount(); index++) {
                    String value = (String) subscribeForcedBindings.getValueAt(index, 1);
                    boolean literal = (boolean) subscribeForcedBindings.getValueAt(index, 2);
                    String var = (String) subscribeForcedBindings.getValueAt(index, 0);
                    if (value.equals("")) {
                        lblInfo.setText("Please specify binding value: " + var);
                        lblInfo.setToolTipText("Please specify binding value: " + var);
                        return;
                    }
                    ;
                    if (literal)
                        forced.addBinding(var, new RDFTermLiteral(value));
                    else
                        forced.addBinding(var, new RDFTermURI(value));
                }
                String query = SPARQLSubscribe.getText().replaceAll("[\n\t]", "");
                response = sepaClient.subscribe(query, forced);
                if (response.getClass().equals(ErrorResponse.class)) {
                    lblInfo.setText(response.toString());
                    lblInfo.setToolTipText(response.toString());
                    return;
                }
                // SPUID and results
                String spuid = ((SubscribeResponse) response).getSpuid();
                BindingsResults ret = ((SubscribeResponse) response).getBindingsResults();
                // Subscription panel
                JPanel sub = new JPanel();
                // Results label
                JLabel infoLabel = new JLabel();
                infoLabel.setText("Subscribed. First results: " + ret.size());
                subscriptionResultsLabels.put(spuid, infoLabel);
                // Results table
                subscriptionResultsDM.put(spuid, new BindingsTableModel());
                JTable bindingsResultsTable = new JTable(subscriptionResultsDM.get(spuid));
                bindingsResultsTable.setDefaultRenderer(Object.class, bindingsRender);
                bindingsResultsTable.setAutoCreateRowSorter(true);
                bindingsResultsTable.registerKeyboardAction(new CopyAction(), KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), JComponent.WHEN_FOCUSED);
                bindingsResultsTable.setCellSelectionEnabled(true);
                subscriptionResultsTables.put(spuid, bindingsResultsTable);
                subscriptionResultsDM.get(spuid).setAddedResults(ret, spuid);
                JScrollPane bindingsResults = new JScrollPane();
                bindingsResults.setViewportView(bindingsResultsTable);
                // Unsubscribe button
                JButton unsubscribeButton = new JButton(spuid);
                unsubscribeButton.setEnabled(true);
                unsubscribeButton.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
                        response = sepaClient.unsubscribe(spuid);
                        // if (response.isUnsubscribeResponse()) {
                        subscriptions.remove(sub);
                        subscriptionResultsDM.remove(spuid);
                        subscriptionResultsLabels.remove(spuid);
                        subscriptionResultsTables.remove(spuid);
                    // }
                    }
                });
                // Query label
                JLabel queryLabel = new JLabel("<html>" + query + " forced bindings: " + forced.toString() + "</html>");
                queryLabel.setFont(new Font("Arial", Font.BOLD, 14));
                // Layout
                GridBagConstraints layoutFill = new GridBagConstraints();
                layoutFill.fill = GridBagConstraints.BOTH;
                sub.setLayout(new BoxLayout(sub, BoxLayout.Y_AXIS));
                sub.setName(subscribesList.getSelectedValue());
                // Add components
                sub.add(queryLabel);
                sub.add(unsubscribeButton);
                sub.add(bindingsResults);
                sub.add(infoLabel);
                subscriptions.add(sub, layoutFill);
            }
        }
    });
    GridBagConstraints gbc_btnSubscribe = new GridBagConstraints();
    gbc_btnSubscribe.gridx = 1;
    gbc_btnSubscribe.gridy = 0;
    panel.add(btnSubscribe, gbc_btnSubscribe);
    JScrollPane bindingsResults = new JScrollPane();
    GridBagConstraints gbc_bindingsResults = new GridBagConstraints();
    gbc_bindingsResults.fill = GridBagConstraints.BOTH;
    gbc_bindingsResults.gridwidth = 2;
    gbc_bindingsResults.gridx = 0;
    gbc_bindingsResults.gridy = 3;
    primitives.add(bindingsResults, gbc_bindingsResults);
    bindingsResultsTable = new JTable(bindingsDM);
    bindingsResults.setViewportView(bindingsResultsTable);
    bindingsResultsTable.setDefaultRenderer(Object.class, bindingsRender);
    bindingsResultsTable.setAutoCreateRowSorter(true);
    bindingsResultsTable.registerKeyboardAction(new CopyAction(), KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), JComponent.WHEN_FOCUSED);
    bindingsResultsTable.setCellSelectionEnabled(true);
    subscriptions = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.addTab("Subscriptions", null, subscriptions, null);
    JPanel namespaces = new JPanel();
    tabbedPane.addTab("Namespaces", null, namespaces, null);
    namespaces.setBorder(new TitledBorder(null, "Namespaces", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    GridBagLayout gbl_namespaces = new GridBagLayout();
    gbl_namespaces.columnWidths = new int[] { 0, 0, 0 };
    gbl_namespaces.rowHeights = new int[] { 43, 0 };
    gbl_namespaces.columnWeights = new double[] { 1.0, 1.0, Double.MIN_VALUE };
    gbl_namespaces.rowWeights = new double[] { 1.0, Double.MIN_VALUE };
    namespaces.setLayout(gbl_namespaces);
    JScrollPane scrollPane_4 = new JScrollPane();
    GridBagConstraints gbc_scrollPane_4 = new GridBagConstraints();
    gbc_scrollPane_4.gridwidth = 2;
    gbc_scrollPane_4.insets = new Insets(0, 0, 0, 5);
    gbc_scrollPane_4.fill = GridBagConstraints.BOTH;
    gbc_scrollPane_4.gridx = 0;
    gbc_scrollPane_4.gridy = 0;
    namespaces.add(scrollPane_4, gbc_scrollPane_4);
    namespacesTable = new JTable(namespacesDM);
    scrollPane_4.setViewportView(namespacesTable);
    JPanel infoPanel = new JPanel();
    GridBagConstraints gbc_infoPanel = new GridBagConstraints();
    gbc_infoPanel.anchor = GridBagConstraints.SOUTH;
    gbc_infoPanel.fill = GridBagConstraints.HORIZONTAL;
    gbc_infoPanel.gridx = 0;
    gbc_infoPanel.gridy = 2;
    frmSepaDashboard.getContentPane().add(infoPanel, gbc_infoPanel);
    GridBagLayout gbl_infoPanel = new GridBagLayout();
    gbl_infoPanel.columnWidths = new int[] { 73, 0, 0, 97, 76, 0 };
    gbl_infoPanel.rowHeights = new int[] { 29, 0 };
    gbl_infoPanel.columnWeights = new double[] { 1.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE };
    gbl_infoPanel.rowWeights = new double[] { 0.0, Double.MIN_VALUE };
    infoPanel.setLayout(gbl_infoPanel);
    lblInfo = new JLabel("Info");
    GridBagConstraints gbc_lblInfo = new GridBagConstraints();
    gbc_lblInfo.anchor = GridBagConstraints.WEST;
    gbc_lblInfo.insets = new Insets(0, 10, 0, 5);
    gbc_lblInfo.gridx = 0;
    gbc_lblInfo.gridy = 0;
    infoPanel.add(lblInfo, gbc_lblInfo);
    ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
    chckbxClearonnotify = new JCheckBox("ClearOnNotify");
    chckbxClearonnotify.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
        }
    });
    GridBagConstraints gbc_chckbxClearonnotify = new GridBagConstraints();
    gbc_chckbxClearonnotify.insets = new Insets(0, 0, 0, 5);
    gbc_chckbxClearonnotify.gridx = 1;
    gbc_chckbxClearonnotify.gridy = 0;
    infoPanel.add(chckbxClearonnotify, gbc_chckbxClearonnotify);
    JCheckBox chckbxQname = new JCheckBox("Qname");
    chckbxQname.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            bindingsRender.showAsQName(chckbxQname.isSelected());
            bindingsDM.fireTableDataChanged();
            for (BindingsTableModel table : subscriptionResultsDM.values()) {
                table.fireTableDataChanged();
            }
        }
    });
    chckbxQname.setSelected(true);
    GridBagConstraints gbc_chckbxQname = new GridBagConstraints();
    gbc_chckbxQname.insets = new Insets(0, 0, 0, 5);
    gbc_chckbxQname.gridx = 2;
    gbc_chckbxQname.gridy = 0;
    infoPanel.add(chckbxQname, gbc_chckbxQname);
    chckbxAutoscroll = new JCheckBox("Autoscroll");
    GridBagConstraints gbc_chckbxAutoscroll = new GridBagConstraints();
    gbc_chckbxAutoscroll.anchor = GridBagConstraints.WEST;
    gbc_chckbxAutoscroll.insets = new Insets(0, 0, 0, 5);
    gbc_chckbxAutoscroll.gridx = 3;
    gbc_chckbxAutoscroll.gridy = 0;
    infoPanel.add(chckbxAutoscroll, gbc_chckbxAutoscroll);
    chckbxAutoscroll.setSelected(true);
    JButton btnClean = new JButton("Clear");
    GridBagConstraints gbc_btnClean = new GridBagConstraints();
    gbc_btnClean.anchor = GridBagConstraints.NORTHWEST;
    gbc_btnClean.gridx = 4;
    gbc_btnClean.gridy = 0;
    infoPanel.add(btnClean, gbc_btnClean);
    btnClean.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (primitives.isShowing()) {
                bindingsDM.clear();
                lblInfo.setText("Results cleaned");
                lblInfo.setToolTipText("Results cleaned");
            } else {
                for (String spuid : subscriptionResultsTables.keySet()) {
                    if (subscriptionResultsTables.get(spuid).isShowing()) {
                        subscriptionResultsDM.get(spuid).clear();
                        subscriptionResultsLabels.get(spuid).setText("Results cleaned");
                    }
                }
            }
        }
    });
    bindingsRender.setNamespaces(namespacesDM);
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) BindingsResults(it.unibo.arces.wot.sepa.commons.sparql.BindingsResults) ARBindingsResults(it.unibo.arces.wot.sepa.commons.sparql.ARBindingsResults) Insets(java.awt.Insets) JTextArea(javax.swing.JTextArea) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) DefaultTableModel(javax.swing.table.DefaultTableModel) JTabbedPane(javax.swing.JTabbedPane) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) FileNotFoundException(java.io.FileNotFoundException) ListSelectionEvent(javax.swing.event.ListSelectionEvent) RDFTermURI(it.unibo.arces.wot.sepa.commons.sparql.RDFTermURI) TitledBorder(javax.swing.border.TitledBorder) Properties(java.util.Properties) Bindings(it.unibo.arces.wot.sepa.commons.sparql.Bindings) RDFTermLiteral(it.unibo.arces.wot.sepa.commons.sparql.RDFTermLiteral) Font(java.awt.Font) JFrame(javax.swing.JFrame) ChangeListener(javax.swing.event.ChangeListener) JScrollPane(javax.swing.JScrollPane) JLabel(javax.swing.JLabel) IOException(java.io.IOException) ListSelectionListener(javax.swing.event.ListSelectionListener) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) QueryResponse(it.unibo.arces.wot.sepa.commons.response.QueryResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Response(it.unibo.arces.wot.sepa.commons.response.Response) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) JCheckBox(javax.swing.JCheckBox) ActionListener(java.awt.event.ActionListener) JFileChooser(javax.swing.JFileChooser) ChangeEvent(javax.swing.event.ChangeEvent) FileOutputStream(java.io.FileOutputStream) JTable(javax.swing.JTable) JSplitPane(javax.swing.JSplitPane)

Example 7 with ErrorResponse

use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse in project SEPA by arces-wot.

the class JWTRequestHandler method handle.

@Override
public void handle(HttpRequest request, HttpAsyncExchange httpExchange, HttpContext context) throws HttpException, IOException {
    logger.info(">> REQUEST TOKEN");
    Header[] headers;
    // Parsing and validating request headers
    // Content-Type: application/json
    // Accept: application/json
    headers = request.getHeaders("Content-Type");
    if (headers.length == 0) {
        logger.error("Content-Type is missing");
        HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Content-Type is missing");
    }
    if (headers.length > 1) {
        logger.error("Too many Content-Type headers");
        HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Too many Content-Type headers");
    }
    if (!headers[0].getValue().equals("application/json")) {
        logger.error("Content-Type must be: application/json");
        HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Content-Type must be: application/json");
    }
    headers = request.getHeaders("Accept");
    if (headers.length == 0) {
        logger.error("Accept is missing");
        HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Accept is missing");
    }
    if (headers.length > 1) {
        logger.error("Too many Accept headers");
        HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Too many Accept headers");
    }
    if (!headers[0].getValue().equals("application/json")) {
        logger.error("Accept must be: application/json");
        HttpUtilities.sendFailureResponse(httpExchange, HttpStatus.SC_BAD_REQUEST, "Accept must be: application/json");
    }
    // Authorization header
    headers = request.getHeaders("Authorization");
    if (headers.length != 1) {
        logger.error("Authorization is missing or multiple");
        HttpUtilities.sendFailureResponse(httpExchange, 401, "Authorization is missing or multiple");
        return;
    }
    // Extract Basic64 authorization
    String basic = headers[0].getValue();
    if (!basic.startsWith("Basic ")) {
        logger.error("Authorization must be \"Basic Basic64(<client_id>:<client_secret>)\"");
        HttpUtilities.sendFailureResponse(httpExchange, 401, "Authorization must be \"Basic Basic64(<client_id>:<client_secret>)\"");
        return;
    }
    // *************
    // Get token
    // *************
    Response token = am.getToken(basic.split(" ")[1]);
    if (token.getClass().equals(ErrorResponse.class)) {
        ErrorResponse error = (ErrorResponse) token;
        logger.error(token.toString());
        HttpUtilities.sendFailureResponse(httpExchange, error.getErrorCode(), error.getErrorMessage());
    } else {
        HttpUtilities.sendResponse(httpExchange, HttpStatus.SC_CREATED, token.toString());
    }
}
Also used : Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Header(org.apache.http.Header) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Example 8 with ErrorResponse

use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse in project SEPA by arces-wot.

the class RegisterHandler method handle.

@Override
public void handle(HttpRequest data, HttpAsyncExchange exchange, HttpContext context) throws HttpException, IOException {
    logger.info(">> REGISTRATION");
    String name = null;
    try {
        Header[] headers;
        // Parsing and validating request headers
        // Content-Type: application/json
        // Accept: application/json
        headers = exchange.getRequest().getHeaders("Content-Type");
        if (headers.length == 0) {
            logger.error("Content-Type is missing");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Content-Type is missing");
        }
        if (headers.length > 1) {
            logger.error("Too many Content-Type headers");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Too many Content-Type headers");
        }
        if (!headers[0].getValue().equals("application/json")) {
            logger.error("Content-Type must be: application/json");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Content-Type must be: application/json");
        }
        headers = exchange.getRequest().getHeaders("Accept");
        if (headers.length == 0) {
            logger.error("Accept is missing");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Accept is missing");
        }
        if (headers.length > 1) {
            logger.error("Too many Accept headers");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Too many Accept headers");
        }
        if (!headers[0].getValue().equals("application/json")) {
            logger.error("Accept must be: application/json");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "Accept must be: application/json");
        }
        // Parsing and validating request body
        /*
			 * { "client_identity": "IDENTITY", "grant_types":
			 * ["client_credentials"] }
			 */
        String jsonString = "";
        HttpEntity entity = ((HttpEntityEnclosingRequest) exchange.getRequest()).getEntity();
        try {
            jsonString = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        } catch (ParseException | IOException e) {
            jsonString = e.getLocalizedMessage();
        }
        JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
        JsonArray credentials = json.get("grant_types").getAsJsonArray();
        boolean found = false;
        for (JsonElement elem : credentials) {
            if (elem.getAsString() != null)
                if (elem.getAsString().equals("client_credentials")) {
                    found = true;
                    break;
                }
        }
        if (!found) {
            logger.error("\"grant_types\" must contain \"client_credentials\"");
            HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, "\"grant_types\" must contain \"client_credentials\"");
            return;
        }
        name = json.get("client_identity").getAsString();
    } catch (NullPointerException e) {
        logger.error(e.getMessage());
        HttpUtilities.sendFailureResponse(exchange, HttpStatus.SC_BAD_REQUEST, e.getMessage());
        return;
    }
    // *****************************************
    // Register client and retrieve credentials
    // *****************************************
    Response cred = am.register(name);
    if (cred.getClass().equals(ErrorResponse.class)) {
        ErrorResponse error = (ErrorResponse) cred;
        logger.error(error.toString());
        HttpUtilities.sendFailureResponse(exchange, error.getErrorCode(), error.getErrorMessage());
        return;
    }
    HttpUtilities.sendResponse(exchange, HttpStatus.SC_CREATED, cred.toString());
}
Also used : HttpEntity(org.apache.http.HttpEntity) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonArray(com.google.gson.JsonArray) Response(it.unibo.arces.wot.sepa.commons.response.Response) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) Header(org.apache.http.Header) JsonElement(com.google.gson.JsonElement) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) ParseException(org.apache.http.ParseException) JsonParser(com.google.gson.JsonParser)

Example 9 with ErrorResponse

use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse in project SEPA by arces-wot.

the class AuthorizationManager method getToken.

/**
 * POST https://wot.arces.unibo.it:8443/oauth/token
 *
 * Content-Type: application/x-www-form-urlencoded
 * Accept: application/json
 * Authorization: Basic Basic64(id:secret)
 *
 * Response example:
 * { 	"access_token": "eyJraWQiOiIyN.........",
 * 		"token_type": "bearer",
 * 		"expires_in": 3600
 * }
 *
 * In case of error, the following applies:
 * {
 * 		"code": Error code,
 * 		"body": "Error details"
 *
 * }
 */
public Response getToken(String encodedCredentials) {
    logger.debug("Get token");
    // Decode credentials
    byte[] decoded = null;
    try {
        decoded = Base64.getDecoder().decode(encodedCredentials);
    } catch (IllegalArgumentException e) {
        logger.error("Not authorized");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    String decodedCredentials = new String(decoded);
    String[] clientID = decodedCredentials.split(":");
    if (clientID == null) {
        logger.error("Wrong Basic authorization");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    if (clientID.length != 2) {
        logger.error("Wrong Basic authorization");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    String id = decodedCredentials.split(":")[0];
    String secret = decodedCredentials.split(":")[1];
    logger.debug("Credentials: " + id + " " + secret);
    // Verify credentials
    if (!credentials.containsKey(id)) {
        logger.error("Client id: " + id + " is not registered");
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    if (!credentials.get(id).equals(secret)) {
        logger.error("Wrong secret: " + secret + " for client id: " + id);
        return new ErrorResponse(0, HttpStatus.SC_UNAUTHORIZED, "Client not authorized");
    }
    // Check is a token has been release for this client
    if (clientClaims.containsKey(id)) {
        // Do not return a new token if the previous one is not expired
        Date expires = clientClaims.get(id).getExpirationTime();
        Date now = new Date();
        logger.debug("Check token expiration: " + now + " > " + expires + " ?");
        if (now.before(expires)) {
            logger.warn("Token is not expired");
            return new ErrorResponse(0, HttpStatus.SC_BAD_REQUEST, "Token is not expired");
        }
    }
    // Prepare JWT with claims set
    JWTClaimsSet.Builder claimsSetBuilder = new JWTClaimsSet.Builder();
    long timestamp = new Date().getTime();
    /*
		 * 4.1.1.  "iss" (Issuer) Claim

	   The "iss" (issuer) claim identifies the principal that issued the
	   JWT.  The processing of this claim is generally application specific.
	   The "iss" value is a case-sensitive string containing a StringOrURI
	   value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.issuer(AuthorizationManagerBeans.getIssuer());
    /* 4.1.2.  "sub" (Subject) Claim

	   The "sub" (subject) claim identifies the principal that is the
	   subject of the JWT.  The Claims in a JWT are normally statements
	   about the subject.  The subject value MUST either be scoped to be
	   locally unique in the context of the issuer or be globally unique.
	   The processing of this claim is generally application specific.  The
	   "sub" value is a case-sensitive string containing a StringOrURI
	   value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.subject(AuthorizationManagerBeans.getSubject());
    /* 4.1.3.  "aud" (Audience) Claim

	   The "aud" (audience) claim identifies the recipients that the JWT is
	   intended for.  Each principal intended to process the JWT MUST
	   identify itself with a value in the audience claim.  If the principal
	   processing the claim does not identify itself with a value in the
	   "aud" claim when this claim is present, then the JWT MUST be
	   rejected.  In the general case, the "aud" value is an array of case-
	   sensitive strings, each containing a StringOrURI value.  In the
	   special case when the JWT has one audience, the "aud" value MAY be a
	   single case-sensitive string containing a StringOrURI value.  The
	   interpretation of audience values is generally application specific.
	   Use of this claim is OPTIONAL.*/
    ArrayList<String> audience = new ArrayList<String>();
    audience.add(AuthorizationManagerBeans.getHttpsAudience());
    audience.add(AuthorizationManagerBeans.getWssAudience());
    claimsSetBuilder.audience(audience);
    /* 4.1.4.  "exp" (Expiration Time) Claim

	   The "exp" (expiration time) claim identifies the expiration time on
	   or after which the JWT MUST NOT be accepted for processing.  The
	   processing of the "exp" claim requires that the current date/time
	   MUST be before the expiration date/time listed in the "exp" claim.
	   Implementers MAY provide for some small leeway, usually no more than
	   a few minutes, to account for clock skew.  Its value MUST be a number
	   containing a NumericDate value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.expirationTime(new Date(timestamp + (AuthorizationManagerBeans.getTokenExpiringPeriod() * 1000)));
    /*4.1.5.  "nbf" (Not Before) Claim

	   The "nbf" (not before) claim identifies the time before which the JWT
	   MUST NOT be accepted for processing.  The processing of the "nbf"
	   claim requires that the current date/time MUST be after or equal to
	   the not-before date/time listed in the "nbf" claim.  Implementers MAY
	   provide for some small leeway, usually no more than a few minutes, to
	   account for clock skew.  Its value MUST be a number containing a
	   NumericDate value.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.notBeforeTime(new Date(timestamp - 1000));
    /* 4.1.6.  "iat" (Issued At) Claim

	   The "iat" (issued at) claim identifies the time at which the JWT was
	   issued.  This claim can be used to determine the age of the JWT.  Its
	   value MUST be a number containing a NumericDate value.  Use of this
	   claim is OPTIONAL.*/
    claimsSetBuilder.issueTime(new Date(timestamp));
    /*4.1.7.  "jti" (JWT ID) Claim

	   The "jti" (JWT ID) claim provides a unique identifier for the JWT.
	   The identifier value MUST be assigned in a manner that ensures that
	   there is a negligible probability that the same value will be
	   accidentally assigned to a different data object; if the application
	   uses multiple issuers, collisions MUST be prevented among values
	   produced by different issuers as well.  The "jti" claim can be used
	   to prevent the JWT from being replayed.  The "jti" value is a case-
	   sensitive string.  Use of this claim is OPTIONAL.*/
    claimsSetBuilder.jwtID(id + ":" + secret);
    JWTClaimsSet jwtClaims = claimsSetBuilder.build();
    // ******************************
    // Sign JWT with private RSA key
    // ******************************
    SignedJWT signedJWT;
    try {
        signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), JWTClaimsSet.parse(jwtClaims.toString()));
    } catch (ParseException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (1)");
    }
    try {
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        logger.error(e.getMessage());
        return new ErrorResponse(0, HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error on signing JWT (2)");
    }
    // Add the token to the released tokens
    clientClaims.put(id, jwtClaims);
    return new JWTResponse(signedJWT.serialize(), "bearer", AuthorizationManagerBeans.getTokenExpiringPeriod());
}
Also used : ArrayList(java.util.ArrayList) SignedJWT(com.nimbusds.jwt.SignedJWT) Date(java.util.Date) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) JOSEException(com.nimbusds.jose.JOSEException) BadJOSEException(com.nimbusds.jose.proc.BadJOSEException) JWSHeader(com.nimbusds.jose.JWSHeader) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 10 with ErrorResponse

use of it.unibo.arces.wot.sepa.commons.response.ErrorResponse in project SEPA by arces-wot.

the class AuthorizationManager method securityCheck.

private void securityCheck(String identity) {
    logger.debug("*** Security check ***");
    // Add identity
    addAuthorizedIdentity(identity);
    // Register
    logger.debug("Register: " + identity);
    Response response = register(identity);
    if (response.getClass().equals(RegistrationResponse.class)) {
        RegistrationResponse ret = (RegistrationResponse) response;
        String auth = ret.getClientId() + ":" + ret.getClientSecret();
        logger.debug("ID:SECRET=" + auth);
        // Get token
        String encodedCredentials = Base64.getEncoder().encodeToString(auth.getBytes());
        logger.debug("Authorization Basic " + encodedCredentials);
        response = getToken(encodedCredentials);
        if (response.getClass().equals(JWTResponse.class)) {
            logger.debug("Access token: " + ((JWTResponse) response).getAccessToken());
            // Validate token
            Response valid = validateToken(((JWTResponse) response).getAccessToken());
            if (!valid.getClass().equals(ErrorResponse.class))
                logger.debug("PASSED");
            else {
                ErrorResponse error = (ErrorResponse) valid;
                logger.debug("FAILED Code: " + error.getErrorCode() + "Message: " + error.getErrorMessage());
            }
        } else
            logger.debug("FAILED");
    } else
        logger.debug("FAILED");
    logger.debug("**********************");
    System.out.println("");
    // Add identity
    removeAuthorizedIdentity(identity);
}
Also used : ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) Response(it.unibo.arces.wot.sepa.commons.response.Response) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse)

Aggregations

ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)23 Response (it.unibo.arces.wot.sepa.commons.response.Response)8 JsonParser (com.google.gson.JsonParser)6 IOException (java.io.IOException)6 JsonObject (com.google.gson.JsonObject)5 JsonParseException (com.google.gson.JsonParseException)5 JWTResponse (it.unibo.arces.wot.sepa.commons.response.JWTResponse)4 QueryResponse (it.unibo.arces.wot.sepa.commons.response.QueryResponse)4 HttpEntity (org.apache.http.HttpEntity)4 SEPAProtocolException (it.unibo.arces.wot.sepa.commons.exceptions.SEPAProtocolException)3 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)3 UpdateRequest (it.unibo.arces.wot.sepa.commons.request.UpdateRequest)3 SubscribeResponse (it.unibo.arces.wot.sepa.commons.response.SubscribeResponse)3 UpdateResponse (it.unibo.arces.wot.sepa.commons.response.UpdateResponse)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 JOSEException (com.nimbusds.jose.JOSEException)2 BadJOSEException (com.nimbusds.jose.proc.BadJOSEException)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 SignedJWT (com.nimbusds.jwt.SignedJWT)2 SubscribeRequest (it.unibo.arces.wot.sepa.commons.request.SubscribeRequest)2