Example usage for java.net URISyntaxException getMessage

List of usage examples for java.net URISyntaxException getMessage

Introduction

In this page you can find the example usage for java.net URISyntaxException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns a string describing the parse error.

Usage

From source file:com.virus.removal.javafxapplication.FXMLDocumentController.java

/**
 * @param event/*w  w w.  j av a  2  s.  c  o  m*/
 */
@FXML
public void handleHelpButtonAction(final ActionEvent event) {
    try {
        java.awt.Desktop.getDesktop().browse(new URI("http://virusrem.com/support"));
    } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
    } catch (URISyntaxException use) {
        System.out.println(use.getMessage());
    }
}

From source file:com.virus.removal.javafxapplication.FXMLDocumentController.java

/**
 * @param event/*  ww w. jav a 2s  .  c om*/
 */
@FXML
public void handleRegisterButtonAction(final ActionEvent event) {
    try {
        java.awt.Desktop.getDesktop().browse(new URI("http://virusrem.com/register"));
    } catch (IOException ioe) {
        System.out.println(ioe.getMessage());
    } catch (URISyntaxException use) {
        System.out.println(use.getMessage());
    }
}

From source file:edu.jhu.pha.vosync.rest.DropboxService.java

@Path("search/{root:dropbox|sandbox}/{path:.+}")
@GET/*from  w  w w  .  j av a2s  .  c o  m*/
@RolesAllowed({ "user", "rwshareuser", "roshareuser" })
public byte[] search(@PathParam("root") String root, @PathParam("path") String fullPath,
        @QueryParam("query") String query, @QueryParam("file_limit") @DefaultValue("1000") int fileLimit,
        @QueryParam("include_deleted") @DefaultValue("false") boolean includeDeleted) {
    SciDriveUser user = ((SciDriveUser) security.getUserPrincipal());

    if (null == query || query.length() < 3) {
        throw new BadRequestException("Wrong query parameter");
    }

    VospaceId identifier;
    try {
        identifier = new VospaceId(new NodePath(fullPath, user.getRootContainer()));
    } catch (URISyntaxException e) {
        throw new BadRequestException("InvalidURI");
    }

    Node node;
    try {
        node = NodeFactory.getNode(identifier, user.getName());
    } catch (edu.jhu.pha.vospace.api.exceptions.NotFoundException ex) {
        throw new NotFoundException(identifier.getNodePath().getNodeStoragePath());
    }

    if (!(node instanceof ContainerNode)) {
        throw new NotFoundException("Not a container");
    }

    List<VospaceId> nodesList = ((ContainerNode) node).search(query, fileLimit, includeDeleted);

    TokenBuffer g = new TokenBuffer(null);

    try {
        g.writeStartArray();

        for (VospaceId childNodeId : nodesList) {
            Node childNode = NodeFactory.getNode(childNodeId, user.getName());
            JsonNode jnode = (JsonNode) childNode.export("json-dropbox-object", Detail.min);
            g.writeTree(jnode);

            /*CharBuffer cBuffer = Charset.forName("ISO-8859-1").decode(ByteBuffer.wrap((byte[])childNode.export("json-dropbox", Detail.min)));
            while(cBuffer.remaining() > 0)
               g.writeRaw(cBuffer.get());
            if(ind++ < nodesList.size()-1)
               g.writeRaw(',');*/
        }

        g.writeEndArray();

        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        MappingJsonFactory f = new MappingJsonFactory();
        JsonGenerator g2 = f.createJsonGenerator(byteOut).useDefaultPrettyPrinter();
        g.serialize(g2);
        g2.close();
        byteOut.close();

        return byteOut.toByteArray();
    } catch (JsonGenerationException e) {
        e.printStackTrace();
        throw new InternalServerErrorException("Error generationg JSON: " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new InternalServerErrorException("Error generationg JSON: " + e.getMessage());
    } finally {
        try {
            g.close();
        } catch (IOException ex) {
        }
    }

}

From source file:microsoft.exchange.webservices.data.AutodiscoverService.java

/**
 * Tries to get Autodiscover settings using redirection Url.
 *
 * @param <TSettings>    the generic type
 * @param cls            the cls/* ww w . j  a va2 s  .c  o m*/
 * @param emailAddress   The email address.
 * @param redirectionUrl Redirection Url.
 * @param settings       The settings.
 * @return boolean The boolean.
 * @throws AutodiscoverLocalException  the autodiscover local exception
 * @throws AutodiscoverRemoteException the autodiscover remote exception
 * @throws Exception                   the exception
 */
private <TSettings extends ConfigurationSettingsBase> boolean tryLastChanceHostRedirection(Class<TSettings> cls,
        String emailAddress, URI redirectionUrl, OutParam<TSettings> settings)
        throws AutodiscoverLocalException, AutodiscoverRemoteException, Exception {
    List<String> redirectionEmailAddresses = new ArrayList<String>();

    // Bug 60274: Performing a non-SSL HTTP GET to retrieve a redirection
    // URL is potentially unsafe. We allow the caller
    // to specify delegate to be called to determine whether we are allowed
    // to use the redirection URL.
    if (this.callRedirectionUrlValidationCallback(redirectionUrl.toString())) {
        for (int currentHop = 0; currentHop < AutodiscoverService.AutodiscoverMaxRedirections; currentHop++) {
            try {
                settings.setParam(this.getLegacyUserSettingsAtUrl(cls, emailAddress, redirectionUrl));

                switch (settings.getParam().getResponseType()) {
                case Success:
                    return true;
                case Error:
                    throw new AutodiscoverRemoteException(Strings.AutodiscoverError,
                            settings.getParam().getError());
                case RedirectAddress:
                    // If this email address was already tried,
                    //we may have a loop
                    // in SCP lookups. Disable consideration of SCP records.
                    this.disableScpLookupIfDuplicateRedirection(settings.getParam().getRedirectTarget(),
                            redirectionEmailAddresses);
                    OutParam<Integer> outParam = new OutParam<Integer>();
                    outParam.setParam(currentHop);
                    settings.setParam(this.internalGetLegacyUserSettings(cls, emailAddress,
                            redirectionEmailAddresses, outParam));
                    currentHop = outParam.getParam();
                    return true;
                case RedirectUrl:
                    try {
                        redirectionUrl = new URI(settings.getParam().getRedirectTarget());
                    } catch (URISyntaxException ex) {
                        this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                                String.format("Service " + "returned " + "invalid " + "redirection " + "URL %s",
                                        settings.getParam().getRedirectTarget()));
                        return false;
                    }
                    break;
                default:
                    String failureMessage = String.format(
                            "Autodiscover call at %s failed with error %s, target %s", redirectionUrl,
                            settings.getParam().getResponseType(), settings.getParam().getRedirectTarget());
                    this.traceMessage(TraceFlags.AutodiscoverConfiguration, failureMessage);

                    return false;
                }
            } catch (XMLStreamException ex) {
                // If the response is malformed, it wasn't a valid
                // Autodiscover endpoint.
                this.traceMessage(TraceFlags.AutodiscoverConfiguration, String.format(
                        "%s failed: XML parsing error: %s", redirectionUrl.toString(), ex.getMessage()));
                return false;
            } catch (IOException ex) {
                this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                        String.format("%s failed: I/O error: %s", redirectionUrl, ex.getMessage()));
                return false;
            } catch (Exception ex) {
                // TODO: BUG response is always null
                HttpWebRequest response = null;
                OutParam<URI> outParam = new OutParam<URI>();
                if ((response != null) && this.tryGetRedirectionResponse(response, outParam)) {
                    redirectionUrl = outParam.getParam();
                    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                            String.format("Host returned a " + "redirection" + " to url %s", redirectionUrl));

                } else {
                    if (response != null) {
                        this.processHttpErrorResponse(response, ex);
                    }

                    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                            String.format("%s failed: %s (%s)", url, ex.getClass().getName(), ex.getMessage()));
                    return false;
                }
            }
        }
    }

    return false;
}

From source file:microsoft.exchange.webservices.data.autodiscover.AutodiscoverService.java

/**
 * Tries to get Autodiscover settings using redirection Url.
 *
 * @param <TSettings>    the generic type
 * @param cls            the cls//from  w  w  w .  j  ava  2  s  .  c  o  m
 * @param emailAddress   The email address.
 * @param redirectionUrl Redirection Url.
 * @param settings       The settings.
 * @return boolean The boolean.
 * @throws AutodiscoverLocalException  the autodiscover local exception
 * @throws AutodiscoverRemoteException the autodiscover remote exception
 * @throws Exception                   the exception
 */
private <TSettings extends ConfigurationSettingsBase> boolean tryLastChanceHostRedirection(Class<TSettings> cls,
        String emailAddress, URI redirectionUrl, OutParam<TSettings> settings)
        throws AutodiscoverLocalException, AutodiscoverRemoteException, Exception {
    List<String> redirectionEmailAddresses = new ArrayList<String>();

    // Bug 60274: Performing a non-SSL HTTP GET to retrieve a redirection
    // URL is potentially unsafe. We allow the caller
    // to specify delegate to be called to determine whether we are allowed
    // to use the redirection URL.
    if (this.callRedirectionUrlValidationCallback(redirectionUrl.toString())) {
        for (int currentHop = 0; currentHop < AutodiscoverService.AutodiscoverMaxRedirections; currentHop++) {
            try {
                settings.setParam(this.getLegacyUserSettingsAtUrl(cls, emailAddress, redirectionUrl));

                switch (settings.getParam().getResponseType()) {
                case Success:
                    return true;
                case Error:
                    throw new AutodiscoverRemoteException("The Autodiscover service returned an error.",
                            settings.getParam().getError());
                case RedirectAddress:
                    // If this email address was already tried,
                    //we may have a loop
                    // in SCP lookups. Disable consideration of SCP records.
                    this.disableScpLookupIfDuplicateRedirection(settings.getParam().getRedirectTarget(),
                            redirectionEmailAddresses);
                    OutParam<Integer> outParam = new OutParam<Integer>();
                    outParam.setParam(currentHop);
                    settings.setParam(this.internalGetLegacyUserSettings(cls, emailAddress,
                            redirectionEmailAddresses, outParam));
                    currentHop = outParam.getParam();
                    return true;
                case RedirectUrl:
                    try {
                        redirectionUrl = new URI(settings.getParam().getRedirectTarget());
                    } catch (URISyntaxException ex) {
                        this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                                String.format("Service " + "returned " + "invalid " + "redirection " + "URL %s",
                                        settings.getParam().getRedirectTarget()));
                        return false;
                    }
                    break;
                default:
                    String failureMessage = String.format(
                            "Autodiscover call at %s failed with error %s, target %s", redirectionUrl,
                            settings.getParam().getResponseType(), settings.getParam().getRedirectTarget());
                    this.traceMessage(TraceFlags.AutodiscoverConfiguration, failureMessage);

                    return false;
                }
            } catch (XMLStreamException ex) {
                // If the response is malformed, it wasn't a valid
                // Autodiscover endpoint.
                this.traceMessage(TraceFlags.AutodiscoverConfiguration, String.format(
                        "%s failed: XML parsing error: %s", redirectionUrl.toString(), ex.getMessage()));
                return false;
            } catch (IOException ex) {
                this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                        String.format("%s failed: I/O error: %s", redirectionUrl, ex.getMessage()));
                return false;
            } catch (Exception ex) {
                // TODO: BUG response is always null
                HttpWebRequest response = null;
                OutParam<URI> outParam = new OutParam<URI>();
                if ((response != null) && this.tryGetRedirectionResponse(response, outParam)) {
                    redirectionUrl = outParam.getParam();
                    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                            String.format("Host returned a " + "redirection" + " to url %s", redirectionUrl));

                } else {
                    if (response != null) {
                        this.processHttpErrorResponse(response, ex);
                    }

                    this.traceMessage(TraceFlags.AutodiscoverConfiguration,
                            String.format("%s failed: %s (%s)", url, ex.getClass().getName(), ex.getMessage()));
                    return false;
                }
            }
        }
    }

    return false;
}

From source file:com.unicauca.braim.braimclient.BraimGui.java

private void create_socket() {
    try {/*from   w ww  .  java  2 s . co m*/
        socket = IO.socket(Util.server_url + Util.socket_port);
    } catch (URISyntaxException ex) {
        System.out.println("There is an error with node" + ex);
    }
    socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

        @Override
        public void call(Object... args) {
            lbl_status.setText("Connected to Braim Server");
            lbl_status.setForeground(Color.GREEN);
            lbl_username.setText(currentUser.getUsername());
            enable_panels(true);
        }
    });
    socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
        @Override
        public void call(Object... os) {
            System.out.println("Disconnected of Braim Server..");
            lbl_status.setText("Without Connection...");
            lbl_status.setForeground(Color.BLACK);
            enable_panels(false);
            lbl_username.setText("No user connected");
            menu_item_emo_device.setEnabled(true);

            //** Emotiv disconnection task generates a fatal error **
            //emotivTask.cancel(true);
            //emotivTask = null;
        }
    });
    socket.on("init_capture", new Emitter.Listener() {

        @Override
        public void call(Object... os) {
            menu_item_emo_device.setEnabled(false);
            (emotivTask = new EmotivEngineTask()).execute();
        }
    });

    try {
        Session session = client.POST_Session(currentUser.getId(), token.getAccess_token());
        socket.connect();
        String session_json = new Gson().toJson(session);
        socket.emit("register_session", session_json);
        lbl_session_id.setText(session.getId());
    } catch (IOException ex) {
        Logger.getLogger(BraimGui.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, ex.getMessage());
        socket.disconnect();
    }

}

From source file:eu.europena.research.EdmMetadataConverter.java

public static Record toB2shareMetadata(Document edmDom) {

    try {//from w w  w.  ja  va2 s . co m
        LinguisticsRecord record = new LinguisticsRecord();
        record.setOpenAccess(true);

        NodeList titles = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                "(//edm:ProvidedCHO/dc:title | //edm:ProvidedCHO/dcterms:alternative)", edmDom);
        for (int i = 0; i < titles.getLength(); i++) {
            String val = XmlUtil.getElementText(((Element) titles.item(i))).trim();
            if (val != null) {
                Title title = new Title();
                title.setTitle(val);
                record.getTitles().add(title);
                break;
            }
        }

        NodeList creators = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap, "//edm:ProvidedCHO/dc:creator",
                edmDom);
        for (int i = 0; i < creators.getLength(); i++) {
            String resourceIri = XmlUtil.getElementText(((Element) creators.item(i))).trim();
            String creatorVal = null;
            if (resourceIri != null) {
                NodeList agents = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                        "//edm:Agent[@rdf:about='" + resourceIri + "']/skos:prefLabel", edmDom);
                if (agents.getLength() > 0) {
                    creatorVal = XmlUtil.getElementText(((Element) agents.item(0))).trim();
                }
            }
            if (creatorVal == null || StringUtils.isEmpty(creatorVal)) {
                creatorVal = XmlUtil.getElementText(((Element) creators.item(i))).trim();
            }
            if (creatorVal != null && !StringUtils.isEmpty(creatorVal)) {
                Creator creator = new Creator();
                creator.setCreatorName(creatorVal);
                record.getCreators().add(creator);
            }
        }
        {
            NodeList contributoors = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dc:contributor", edmDom);
            for (int i = 0; i < contributoors.getLength(); i++) {
                String resourceIri = XmlUtil.getElementText(((Element) contributoors.item(i))).trim();
                String creatorVal = null;
                if (resourceIri != null) {
                    NodeList agents = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                            "//edm:Agent[@rdf:about='" + resourceIri + "']/skos:prefLabel", edmDom);
                    if (agents.getLength() > 0) {
                        creatorVal = XmlUtil.getElementText(((Element) agents.item(0))).trim();
                    }
                }
                if (creatorVal == null || StringUtils.isEmpty(creatorVal)) {
                    creatorVal = XmlUtil.getElementText(((Element) contributoors.item(i))).trim();
                }
                if (creatorVal != null && !StringUtils.isEmpty(creatorVal)) {
                    Contributor contrib = new Contributor();
                    contrib.setContributorName(creatorVal);
                    record.getContributors().add(contrib);
                }
            }
        }
        {
            NodeList contributoors = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dc:publisher", edmDom);
            for (int i = 0; i < contributoors.getLength(); i++) {
                String resourceIri = XmlUtil.getElementText(((Element) contributoors.item(i))).trim();
                String creatorVal = null;
                if (resourceIri != null) {
                    NodeList agents = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                            "//edm:Agent[@rdf:about='" + resourceIri + "']/skos:prefLabel", edmDom);
                    if (agents.getLength() > 0) {
                        creatorVal = XmlUtil.getElementText(((Element) agents.item(0))).trim();
                    }
                }
                if (creatorVal == null || StringUtils.isEmpty(creatorVal)) {
                    creatorVal = XmlUtil.getElementText(((Element) contributoors.item(i))).trim();
                }
                if (creatorVal != null && !StringUtils.isEmpty(creatorVal)) {
                    record.setPublisher(creatorVal);
                }
            }
        }
        {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dc:description", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    Description description = new Description();
                    description.setDescription(desc);
                    description.setDescriptionType(DescriptionType.OTHER);
                    record.getDescriptions().add(description);
                }
            }
        }
        {
            NodeList contributoors = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dc:subject", edmDom);
            for (int i = 0; i < contributoors.getLength(); i++) {
                String resourceIri = XmlUtil.getElementText(((Element) contributoors.item(i))).trim();
                String creatorVal = null;
                if (resourceIri != null) {
                    NodeList agents = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                            "//edm:Agent[@rdf:about='" + resourceIri + "']/skos:prefLabel", edmDom);
                    if (agents.getLength() > 0) {
                        creatorVal = XmlUtil.getElementText(((Element) agents.item(0))).trim();
                    } else {
                        NodeList concepts = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                                "//edm:Concept[@rdf:about='" + resourceIri + "']/skos:prefLabel", edmDom);
                        if (concepts.getLength() > 0) {
                            creatorVal = XmlUtil.getElementText(((Element) concepts.item(0))).trim();
                        } else {
                            NodeList places = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                                    "//edm:Place[@rdf:about='" + resourceIri + "']/skos:prefLabel", edmDom);
                            if (concepts.getLength() > 0) {
                                creatorVal = XmlUtil.getElementText(((Element) places.item(0))).trim();
                            }
                        }
                    }
                }
                if (creatorVal == null || StringUtils.isEmpty(creatorVal)) {
                    creatorVal = XmlUtil.getElementText(((Element) contributoors.item(i))).trim();
                }
                if (creatorVal != null && !StringUtils.isEmpty(creatorVal)) {
                    record.getKeywords().add(creatorVal);
                }
            }
        }
        {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dcterms:tableOfContents", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    Description description = new Description();
                    description.setDescription(desc);
                    description.setDescriptionType(DescriptionType.TABLE_OF_CONTENTS);
                    record.getDescriptions().add(description);
                }
            }
        }
        {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dcterms:abstract", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    Description description = new Description();
                    description.setDescription(desc);
                    description.setDescriptionType(DescriptionType.ABSTRACT);
                    record.getDescriptions().add(description);
                }
            }
        }
        {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dc:identifier", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    AlternateIdentifier altId = new AlternateIdentifier();
                    altId.setAlternateIdentifier(desc);
                    altId.setAlternateIdentifierType("");
                    record.getAlternateIdentifiers().add(altId);
                }
            }
        }
        {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dcterms:issued", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    record.setPublicationDate(desc);
                }
            }
        }
        {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/edm:rights", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                License license = null;
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    try {
                        license = new License();
                        license.setLicenseUri(new URI(desc));
                        record.setLicense(license);
                        break;
                    } catch (URISyntaxException e) {
                        //invalid URI, do not map
                    }
                }
                String resourceIri = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (!StringUtils.isEmpty(resourceIri)) {
                    try {
                        license = new License();
                        record.setLicense(license);
                        URI licUri = new URI(resourceIri);
                        license.setLicenseUri(licUri);
                    } catch (URISyntaxException e) {
                        //invalid URI, do not map
                    }
                }
            }
        }
        if (record.getLicense() == null) {
            NodeList descriptions = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap,
                    "//edm:ProvidedCHO/dc:rights", edmDom);
            for (int i = 0; i < descriptions.getLength(); i++) {
                String desc = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                License license = null;
                if (desc != null && !StringUtils.isEmpty(desc)) {
                    license = new License();
                    license.setLicense(desc);
                    record.setLicense(license);
                }
                String resourceIri = XmlUtil.getElementText(((Element) descriptions.item(i))).trim();
                if (!StringUtils.isEmpty(resourceIri)) {
                    if (license == null) {
                        license = new License();
                        record.setLicense(license);
                    }
                    try {
                        URI licUri = new URI(resourceIri);
                        license.setLicenseUri(licUri);
                    } catch (URISyntaxException e) {
                        //invalid URI, do not map
                    }
                }
            }
        }

        NodeList dcLangs = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap, "//edm:ProvidedCHO/dc:language",
                edmDom);
        for (int i = 0; i < dcLangs.getLength(); i++) {
            String lVal = XmlUtil.getElementText(((Element) dcLangs.item(i))).trim();
            NalLanguage nalLang = languagesNal.lookupIsoCode(lVal);
            if (nalLang != null) {
                record.getCommunityFields().setLanguageCode("eng");
                break;
            }
        }

        NodeList edmTypes = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap, "//edm:ProvidedCHO/edm:type",
                edmDom);
        for (int i = 0; i < edmTypes.getLength(); i++) {
            String val = XmlUtil.getElementText(((Element) edmTypes.item(i))).trim();
            LingResourceType lingType = convertEdmType(val);
            if (lingType != null) {
                record.getCommunityFields().getLingResourceType().add(lingType);
                ResourceType resourceType = new ResourceType();
                resourceType.setResourceTypeGeneral(convertEdmTypeToResourceTypeGeneral(val));
                record.getResourceTypes().add(resourceType);
            }
        }
        record.getCommunityFields().setProjectName("Europeana Newspapers");

        NodeList dcFormats = XPathUtil.queryDom(XmlNsUtil.xpathEdmPrefixMap, "//edm:ProvidedCHO/dc:format",
                edmDom);
        for (int i = 0; i < dcFormats.getLength(); i++) {
            String val = XmlUtil.getElementText(((Element) dcFormats.item(i))).trim();
            if (val != null && val.startsWith("[OCR confidence]")) {
                record.getCommunityFields().setQuality(val);
                break;
            }
        }

        return record;
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.dasein.cloud.terremark.TerremarkMethod.java

public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")");
    }/* w w  w . j a  v a2 s  .  c  o  m*/
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Talking to server at " + url);
        }

        if (parameters != null) {
            URIBuilder uri = null;
            try {
                uri = new URIBuilder(url);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            for (NameValuePair parameter : parameters) {
                uri.addParameter(parameter.getName(), parameter.getValue());
            }
            url = uri.toString();
        }

        HttpUriRequest method = null;
        if (methodType.equals(HttpMethodName.GET)) {
            method = new HttpGet(url);
        } else if (methodType.equals(HttpMethodName.POST)) {
            method = new HttpPost(url);
        } else if (methodType.equals(HttpMethodName.DELETE)) {
            method = new HttpDelete(url);
        } else if (methodType.equals(HttpMethodName.PUT)) {
            method = new HttpPut(url);
        } else if (methodType.equals(HttpMethodName.HEAD)) {
            method = new HttpHead(url);
        } else {
            method = new HttpGet(url);
        }
        HttpResponse status = null;
        try {
            HttpClient client = new DefaultHttpClient();
            HttpParams params = new BasicHttpParams();

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "Dasein Cloud");

            attempts++;

            String proxyHost = provider.getProxyHost();
            if (proxyHost != null) {
                int proxyPort = provider.getProxyPort();
                boolean ssl = url.startsWith("https");
                params.setParameter(ConnRoutePNames.DEFAULT_PROXY,
                        new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http"));
            }
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                method.addHeader(entry.getKey(), entry.getValue());
            }
            if (body != null && body != ""
                    && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) {
                try {
                    HttpEntity entity = new StringEntity(body, "UTF-8");
                    ((HttpEntityEnclosingRequestBase) method).setEntity(entity);
                } catch (UnsupportedEncodingException e) {
                    logger.warn(e);
                }
            }
            if (wire.isDebugEnabled()) {

                wire.debug(methodType.name() + " " + method.getURI());
                for (Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                if (body != null) {
                    wire.debug(body);
                }
            }
            try {
                status = client.execute(method);
                if (wire.isDebugEnabled()) {
                    wire.debug("HTTP STATUS: " + status);
                }
            } catch (IOException e) {
                logger.error("I/O error from server communications: " + e.getMessage());
                e.printStackTrace();
                throw new InternalException(e);
            }
            int statusCode = status.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                    || statusCode == HttpStatus.SC_ACCEPTED) {
                try {
                    InputStream input = status.getEntity().getContent();

                    try {
                        return parseResponse(input);
                    } finally {
                        input.close();
                    }
                } catch (IOException e) {
                    logger.error("Error parsing response from Teremark: " + e.getMessage());
                    e.printStackTrace();
                    throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage());
                }
            } else if (statusCode == HttpStatus.SC_NO_CONTENT) {
                logger.debug("Recieved no content in response. Creating an empty doc.");
                DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = null;
                try {
                    docBuilder = dbfac.newDocumentBuilder();
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                }
                return docBuilder.newDocument();
            } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
                String msg = "OperationNotAllowed ";
                try {
                    msg += parseResponseToString(status.getEntity().getContent());
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                wire.error(msg);
                throw new TerremarkException(statusCode, "OperationNotAllowed", msg);
            } else {
                String response = "Failed to parse response.";
                ParsedError parsedError = null;
                try {
                    response = parseResponseToString(status.getEntity().getContent());
                    parsedError = parseErrorResponse(response);
                } catch (IllegalStateException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("Received " + status + " from " + url);
                }
                if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE
                        || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    if (attempts >= 5) {
                        String msg;
                        wire.warn(response);
                        if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) {
                            msg = "Cloud service is currently unavailable.";
                        } else {
                            msg = "The cloud service encountered a server error while processing your request.";
                            try {
                                msg = msg + "Response from server was:\n" + response;
                            } catch (RuntimeException runException) {
                                logger.warn(runException);
                            } catch (Error error) {
                                logger.warn(error);
                            }
                        }
                        wire.error(response);
                        logger.error(msg);
                        if (parsedError != null) {
                            throw new TerremarkException(parsedError);
                        } else {
                            throw new CloudException("HTTP Status " + statusCode + msg);
                        }
                    } else {
                        try {
                            Thread.sleep(5000L);
                        } catch (InterruptedException e) {
                            /* ignore */ }
                        return invoke();
                    }
                }
                wire.error(response);
                if (parsedError != null) {
                    throw new TerremarkException(parsedError);
                } else {
                    String msg = "\nResponse from server was:\n" + response;
                    logger.error(msg);
                    throw new CloudException("HTTP Status " + statusCode + msg);
                }
            }
        } finally {
            try {
                if (status != null) {
                    EntityUtils.consume(status.getEntity());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()");
        }
    }
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

protected void performCommand(Environment env, ProjectService service, String projectId, String path,
        String requestPath, RequestHeadersSupport headers) throws CommandException {
    String internalProxyUri = service.computeInternalProxyBaseUri(false);
    if (internalProxyUri == null) {
        throw new IllegalStateException();
    }//from ww  w .ja  v a 2s .c o m
    URI targetUri;
    try {
        if (!internalProxyUri.endsWith("/")) {
            internalProxyUri += "/";
        }
        internalProxyUri += getName() + '/' + path;

        targetUri = new URI(internalProxyUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String host = targetUri.getHost();
    int port = targetUri.getPort();
    if (port < 0) {
        port = 80;
    }
    if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) {
        throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported");
    }
    HeaderGroup headerGroup = computeHeaders(targetUri);
    for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) {
        for (String value : headerEntry.getValue()) {
            headerGroup.addHeader(new Header(headerEntry.getKey(), value));
        }
    }
    getLogger().info("Proxying " + getName() + " to " + targetUri);
    try {
        Socket socket = socketFactory.openConnection(host, port);
        try {
            // initiate an HTTP request with Transfer-Encoding: chunked
            OutputStream proxyOut = socket.getOutputStream();
            emitHttpRequestLine(proxyOut, targetUri);
            emitHeaders(proxyOut, headerGroup);

            proxyOut.flush();

            List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3);
            FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut);
            tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true));

            // start these pipes
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            try {
                for (Callable<Void> task : tasks) {
                    executor.submit(task);
                }

                InputStream proxyInput = socket.getInputStream();
                try {
                    readHttpResponse(proxyInput);
                    MultiplexingInputStream input = new MultiplexingInputStream(
                            new ChunkedInputStream(proxyInput));
                    for (;;) {
                        PacketType packetType = input.getPacketType();
                        if (packetType == null) {
                            break;
                        }
                        int length = input.getPacketLength();

                        processData(input, packetType, length);
                    }
                } finally {
                    try {
                        executor.shutdown();
                        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            } finally {
                executor.shutdownNow();
                try {
                    executor.awaitTermination(3000L, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // ignore
                }
                Thread.interrupted();

                try {
                    // attempt to close the chunked output, since this will make us a well-behaved client
                    // by sending the closing chunk.
                    chunkedRequestOut.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        getLogger().error(e.getMessage(), e);
        throw new CommandException(-1, "Service temporarily unavailable");
    } catch (IOException e) {
        getLogger().warn(e.getMessage(), e);
        throw new CommandException(-1, e.getMessage());
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.rss.RSSConnector.java

/** Convert an absolute or relative URL to a document identifier.  This may involve several steps at some point,
* but right now it does NOT involve converting the host name to a canonical host name.
* (Doing so would destroy the ability of virtually hosted sites to do the right thing,
* since the original host name would be lost.)  Thus, we do the conversion to IP address
* right before we actually fetch the document.
*@param policies are the canonicalization policies in effect.
*@param parentIdentifier the identifier of the document in which the raw url was found, or null if none.
*@param rawURL is the raw, un-normalized and un-canonicalized url.
*@return the canonical URL (the document identifier), or null if the url was illegal.
*//*from w ww . j  a v a  2s . com*/
protected static String makeDocumentIdentifier(CanonicalizationPolicies policies, String parentIdentifier,
        String rawURL) throws ManifoldCFException {
    try {
        // First, find the matching canonicalization policy, if any
        CanonicalizationPolicy p = policies.findMatch(rawURL);

        // Filter out control characters
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < rawURL.length()) {
            char x = rawURL.charAt(i++);
            // Only 7-bit ascii is allowed in URLs - and that has limits too (no control characters)
            if (x >= ' ' && x < 128)
                sb.append(x);
        }
        rawURL = sb.toString();

        WebURL url;
        if (parentIdentifier != null) {
            WebURL parentURL = new WebURL(parentIdentifier);
            url = parentURL.resolve(rawURL);
        } else
            url = new WebURL(rawURL);

        String protocol = url.getScheme();
        String host = url.getHost();

        // The new URL better darn well have a host and a protocol, and we only know how to deal with
        // http and https.
        if (protocol == null || host == null) {
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors
                        .debug("RSS: Can't use url '" + rawURL + "' because it has no protocol or host");
            return null;
        }
        if (understoodProtocols.get(protocol) == null) {
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors.debug("RSS: Can't use url '" + rawURL
                        + "' because it has an unsupported protocol '" + protocol + "'");
            return null;
        }

        // Canonicalization procedure.
        // The query part of the URL may contain bad parameters (session id's, for instance), or may be ordered in such a
        // way as to prevent an effectively identical URL from being matched.  The anchor part of the URL should also be stripped.
        // This code performs both of these activities in a simple way; rewrites of various pieces may get more involved if we add
        // the ability to perform mappings using criteria specified in the UI.  Right now we don't.
        String id = doCanonicalization(p, url);
        if (id == null) {
            if (Logging.connectors.isDebugEnabled())
                Logging.connectors
                        .debug("RSS: Can't use url '" + rawURL + "' because it could not be canonicalized");
            return null;
        }

        // As a last basic legality check, go through looking for illegal characters.
        i = 0;
        while (i < id.length()) {
            char x = id.charAt(i++);
            // Only 7-bit ascii is allowed in URLs - and that has limits too (no control characters)
            if (x < ' ' || x > 127) {
                if (Logging.connectors.isDebugEnabled())
                    Logging.connectors.debug(
                            "RSS: Can't use url '" + rawURL + "' because it has illegal characters in it");
                return null;
            }
        }

        return id;
    } catch (java.net.URISyntaxException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors
                    .debug("RSS: Can't use url '" + rawURL + "' because it is badly formed: " + e.getMessage());
        return null;
    } catch (java.lang.IllegalArgumentException e) {
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug("RSS: Can't use url '" + rawURL + "' because there was an argument error: "
                    + e.getMessage(), e);
        return null;
    } catch (java.lang.NullPointerException e) {
        // This gets tossed by url.toAsciiString() for reasons I don't understand, but which have to do with a malformed URL.
        if (Logging.connectors.isDebugEnabled())
            Logging.connectors.debug(
                    "RSS: Can't use url '" + rawURL + "' because it is missing fields: " + e.getMessage(), e);
        return null;
    }
}