List of usage examples for java.lang System gc
public static void gc()
From source file:de.blizzy.backup.check.CheckRun.java
@Override public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { database = new Database(settings, false); final boolean[] ok = { true }; List<StorageInterceptorDescriptor> descs = BackupPlugin.getDefault().getStorageInterceptors(); for (final StorageInterceptorDescriptor desc : descs) { final IStorageInterceptor interceptor = desc.getStorageInterceptor(); SafeRunner.run(new ISafeRunnable() { @Override/*from w w w. j ava 2 s . com*/ public void run() { IDialogSettings settings = Utils.getChildSection(Utils.getSection("storageInterceptors"), //$NON-NLS-1$ desc.getId()); if (!interceptor.initialize(parentShell, settings)) { ok[0] = false; } } @Override public void handleException(Throwable t) { ok[0] = false; interceptor.showErrorMessage(t, parentShell); BackupPlugin.getDefault() .logError("error while initializing storage interceptor '" + desc.getName() + "'", t); //$NON-NLS-1$ //$NON-NLS-2$ } }); storageInterceptors.add(interceptor); } if (!ok[0]) { monitor.done(); throw new InterruptedException(); } try { database.open(storageInterceptors); database.initialize(); int numFiles = database.factory().select(Factory.count()).from(Tables.FILES).fetchOne(Factory.count()) .intValue(); monitor.beginTask(Messages.Title_CheckBackupIntegrity, numFiles); Cursor<Record> cursor = null; try { cursor = database.factory().select(Tables.FILES.ID, Tables.FILES.BACKUP_PATH, Tables.FILES.CHECKSUM, Tables.FILES.LENGTH, Tables.FILES.COMPRESSION).from(Tables.FILES).fetchLazy(); while (cursor.hasNext()) { if (monitor.isCanceled()) { throw new InterruptedException(); } Record record = cursor.fetchOne(); String backupPath = record.getValue(Tables.FILES.BACKUP_PATH); String checksum = record.getValue(Tables.FILES.CHECKSUM); long length = record.getValue(Tables.FILES.LENGTH).longValue(); Compression compression = Compression .fromValue(record.getValue(Tables.FILES.COMPRESSION).intValue()); FileCheckResult checkResult = checkFile(backupPath, checksum, length, compression); if (!checkResult.ok) { backupOk = false; break; } if (checksum.length() != SHA256_LENGTH) { Integer id = record.getValue(Tables.FILES.ID); database.factory().update(Tables.FILES) .set(Tables.FILES.CHECKSUM, checkResult.checksumSHA256) .where(Tables.FILES.ID.equal(id)).execute(); } monitor.worked(1); } } finally { database.closeQuietly(cursor); } } catch (SQLException | IOException e) { boolean handled = false; for (IStorageInterceptor interceptor : storageInterceptors) { if (interceptor.showErrorMessage(e, parentShell)) { handled = true; } } if (handled) { throw new InterruptedException(); } throw new InvocationTargetException(e); } finally { database.close(); for (final IStorageInterceptor interceptor : storageInterceptors) { SafeRunner.run(new ISafeRunnable() { @Override public void run() { interceptor.destroy(); } @Override public void handleException(Throwable t) { BackupPlugin.getDefault().logError("error while destroying storage interceptor", t); //$NON-NLS-1$ } }); } System.gc(); monitor.done(); } }
From source file:de.blizzy.backup.backup.BackupRun.java
@Override public void run() { BackupPlugin.getDefault().logMessage("Starting backup"); //$NON-NLS-1$ fireBackupStatusChanged(BackupStatus.INITIALIZE); final boolean[] ok = { true }; List<StorageInterceptorDescriptor> descs = BackupPlugin.getDefault().getStorageInterceptors(); for (final StorageInterceptorDescriptor desc : descs) { final IStorageInterceptor interceptor = desc.getStorageInterceptor(); SafeRunner.run(new ISafeRunnable() { @Override/*from w w w .j av a2 s.c o m*/ public void run() { IDialogSettings settings = Utils.getChildSection(Utils.getSection("storageInterceptors"), //$NON-NLS-1$ desc.getId()); if (!interceptor.initialize(BackupApplication.getBackupShellWindow(), settings)) { ok[0] = false; } } @Override public void handleException(Throwable t) { ok[0] = false; interceptor.showErrorMessage(t, BackupApplication.getBackupShellWindow()); BackupPlugin.getDefault() .logError("error while initializing storage interceptor '" + desc.getName() + "'", t); //$NON-NLS-1$ //$NON-NLS-2$ } }); storageInterceptors.add(interceptor); } try { if (ok[0]) { database = new Database(settings, true); try { database.open(storageInterceptors); database.initialize(); database.factory().insertInto(Tables.BACKUPS) .set(Tables.BACKUPS.RUN_TIME, new Timestamp(System.currentTimeMillis())).execute(); backupId = database.factory().lastID().intValue(); for (ILocation location : settings.getLocations()) { if (!running) { break; } doPause(); try { backupFolder(location.getRootFolder(), -1, location.getRootFolder().getAbsolutePath()); } catch (IOException | RuntimeException e) { BackupPlugin.getDefault().logError("error while running backup", e); //$NON-NLS-1$ fireBackupErrorOccurred(e, BackupErrorEvent.Severity.ERROR); } finally { location.close(); } } database.factory().update(Tables.BACKUPS) .set(Tables.BACKUPS.NUM_ENTRIES, Integer.valueOf(numEntries)) .where(Tables.BACKUPS.ID.equal(Integer.valueOf(backupId))).execute(); fireBackupStatusChanged(BackupStatus.CLEANUP); removeOldBackups(); consolidateDuplicateFiles(); removeUnusedFiles(); removeOldDatabaseBackups(); database.factory().query("ANALYZE").execute(); //$NON-NLS-1$ } catch (SQLException | IOException | RuntimeException e) { for (IStorageInterceptor interceptor : storageInterceptors) { interceptor.showErrorMessage(e, BackupApplication.getBackupShellWindow()); } BackupPlugin.getDefault().logError("error while running backup", e); //$NON-NLS-1$ fireBackupErrorOccurred(e, BackupErrorEvent.Severity.ERROR); } finally { fireBackupStatusChanged(BackupStatus.FINALIZE); database.close(); backupDatabase(); for (final IStorageInterceptor interceptor : storageInterceptors) { SafeRunner.run(new ISafeRunnable() { @Override public void run() { interceptor.destroy(); } @Override public void handleException(Throwable t) { BackupPlugin.getDefault().logError("error while destroying storage interceptor", t); //$NON-NLS-1$ } }); } } } } finally { System.gc(); fireBackupEnded(); BackupPlugin.getDefault().logMessage("Backup done"); //$NON-NLS-1$ } }
From source file:gov.nist.appvet.tool.synchtest.Service.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get received HTTP parameters and file upload FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null;//from ww w. j av a 2s . co m FileItem fileItem = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } // Get received items Iterator iter = items.iterator(); FileItem item = null; while (iter.hasNext()) { item = (FileItem) iter.next(); if (item.isFormField()) { // Get HTML form parameters String incomingParameter = item.getFieldName(); String incomingValue = item.getString(); if (incomingParameter.equals("appid")) { appId = incomingValue; log.info("Received app ID: " + appId); } /** CHANGE (START): Get other tools-specific form parameters **/ /** CHANGE (END): Get other tools-specific form parameters **/ } else { // item should now hold the received file if (item != null) { fileItem = item; log.info("Received file: " + fileItem.getName()); } } } if (appId == null) { // All tool services require an AppVet app ID log.error("Received null app ID. Returning HTTP 400"); HttpUtil.sendHttp400(response, "No app ID specified"); return; } if (fileItem != null) { // Get app file fileName = FileUtil.getFileName(fileItem.getName()); if (!fileName.endsWith(".apk")) { log.error("Received invalid app file. Returning HTTP 400"); HttpUtil.sendHttp400(response, "Invalid app file: " + fileItem.getName()); return; } // Create app directory appDirPath = Properties.TEMP_DIR + "/" + appId; File appDir = new File(appDirPath); if (!appDir.exists()) { appDir.mkdir(); } // Create report path reportFilePath = Properties.TEMP_DIR + "/" + appId + "/" + reportName + "." + Properties.reportFormat.toLowerCase(); appFilePath = Properties.TEMP_DIR + "/" + appId + "/" + fileName; log.debug("App file path: " + appFilePath); if (!FileUtil.saveFileUpload(fileItem, appFilePath)) { log.error("Could not save file. Returning HTTP 500"); HttpUtil.sendHttp500(response, "Could not save uploaded file"); return; } log.debug("Saved app file"); } else { HttpUtil.sendHttp400(response, "No app was received."); return; } // Use if reading command from ToolProperties.xml. Otherwise, // comment-out if using custom command (called by customExecute()) //command = getCommand(); /* * CHANGE: Select either execute() to execute a native OS command or * customExecute() to execute your own custom code. Make sure that the * unused method call is commented-out. */ reportBuffer = new StringBuffer(); boolean succeeded = customExecute(reportBuffer); if (!succeeded) { log.error("Error detected: " + reportBuffer.toString()); String errorReport = ReportUtil.getHtmlReport(response, fileName, ToolStatus.ERROR, reportBuffer.toString()); // Send report to AppVet if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) { // Send back ASCII in HTTP Response ReportUtil.sendInHttpResponse(response, errorReport, ToolStatus.ERROR); } return; } // Analyze report and generate tool status log.info("Analyzing report for " + appFilePath); // ToolStatus risk = ReportUtil.analyzeReport(reportBuffer // .toString()); ToolStatus risk = ToolStatus.LOW; // Just set to LOW for testing log.info("Result: " + risk.name()); String reportContent = null; // Get report if (Properties.reportFormat.equals(ReportFormat.HTML.name())) { reportContent = ReportUtil.getHtmlReport(response, fileName, risk, reportBuffer.toString()); } // else if (Properties.reportFormat.equals(ReportFormat.TXT.name())) { // reportContent = getTxtReport(); // } else if (Properties.reportFormat.equals(ReportFormat.PDF.name())) { // reportContent = getPdfReport(); // } else if (Properties.reportFormat.equals(ReportFormat.JSON.name())) { // reportContent = getJsonReport(); // } // If report is null or empty, stop processing if (reportContent == null || reportContent.isEmpty()) { log.error("Tool report is null or empty"); return; } else { log.info("Report generated"); } // Send report to AppVet if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) { // Send back ASCII in HTTP Response ReportUtil.sendPDFInHttpResponse(response, reportContent, risk); } // Clean up if (!Properties.keepApps) { if (FileUtil.deleteDirectory(new File(appDirPath))) { log.debug("Deleted " + appFilePath); } else { log.error("Could not delete " + appFilePath); } } log.info("Done processing app " + appId); reportBuffer = null; System.gc(); }
From source file:burstcoin.jminer.JMinerCommandLine.java
private void initApplicationListeners() { context.addApplicationListener(new ApplicationListener<RoundFinishedEvent>() { @Override/*from www.j av a2 s .com*/ public void onApplicationEvent(RoundFinishedEvent event) { previousRemainingCapacity = 0; previousElapsedTime = 0; long s = event.getRoundTime() / 1000; long ms = event.getRoundTime() % 1000; String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A" : String.valueOf(event.getBestCommittedDeadline()); LOG.info("FINISH block '" + event.getBlockNumber() + "', " + "best deadline '" + bestDeadline + "', " + "round time '" + s + "s " + ms + "ms'"); } }); context.addApplicationListener(new ApplicationListener<RoundStoppedEvent>() { @Override public void onApplicationEvent(RoundStoppedEvent event) { previousRemainingCapacity = 0; previousElapsedTime = 0; long s = event.getElapsedTime() / 1000; long ms = event.getElapsedTime() % 1000; BigDecimal totalCapacity = new BigDecimal(event.getCapacity()); BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32); BigDecimal progress = factor .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity())); int percentage = (int) Math.ceil(progress.doubleValue() * 100); percentage = percentage > 100 ? 100 : percentage; String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A" : String.valueOf(event.getBestCommittedDeadline()); LOG.info("STOP block '" + event.getBlockNumber() + "', " + String.valueOf(percentage) + "% done, " + "best deadline '" + bestDeadline + "', " + "elapsed time '" + s + "s " + ms + "ms'"); } }); context.addApplicationListener(new ApplicationListener<NetworkLastWinnerEvent>() { @Override public void onApplicationEvent(NetworkLastWinnerEvent event) { if (blockNumber - 1 == event.getLastBlockNumber()) { LOG.info( " winner block '" + event.getLastBlockNumber() + "', '" + event.getWinner() + "'"); } else { LOG.error("Error: NetworkLastWinnerEvent for block: " + event.getLastBlockNumber() + " is outdated!"); } } }); context.addApplicationListener(new ApplicationListener<NetworkStateChangeEvent>() { @Override public void onApplicationEvent(NetworkStateChangeEvent event) { blockNumber = event.getBlockNumber(); } }); context.addApplicationListener(new ApplicationListener<RoundStartedEvent>() { @Override public void onApplicationEvent(RoundStartedEvent event) { progressLogStep = NUMBER_OF_PROGRESS_LOGS_PER_ROUND; LOG.info("-------------------------------------------------------"); LOG.info("START block '" + event.getBlockNumber() + "', " + "scoopNumber '" + event.getScoopNumber() + "', " + "capacity '" + event.getCapacity() / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR + " " + G_UNIT + "'"); String target = event.getTargetDeadline() == Long.MAX_VALUE ? "N/A" : String.valueOf(event.getTargetDeadline()); LOG.info(" targetDeadline '" + target + "', " + "baseTarget '" + String.valueOf(event.getBaseTarget()) + "'"); } }); context.addApplicationListener(new ApplicationListener<ReaderProgressChangedEvent>() { @Override public void onApplicationEvent(ReaderProgressChangedEvent event) { long logStepCapacity = event.getCapacity() / NUMBER_OF_PROGRESS_LOGS_PER_ROUND; if (event.getRemainingCapacity() < logStepCapacity * progressLogStep || event.getRemainingCapacity() == 0) { progressLogStep--; // trigger garbage collection on every progress step System.gc(); BigDecimal totalCapacity = new BigDecimal(event.getCapacity()); BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32); BigDecimal progress = factor .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity())); int percentage = (int) Math.ceil(progress.doubleValue() * 100); percentage = percentage > 100 ? 100 : percentage; // calculate capacity long effMBPerSec = 0; if (previousRemainingCapacity > 0) { long effDoneBytes = previousRemainingCapacity - event.getRemainingCapacity(); // calculate current reading speed (since last info) long effBytesPerMs = (effDoneBytes / 4096) / (event.getElapsedTime() - previousElapsedTime); effMBPerSec = (effBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR; } // calculate capacity long doneBytes = event.getCapacity() - event.getRemainingCapacity(); long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR; long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR; // calculate reading speed (average) long averageBytesPerMs = (doneBytes / 4096) / event.getElapsedTime(); long averageMBPerSec = (averageBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR; previousRemainingCapacity = event.getRemainingCapacity(); previousElapsedTime = event.getElapsedTime(); LOG.info(String.valueOf(percentage) + "% done (" + doneTB + T_UNIT + " " + doneGB + G_UNIT + "), avg.'" + averageMBPerSec + " " + M_UNIT + "/s'" + (effMBPerSec > 0 ? ", eff.'" + effMBPerSec + " " + M_UNIT + "/s'" : "")); } } }); context.addApplicationListener(new ApplicationListener<RoundSingleResultEvent>() { @Override public void onApplicationEvent(RoundSingleResultEvent event) { LOG.info("dl '" + event.getCalculatedDeadline() + "' send (" + (event.isPoolMining() ? "pool" : "solo") + ")"); } }); context.addApplicationListener(new ApplicationListener<RoundSingleResultSkippedEvent>() { @Override public void onApplicationEvent(RoundSingleResultSkippedEvent event) { LOG.info( "dl '" + event.getCalculatedDeadline() + "' > '" + event.getTargetDeadline() + "' skipped"); } }); context.addApplicationListener(new ApplicationListener<NetworkResultConfirmedEvent>() { @Override public void onApplicationEvent(NetworkResultConfirmedEvent event) { LOG.info("dl '" + event.getDeadline() + "' confirmed! [ " + getDeadlineTime(event.getDeadline()) + " ]"); } }); context.addApplicationListener(new ApplicationListener<NetworkDevResultConfirmedEvent>() { @Override public void onApplicationEvent(NetworkDevResultConfirmedEvent event) { LOG.info("devPool response '" + event.getResponse() + "', block '" + event.getBlockNumber() + "'"); for (DevPoolResult devPoolResult : event.getDevPoolResults()) { LOG.info("dl '" + devPoolResult.getCalculatedDeadline() + "' successful committed! [ " + getDeadlineTime(devPoolResult.getCalculatedDeadline()) + " ]"); } } }); context.addApplicationListener(new ApplicationListener<NetworkResultErrorEvent>() { @Override public void onApplicationEvent(NetworkResultErrorEvent event) { LOG.info("strange dl result '" + event.getStrangeDeadline() + "', calculated '" + event.getCalculatedDeadline() + "' " + "block '" + event.getBlockNumber() + "' nonce '" + event.getNonce() + "'"); } }); context.addApplicationListener(new ApplicationListener<ReaderCorruptFileEvent>() { @Override public void onApplicationEvent(ReaderCorruptFileEvent event) { LOG.info("strange dl source '" + event.getFilePath() + "' (try replotting!?)"); LOG.info("strange dl file chunks '" + event.getNumberOfChunks() + "', " + "parts per chunk '" + event.getNumberOfParts() + "', " + "block '" + event.getBlockNumber() + "'"); } }); context.addApplicationListener(new ApplicationListener<ReaderDriveFinishEvent>() { @Override public void onApplicationEvent(ReaderDriveFinishEvent event) { if (blockNumber == event.getBlockNumber()) { // calculate capacity long doneBytes = event.getSize(); long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR; long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR; long s = event.getTime() / 1000; long ms = event.getTime() % 1000; LOG.info("read '" + event.getDirectory() + "' (" + doneTB + T_UNIT + " " + doneGB + G_UNIT + ") in '" + s + "s " + ms + "ms'"); } } }); context.addApplicationListener(new ApplicationListener<ReaderDriveInterruptedEvent>() { @Override public void onApplicationEvent(ReaderDriveInterruptedEvent event) { LOG.info("stopped '" + event.getDirectory() + "' for block '" + event.getBlockNumber() + "'."); } }); context.addApplicationListener(new ApplicationListener<NetworkPoolInfoEvent>() { @Override public void onApplicationEvent(NetworkPoolInfoEvent event) { String value = event.getPoolBalanceNQT(); String amount = value.length() > 8 ? value.substring(0, value.length() - 8) : value; value = event.getPoolForgedBalanceNQT(); String totalForget = value.length() > 8 ? value.substring(0, value.length() - 8) : value; LOG.info("-------------------------------------------------------"); LOG.info("POOL account '" + event.getPoolAccountRS() + "', assigned miners '" + event.getPoolNumberOfMiningAccounts() + "'"); LOG.info(" balance '" + amount + " BURST', total mined '" + totalForget + " BURST'"); } }); }
From source file:GridFDock.GridFDockRunner.java
public JPPFJob buildJob(final String jobName) throws Exception { // Read the parameters from the file. try {//from ww w . j av a 2 s. c o m fl = new File("parameter.mgc"); } catch (Exception e) { System.out.println("The parameter of \"parameter.mgc\" can not be found, please create it!"); } try { rd = new BufferedReader(new FileReader(fl)); userdir = System.getProperty("user.dir"); while ((tempStr = rd.readLine()) != null) { if (tempStr.length() == 0) { } else { temArray = tempStr.split("\\s+"); if (temArray[0].equalsIgnoreCase("Ipaddress")) { ip = temArray[1]; } else if (temArray[0].equalsIgnoreCase("IpPort")) { port = Integer.parseInt(temArray[1]); } else if (temArray[0].equalsIgnoreCase("User")) { user = temArray[1]; } else if (temArray[0].equalsIgnoreCase("Password")) { passwd = temArray[1]; } else if (temArray[0].equalsIgnoreCase("Downloaddir")) { downdir = temArray[1]; } else if (temArray[0].equalsIgnoreCase("UploadDir")) { uploaddir = temArray[1]; } else if (temArray[0].equalsIgnoreCase("Program")) { program = temArray[1]; } else if (temArray[0].equalsIgnoreCase("Command")) { command = temArray[1]; } else if (temArray[0].equalsIgnoreCase("Token")) { sign = temArray[1]; } else if (temArray[0].equalsIgnoreCase("MaxNodes")) { maxNodes = Integer.parseInt(temArray[1]); } else if (temArray[0].startsWith("#")) { } else { System.out.println("***********: " + tempStr); System.out.println("Configure the wrong parameters in \"parameter.mgc\", please " + "check \"IpPort\", \"User\", \"Password\", \"Downloaddir\", " + "\"UploadDir\", \"Program\", \"Command\" and comments \"#\" so on," + " and add it according manual!"); } } } } catch (Exception e) { e.printStackTrace(); System.out.println("Exception happen when read the \"parameter.mgc\", please check the parameters!"); } finally { if (rd != null) { rd.close(); } } if (ip == null) { System.out.println("The FTP ip address should be setting, please check paramter file!"); } else if (port == 0) { System.out.println("The FTP ip port should be setting, please check paramter file!"); } else if (user == null) { System.out.println("The FTP user should be setting, please check paramter file!"); } else if (passwd == null) { System.out.println("The FTP password should be setting, please check paramter file!"); } else if (downdir == null) { System.out.println("The FTP download directory should be setting, please check paramter file!"); } else if (uploaddir == null) { System.out.println("The FTP upload directory should be setting, please check paramter file!"); } else if (program == null) { System.out.println( "The run program should be setting such as Autodock_vina etc., please check paramter file!"); } else if (command == null) { System.out .println("The program command should be setting such as \"vina\", please check paramter file!"); } else if (sign == null) { System.out.println("The token should be for delete no use files, please check paramter file!"); } else { System.out.println("Every parameter is ok! Now preparing for work!"); } try { dt.connect(ip, port, user, passwd); if (dt.isconnect() == true) { System.out.println("The ftp had connected!"); } else { System.out.println("The ftp can not connect! Please check FTP!"); } } catch (IOException e3) { System.out.println("FTP connect err in the server!"); } try { // DataDistribute.ftpClient.changeWorkingDirectory(downdir); fileList = dt.ftpClient.listFiles(downdir); } catch (IOException e) { System.out.println("The change working directory is wrong!"); e.printStackTrace(); } DataProvider dp = new MemoryMapDataProvider(); JPPFJob job = new JPPFJob(); job.setDataProvider(dp); if (program.equalsIgnoreCase("Autodock_Vina")) { for (int i = countStart; i < countEnd; i++) { fltmp = fileList[i].getName(); // System.out.println("This is test: " + countStart); //System.out.println("The finish blocks: " + df.format((float) (i + 1) / tmpCount)); job.add(new GridFVinaTask(ip, port, user, passwd, downdir, uploaddir, program, command, fltmp, sign)); System.gc(); } dt.disconnect(); } else if (program.equalsIgnoreCase("Autodock4")) { for (int i = countStart; i < countEnd; i++) { Arraytmp = fileList[i].getName().split("\\."); if (fileList[i].getName().contains("pdbqt")) { fltmp = Arraytmp[0]; job.add(new GridFAutodock4Task(ip, port, user, passwd, downdir, uploaddir, program, command, fltmp, sign)); System.gc(); } // System.out.println(Arraytmp[0]); } dt.disconnect(); } System.gc(); return job; }
From source file:com.trailbehind.android.iburn.map.MapActivity.java
@Override public void onDestroy() { try {//from ww w .j a va2 s . c o m if (mDefaultHttpClient1 != null) { mDefaultHttpClient1.getConnectionManager().shutdown(); } } catch (Exception e) { // we dont care } getBurnApplication().onDestroy(); doCleanup(); System.gc(); Log.d(TAG, "onDestroy called.."); super.onDestroy(); }
From source file:org.callimachusproject.test.TemporaryServerFactory.java
private synchronized TemporaryServer createTemporaryServer() { try {//from w ww .j a va 2 s . c om final File dir = createCallimachus(origin); return new TemporaryServer() { private LocalRepositoryManager manager; private WebServer server; private CalliRepository repository; private boolean stopped; public synchronized void start() throws InterruptedException, Exception { manager = RepositoryProvider.getRepositoryManager(dir); File dataDir = manager.getRepositoryDir("callimachus"); Repository repo = manager.getRepository("callimachus"); repository = new CalliRepository(repo, dataDir); repository.setDatasourceManager(new DatasourceManager(manager, "callimachus") { protected CalliRepository createCalliRepository(URI uri, Repository delegate, File dataDir) throws OpenRDFException, IOException { CalliRepository secondary; secondary = super.createCalliRepository(uri, delegate, dataDir); String uriSpace = repository.getChangeFolder(); String webapp = repository.getCallimachusWebapp(uriSpace); secondary.setChangeFolder(uriSpace, webapp); return secondary; } }); String url = repository.getCallimachusUrl(origin, CHANGES_PATH); String schema = repository.getCallimachusUrl(origin, SCHEMA_GRAPH); repository.addSchemaGraphType(schema); repository.setChangeFolder(url); repository.setCompileRepository(true); server = new WebServer(new File(dataDir, "cache/server")); server.addOrigin(origin, repository); server.listen(new int[] { port }, new int[0]); server.start(); HttpHost host = URIUtils.extractHost(java.net.URI.create(origin + "/")); HttpClientFactory.getInstance().setProxy(host, server); Thread.sleep(100); } public synchronized void pause() throws Exception { } public synchronized void resume() throws Exception { synchronized (running) { TemporaryServer other = running.get(port); if (stopped || !this.equals(other)) { if (other != null) { other.stop(); } start(); running.put(port, this); } } } public synchronized void stop() throws Exception { if (!stopped) { server.stop(); server.destroy(); server = null; repository = null; manager.shutDown(); stopped = true; Thread.sleep(100); System.gc(); System.runFinalization(); } } public synchronized void destroy() throws Exception { stop(); FileUtil.deltree(dir); } @Override protected void finalize() throws Exception { destroy(); } public String getOrigin() { return origin; } public String getUsername() { return email; } public char[] getPassword() { return password; } public CalliRepository getRepository() { return this.repository; } public String toString() { return server.toString(); } }; } catch (Exception e) { throw new AssertionError(e); } }
From source file:com.phonegap.CameraLauncher.java
/** * Called when the camera view exits. /*from w w w. j av a2 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) { // Get src and dest types from request code int srcType = (requestCode / 16) - 1; int destType = (requestCode % 16) - 1; // If CAMERA if (srcType == CAMERA) { // If image available if (resultCode == Activity.RESULT_OK) { try { // Read in bitmap of captured image Bitmap bitmap = android.provider.MediaStore.Images.Media .getBitmap(this.ctx.getContentResolver(), imageUri); // If sending base64 image back if (destType == DATA_URL) { this.processPicture(bitmap); } // If sending filename back else if (destType == FILE_URI) { // 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) { System.out.println("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) { System.out.println("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(); // 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(); } 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!"); } } // If retrieving photo from library else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) { if (resultCode == Activity.RESULT_OK) { Uri uri = intent.getData(); android.content.ContentResolver resolver = this.ctx.getContentResolver(); // If sending base64 image back if (destType == DATA_URL) { try { Bitmap bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri)); this.processPicture(bitmap); bitmap.recycle(); bitmap = null; System.gc(); } catch (FileNotFoundException e) { e.printStackTrace(); this.failPicture("Error retrieving image."); } } // If sending filename back else if (destType == FILE_URI) { this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId); } } else if (resultCode == Activity.RESULT_CANCELED) { this.failPicture("Selection cancelled."); } else { this.failPicture("Selection did not complete!"); } } }
From source file:fileMapper.ws.FileMapperServiceDriver.java
/** * Function to send getCodeInfo requestVdo to ONT web service * // w ww. j a v a 2 s. c o m * @param VocabRequestType vocabType we wish to get data for * @return A String containing the ONT web service response */ public static String sendREST(EndpointReference restEPR, String requestString, String type) throws Exception { if (UserInfoBean.getInstance().getCellDataUrl("ont") == null) { throw new I2B2Exception("Ontology cell (ONT) not configured in PM"); } // requestString.replaceAll("\\p{Cntrl}", ""); did not fix illegal control char error OMElement getOnt = getOntPayLoad(requestString); if (type != null) { if (type.equals("ONT")) MessageUtil.getInstance().setNavRequest("URL: " + restEPR + "\n" + getOnt.toString()); else if (type.equals("EDIT")) MessageUtil.getInstance().setEditRequest("URL: " + restEPR + "\n" + getOnt.toString()); else MessageUtil.getInstance().setFindRequest("URL: " + restEPR + "\n" + getOnt.toString()); } Options options = new Options(); log.debug(restEPR.toString()); options.setTo(restEPR); options.setTransportInProtocol(Constants.TRANSPORT_HTTP); options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); options.setProperty(HTTPConstants.SO_TIMEOUT, new Integer(125000)); options.setProperty(HTTPConstants.CONNECTION_TIMEOUT, new Integer(125000)); ServiceClient sender = FileMapperServiceClient.getServiceClient(); sender.setOptions(options); OMElement result; try { result = sender.sendReceive(getOnt); } catch (java.lang.OutOfMemoryError e) { System.gc(); throw new I2B2Exception("Out of memory"); // return null; } String response = result.toString(); if (type != null) { if (type.equals("ONT")) MessageUtil.getInstance().setNavResponse("URL: " + restEPR + "\n" + response); else if (type.equals("EDIT")) MessageUtil.getInstance().setEditResponse("URL: " + restEPR + "\n" + response); else MessageUtil.getInstance().setFindResponse("URL: " + restEPR + "\n" + response); } int timeout = processSecurityResult(response); // log.info("get timeout from server: "+ timeout + " at: "+Calendar.getInstance().getTime()); if (timeout != -1) { UserInfoBean.setLastActivityTime(Calendar.getInstance().getTime()); UserInfoBean.getInstance().setUserPasswordTimeout(timeout); //log.info("get timeout from server: "+ timeout + " at: "+Calendar.getInstance().getTime()); } return response; }
From source file:de.topicmapslab.majortom.server.admin.controller.AdminController.java
/** * Starts the garbage collector and returns to the memory page * //w w w . j av a2 s . com * @return redirect to "memory" */ @RequestMapping("garbagecollect") public ModelAndView collectGarbage() { System.gc(); return getMemory(); }