List of usage examples for java.io IOException getCause
public synchronized Throwable getCause()
From source file:de.unirostock.sems.cbarchive.web.rest.ShareApi.java
@POST @Path("/import") @Produces(MediaType.TEXT_PLAIN)/*w w w . jav a 2s. c o m*/ @Consumes(MediaType.APPLICATION_JSON) public Response importRemoteArchive(@CookieParam(Fields.COOKIE_PATH) String userPath, @CookieParam(Fields.COOKIE_USER) String userJson, ImportRequest request, @Context HttpServletRequest requestContext) { // user stuff UserManager user = null; try { user = new UserManager(userPath); if (userJson != null && !userJson.isEmpty()) user.setData(UserData.fromJson(userJson)); } catch (IOException e) { LOGGER.error(e, "Cannot create user"); return buildTextErrorResponse(500, null, "user not creatable!", e.getMessage()); } if (request == null || request.isValid() == false) return buildTextErrorResponse(400, user, "import request is not set properly"); // check maximum archives if (Tools.checkQuota(user.getWorkspace().getArchives().size(), Fields.QUOTA_ARCHIVE_LIMIT) == false) { LOGGER.warn("QUOTA_ARCHIVE_LIMIT reached in workspace ", user.getWorkspaceId()); return buildTextErrorResponse(507, user, "Maximum number of archives in one workspace reached!"); } String archiveId = null; try { archiveId = importOrCreateArchive(user, request, null); } catch (ImporterException e) { return buildTextErrorResponse(400, user, e.getMessage(), e.getCause().getMessage()); } try (Archive archive = user.getArchive(archiveId)) { // set own VCard if (request.isOwnVCard()) setOwnVCard(user, request, archive); try { // import additional files if (request.getAdditionalFiles() != null && request.getAdditionalFiles().size() > 0) { addAdditionalFiles(user, request, archive, null); } } catch (ImporterException e) { // catch quota-exceeding-exception (Logging already done) user.deleteArchiveSilent(archiveId); return buildTextErrorResponse(507, user, e.getMessage(), e.getCause() != null ? e.getCause().getMessage() : null); } archive.getArchive().pack(); } catch (IOException | CombineArchiveWebException e) { LOGGER.error(e, "Cannot open/pack newly created archive"); user.deleteArchiveSilent(archiveId); return buildTextErrorResponse(500, user, "Cannot open newly created archive: ", e.getMessage()); } catch (ImporterException e) { LOGGER.error(e, "Something went wrong with the extended import"); user.deleteArchiveSilent(archiveId); return buildTextErrorResponse(500, user, "Error while applying additional data to the archive"); } catch (TransformerException e) { LOGGER.error(e, "Something went wrong while packing the archive"); user.deleteArchiveSilent(archiveId); return buildTextErrorResponse(500, user, "Something went wrong while packing the archive"); } // redirect to workspace return buildSuccesResponse(user, request, archiveId, requestContext); }
From source file:jproxy.ProxyControl.java
/** * Initialise the dynamic domain keystore *///from w w w .j a va 2s .c o m private void initDynamicKeyStore() throws IOException, GeneralSecurityException { if (storePassword != null) { // Assume we have already created the store try { keyStore = getKeyStore(storePassword.toCharArray()); for (String alias : KeyToolUtils.getCAaliases()) { X509Certificate caCert = (X509Certificate) keyStore.getCertificate(alias); if (caCert == null) { keyStore = null; // no CA key - probably the wrong store type. break; // cannot continue } else { caCert.checkValidity(new Date(System.currentTimeMillis() + DateUtils.MILLIS_PER_DAY)); log.info("Valid alias found for " + alias); } } } catch (IOException e) { // store is faulty, we need to recreate it keyStore = null; // if cert is not valid, flag up to recreate it if (e.getCause() instanceof UnrecoverableKeyException) { log.warn( "Could not read key store " + e.getMessage() + "; cause: " + e.getCause().getMessage()); } else { log.warn("Could not open/read key store " + e.getMessage()); // message includes the file name } } catch (GeneralSecurityException e) { keyStore = null; // if cert is not valid, flag up to recreate it log.warn("Problem reading key store: " + e.getMessage()); } } if (keyStore == null) { // no existing file or not valid storePassword = RandomStringUtils.randomAlphanumeric(20); // Alphanum to avoid issues with command-line quoting keyPassword = storePassword; // we use same password for both setPassword(storePassword); log.info("Creating Proxy CA in " + CERT_PATH_ABS); KeyToolUtils.generateProxyCA(CERT_PATH, storePassword, CERT_VALIDITY); log.info("Created keystore in " + CERT_PATH_ABS); keyStore = getKeyStore(storePassword.toCharArray()); // This should now work } final String sslDomains = getSslDomains().trim(); if (sslDomains.length() > 0) { final String[] domains = sslDomains.split(","); // The subject may be either a host or a domain for (String subject : domains) { if (isValid(subject)) { if (!keyStore.containsAlias(subject)) { log.info("Creating entry " + subject + " in " + CERT_PATH_ABS); KeyToolUtils.generateHostCert(CERT_PATH, storePassword, subject, CERT_VALIDITY); keyStore = getKeyStore(storePassword.toCharArray()); // reload to pick up new aliases // reloading is very quick compared with creating an entry currently } } else { log.warn("Attempt to create an invalid domain certificate: " + subject); } } } }
From source file:com.linkedin.databus2.core.container.netty.ServerContainer.java
protected void doStart() { _controlLock.lock();/*from ww w.j ava2 s . c om*/ try { // Bind and start to accept incoming connections. int portNum = getContainerStaticConfig().getHttpPort(); _tcpChannelGroup = new DefaultChannelGroup(); _httpChannelGroup = new DefaultChannelGroup(); _httpServerChannel = _httpBootstrap.bind(new InetSocketAddress(portNum)); InetSocketAddress actualAddress = (InetSocketAddress) _httpServerChannel.getLocalAddress(); _containerPort = actualAddress.getPort(); // persist the port number (file name should be unique for the container) File portNumFile = new File(getHttpPortFileName()); portNumFile.deleteOnExit(); try { FileWriter portNumFileW = new FileWriter(portNumFile); portNumFileW.write(Integer.toString(_containerPort)); portNumFileW.close(); LOG.info("Saving port number in " + portNumFile.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException(e); } _httpChannelGroup.add(_httpServerChannel); LOG.info("Serving container " + getContainerStaticConfig().getId() + " HTTP listener on port " + _containerPort); if (_containerStaticConfig.getTcp().isEnabled()) { int tcpPortNum = _containerStaticConfig.getTcp().getPort(); _tcpServerChannel = _tcpBootstrap.bind(new InetSocketAddress(tcpPortNum)); _tcpChannelGroup.add(_tcpServerChannel); LOG.info("Serving container " + getContainerStaticConfig().getId() + " TCP listener on port " + tcpPortNum); } _nettyShutdownThread = new NettyShutdownThread(); Runtime.getRuntime().addShutdownHook(_nettyShutdownThread); // Start the producer thread after 5 seconds if (null != _jmxConnServer && _containerStaticConfig.getJmx().isRmiEnabled()) { try { _jmxShutdownThread = new JmxShutdownThread(_jmxConnServer); Runtime.getRuntime().addShutdownHook(_jmxShutdownThread); _jmxConnServer.start(); LOG.info("JMX server listening on port " + _containerStaticConfig.getJmx().getJmxServicePort()); } catch (IOException ioe) { if (ioe.getCause() != null && ioe.getCause() instanceof NameAlreadyBoundException) { LOG.warn( "Unable to bind JMX server connector. Likely cause is that the previous instance was not cleanly shutdown: killed in Eclipse?"); if (_jmxConnServer.isActive()) { LOG.warn("JMX server connector seems to be running anyway. "); } else { LOG.warn("Unable to determine if JMX server connector is running"); } } else { LOG.error("Unable to start JMX server connector", ioe); } } } _globalStatsThread.start(); } catch (RuntimeException ex) { LOG.error("Got runtime exception :" + ex, ex); throw ex; } finally { _controlLock.unlock(); } }
From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Extract sample data as defined in an uploaded RAML file * <p>// w w w . ja v 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 * @return HTTP response containing sample data extracted from the uploaded RAML file, in JSON format */ @POST @Path("sampleData") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public Response getSampleData(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream, @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail) { log.info("POST raml/sampleData"); 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"); } 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()); log.error(msg, e.getCause()); 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; //String schemaJson = RamlUtil.getSchemaJson(raml, ramlFile.getParentFile()); String sampleData = RamlUtil.getSampleJson(raml, ramlFile.getParentFile()); response = Response.status(Status.OK).entity(sampleData).build(); } else { // RAML file failed validation response = Response.status(Status.BAD_REQUEST).entity(RamlUtil.validationMessages(results)).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:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Produce an EDM from an uploaded RAML file * <p>/*from w w w. j av a2s .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 * @return an HTTP response containing the EDM transformation for the uploaded RAML file */ @POST @Path("edm") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) public Response genEdm(@DefaultValue("") @FormDataParam("file") InputStream uploadedInputStream, @DefaultValue("") @FormDataParam("file") FormDataContentDisposition fileDetail) { log.info("POST raml/edm"); 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"); } 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; EDM edm = new EDM(raml); Document doc = null; try { doc = edm.getDocument(); StringWriter stringWriter = new StringWriter(); EDM.prettyPrint(doc, stringWriter); response = Response.status(Status.OK).entity(stringWriter.toString()).build(); } catch (Exception e) { String msg = String.format("Failed to build EDM document - %s", e.getMessage()); throw new Exception(msg, e.getCause()); } } else { // RAML file failed validation response = Response.status(Status.BAD_REQUEST).entity(RamlUtil.validationMessages(results)).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:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Produce a list of request operations from an uploaded RAML file * <p>//from w w w .j a v a 2s . 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 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>//from ww w. j a v a 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 www . ja v 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 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 www .j a v a2 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. * @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; }
From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Deploys an REST virtual service from an uploaded RAML file * <p>/*ww w . j a v a 2s . 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; }