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.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Deploys an REST virtual service from an uploaded RAML file
 * <p>//from w  w w .ja  va2 s. c om
 * @param uploadedInputStream the file content associated with the RAML file upload
 * @param fileDetail the file details associated with the RAML file upload
 * @param baseUri the baseUri to use in the returned WADL file.  Optionally provided, this will override that which is defined in the uploaded RAML.
 * @param authorization basic authorization string (user:password) used to grant access to LISA/DevTest REST APIs (when required)
 * @return HTTP response containing a status of REST virtual service deployed from uploaded RAML file
 */
@POST
@Path("restVs")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response deployRestVS(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("false") @FormDataParam("generateServiceDocument") Boolean generateServiceDocument,
        @DefaultValue("") @FormDataParam("authorization") String authorization) {

    log.info("POST raml/restVs");

    Response response = null;
    File uploadedFile = null;
    File ramlFile = null;
    FileInputStream ramlFileStream = null;

    try {

        if (fileDetail == null || fileDetail.getFileName() == null || fileDetail.getName() == null) {
            throw new InvalidParameterException("file");
        }

        if (!baseUri.isEmpty()) { // validate URI syntax
            try {

                new URI(baseUri);

            } catch (URISyntaxException uriEx) {

                throw new InvalidParameterException(String.format("baseUri - %s", uriEx.getMessage()));

            }
        }

        uploadedFile = FileUtil.getUploadedFile(uploadedInputStream, fileDetail);

        if (uploadedFile.isDirectory()) { // find RAML file in directory

            // First, look for a raml file that has the same base name as the uploaded file
            String targetName = Files.getNameWithoutExtension(fileDetail.getFileName()) + ".raml";

            ramlFile = FileUtil.selectRamlFile(uploadedFile, targetName);

        } else {

            ramlFile = uploadedFile;

        }

        List<ValidationResult> results = null;

        try {

            results = RamlUtil.validateRaml(ramlFile);

        } catch (IOException e) {

            String msg = String.format("RAML validation failed catastrophically for %s", ramlFile.getName());
            throw new Exception(msg, e.getCause());
        }

        // If the RAML file is valid, get to work...
        if (ValidationResult.areValid(results)) {

            try {

                ramlFileStream = new FileInputStream(ramlFile.getAbsolutePath());

            } catch (FileNotFoundException e) {

                String msg = String.format("Failed to open input stream from %s", ramlFile.getAbsolutePath());

                throw new Exception(msg, e.getCause());

            }

            FileResourceLoader resourceLoader = new FileResourceLoader(ramlFile.getParentFile());
            RamlDocumentBuilder rdb = new RamlDocumentBuilder(resourceLoader);
            Raml raml = rdb.build(ramlFileStream, ramlFile.getAbsolutePath());

            ramlFileStream.close();
            ramlFileStream = null;

            if (!baseUri.isEmpty()) {
                raml.setBaseUri(baseUri);
            }

            try {

                Context initialContext = new InitialContext();
                Context envContext = (Context) initialContext.lookup("java:comp/env");

                String vseServerUrl = (String) envContext.lookup("vseServerUrl");
                String vseServicePortRange = (String) envContext.lookup("vseServicePortRange");
                int vseServiceReadyWaitSeconds = (Integer) envContext.lookup("vseServiceReadyWaitSeconds");

                // Generate mar and deploy VS
                VirtualServiceBuilder vs = new VirtualServiceBuilder(vseServerUrl, vseServicePortRange,
                        vseServiceReadyWaitSeconds, generateServiceDocument, authorization);
                response = vs.setInputFile(raml, ramlFile.getParentFile(), true);

            } catch (Exception e) {

                String msg = String.format("Failed to deploy service - %s", e.getMessage());

                throw new Exception(msg, e.getCause());

            }

        } else { // RAML file failed validation

            StringBuilder sb = new StringBuilder();

            for (ValidationResult result : results) {

                sb.append(result.getLevel());

                if (result.getLine() > 0) {

                    sb.append(String.format(" (line %d)", result.getLine()));

                }

                sb.append(String.format(" - %s\n", result.getMessage()));
            }

            response = Response.status(Status.BAD_REQUEST).entity(sb.toString()).build();

        }

    } catch (Exception ex) {

        ex.printStackTrace();

        String msg = ex.getMessage();

        log.error(msg, ex);

        if (ex instanceof JsonSyntaxException) {

            response = Response.status(Status.BAD_REQUEST).entity(msg).build();

        } else if (ex instanceof InvalidParameterException) {

            response = Response.status(Status.BAD_REQUEST)
                    .entity(String.format("Invalid form parameter - %s", ex.getMessage())).build();

        } else {

            response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(msg).build();

        }

        return response;

    } finally {

        if (null != ramlFileStream) {

            try {

                ramlFileStream.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        if (null != uploadedFile) {

            if (uploadedFile.isDirectory()) {

                try {

                    System.gc(); // To help release files that snakeyaml abandoned open streams on -- otherwise, some files may not delete

                    // Wait a bit for the system to close abandoned streams
                    try {

                        Thread.sleep(1000);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

                    FileUtils.deleteDirectory(uploadedFile);

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                uploadedFile.delete();
            }

        }
    }

    return response;
}

From source file:org.dasein.cloud.tier3.APIHandler.java

public @Nonnull APIResponse put(@Nonnull String resource, @Nonnull String id, @Nonnull String json)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace(/*from w  ww.j  a va  2s .c o  m*/
                "ENTER - " + APIHandler.class.getName() + ".put(" + resource + "," + id + "," + json + ")");
    }
    try {
        String target = getEndpoint(resource, id);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [PUT (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }
                HttpPut put = new HttpPut(target);

                put.addHeader("Accept", "application/json");
                put.addHeader("Content-type", "application/json");
                put.addHeader("Cookie", provider.logon());

                try {
                    put.setEntity(new StringEntity(json, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    logger.error("Unsupported encoding UTF-8: " + e.getMessage());
                    throw new InternalException(e);
                }

                if (wire.isDebugEnabled()) {
                    wire.debug(put.getRequestLine().toString());
                    for (Header header : put.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                    wire.debug(json);
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "PUT " + resource);
                    response = client.execute(put);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND || status.getStatusCode() == NO_CONTENT) {
                    APIResponse r = new APIResponse();

                    r.receive();
                    return r;
                }
                if (status.getStatusCode() != ACCEPTED) {
                    logger.error(
                            "Expected ACCEPTED or CREATED for POST request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), json);
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudException("No response to the PUT");
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    APIResponse r = new APIResponse();

                    try {
                        r.receive(status.getStatusCode(), new JSONObject(json), true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [PUT (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + APIHandler.class.getName() + ".put()");
        }
    }
}

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

private void showUpdateResults(boolean updateAvailable) {
    String text = "";
    if (updateAvailable) {
        text = "<html><body>jMetrik Update Available. <br>"
                + "Go to  <a href=http://www.itemanalysis.com/jmetrik_download.php>http://www.itemanalysis.com/jmetrik-download.php</a><br>"
                + "and download the new version.<br>" + "</body></html>";
    } else {/*from   ww w  .  ja  va  2 s  . c om*/
        text = "<html><body>No Update Available. <br>"
                + "You have the most current version of jMetrik. <br></body></html>";
    }

    final JEditorPane p = new JEditorPane("text/html", text);
    p.setEditable(false);
    p.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
                Desktop deskTop = Desktop.getDesktop();
                try {
                    URI uri = new URI("http://www.itemanalysis.com/jmetrik-download.php");
                    deskTop.browse(uri);
                } catch (URISyntaxException ex) {
                    logger.fatal(ex.getMessage(), ex);
                } catch (IOException ex) {
                    logger.fatal(ex.getMessage(), ex);
                }
            }
        }
    });
    JOptionPane.showMessageDialog(Jmetrik.this, p, "jMetrik Update Status", JOptionPane.INFORMATION_MESSAGE);
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

public FrameConfigAdmin() {
    super("Configuracion", true, //resizable
            true, //closable
            true, //maximizable
            true);//iconifiable
    try {/* w  w w . j a  va  2  s  .  co  m*/
        initComponents();

        final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

        if (jarFile.isFile()) { // Run with JAR file
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
            while (entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                if (name.startsWith("sql/")) { //filter according to the path
                    cboSqlFiles.addItem("/" + name);
                }
            }
            jar.close();
        } else { // Run with IDE
            final URL url = getClass().getResource("/sql");
            if (url != null) {
                try {
                    final File apps = new File(url.toURI());
                    for (File app : apps.listFiles()) {
                        cboSqlFiles.addItem("/sql/" + app.getName());
                    }
                } catch (URISyntaxException ex) {
                    // never happens
                }
            }
        }
        /*CurrentUser currentUser = CurrentUser.getInstance();
        if (currentUser.getUser().getId() == 9999) {
        cmdReset.setEnabled(true);
        jButton3.setEnabled(true);
        } else {
        cmdReset.setEnabled(false);
        jButton3.setEnabled(false);
        }*/

        /*
                   File[] files = (new File(getClass().getResource("/sql").toURI())).listFiles();
                   for (File f : files) {
        cboSqlFiles.addItem(f.getName());
                   }*/
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}

From source file:com.couchbase.jdbc.core.ProtocolImpl.java

public CBResultSet query(CBStatement statement, String sql) throws SQLException {

    Instance instance = getNextEndpoint();

    @SuppressWarnings("unchecked")
    Map<String, String> parameters = new HashMap();

    parameters.put(STATEMENT, sql);//from  ww w  .  j  a v  a  2 s .  c  o  m
    addOptions(parameters);

    List<NameValuePair> parms = new ArrayList<NameValuePair>();

    for (String parameter : parameters.keySet()) {
        parms.add(new BasicNameValuePair(parameter, parameters.get(parameter)));
    }

    while (true) {
        String url = instance.getEndpointURL(ssl);
        logger.trace("Using endpoint {}", url);

        URI uri = null;
        try {
            uri = new URIBuilder(url).addParameters(parms).build();
        } catch (URISyntaxException ex) {
            logger.error("Invalid request {}", url);
        }

        HttpGet httpGet = new HttpGet(uri);

        httpGet.setHeader("Accept", "application/json");
        logger.trace("Get request {}", httpGet.toString());

        try {

            CloseableHttpResponse response = httpClient.execute(httpGet);
            return new CBResultSet(statement, handleResponse(sql, response));

        } catch (ConnectTimeoutException cte) {
            logger.trace(cte.getLocalizedMessage());

            // this one failed, lets move on
            invalidateEndpoint(instance);
            // get the next one
            instance = getNextEndpoint();
            if (instance == null) {
                throw new SQLException("All endpoints have failed, giving up");
            }

        } catch (IOException ex) {
            logger.error("Error executing query [{}] {}", sql, ex.getMessage());
            throw new SQLException("Error executing update", ex.getCause());
        }
    }
}

From source file:com.inmobi.rendering.RenderView.java

public void m1956b(String str, String str2, String str3) {
    try {/*from www .  java 2 s.c o m*/
        Intent parseUri = Intent.parseUri(str3, 0);
        parseUri.setFlags(268435456);
        getContext().startActivity(parseUri);
        getListener().m1907g(this);
        m1946a(str2, "broadcastEvent('" + str + "Successful','" + str3 + "');");
    } catch (URISyntaxException e) {
        m1949a(str2, "Cannot resolve URI (" + str3 + ")", str);
        Logger.m1744a(InternalLogLevel.INTERNAL, f1748a,
                "Error message in processing openExternal: " + e.getMessage());
    } catch (ActivityNotFoundException e2) {
        m1949a(str2, "No app can handle the URI (" + str3 + ")", str);
        Logger.m1744a(InternalLogLevel.INTERNAL, f1748a,
                "Error message in processing openExternal: " + e2.getMessage());
    }
}

From source file:org.dasein.cloud.tier3.APIHandler.java

public @Nonnull APIResponse post(@Nonnull String resource, @Nonnull String json)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + APIHandler.class.getName() + ".post(" + resource + "," + json + ")");
    }//from  w w w.j  a  va  2s  . c o m
    try {
        String target = getEndpoint(resource, null);

        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug(">>> [POST (" + (new Date()) + ")] -> " + target
                    + " >--------------------------------------------------------------------------------------");
        }
        try {
            URI uri;

            try {
                uri = new URI(target);
            } catch (URISyntaxException e) {
                throw new ConfigurationException(e);
            }
            HttpClient client = getClient(uri);

            try {
                ProviderContext ctx = provider.getContext();

                if (ctx == null) {
                    throw new NoContextException();
                }

                HttpPost post = new HttpPost(target);

                post.addHeader("Accept", "application/json");
                post.addHeader("Content-type", "application/json");

                if (!resource.contains("Auth/Logon/")) {
                    post.addHeader("Cookie", provider.logon());
                }

                try {
                    post.setEntity(new StringEntity(json, "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    logger.error("Unsupported encoding UTF-8: " + e.getMessage());
                    throw new InternalException(e);
                }

                if (wire.isDebugEnabled()) {
                    wire.debug(post.getRequestLine().toString());
                    for (Header header : post.getAllHeaders()) {
                        wire.debug(header.getName() + ": " + header.getValue());
                    }
                    wire.debug("");
                    wire.debug(json);
                    wire.debug("");
                }
                HttpResponse response;
                StatusLine status;

                try {
                    APITrace.trace(provider, "POST " + resource);
                    response = client.execute(post);
                    status = response.getStatusLine();
                } catch (IOException e) {
                    logger.error("Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                if (logger.isDebugEnabled()) {
                    logger.debug("HTTP Status " + status);
                }
                Header[] headers = response.getAllHeaders();

                if (wire.isDebugEnabled()) {
                    wire.debug(status.toString());
                    for (Header h : headers) {
                        if (h.getValue() != null) {
                            wire.debug(h.getName() + ": " + h.getValue().trim());
                        } else {
                            wire.debug(h.getName() + ":");
                        }
                    }
                    wire.debug("");
                }
                if (status.getStatusCode() == NOT_FOUND) {
                    throw new CloudException("No such endpoint: " + target);
                }
                if (resource.contains("/Logon/") && status.getStatusCode() == OK) {
                    APIResponse r = new APIResponse();

                    try {
                        JSONObject jsonCookie = new JSONObject();

                        // handle logon response specially
                        Header[] cookieHdrs = response.getHeaders("Set-Cookie");
                        for (int c = 0; c < cookieHdrs.length; c++) {
                            Header cookieHdr = cookieHdrs[c];
                            if (cookieHdr.getValue().startsWith("Tier3.API.Cookie")) {
                                jsonCookie.put("Session", cookieHdr.getValue());
                                break;
                            }
                        }

                        r.receive(status.getStatusCode(), jsonCookie, true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;

                } else if (status.getStatusCode() != ACCEPTED && status.getStatusCode() != CREATED
                        && status.getStatusCode() != OK) {
                    logger.error(
                            "Expected OK, ACCEPTED or CREATED for POST request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    throw new Tier3Exception(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), json);
                } else {
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new CloudException("No response to the POST");
                    }
                    try {
                        json = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new Tier3Exception(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(json);
                    }
                    wire.debug("");
                    APIResponse r = new APIResponse();

                    try {
                        r.receive(status.getStatusCode(), new JSONObject(json), true);
                    } catch (JSONException e) {
                        throw new CloudException(e);
                    }
                    return r;
                }
            } finally {
                try {
                    client.getConnectionManager().shutdown();
                } catch (Throwable ignore) {
                }
            }
        } finally {
            if (wire.isDebugEnabled()) {
                wire.debug("<<< [POST (" + (new Date()) + ")] -> " + target
                        + " <--------------------------------------------------------------------------------------");
                wire.debug("");
            }
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + APIHandler.class.getName() + ".post()");
        }
    }
}