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:org.deviceconnect.message.event.AbstractEventManager.java

/**
 * ??URIBuilder???API???. ????????/* www  .  j a v  a 2s.com*/
 * {@link #registerEvent(URIBuilder, EventHandler)}??????
 * 
 * @param builder ?API??URI???????
 * @return ???
 * @throws IOException ????????
 */
public HttpResponse unregisterEvent(final URIBuilder builder) throws IOException {

    if (builder == null) {
        throw new IllegalArgumentException("builder must not be null.");
    }

    HttpDelete request;
    String key;
    try {
        List<NameValuePair> params = builder.getQueryParams();
        key = getKey(builder);
        builder.setParameters(params);
        request = new HttpDelete(builder.build());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URI parameter.");
    }

    HttpResponse response = execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        String entity = EntityUtils.toString(response.getEntity(), "UTF-8");
        try {
            JSONObject json = new JSONObject(entity);
            if (json != null) {
                int result = json.getInt(DConnectMessage.EXTRA_RESULT);
                if (result == DConnectMessage.RESULT_OK) {
                    removeHandler(key);
                }
            }
        } catch (JSONException e) {
            // JSON??????response?????????????
            mLogger.warning("AbstractEventManager#unregisterEvent. Invalid response. : " + e.getMessage());
        }
    }

    return response;
}

From source file:org.deviceconnect.message.event.AbstractEventManager.java

/**
 * ??URIBuilder???API???. ??????????????
 * ?????/*from   w ww .  jav a  2 s  .c o  m*/
 * 
 * @param builder ?API??URI???????
 * @param handler ???
 * @return ???
 * @throws IOException ????????
 * 
 */
public HttpResponse registerEvent(final URIBuilder builder, final EventHandler handler) throws IOException {

    if (builder == null) {
        throw new IllegalArgumentException("builder must not be null.");
    } else if (handler == null) {
        throw new IllegalArgumentException("handler must not be null.");
    }

    HttpPut request;
    String key;
    try {
        List<NameValuePair> params = builder.getQueryParams();
        key = getKey(builder);
        // ????null?body??
        builder.setParameters(null);
        request = new HttpPut(builder.build());
        request.setEntity(new UrlEncodedFormEntity(params));
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid URI parameter.");
    }

    HttpResponse response = execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        String entity = EntityUtils.toString(response.getEntity(), "UTF-8");
        try {
            JSONObject json = new JSONObject(entity);
            if (json != null) {
                int result = json.getInt(DConnectMessage.EXTRA_RESULT);
                if (result == DConnectMessage.RESULT_OK) {
                    addHandler(key, handler);
                }
            }
        } catch (JSONException e) {
            // JSON??????response?????????????
            mLogger.warning("AbstractEventManager#registerEvent. Invalid response. : " + e.getMessage());
        }
    }

    return response;
}

From source file:pl.nask.hsn2.service.urlfollower.WebClientWorker.java

private void processEmbeddedFile(String urlOfFileToSave)
        throws IOException, ParameterException, ResourceException, StorageException {
    boolean processingSubPage = false;
    try {//from   w  ww . j av a 2s .co m
        wc.getOptions().setJavaScriptEnabled(false);
        processingSubPage = prepareSubPage(urlOfFileToSave, WebClientOrigin.EMBEDDED);

        if (processingSubPage) {
            // Checks for illegal characters in URI.
            new Link(urlOfFileToSave, "");

            ProcessedPage processedPage = new ProcessedPage(wc.getPage(urlOfFileToSave));
            processPage(processedPage);
        }
    } catch (java.net.URISyntaxException e) {
        addNoHostFailedInfoToEmbeddedUrlObject(e.getMessage());
        LOGGER.warn(e.getMessage());
        LOGGER.debug(e.getMessage(), e);
    } catch (ContextSizeLimitExceededException e) {
        processingSubPage = false;
        LOGGER.warn(e.getMessage());
        LOGGER.debug(e.getMessage(), e);
    } catch (java.net.UnknownHostException e) {
        addNoHostFailedInfoToEmbeddedUrlObject("Host not found: " + e.getMessage());
        LOGGER.warn(e.getMessage());
        LOGGER.debug(e.getMessage(), e);
    } catch (org.apache.commons.httpclient.URIException e) {
        addNoHostFailedInfoToEmbeddedUrlObject(e.getMessage());
        LOGGER.warn(e.getMessage());
        LOGGER.debug(e.getMessage(), e);
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        addNoHostFailedInfoToEmbeddedUrlObject("Connection error: " + e.getMessage());
        LOGGER.warn(e.getMessage());
        LOGGER.debug(e.getMessage(), e);
    } catch (Exception e) {
        addNoHostFailedInfoToEmbeddedUrlObject(
                "Unknown error while processing embedded resource: " + urlOfFileToSave + "; " + e.getMessage());
        LOGGER.warn("Exception while saving embedded file: " + urlOfFileToSave);
        LOGGER.debug(e.getMessage(), e);
    } finally {
        if (processingSubPage) {
            ctx.closeSubContext();
        }
        wc.getOptions().setJavaScriptEnabled(true);
    }
}

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

@GET
@Path("metadata/{root:dropbox|sandbox}/{path:.+}")
@RolesAllowed({ "user", "rwshareuser", "roshareuser" })
public Response getFileMetadata(@PathParam("root") String root, @PathParam("path") String fullPath,
        @QueryParam("list") @DefaultValue("true") Boolean list,
        @QueryParam("file_limit") @DefaultValue("25000") int file_limit,
        @QueryParam("start") @DefaultValue("0") int start, @QueryParam("count") @DefaultValue("-1") int count,
        @QueryParam("include_deleted") @DefaultValue("false") boolean includeDeleted) {
    logger.debug(includeDeleted);/*from  w w w  .j a  v  a 2s. c om*/
    SciDriveUser user = ((SciDriveUser) security.getUserPrincipal());
    VospaceId identifier;
    try {
        identifier = new VospaceId(new NodePath(fullPath, user.getRootContainer()));
    } catch (URISyntaxException e) {
        logger.debug(e.getMessage());
        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());
    }

    Detail detailLevel = list ? Detail.max : Detail.min;

    long time = System.currentTimeMillis();
    byte[] nodeExport;
    try {
        if (node.getType() == NodeType.CONTAINER_NODE) {
            nodeExport = (byte[]) (((ContainerNode) node).export("json-dropbox", detailLevel, start, count,
                    includeDeleted));
        } else {
            nodeExport = (byte[]) (node.export("json-dropbox", detailLevel));
        }
    } catch (edu.jhu.pha.vospace.api.exceptions.NotFoundException ex) {
        throw new NotFoundException(identifier.getId().toASCIIString());
    }
    logger.debug("Generated node contents in " + (System.currentTimeMillis() - time) / 1000.0);

    return Response.ok(nodeExport).build();
}

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

/**
 * Create new share/*from   www . j a v  a2  s  .  co  m*/
 * @param root
 * @param fullPath
 * @param group
 * @param write_perm
 * @return
 */
@PUT
@Path("shares/{root:dropbox|sandbox}/{path:.+}")
@RolesAllowed({ "user" })
public byte[] putShares(@PathParam("root") String root, @PathParam("path") String fullPath,
        @QueryParam("group") String group,
        @DefaultValue("false") @QueryParam("write_perm") Boolean write_perm) {
    SciDriveUser user = ((SciDriveUser) security.getUserPrincipal());

    VospaceId identifier;
    try {
        identifier = new VospaceId(new NodePath(fullPath, user.getRootContainer()));
    } catch (URISyntaxException e) {
        logger.debug(e.getMessage());
        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());
    }

    ByteArrayOutputStream byteOut = null;
    try {
        JsonFactory f = new JsonFactory();
        byteOut = new ByteArrayOutputStream();
        JsonGenerator g2 = f.createJsonGenerator(byteOut);

        g2.writeStartObject();
        g2.writeStringField("id", node.getMetastore().createShare(node.getUri(), group, write_perm));
        g2.writeStringField("uri", "");
        g2.writeStringField("expires", "never");
        g2.writeEndObject();

        g2.close();
        byteOut.close();

        return byteOut.toByteArray();
    } catch (IOException ex) {
        throw new InternalServerErrorException(ex);
    }
}

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

@Path("media/{root:dropbox|sandbox}/{path:.+}")
@GET/*from w  w  w . ja  va  2 s .  c o m*/
@RolesAllowed({ "user", "rwshareuser", "roshareuser" })
public Response media(@PathParam("root") String root, @PathParam("path") String fullPath) {
    SciDriveUser user = ((SciDriveUser) security.getUserPrincipal());

    VospaceId identifier;
    try {
        identifier = new VospaceId(new NodePath(fullPath, user.getRootContainer()));
    } catch (URISyntaxException e) {
        logger.debug(e.getMessage());
        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 DataNode)) {
        throw new BadRequestException("Invalid NodeType");
    }

    try {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        JsonGenerator g2 = f.createJsonGenerator(byteOut).useDefaultPrettyPrinter();

        g2.writeStartObject();

        g2.writeStringField("url", ((DataNode) node).getHttpDownloadLink().toASCIIString());
        g2.writeStringField("expires", "never (yet)");

        g2.writeEndObject();

        g2.close();
        byteOut.close();

        return Response.ok(byteOut.toByteArray()).build();
    } catch (Exception e) {
        throw new InternalServerErrorException(e.getMessage());
    }
}

From source file:com.example.memorycalendar3.LED_Setting_Dialog.java

public void connectWebSocket() throws JSONException {
    URI uri;/*w  ww . ja  v a  2  s  . c  o m*/
    final String uemail = SplashActivity.getEmail();
    final JSONObject Event_Obj = new JSONObject();//event 
    final JSONObject Sync_Obj = new JSONObject();

    Map<String, ?> MapObject = data.getAll(); //map sharedpreference  key-value .(sharedpreferenced  event   .)
    for (Map.Entry<String, ?> entry : MapObject.entrySet()) {
        Event_Obj.put(entry.getKey(), entry.getValue().toString());
    }
    Sync_Obj.put("Event_Classify", Event_Obj.toString());

    //.
    try {
        uri = new URI("ws://175.126.125.198:8081/App");
    } catch (URISyntaxException e) {
        e.printStackTrace();
        return;
    }

    mWebSocketClient = new WebSocketClient(uri, uemail) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i("Websocket", "Opened");

            mWebSocketClient.send("Sync_Event_Classify#" + Sync_Obj.toString());
        }

        @Override
        public void onMessage(String s) {
            final String message = s;
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub

                }

            });
        }

        private void runOnUiThread(Runnable runnable) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i("Websocket", "Closed " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
        }
    };

    mWebSocketClient.connect();
}

From source file:org.modeshape.web.jcr.rest.AbstractRestTest.java

private <T extends HttpRequestBase> T newRequest(Class<T> clazz, InputStream inputStream, String contentType,
        String accepts, String... pathSegments) {
    String url = RestHelper.urlFrom(getServerContext(), pathSegments);

    try {/*from   ww w .j  av a2  s .c o  m*/
        URIBuilder uriBuilder;
        try {
            uriBuilder = new URIBuilder(url);
        } catch (URISyntaxException e) {
            uriBuilder = new URIBuilder(URL_ENCODER.encode(url));
        }

        T result = clazz.getConstructor(URI.class).newInstance(uriBuilder.build());
        result.setHeader("Accept", accepts);
        result.setHeader("Content-Type", contentType);

        if (inputStream != null) {
            assertTrue("Invalid request clazz (requires an entity)",
                    result instanceof HttpEntityEnclosingRequestBase);
            InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream, inputStream.available());
            ((HttpEntityEnclosingRequestBase) result).setEntity(new BufferedHttpEntity(inputStreamEntity));
        }

        return result;
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
        return null;
    }
}

From source file:edu.unc.lib.dl.ingest.sip.METSPackageFileValidator.java

/**
 * Checks that there are as many files packaged as there are non-staged file references. Computes and compares the
 * MD5 digest of packaged files that have a checksum in METS. Checks access to all files referenced in staging
 * locations./*w ww .j a  v  a  2 s  .  co m*/
 *
 * @param mets
 * @param metsPack
 * @param aip
 * @throws IngestException
 */
@SuppressWarnings("unchecked")
public void validateFiles(Document mets, METSPackageSIP metsPack) throws IngestException {
    StringBuffer errors = new StringBuffer();
    List<File> manifestFiles = new ArrayList<File>();
    List<String> missingFiles = new ArrayList<String>();
    List<String> badChecksumFiles = new ArrayList<String>();

    // find missing or corrupt files listed in manifest
    try {
        for (Element fileEl : (List<Element>) allFilesXpath.selectNodes(mets)) {
            String href = null;
            try {
                href = fileEl.getChild("FLocat", JDOMNamespaceUtil.METS_NS).getAttributeValue("href",
                        JDOMNamespaceUtil.XLINK_NS);
                URI uri = new URI(href);
                if (uri.getScheme() != null && !uri.getScheme().contains("file")) {
                    continue;
                }
            } catch (URISyntaxException e) {
                errors.append("Cannot parse file location: " + e.getLocalizedMessage() + " (" + href + ")");
                missingFiles.add(href);
                continue;
            } catch (NullPointerException e) {
                errors.append("A file location is missing for file ID: " + fileEl.getAttributeValue("ID"));
                continue;
            }
            File file = null;
            // locate the file and check that it exists
            try {
                log.debug("Looking in SIP");
                file = metsPack.getFileForLocator(href);
                file.equals(file);
                manifestFiles.add(file);
                log.debug("FILE IS IN METSPackage: " + file.getPath());
                if (file == null || !file.exists()) {
                    missingFiles.add(href);
                    continue;
                }
            } catch (IOException e) {
                log.debug(e);
                missingFiles.add(href);
                errors.append(e.getMessage());
            }

            String checksum = fileEl.getAttributeValue("CHECKSUM");
            if (checksum != null) {
                log.debug("found a checksum in METS");
                Checksum checker = new Checksum();
                try {
                    String sum = checker.getChecksum(file);
                    if (!sum.equals(checksum.toLowerCase())) {
                        log.debug("Checksum failed for file: " + href + " (METS says " + checksum
                                + ", but we got " + sum + ")");
                        badChecksumFiles.add(href);
                    }
                    log.debug("METS manifest checksum was verified for file: " + href);
                } catch (IOException e) {
                    throw new IngestException("Checksum failed to find file: " + href);
                }
            }
        }
    } catch (JDOMException e1) {
        throw new Error("Unexpected JDOM Exception", e1);
    }

    // TODO: account for local (not inline xmlData) MODS files
    // see if there are extra files in the SIP
    List<String> extraFiles = new ArrayList<String>();

    if (metsPack.getSIPDataDir() != null) {
        int zipPathLength = 0;
        try {
            zipPathLength = metsPack.getSIPDataDir().getCanonicalPath().length();

            for (File received : metsPack.getDataFiles()) {
                if (!manifestFiles.contains(received) && received.compareTo(metsPack.getMetsFile()) != 0) {
                    extraFiles.add("file://" + received.getCanonicalPath().substring(zipPathLength));
                }
            }
        } catch (IOException e) {
            throw new Error("Unexpected IO Exception trying to get path of a known file.", e);
        }
    }
    if (missingFiles.size() > 0 || badChecksumFiles.size() > 0 || extraFiles.size() > 0) {
        // We have an error here...
        String msg = "The files submitted do not match those listed in the METS manifest.";
        FilesDoNotMatchManifestException e = new FilesDoNotMatchManifestException(msg);
        e.setBadChecksumFiles(badChecksumFiles);
        e.setExtraFiles(extraFiles);
        e.setMissingFiles(missingFiles);
        throw e;
    }
}

From source file:com.jaspersoft.android.sdk.client.JsRestClient.java

/**
 * Downloads report output, once it has been generated and saves it in the specified file.
 *
 * @param reportUrl the fully qualified report URL
 * @param file      The file in which the output will be saved
 * @throws RestClientException thrown by RestTemplate whenever it encounters client-side HTTP errors
 * @since 1.4/*from ww w  . ja va  2  s.com*/
 */
public void saveReportOutputToFile(String reportUrl, File file) throws RestClientException {
    URI uri;
    try {
        uri = new URI(reportUrl);
    } catch (URISyntaxException ex) {
        throw new IllegalStateException("Could not create URI object: " + ex.getMessage(), ex);
    }

    downloadFile(uri, file);
}