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.apache.nifi.remote.util.SiteToSiteRestApiClient.java

private URI getUri(final String path) {
    final URI url;
    try {/*from www  . ja  v  a  2  s.  c  o m*/
        if (HTTP_ABS_URL.matcher(path).find()) {
            url = new URI(path);
        } else {
            if (StringUtils.isEmpty(getBaseUrl())) {
                throw new IllegalStateException(
                        "API baseUrl is not resolved yet, call setBaseUrl or resolveBaseUrl before sending requests with relative path.");
            }
            url = new URI(baseUrl + path);
        }
    } catch (final URISyntaxException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    return url;
}

From source file:com.zenkey.net.prowser.Request.java

/**************************************************************************
 * Uses this <code>Request</code> object's current collection of
 * parameters to build a query string for the request's URI.
 * <p>/*from  w w  w  .  ja va 2  s.  c  o m*/
 * This method should be called internally by any method of the
 * <code>Request</code> class that adds, changes or removes a parameter.
 * However, this method should <b>only</b> be called for a request that
 * uses the HTTP <code>GET</code> method because the <code>POST</code>
 * method does not use query strings within URIs.
 */
private void updateQueryString() {

    String newQueryString = null;

    // If request parameters exist, process them
    Map<String, String[]> parameterMap;
    if ((parameterMap = getParameterMap()) != null) {

        // Build a query string from the parameters
        StringBuffer newQueryStringBuffer = new StringBuffer(EMPTY_STRING);
        for (String name : parameterMap.keySet()) {
            String[] values = getParameterValues(name);
            for (String value : values) {
                newQueryStringBuffer.append(name + "=" + value + "&");
            }
        }

        // Remove the trailing "&" from the new query string
        if (newQueryStringBuffer.length() > 0)
            newQueryStringBuffer.setLength(newQueryStringBuffer.length() - 1);

        // Convert the StringBuffer to a String
        newQueryString = newQueryStringBuffer.toString();
    }

    // Rebuild the URI with the new query string
    try {
        String encodedUri = (uri.getScheme() == null ? EMPTY_STRING : uri.getScheme())
                + (uri.getRawAuthority() == null ? EMPTY_STRING : "://" + uri.getRawAuthority())
                + (uri.getRawPath() == null ? EMPTY_STRING : uri.getRawPath())
                + (newQueryString == null ? EMPTY_STRING : "?" + newQueryString)
                + (uri.getRawFragment() == null ? EMPTY_STRING : "#" + uri.getRawFragment());
        uri = new URI(encodedUri);
    }

    // This catch block should never be reached because this method is only
    // called after a valid URI established
    catch (URISyntaxException e) {
        throw new IllegalStateException("URI syntax exception occurred during update of request query "
                + "string (" + e.getMessage() + ")");
    }
}

From source file:org.dasein.cloud.zimory.ZimoryMethod.java

public @Nullable String create(@Nonnull String resource, @Nonnull String body)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + Zimory.class.getName() + ".create(" + resource + "," + body + ")");
    }/*from ww  w .j  a  va2s  .  co m*/

    try {
        String target = getEndpoint(resource);

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

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

            try {
                ProviderContext ctx = provider.getContext();

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

                post.addHeader("Content-type", "application/xml;charset=utf-8");
                try {
                    post.setEntity(new StringEntity(body, "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(body);
                    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) {
                    return null;
                }
                if (status.getStatusCode() != CREATED) {
                    logger.error("Expected OK for POST request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

                    if (entity == null) {
                        throw new ZimoryException(CloudErrorType.GENERAL, status.getStatusCode(),
                                status.getReasonPhrase(), status.getReasonPhrase());
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new ZimoryException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    throw new ZimoryException(CloudErrorType.GENERAL, status.getStatusCode(),
                            status.getReasonPhrase(), body);
                } else {
                    Header location = response.getFirstHeader("Location");

                    if (location == null || location.getValue() == null) {
                        throw new CloudException("No location header specified");
                    }
                    int idx = location.getValue().lastIndexOf("/");

                    if (idx == -1) {
                        return location.getValue();
                    }
                    return location.getValue().substring(idx + 1);
                }
            } 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 - " + Zimory.class.getName() + ".create()");
        }
    }
}

From source file:org.dasein.cloud.zimory.ZimoryMethod.java

public @Nullable String postString(@Nonnull String resource, @Nonnull String body)
        throws InternalException, CloudException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + Zimory.class.getName() + ".postString(" + resource + "," + body + ")");
    }/*from  ww  w . j  av a 2s. c o m*/

    try {
        String target = getEndpoint(resource);

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

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

            try {
                ProviderContext ctx = provider.getContext();

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

                post.addHeader("Content-type", "application/xml;charset=utf-8");
                try {
                    post.setEntity(new StringEntity(body, "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(body);
                    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) {
                    return null;
                }
                if (status.getStatusCode() != OK && status.getStatusCode() != NO_CONTENT) {
                    logger.error("Expected OK for POST request, got " + status.getStatusCode());
                    HttpEntity entity = response.getEntity();

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

                    if (entity == null) {
                        return "";
                    }
                    try {
                        body = EntityUtils.toString(entity);
                    } catch (IOException e) {
                        throw new ZimoryException(e);
                    }
                    if (wire.isDebugEnabled()) {
                        wire.debug(body);
                    }
                    wire.debug("");
                    return body;
                }
            } 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 - " + Zimory.class.getName() + ".postString()");
        }
    }
}

From source file:com.shmsoft.dmass.main.ActionStaging.java

private boolean downloadUri(String[] dirs) throws Exception {
    boolean anyDownload = false;
    File downloadDirFile = new File(ParameterProcessing.DOWNLOAD_DIR);
    if (downloadDirFile.exists()) {
        Util.deleteDirectory(downloadDirFile);
    }/*from www .  j  a v  a2  s.c om*/
    new File(ParameterProcessing.DOWNLOAD_DIR).mkdirs();

    List<DownloadItem> downloadItems = new ArrayList<>();

    for (String dir : dirs) {
        URI uri = null;

        String path;
        String savePath;
        try {
            uri = new URI(dir);
            path = uri.getPath();
            path = StringUtils.replace(path, "/", "");
            savePath = ParameterProcessing.DOWNLOAD_DIR + "/" + path;

            DownloadItem di = new DownloadItem();
            di.uri = uri;
            di.file = dir;
            di.savePath = savePath;

            downloadItems.add(di);
        } catch (URISyntaxException e) {
            History.appendToHistory("Incorrect URI syntax, skipping that: " + uri);
            continue;
        }
    }

    setDownloadState(downloadItems.size());

    for (DownloadItem di : downloadItems) {
        try {
            if (interrupted) {
                return anyDownload;
            }

            setProcessingFile(di.uri.toString());

            URL url = new URL(di.file);
            URLConnection con = url.openConnection();
            BufferedInputStream in = new BufferedInputStream(con.getInputStream());
            FileOutputStream out = new FileOutputStream(di.savePath);
            History.appendToHistory("Download from " + di.uri + " to " + di.savePath);
            int i;
            byte[] bytesIn = new byte[1024];
            while ((i = in.read(bytesIn)) >= 0) {
                out.write(bytesIn, 0, i);
            }
            out.close();
            in.close();
            anyDownload = true;

            File downloadedFile = new File(di.savePath);
            totalSize += downloadedFile.length();

            progress(1);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
    return anyDownload;
}

From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java

/**
 * Produce a list of request operations from an uploaded RAML file
 * <p>/*from   ww  w  .j  av  a 2 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 generateServiceDocument when true, the VSI transformation will include a service document transaction defined. (default: false)
 * @return HTTP response containing a list of REST operations defined in the uploaded RAML file
 */
@POST
@Path("vsiOperations")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response genVsiOperations(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("false") @FormDataParam("generateServiceDocument") Boolean generateServiceDocument) {

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

    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);
            }

            VSI vsi = new VSI(raml, ramlFile.getParentFile(), generateServiceDocument);

            StringBuffer sb = new StringBuffer();
            for (String operation : vsi.getOperationsList(raml.getResources())) {
                sb.append(String.format("%s\n", operation));
            }

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

        } 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.getCause());

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

/**
 * Produce a WADL file from an uploaded RAML file
 * <p>// w  w  w  .ja  va 2  s .  co  m
 * @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.
 * @return HTTP response containing the WADL transformation from the uploaded RAML file
 */
@POST
@Path("wadl")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
public Response genWadl(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri) {

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

    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);
            }

            WADL wadl = new WADL(raml, ramlFile.getParentFile());
            Document doc = null;

            doc = wadl.getDocument();

            StringWriter stringWriter = new StringWriter();

            WADL.prettyPrint(doc, stringWriter);

            response = Response.status(Status.OK).entity(stringWriter.toString()).build();

        } 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.getCause());

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

/**
 * Produce a CA LISA/DevTest Virtual Service Image (VSI) from an uploaded RAML file
 * <p>//from w w  w  . ja v  a2 s.  c o  m
 * @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 generateServiceDocument when true, the VSI transformation will include a service document transaction defined. (default: false)
 * @return HTTP response containing the VSI transformation from the uploaded RAML file
 */
@POST
@Path("vsi")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_XML)
public Response genVsi(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("false") @FormDataParam("generateServiceDocument") Boolean generateServiceDocument) {

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

    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);
            }

            VSI vsi = new VSI(raml, ramlFile.getParentFile(), generateServiceDocument);
            Document doc = null;

            doc = vsi.getDocument();

            StringWriter stringWriter = new StringWriter();

            VSI.prettyPrint(doc, stringWriter);

            response = Response.status(Status.OK).entity(stringWriter.toString()).build();

        } 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.getCause());

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

/**
 * Deploys an OData virtual service from an uploaded RAML file
 * <p>/*from w  w w.  j a  v a2s  . co  m*/
 * @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 OData virtual service deployed from uploaded RAML file
 */
@POST
@Path("odataVs")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response deployOdataVS(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream,
        @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail,
        @DefaultValue("") @FormDataParam("baseUri") String baseUri,
        @DefaultValue("") @FormDataParam("authorization") String authorization) {

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

    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, false, authorization);
                response = vs.setInputFile(raml, ramlFile.getParentFile(), false);

            } 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;
}