List of usage examples for java.lang System gc
public static void gc()
From source file:jmupen.JMupenUpdater.java
public static void startWinUpdaterApplication() { final String javaBin; javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java.exe"; File updaterJar = new File(tmpDir.getAbsolutePath() + File.separator + "bin" + File.separator + "win" + File.separator + "JMupenWinupdater.jar"); File currentJarPathTxt = new File( tmpDir.getAbsolutePath() + File.separator + "bin" + File.separator + "currentjar.txt"); try {//from w w w.java 2 s . c om FileUtils.writeStringToFile(currentJarPathTxt, getJarFile().getAbsolutePath()); } catch (IOException e) { System.err.println("Error writing jar filepath " + e.getLocalizedMessage()); JMupenGUI.getInstance().showError("Error writing jar filepath to txt", e.getLocalizedMessage()); } catch (URISyntaxException ex) { System.err.println("Error writing jar filepath " + ex.getLocalizedMessage()); } if (!updaterJar.exists()) { JMupenGUI.getInstance().showError("WinUpdater not found", "in folder: " + updaterJar.getAbsolutePath()); return; } /* is it a jar file? */ if (!updaterJar.getName().endsWith(".jar")) { JMupenGUI.getInstance().showError("WinUpdater does not end with .jar????", updaterJar.getAbsolutePath()); return; } /* Build command: java -jar application.jar */ final ArrayList<String> command = new ArrayList<String>(); command.add(javaBin); command.add("-jar"); command.add(updaterJar.getPath()); final ProcessBuilder builder = new ProcessBuilder(command); try { builder.start(); } catch (IOException ex) { System.err.println("Error starting updater. " + ex.getLocalizedMessage()); JMupenGUI.getInstance().showError("Error starting updater", ex.getLocalizedMessage()); } System.gc(); System.exit(0); }
From source file:org.ala.apps.BieReport.java
/** * scan whole columnFamily tree and counting image; vertebrate; invertebrate; * plant and other in Australia./*w ww.j a v a 2s .com*/ * * @param infoSourceIds * @throws Exception */ public void doFullScanAndCount(String fileName) throws Exception { long start = System.currentTimeMillis(); long ctr = 1; int[] totalCtr = new int[NUMBER_OF_COUNTER]; ColumnType[] columns = new ColumnType[] { ColumnType.TAXONCONCEPT_COL, ColumnType.CLASSIFICATION_COL, ColumnType.IMAGE_COL, ColumnType.SYNONYM_COL, }; Map<String, Map<String, Object>> rowMaps = storeHelper.getPageOfSubColumns(columnFamily, columns, "", ROWS); // KeySlice startKey = new KeySlice(); // KeySlice lastKey = null; String lastKey = ""; String startKey = ""; System.out.println("BieReport process is started....."); // ColumnParent columnParent = new ColumnParent(columnFamily); // // KeyRange keyRange = new KeyRange(ROWS); // keyRange.setStart_key(""); // keyRange.setEnd_key(""); // // SliceRange sliceRange = new SliceRange(); // sliceRange.setStart(new byte[0]); // sliceRange.setFinish(new byte[0]); // // SlicePredicate slicePredicate = new SlicePredicate(); // slicePredicate.setSlice_range(sliceRange); // // Client client = Pelops.getDbConnPool(POOL_NAME).getConnection().getAPI(); // // // Iterate over all the rows in a ColumnFamily...... // // start with the empty string, and after each call use the last key read as the start key // // in the next iteration. // // when lastKey == startKey is finish. // List<KeySlice> keySlices = client.get_range_slices(keyspace, columnParent, slicePredicate, keyRange, ConsistencyLevel.ONE); totalCtr = getBieReportCount(rowMaps); while (rowMaps.size() > 0) { lastKey = rowMaps.keySet().toArray()[rowMaps.size() - 1].toString(); //end of scan ? if (lastKey.equals(startKey)) { break; } startKey = lastKey; rowMaps = storeHelper.getPageOfSubColumns(columnFamily, columns, startKey, ROWS); //keyRange.setStart_key(lastKey.getKey()); //keySlices = client.get_range_slices(keyspace, columnParent, slicePredicate, keyRange, ConsistencyLevel.ONE); int[] counters = getBieReportCount(rowMaps); for (int i = 0; i < counters.length; i++) { totalCtr[i] += counters[i]; } System.out.println("Row Count:" + (ROWS * ctr++) + " >>>> lastKey: " + lastKey); System.gc(); } System.out.println("\n==========< Summary >=========="); System.out.println("Australian vertebrates: " + totalCtr[CtrIndex.VERTEBRATE_CTR_INDEX.ordinal()]); System.out.println("Australian invertebrates: " + totalCtr[CtrIndex.INVERTEBRATE_CTR_INDEX.ordinal()]); System.out.println("Australian plants: " + totalCtr[CtrIndex.PLANT_CTR_INDEX.ordinal()]); System.out.println("Australian other: " + totalCtr[CtrIndex.OTHER_CTR_INDEX.ordinal()]); System.out.println("Australian vertebrates with at least one image: " + totalCtr[CtrIndex.VERTEBRATE_WITH_IMAGE_CTR_INDEX.ordinal()]); System.out.println("Australian invertebrates with at least one image: " + totalCtr[CtrIndex.INVERTEBRATE_WITH_IMAGE_CTR_INDEX.ordinal()]); System.out.println("Australian plants with at least one image: " + totalCtr[CtrIndex.PLANT_WITH_IMAGE_CTR_INDEX.ordinal()]); System.out.println("Australian other with at least one image: " + totalCtr[CtrIndex.OTHER_WITH_IMAGE_CTR_INDEX.ordinal()]); System.out.println("All Image Counter: " + totalCtr[CtrIndex.IMAGE_CTR_INDEX.ordinal()]); System.out.println("Vertebrate Image Counter: " + totalCtr[CtrIndex.VERTEBRATE_IMAGE_CTR_INDEX.ordinal()]); System.out.println( "Invertebrate Image Counter: " + totalCtr[CtrIndex.INVERTEBRATE_IMAGE_CTR_INDEX.ordinal()]); System.out.println("Plant Image Counter: " + totalCtr[CtrIndex.PLANT_IMAGE_CTR_INDEX.ordinal()]); System.out.println("Other Image Counter: " + totalCtr[CtrIndex.OTHER_IMAGE_CTR_INDEX.ordinal()]); System.out.println("Vertebrate Name Counter: " + totalCtr[CtrIndex.VERTEBRATE_NAME_CTR_INDEX.ordinal()]); System.out .println("Invertebrate Name Counter: " + totalCtr[CtrIndex.INVERTEBRATE_NAME_CTR_INDEX.ordinal()]); System.out.println("Plant Name Counter: " + totalCtr[CtrIndex.PLANT_NAME_CTR_INDEX.ordinal()]); System.out.println("Other Name Counter: " + totalCtr[CtrIndex.OTHER_NAME_CTR_INDEX.ordinal()]); System.out.println("Row Count:" + ROWS * ctr); System.out.println("Total time taken (sec): " + ((System.currentTimeMillis() - start) / 1000)); writeToFile(fileName, totalCtr, ROWS * ctr); }
From source file:net.mutina.uclimb.ForegroundCameraLauncher.java
/** * Called when the camera view exits. /* w ww . j a v a 2 s .co m*/ * * @param requestCode The request code originally supplied to startActivityForResult(), * allowing you to identify who this result came from. * @param resultCode The integer result code returned by the child activity through its setResult(). * @param intent An Intent, which can return result data to the caller (various data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost during compression ExifHelper exif = new ExifHelper(); exif.createInFile(getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg"); exif.readExifData(); // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // Create entry in media store for image // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.ctx.getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.ctx.getContentResolver() .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media store Uri OutputStream os = this.ctx.getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file exif.createOutFile(getRealPathFromURI(uri, this.ctx)); exif.writeExifData(); // Send Uri back to JavaScript for viewing image this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } }
From source file:de.teambluebaer.patientix.activities.EndActivity.java
@Override protected void onStop() { super.onStop(); Log.d("Stop", "Stop motherfucker"); System.gc(); deleteCache(getApplicationContext()); }
From source file:com.duroty.task.InitServerTask.java
/** * DOCUMENT ME!/*from ww w . j a va 2 s. c o m*/ * * @param dirUsers DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ public void flush() throws Exception { SessionFactory hfactory = null; Session hsession = null; try { hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory); hsession = hfactory.openSession(); Criteria crit1 = hsession.createCriteria(Roles.class); List roles = crit1.list(); if ((roles != null) && (roles.size() > 0)) { return; } else { Roles guest = new Roles(); guest.setRolName("guest"); hsession.save(guest); Roles member = new Roles(); member.setRolName("member"); hsession.save(member); Roles mail = new Roles(); mail.setRolName("mail"); hsession.save(mail); Roles bookmark = new Roles(); bookmark.setRolName("bookmark"); hsession.save(bookmark); Roles chat = new Roles(); chat.setRolName("chat"); hsession.save(chat); Roles admin = new Roles(); admin.setRolName("admin"); hsession.save(admin); hsession.flush(); Criteria crit2 = hsession.createCriteria(Users.class); crit2.add(Restrictions.eq("useUsername", "duroty")); Users duroty = (Users) crit2.uniqueResult(); if (duroty == null) { duroty = new Users(); duroty.setUseActive(true); duroty.setUseEmail("duroty@localhost"); duroty.setUseLanguage("en"); duroty.setUseName("Duroty System"); duroty.setUsePassword("duroty"); duroty.setUseRegisterDate(new Date()); duroty.setUseUsername("duroty"); UserRole userRole1 = new UserRole(new UserRoleId(duroty, member)); UserRole userRole2 = new UserRole(new UserRoleId(duroty, bookmark)); UserRole userRole3 = new UserRole(new UserRoleId(duroty, chat)); UserRole userRole4 = new UserRole(new UserRoleId(duroty, admin)); duroty.addUserRole(userRole1); duroty.addUserRole(userRole2); duroty.addUserRole(userRole3); duroty.addUserRole(userRole4); MailPreferences mailPreferences = new MailPreferences(); mailPreferences.setMaprHtmlMessage(true); mailPreferences.setMaprMessagesByPage(20); mailPreferences.setMaprQuotaSize(1048576); mailPreferences.setUsers(duroty); Identity identity = new Identity(); identity.setIdeActive(true); identity.setIdeCode(RandomStringUtils.randomAlphanumeric(25)); identity.setIdeDefault(true); identity.setIdeEmail("duroty@localhost"); identity.setIdeName("Duroty System"); identity.setIdeReplyTo("duroty@localhost"); identity.setUsers(duroty); HashSet set = new HashSet(); set.add(mailPreferences); duroty.setMailPreferenceses(set); HashSet identities = new HashSet(); identities.add(identity); duroty.setIdentities(identities); hsession.save(duroty); hsession.flush(); } Criteria crit3 = hsession.createCriteria(Users.class); crit3.add(Restrictions.eq("useUsername", "guest")); Users userGuest = (Users) crit3.uniqueResult(); if (userGuest == null) { userGuest = new Users(); userGuest.setUseActive(true); userGuest.setUseEmail("guest@localhost"); userGuest.setUseLanguage("en"); userGuest.setUseName("Guest System"); userGuest.setUsePassword("guest"); userGuest.setUseRegisterDate(new Date()); userGuest.setUseUsername("guest"); UserRole userRole1 = new UserRole(new UserRoleId(userGuest, guest)); ; userGuest.addUserRole(userRole1); MailPreferences mailPreferences = new MailPreferences(); mailPreferences.setMaprHtmlMessage(true); mailPreferences.setMaprMessagesByPage(20); mailPreferences.setMaprQuotaSize(1048576); mailPreferences.setUsers(userGuest); HashSet set = new HashSet(); set.add(mailPreferences); duroty.setMailPreferenceses(set); hsession.save(userGuest); hsession.flush(); } } } catch (Exception e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } catch (OutOfMemoryError e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } catch (Throwable e) { System.gc(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); DLog.log(DLog.ERROR, this.getClass(), writer.toString()); } finally { GeneralOperations.closeHibernateSession(hsession); System.gc(); } }
From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java
@Override public twitter4j.http.HttpResponse request(final twitter4j.http.HttpRequest req) throws TwitterException { final HostAddressResolver resolver = FactoryUtils.getHostAddressResolver(conf); final String urlString = req.getURL(); final URI urlOrig = ParseUtils.parseURI(urlString); final String host = urlOrig.getHost(), authority = urlOrig.getAuthority(); try {// www . j a va 2 s.c o m HttpRequestBaseHC4 commonsRequest; final String resolvedHost = resolver != null ? resolver.resolve(host) : null; final String resolvedUrl = !isEmpty(resolvedHost) ? urlString.replace("://" + host, "://" + resolvedHost) : urlString; final RequestMethod method = req.getMethod(); if (method == RequestMethod.GET) { commonsRequest = new HttpGetHC4(resolvedUrl); } else if (method == RequestMethod.POST) { final HttpPostHC4 post = new HttpPostHC4(resolvedUrl); post.setEntity(getAsEntity(req.getParameters())); post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); commonsRequest = post; } else if (method == RequestMethod.DELETE) { commonsRequest = new HttpDeleteHC4(resolvedUrl); } else if (method == RequestMethod.HEAD) { commonsRequest = new HttpHeadHC4(resolvedUrl); } else if (method == RequestMethod.PUT) { final HttpPutHC4 put = new HttpPutHC4(resolvedUrl); put.setEntity(getAsEntity(req.getParameters())); commonsRequest = put; } else throw new TwitterException("Unsupported request method " + method); final HttpParams httpParams = commonsRequest.getParams(); HttpClientParams.setRedirecting(httpParams, false); final Map<String, String> headers = req.getRequestHeaders(); for (final String headerName : headers.keySet()) { commonsRequest.addHeader(headerName, headers.get(headerName)); } final Authorization authorization = req.getAuthorization(); final String authorizationHeader = authorization != null ? authorization.getAuthorizationHeader(req) : null; if (authorizationHeader != null) { commonsRequest.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); } if (resolvedHost != null && !resolvedHost.isEmpty() && !resolvedHost.equals(host)) { commonsRequest.addHeader(HttpHeaders.HOST, authority); } final ApacheHttpClientHttpResponseImpl res; try { final HttpContext httpContext = new BasicHttpContextHC4(); httpContext.setAttribute(HostResolvedSSLConnectionSocketFactory.HTTP_CONTEXT_KEY_ORIGINAL_HOST, host); res = new ApacheHttpClientHttpResponseImpl(client.execute(commonsRequest, httpContext), conf); } catch (final IllegalStateException e) { throw new TwitterException("Please check your API settings.", e); } catch (final NullPointerException e) { // Bug http://code.google.com/p/android/issues/detail?id=5255 throw new TwitterException("Please check your APN settings, make sure not to use WAP APNs.", e); } catch (final OutOfMemoryError e) { // I don't know why OOM thown, but it should be catched. System.gc(); throw new TwitterException("Unknown error", e); } final int statusCode = res.getStatusCode(); if (statusCode < OK || statusCode > ACCEPTED) throw new TwitterException(res.asString(), req, res); return res; } catch (final IOException e) { // TODO if (resolver instanceof TwidereHostAddressResolver) { final TwidereHostAddressResolver twidereResolver = (TwidereHostAddressResolver) resolver; twidereResolver.removeCachedHost(host); } throw new TwitterException(e); } }
From source file:eu.planets_project.pp.plato.action.ProjectExportAction.java
/** * Exports the project identified by PlanProperties.Id ppid and writes the document * to the given OutputStream - including all binary data. * (currently required by {@link #exportAllProjectsToZip()} ) * - Does NOT clean up temp files written to baseTempPath * /*w ww . ja va 2 s.com*/ * @param ppid * @param out * @param baseTempPath used to write temp files for binary data, * must not be used by other exports at the same time */ public void exportComplete(int ppid, OutputStream out, String baseTempPath) { BASE64Encoder encoder = new BASE64Encoder(); ProjectExporter exporter = new ProjectExporter(); Document doc = exporter.createProjectDoc(); // int i = 0; List<Plan> list = null; try { list = em.createQuery("select p from Plan p where p.planProperties.id = " + ppid).getResultList(); } catch (Exception e1) { list = new ArrayList<Plan>(); FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "An error occured while generating the export file."); log.error("Could not load planProperties: ", e1); } try { if (list.size() != 1) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Skipping the export of the plan with properties" + ppid + ": Couldnt load."); } else { //log.debug("adding project "+p.getplanProperties().getName()+" to XML..."); String tempPath = baseTempPath; File tempDir = new File(tempPath); tempDir.mkdirs(); List<Integer> uploadIDs = new ArrayList<Integer>(); List<Integer> recordIDs = new ArrayList<Integer>(); try { exporter.addProject(list.get(0), doc, uploadIDs, recordIDs); writeBinaryObjects(recordIDs, uploadIDs, tempPath, encoder); // perform XSLT transformation to get the DATA into the PLANS XMLWriter writer = new XMLWriter( new FileOutputStream("/tmp/testout" + System.currentTimeMillis() + ".xml")); writer.write(doc); writer.close(); addBinaryData(doc, out, tempPath); } catch (IOException e) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "An error occured while generating the export file."); log.error("Could not open response-outputstream: ", e); } catch (TransformerException e) { FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "An error occured while generating the export file."); log.error(e); } } } finally { /* clean up */ list.clear(); list = null; em.clear(); System.gc(); } }
From source file:com.foregroundcameraplugin.ForegroundCameraLauncher.java
/** * Called when the camera view exits./* www . j a v a 2 s . c o m*/ * * @param requestCode * The request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode * The integer result code returned by the child activity through * its setResult(). * @param intent * An Intent, which can return result data to the caller (various * data can be attached to Intent "extras"). */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Create an ExifHelper to save the exif data that is lost // during compression ExifHelper exif = new ExifHelper(); exif.createInFile( getTempDirectoryPath(this.cordova.getActivity().getApplicationContext()) + "/Pic.jpg"); exif.readExifData(); // Read in bitmap of captured image Bitmap bitmap; try { bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.cordova.getActivity().getContentResolver(), imageUri); } catch (FileNotFoundException e) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.cordova.getActivity().getContentResolver(); bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); } bitmap = scaleBitmap(bitmap); // Create entry in media store for image // (Don't use insertImage() because it uses default compression // setting of 50 - no way to change it) ContentValues values = new ContentValues(); values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); Uri uri = null; try { uri = this.cordova.getActivity().getContentResolver() .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException e) { LOG.d(LOG_TAG, "Can't write to external media storage."); try { uri = this.cordova.getActivity().getContentResolver() .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values); } catch (UnsupportedOperationException ex) { LOG.d(LOG_TAG, "Can't write to internal media storage."); this.failPicture("Error capturing image - no media storage found."); return; } } // Add compressed version of captured image to returned media // store Uri OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os); os.close(); // Restore exif data to file exif.createOutFile(getRealPathFromURI(uri, this.cordova)); exif.writeExifData(); // Send Uri back to JavaScript for viewing image this.callbackContext.success(getRealPathFromURI(uri, this.cordova)); bitmap.recycle(); bitmap = null; System.gc(); checkForDuplicateImage(); } catch (IOException e) { e.printStackTrace(); this.failPicture("Error capturing image."); } } // If cancelled else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Camera cancelled."); } // If something else else { this.failPicture("Did not complete!"); } }
From source file:com.univocity.app.DataUpdateTest.java
private void validateAbsentRecordsGotRemoved(String entityName, RowDataCollector dataCollector, String deleteFile) {/*from www .jav a 2s . co m*/ String[] fieldNames = dataCollector.getFieldNames(); DataSource dataSource = DataStores.getInstance().getSourceDatabase().getDataSource(); List<Map<String, Object>> results = new JdbcTemplate(dataSource) .queryForList("SELECT " + toString(fieldNames).replace('^', ',') + " FROM " + entityName); Set<String> idsOnDatabase = new HashSet<String>(results.size()); for (Map<String, Object> e : results) { String id = toString(fieldNames, e); idsOnDatabase.add(id); } System.gc(); if (deleteFile == null) { Set<String> sr25Rows = getMapOfRows(entityName, fieldNames, true).keySet(); Set<String> sr26Rows = getMapOfRows(entityName, fieldNames, false).keySet(); @SuppressWarnings("unchecked") Collection<String> commonIds = CollectionUtils.intersection(sr25Rows, sr26Rows); sr25Rows.removeAll(commonIds); sr26Rows.removeAll(commonIds); sr25Rows = new TreeSet<String>(sr25Rows); sr26Rows = new TreeSet<String>(sr26Rows); for (String id : idsOnDatabase) { //table does not retain ids that are not in SR26 assertFalse(sr25Rows.contains(id)); sr26Rows.remove(id); } // ensures no unexpected ID is found on SR26. assertTrue(sr26Rows.isEmpty()); } else { parserSettings.setRowProcessor(dataCollector); new CsvParser(parserSettings) .parse(DataStores.getInstance().getSourceData().openUpdateFile(deleteFile)); Set<String> expectedToBeRemoved = dataCollector.getExpected(); for (String toBeRemoved : expectedToBeRemoved) { assertFalse(idsOnDatabase.contains(toBeRemoved)); } } }
From source file:com.ca.dvs.app.dvs_servlet.resources.RAML.java
/** * Extract sample data as defined in an uploaded RAML file * <p>/*from 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; }