List of usage examples for java.lang Runtime gc
public native void gc();
From source file:com.aurel.track.prop.LoginBL.java
/** * * @param username//from ww w. j a va 2s . c o m * @param userPwd * @param nonce * @param request * @param anonymousLogin * @return Map with two entries: 1. "errors": ArrayList<LabelValueBean>; 2. * "mappingEnum": Integer with 2: bad credentials, 6: license * problems, 7: forward to URL, 8: first time admin user, 18: * request license, 9: standard login * */ public static Map<String, Object> setEnvironment(String username, String userPwd, String nonce, HttpServletRequest request, Map<String, Object> sessionMap, boolean anonymousLogin, boolean usingContainerBasedAuthentication, boolean springAuthenticated) { HttpSession httpSession = request.getSession(); ArrayList<LabelValueBean> errors = new ArrayList<LabelValueBean>(); HashMap<String, Object> result = new HashMap<String, Object>(); Integer mappingEnum = 0; // Make things robust if (username == null) { username = "x"; } if (userPwd == null) { userPwd = "x"; } // Move locale to one that we actually have, in case there // was a request for a locale that we do not have Locale locale = LocaleHandler.getExistingLocale(request.getLocales()); LocaleHandler.exportLocaleToSession(sessionMap, locale); Support support = new Support(); support.setURIs(request); if (username != null) { ACCESSLOGGER.info("LOGON: User '" + username.trim() + "' trying to log on" + " at " + new Date().toString() + " from " + request.getRemoteAddr()); } ServletContext servletContext = org.apache.struts2.ServletActionContext.getServletContext(); try { if (!Torque.isInit()) { Torque.init(HandleHome.getTorqueProperties(servletContext, true)); LOGGER.debug("Database is " + Torque.getDefaultDB()); LOGGER.info("Torque was re-initialized."); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error("Could not initialize Torque (1)"); LOGGER.error(ExceptionUtils.getStackTrace(e)); errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale) + ":" + e.getMessage())); mappingEnum = 1; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } TPersonBean personBean = null; if (anonymousLogin) { personBean = PersonBL.getAnonymousIfActive(); } else { try { String pwd = ""; if (nonce == null || nonce.length() == 0) { pwd = userPwd; // clear text } else { pwd = decrypt(nonce.charAt(0), userPwd); // key is first // character of // nonce } personBean = PersonBL.loadByLoginNameWithRights(username); if (personBean != null) { personBean.setPlainPwd(pwd); if (personBean.isDisabled()) { errors.add( new LabelValueBean("errCredentials", getText("logon.err.user.disabled", locale))); ACCESSLOGGER .warn("LOGON: User " + personBean.getLoginName() + " is disabled, login refused!"); } else if (usingContainerBasedAuthentication == false && springAuthenticated == false && !personBean.authenticate(pwd)) { ACCESSLOGGER.warn("LOGON: Wrong password given for user " + personBean.getFullName() + " at " + new Date().toString() + " from " + request.getRemoteAddr()); errors.add(new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale))); } } else { ACCESSLOGGER.warn("LOGON: No such user: " + username + " at " + new Date().toString() + " from " + request.getRemoteAddr()); errors.add( new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale))); LOGGER.debug("User '" + username + "' is not in database..."); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error("Could not initialize Torque (2)"); LOGGER.error(ExceptionUtils.getStackTrace(e)); errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale))); } } if (errors.size() > 0 || personBean == null) { mappingEnum = 2; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } // At this point, we have successfully identified the user. // Try to set the users preferred locale if (personBean.getPrefLocale() != null && !"".equals(personBean.getPrefLocale())) { // get as stored in user profile locale = LocaleHandler.getExistingLocale(LocaleHandler.getLocaleFromString(personBean.getPrefLocale())); } if (locale == null) { // rely on browser settings locale = LocaleHandler.getExistingLocale(request.getLocales()); } personBean.setLocale(locale); // set the bean with the last saved login date and save the actual date // as // last login date in the database personBean.setLastButOneLogin(personBean.getLastLogin()); personBean.setLastLogin(new Date()); PersonBL.saveSimple(personBean); LocaleHandler.exportLocaleToSession(sessionMap, locale); // ----------------------------------------------------- // check if opState // (reject users, but not admin, in maintenance state) ApplicationBean appBean = ApplicationBean.getInstance(); if (appBean == null) { LOGGER.error("appBean == null: this should never happen"); mappingEnum = 3; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } httpSession.setAttribute(Constants.APPLICATION_BEAN, appBean); TSiteBean siteBean = DAOFactory.getFactory().getSiteDAO().load1(); if (ApplicationBean.OPSTATE_MAINTENNANCE.equals(siteBean.getOpState()) && !personBean.getIsSysAdmin()) { // print error, refuse login errors.add(new LabelValueBean("errGeneralError", getText("logon.err.maintenance", locale))); mappingEnum = 4; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } Runtime rt = Runtime.getRuntime(); long mbyte = 1024 * 1024; long freeMemoryMB = rt.freeMemory() / mbyte; if (freeMemoryMB < 50 && !personBean.getIsSysAdmin()) { rt.gc(); freeMemoryMB = rt.freeMemory() / mbyte; if (freeMemoryMB < 50) { errors.add(new LabelValueBean("errGeneralError", getText("logon.err.freeMemory", locale))); mappingEnum = 19; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } } // Save our logged-in user in the session // and set a cookie so she can conveniently point // directly to issues without having to log on for // the next CookieTimeout seconds httpSession.setAttribute(Constants.USER_KEY, personBean); int maxItemsProUser = GeneralSettings.getMaxItems(); FilterUpperTO filterUpperTO = new FilterUpperTO(); TreeFilterExecuterFacade.prepareFilterUpperTO(filterUpperTO, personBean, locale, null, null); int noOfProjectRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterProjectRoleItems(filterUpperTO, personBean, locale, maxItemsProUser); int noOfRACIRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterRACIRoleItems(filterUpperTO, personBean, locale, maxItemsProUser); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Maximum number of items per user " + maxItemsProUser); LOGGER.debug( "Number of project role items accessible by " + username + ": " + noOfProjectRoleItemsProUser); LOGGER.debug("Number of RACI role items accessible by " + username + ": " + noOfRACIRoleItemsProUser); } boolean projectRoleItemsAboveLimit = noOfProjectRoleItemsProUser >= maxItemsProUser; boolean raciRoleItemsAboveLimit = noOfRACIRoleItemsProUser >= maxItemsProUser; personBean.setProjectRoleItemsAboveLimit(Boolean.valueOf(projectRoleItemsAboveLimit)); personBean.setRaciRoleItemsAboveLimit(Boolean.valueOf(raciRoleItemsAboveLimit)); PersonBL.setLicensedFeatures(personBean); List<TListTypeBean> issueTypes = IssueTypeBL.loadAllByPerson(personBean.getObjectID(), locale); httpSession.setAttribute("issueTypesJSON", JSONUtility.encodeIssueTypes(issueTypes)); Integer sessionTimeoutMinutes = personBean.getSessionTimeoutMinutes(); if (sessionTimeoutMinutes != null && sessionTimeoutMinutes.intValue() != 0) { httpSession.setMaxInactiveInterval(sessionTimeoutMinutes * 60); } // load the my filters in the menu List<FilterInMenuTO> myFilters = FilterBL.loadMyMenuFiltersWithTooltip(personBean, locale); httpSession.setAttribute(FilterBL.MY_MENU_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(myFilters)); List<FilterInMenuTO> lastQueries = FilterInMenuBL.getLastExecutedQueries(personBean, locale); httpSession.setAttribute(FilterBL.LAST_EXECUTED_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(lastQueries)); httpSession.setAttribute(ShortcutBL.SHORTCUTS_JSON, ShortcutBL.encodeShortcutsJSON()); // modules List modules = getModuleDescriptors(personBean); httpSession.setAttribute("usedModules", modules); httpSession.setAttribute("usedModulesJSON", MasterHomeJSON.encodeModules(modules, personBean)); httpSession.setAttribute("loggedInPersonUserLevel", personBean.getUserLevel()); httpSession.setAttribute("clientUserLevelID", TPersonBean.USERLEVEL.CLIENT); // maxFileSize int maxFileSize = AttachBL.getMaxFileSize(siteBean); httpSession.setAttribute("MAXFILESIZE", maxFileSize); // ------------------------------------------------------ // Create a new SessionBean for this session and bind it to the session SessionBean sBean = new SessionBean(); httpSession.setAttribute(Constants.SESSION_BEAN, sBean); ItemLockBL.removeLockedIssuesByUser(personBean.getObjectID()); ACCESSLOGGER.info("LOGON: User '" + personBean.getLoginName().trim() + "' (" + personBean.getFullName() + ")" + " logged in at " + new Date().toString() + " from " + request.getRemoteAddr()); LicenseManager lm = appBean.getLicenseManager(); if (lm != null) { int rf = lm.getErrorCode(); boolean haveLicenseErrors = false; switch (rf) { case 1: haveLicenseErrors = true; errors.add( new LabelValueBean("errLicenseError", getText("logon.err.license.needCommercial", locale))); break; case 2: haveLicenseErrors = true; errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.expired", locale))); break; case 3: haveLicenseErrors = true; errors.add( new LabelValueBean("errLicenseError", getText("logon.err.license.full.exceeded", locale))); break; case 4: haveLicenseErrors = true; errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.invalid", new String[] { ApplicationBean.getIpNumbersString() }, locale))); break; case 7: haveLicenseErrors = true; errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.limited.exceeded", locale))); break; case 8: haveLicenseErrors = true; errors.add( new LabelValueBean("errLicenseError", getText("logon.err.license.gantt.exceeded", locale))); break; default: break; } if (haveLicenseErrors == true) { mappingEnum = 6; result.put("errors", errors); result.put("mappingEnum", mappingEnum); return result; } } result.put("errors", errors); httpSession.setAttribute("DESIGNPATH", personBean.getDesignPath()); Boolean isMobileDevice = LogoffBL.isThisAMobileDevice(request); httpSession.setAttribute("mobile", isMobileDevice); LOGGER.debug("Mobile is " + httpSession.getAttribute("mobile")); // check for post-login forward String forwardUrl = (String) httpSession.getAttribute(Constants.POSTLOGINFORWARD); if (forwardUrl != null) { LOGGER.debug("Forward URL found :" + forwardUrl); mappingEnum = 7; result.put("mappingEnum", mappingEnum); return result; } Map ret = new GroovyScriptExecuter().handleEvent(IEventSubscriber.EVENT_POST_USER_LOGGED_IN, new HashMap()); if (ret.get(BINDING_PARAMS.CONTINUE).equals(Boolean.FALSE)) { mappingEnum = 10; result.put("mappingEnum", mappingEnum); return result; } String extendedKey = ApplicationBean.getInstance().getExtendedKey(); if (extendedKey == null || extendedKey.length() < 10) { // no empty keys // allowed mappingEnum = 18; result.put("mappingEnum", mappingEnum); return result; } String firstTime = (String) servletContext.getAttribute("FirstTime"); result.put("user", personBean); if (personBean.getIsSysAdmin() && firstTime != null && firstTime.equals("FT")) { servletContext.removeAttribute("FirstTime"); mappingEnum = 8; result.put("mappingEnum", mappingEnum); return result; } else { // Forward control to the specified success URI mappingEnum = 9; result.put("mappingEnum", mappingEnum); return result; } }
From source file:graphviewer.GraphCreate.java
/** * Create an instance of a directed graph *///from ww w .j a v a 2s. co m public GraphCreate() { super("SCCFinder"); this.graph = new DirectedSparseMultigraph<Integer, Integer>(); this.layout = new StaticLayout<Integer, Integer>(this.graph, new Dimension(600, 600)); final Transformer<Integer, Paint> redVertexPaint = new Transformer<Integer, Paint>() { public Paint transform(Integer i) { return Color.RED; } }; this.vv = new VisualizationViewer<Integer, Integer>(this.layout); this.vv.setBackground(Color.white); this.vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<Integer>()); this.vv.getRenderer().getVertexLabelRenderer().setPosition(Position.CNTR); Container content = getContentPane(); content.add(this.vv); this.vv.getRenderContext().setVertexFillPaintTransformer(redVertexPaint); // add listeners to our visual component Factory<Integer> vertexFactory = new VertexFactory(); Factory<Integer> edgeFactory = new EdgeFactory(); this.graphMouse = new EditingModalGraphMouse<Integer, Integer>(this.vv.getRenderContext(), vertexFactory, edgeFactory); this.vv.setGraphMouse(this.graphMouse); this.vv.addKeyListener(new MyKeyListener()); final MouseListener[] mls = (MouseListener[]) (this.vv.getListeners(MouseListener.class)); final MouseListener wrapper = new MyWrapperMouseListener(mls[1]); this.graphMouse.setMode(ModalGraphMouse.Mode.EDITING); this.vv.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); this.controls = new JPanel(); final ScalingControl scaler = new CrossoverScalingControl(); // add some buttons this.plus = new JButton("+"); this.plus.setToolTipText("Press this button or use the mouse wheel to zoom out"); this.plus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1.1f, vv.getCenter()); setFocusable(false); } }); this.minus = new JButton("-"); this.minus.setToolTipText("Press this button or use the mouse wheel to zoom in"); this.minus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { scaler.scale(vv, 1 / 1.1f, vv.getCenter()); setFocusable(false); } }); this.edit = new JRadioButton("Editing"); this.edit.setToolTipText("You can just press 'e' to select this radiobutton"); this.edit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { graphMouse.setMode(ModalGraphMouse.Mode.EDITING); vv.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); setFocusable(false); } }); this.transform = new JRadioButton("Transforming"); this.transform.setToolTipText("You can just press 't' to select this radiobutton"); this.transform.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING); vv.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); setFocusable(false); } }); this.pick = new JRadioButton("Picking"); this.pick.setToolTipText("You can just press 'p' to select this radiobutton"); this.pick.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { graphMouse.setMode(ModalGraphMouse.Mode.PICKING); vv.setCursor(new Cursor(Cursor.HAND_CURSOR)); setFocusable(false); } }); GraphCreate.scc = new JButton("SCC"); GraphCreate.scc.setToolTipText("Strongly Connected Components algorithm"); GraphCreate.scc.setEnabled(false); GraphCreate.scc.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createMathgraph(); GraphCreate.scc.setEnabled(false); edit.setEnabled(false); pick.setSelected(true); setFocusable(false); sccButtonPressed = true; graphMouse.setMode(ModalGraphMouse.Mode.PICKING); vv.setCursor(new Cursor(Cursor.HAND_CURSOR)); vv.removeMouseListener(mls[1]); vv.addMouseListener(wrapper); } }); GraphCreate.clear = new JButton("Clear"); GraphCreate.clear.setToolTipText("Clears our graph"); GraphCreate.clear.setEnabled(false); GraphCreate.clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (int k = 0; k <= numberOfVertices; k++) { graph.removeVertex(k); } GraphCreate.scc.setEnabled(false); GraphCreate.clear.setEnabled(false); edit.setEnabled(true); edit.setSelected(true); setFocusable(false); graphMouse.setMode(ModalGraphMouse.Mode.EDITING); vv.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR)); vv.getRenderContext().setVertexFillPaintTransformer(redVertexPaint); if (sccButtonPressed) { vv.removeMouseListener(wrapper); vv.addMouseListener(mls[1]); } vv.repaint(); // calling garbage collector here Runtime r = Runtime.getRuntime(); r.gc(); GraphCreate.numberOfEdges = 0; GraphCreate.numberOfVertices = 0; sccButtonPressed = false; } }); ButtonGroup actions = new ButtonGroup(); actions.add(this.edit); actions.add(this.transform); actions.add(this.pick); this.edit.setSelected(true); this.controls.add(this.plus); this.controls.add(this.minus); this.controls.add(this.edit); this.controls.add(this.transform); this.controls.add(this.pick); this.controls.add(GraphCreate.scc); controls.add(GraphCreate.clear); this.help = new JButton("Help"); this.help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(vv, instructions); setFocusable(false); } }); this.controls.add(this.help); content.add(this.controls, BorderLayout.SOUTH); }
From source file:org.klco.email2html.OutputWriter.java
/** * Writes the attachment contained in the body part to a file. * /* ww w . j ava 2s . c o m*/ * @param containingMessage * the message this body part is contained within * @param part * the part containing the attachment * @return the file that was created/written to * @throws IOException * Signals that an I/O exception has occurred. * @throws MessagingException * the messaging exception */ public boolean writeAttachment(EmailMessage containingMessage, Part part) throws IOException, MessagingException { log.trace("writeAttachment"); File attachmentFolder; File attachmentFile; InputStream in = null; OutputStream out = null; try { attachmentFolder = new File(outputDir.getAbsolutePath() + File.separator + config.getImagesSubDir() + File.separator + FILE_DATE_FORMAT.format(containingMessage.getSentDate())); if (!attachmentFolder.exists()) { log.debug("Creating attachment folder"); attachmentFolder.mkdirs(); } attachmentFile = new File(attachmentFolder, part.getFileName()); log.debug("Writing attachment file: {}", attachmentFile.getAbsolutePath()); if (!attachmentFile.exists()) { attachmentFile.createNewFile(); } in = new BufferedInputStream(part.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(attachmentFile)); log.debug("Downloading attachment"); CRC32 checksum = new CRC32(); for (int b = in.read(); b != -1; b = in.read()) { checksum.update(b); out.write(b); } if (this.excludeDuplicates) { log.debug("Computing checksum"); long value = checksum.getValue(); if (this.attachmentChecksums.contains(value)) { log.info("Skipping duplicate attachment: {}", part.getFileName()); attachmentFile.delete(); return false; } else { attachmentChecksums.add(value); } } log.debug("Attachement saved"); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } if (part.getContentType().toLowerCase().startsWith("image")) { log.debug("Creating renditions"); String contentType = part.getContentType().substring(0, part.getContentType().indexOf(";")); log.debug("Creating renditions of type: " + contentType); for (Rendition rendition : renditions) { File renditionFile = new File(attachmentFolder, rendition.getName() + "-" + part.getFileName()); try { if (!renditionFile.exists()) { renditionFile.createNewFile(); } log.debug("Creating rendition file: {}", renditionFile.getAbsolutePath()); createRendition(attachmentFile, renditionFile, rendition); log.debug("Rendition created"); } catch (OutOfMemoryError oome) { Runtime rt = Runtime.getRuntime(); rt.gc(); log.warn("Ran out of memory creating rendition: " + rendition, oome); log.warn("Free Memory: {}", rt.freeMemory()); log.warn("Max Memory: {}", rt.maxMemory()); log.warn("Total Memory: {}", rt.totalMemory()); String[] command = null; if (rendition.getFill()) { command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize", (rendition.getHeight() * 2) + "x", "-resize", "'x" + (rendition.getHeight() * 2) + "<'", "-resize", "50%", "-gravity", "center", "-crop", rendition.getHeight() + "x" + rendition.getWidth() + "+0+0", "+repage", renditionFile.getAbsolutePath() }; } else { command = new String[] { "convert", attachmentFile.getAbsolutePath(), "-resize", rendition.getHeight() + "x" + rendition.getWidth(), renditionFile.getAbsolutePath() }; } log.debug("Trying to resize with ImageMagick: " + StringUtils.join(command, " ")); rt.exec(command); } catch (Exception t) { log.warn("Exception creating rendition: " + rendition, t); } } } return true; }
From source file:ffx.Main.java
/** * Main does some window initializations. * * @param commandLineFile a {@link java.io.File} object. * @param argList a {@link java.util.List} object. *///from w ww. jav a2 s . com public Main(File commandLineFile, List<String> argList) { super("Force Field X"); // Start the clock. stopWatch.start(); setVisible(false); // Create the MainPanel and MainMenu, then add them to the JFrame java.awt.Toolkit.getDefaultToolkit().setDynamicLayout(true); mainPanel = new MainPanel(this); logHandler.setMainPanel(mainPanel); add(mainPanel); mainPanel.initialize(); setJMenuBar(mainPanel.getMainMenu()); // Set the Title and Icon setTitle("Force Field X"); URL iconURL = getClass().getClassLoader().getResource("ffx/ui/icons/icon64.png"); ImageIcon icon = new ImageIcon(iconURL); setIconImage(icon.getImage()); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (mainPanel != null) { mainPanel.exit(); } System.exit(0); } }); // This is a hack to get GraphicsCanvis to initialize on some // platform/Java3D combinations. mainPanel.setPanel(MainPanel.KEYWORDS); setVisible(true); mainPanel.setPanel(MainPanel.GRAPHICS); // Mac OS X specific features that help Force Field X look native // on Macs. This needs to be done after the MainPanel is created. if (SystemUtils.IS_OS_MAC_OSX) { osxAdapter = new OSXAdapter(mainPanel); } // Finally, open the supplied file if necessary. if (commandLineFile != null && !commandLineFile.exists()) { /** * See if the commandLineFile is an embedded script. */ String name = commandLineFile.getName(); name = name.replace('.', '/'); String pathName = "ffx/scripts/" + name; ClassLoader loader = getClass().getClassLoader(); URL embeddedScript = loader.getResource(pathName + ".ffx"); if (embeddedScript == null) { embeddedScript = loader.getResource(pathName + ".groovy"); } if (embeddedScript != null) { try { commandLineFile = new File(FFXClassLoader.copyInputStreamToTmpFile(embeddedScript.openStream(), commandLineFile.getName(), ".ffx")); } catch (Exception e) { logger.info(String.format(" The embedded script %s could not be extracted.", embeddedScript)); } } } if (commandLineFile != null) { if (commandLineFile.exists()) { mainPanel.getModelingShell().setArgList(argList); mainPanel.open(commandLineFile, null); } else { logger.warning(format("%s was not found.", commandLineFile.toString())); } } if (logger.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder(); sb.append(format("\n Start-up Time (msec): %s.", stopWatch.getTime())); Runtime runtime = Runtime.getRuntime(); runtime.runFinalization(); runtime.gc(); long occupiedMemory = runtime.totalMemory() - runtime.freeMemory(); long KB = 1024; sb.append(format("\n In-Use Memory (Kb): %d", occupiedMemory / KB)); sb.append(format("\n Free Memory (Kb): %d", runtime.freeMemory() / KB)); sb.append(format("\n Total Memory (Kb): %d", runtime.totalMemory() / KB)); logger.fine(sb.toString()); } }
From source file:er.extensions.ERXExtensions.java
/** * Forces the garbage collector to run. The * max loop parameter determines the maximum * number of times to run the garbage collector * if the memory footprint is still going down. * In normal cases you would just need to call * this method with the parameter 1. If called * with the parameter 0 the garbage collector * will continue to run until no more free memory * is available to collect. <br/>/*from w w w. j a va2s .co m*/ * <br/> * Note: This can be a very costly operation and * should only be used in extreme circumstances. * @param maxLoop maximum times to run the garbage * collector. Passing in 0 will cause the * collector to run until all free objects * have been collected. */ public static void forceGC(int maxLoop) { if (_log.isDebugEnabled()) _log.debug("Forcing full Garbage Collection"); Runtime runtime = Runtime.getRuntime(); long isFree = runtime.freeMemory(); long wasFree; int i = 0; do { wasFree = isFree; runtime.gc(); isFree = runtime.freeMemory(); i++; } while (isFree > wasFree && (maxLoop <= 0 || i < maxLoop)); runtime.runFinalization(); //TODO: should this be inside the loop? }
From source file:org.kalypso.kalypsomodel1d2d.sim.ProcessResult2DOperation.java
public File read2DIntoGmlResults(final InputStream is) throws Exception { KalypsoModel1D2DDebug.SIMULATIONRESULT.printf("%s", //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.16")); //$NON-NLS-1$ final Runtime runtime = Runtime.getRuntime(); runtime.gc(); final TimeLogger logger = new TimeLogger( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.17")); //$NON-NLS-1$ final File gmlZipResultFile = new File(m_outputDir, "results.gz"); //$NON-NLS-1$ try {/*w ww.ja v a 2 s. c o m*/ /* GMLWorkspace to put the results */ final GMLWorkspace resultWorkspace = FeatureFactory.createGMLWorkspace(INodeResultCollection.QNAME, gmlZipResultFile.toURI().toURL(), null); final URL lsObsUrl = LengthSectionHandler2d.class.getResource("resources/lengthSectionTemplate.gml"); //$NON-NLS-1$ final String componentID = IWspmDictionaryConstants.LS_COMPONENT_STATION; final LengthSectionHandler1d lsHandler = new LengthSectionHandler1d(componentID, lsObsUrl); /* read .2d files and fill the gml */ final RMA10S2GmlConv conv = new RMA10S2GmlConv(null); final String crs = KalypsoDeegreePlugin.getDefault().getCoordinateSystem(); final MultiTriangleEater multiEater = new MultiTriangleEater(); if (m_boolDoFullEvaluate) { for (final ResultType parameter : m_parameters) { /* GML(s) */ /* the terrain tin is not created in results any more */ /* create TIN-Dir for results */ final File tinPath = new File(m_outputDir, "Tin"); //$NON-NLS-1$ tinPath.mkdirs(); // FIXME: bad name; should be tin.gml.gz or tin.gmlz // FIXME: move into constants final File tinZipResultFile = new File(tinPath, "tin.gz"); //$NON-NLS-1$ final ITriangleEater tinEater = NodeResultHelper.createTinEater(tinZipResultFile, parameter, crs); multiEater.addEater(tinEater); } } final NodeResultsHandler handler = new NodeResultsHandler(resultWorkspace, multiEater, m_flowModel, m_controlModel, m_discModel, m_resultMinMaxCatcher, lsHandler, m_mapResults); conv.setRMA10SModelElementHandler(handler); logger.takeInterimTime(); logger.printCurrentInterim(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.54", //$NON-NLS-1$ m_inputFile.getName())); conv.parse(is); logger.takeInterimTime(); logger.printCurrentInterim(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.56")); //$NON-NLS-1$ // finish MultiEater and engage serializer KalypsoModel1D2DDebug.SIMULATIONRESULT.printf("%s", //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.58")); //$NON-NLS-1$ multiEater.finished(); KalypsoModel1D2DDebug.SIMULATIONRESULT.printf("%s", //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.60")); //$NON-NLS-1$ /* Node-GML write to file */ GmlSerializer.serializeWorkspace(gmlZipResultFile, resultWorkspace, "UTF-8"); //$NON-NLS-1$ /* LengthSection write to file */ final ICalculationUnit1D[] calcUnits = lsHandler.getCalcUnits(); for (final ICalculationUnit1D calcUnit : calcUnits) { final File lsObsFile = new File(m_outputDir, "lengthSection_" + calcUnit.getId() + ".gml"); //$NON-NLS-1$ //$NON-NLS-2$ final IObservation<TupleResult> lsObs = lsHandler.getObservation(calcUnit); final GMLWorkspace lsObsWorkspace = lsHandler.getWorkspace(calcUnit); if (lsObs.getResult().size() > 0) { ObservationFeatureFactory.toFeature(lsObs, lsObsWorkspace.getRootFeature()); GmlSerializer.serializeWorkspace(lsObsFile, lsObsWorkspace, "UTF-8"); //$NON-NLS-1$ /* length section entry in result db */ // TODO: use station range for min max... ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.65") //$NON-NLS-1$ + calcUnit.getName(), Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.66"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.lengthSection, new Path(lsObsFile.getName()), Status.OK_STATUS, new BigDecimal(0), new BigDecimal(0)); } } logger.takeInterimTime(); logger.printCurrentInterim(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.67")); //$NON-NLS-1$ if (m_boolDoFullEvaluate) { for (final ResultType parameter : m_parameters) { // FIXME: strange, use same scale/precision for all parameters... final BigDecimal min = m_resultMinMaxCatcher.getScaledMin(parameter); final BigDecimal max = m_resultMinMaxCatcher.getScaledMax(parameter); /* result db */ switch (parameter) { // FIXME: put parameter names into ResultType enum or similar case DEPTH: // TODO: Handle minimum at infinity ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.71"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.1"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinDepth, new Path("Tin/tin_DEPTH.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case VELOCITY: ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.74"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.75"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinVelo, new Path("Tin/tin_VELOCITY.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case VELOCITY_X: ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.77"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.78"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinVelo, new Path("Tin/tin_VELOCITY_X.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case VELOCITY_Y: ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.80"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.81"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinVelo, new Path("Tin/tin_VELOCITY_Y.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case WATERLEVEL: ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.83"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.84"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinWsp, new Path("Tin/tin_WATERLEVEL.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case SHEARSTRESS: ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.86"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.87"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinShearStress, new Path("Tin/tin_SHEARSTRESS.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; default: throw new UnsupportedOperationException(); } } } // we will set all min max results to the node results meta also ResultMeta1d2dHelper.addDocument(m_stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.89"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.90"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.nodes, new Path("results.gz"), Status.OK_STATUS, //$NON-NLS-1$ m_resultMinMaxCatcher); // TODO: maybe check if time and stepTime are equal? if (m_stepResultMeta != null) ResultMeta1d2dHelper.addToResultDB(m_stepResultMeta, m_stepDate, m_outputDir); return gmlZipResultFile; } finally { IOUtils.closeQuietly(is); logger.takeInterimTime(); logger.printCurrentInterim(Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.92")); //$NON-NLS-1$ runtime.gc(); } }
From source file:org.kalypso.kalypsomodel1d2d.sim.ProcessResultTelemacOperation.java
private IStatus readTelemacResults() { final SerafinReader convTelemac = new SerafinReader(); final FileObject inputFile = getOrUnzipResult(m_inputFile, m_outputDir); if (inputFile == null) { return new Status(IStatus.ERROR, PluginUtilities.id(KalypsoModel1D2DPlugin.getDefault()), "error - no result file found!"); }// w w w.j a v a 2 s . c o m try { convTelemac.setFile(new File(inputFile.getURL().toURI())); convTelemac.doReadAll(); } catch (URISyntaxException | IOException e1) { e1.printStackTrace(); final String msg = "error while reading telemac results file"; return new Status(IStatus.ERROR, PluginUtilities.id(KalypsoModel1D2DPlugin.getDefault()), msg, e1); } // Map<String, Map<String, List<Double>>> mapResults = convTelemac.doRead(); for (Date stepDate : m_stepDates) { // stepDate = findStepDate( file ); // m_geoLog.formatLog( IStatus.INFO, CODE_RUNNING_FINE, Messages.getString( "org.kalypso.kalypsomodel1d2d.sim.ResultManager.14" ), inputFile.getURL().toString() ); //$NON-NLS-1$ final String outDirName = NodeResultHelper.createOutDirName(stepDate); final File resultOutputDir = new File(m_outputDir, outDirName); resultOutputDir.mkdirs(); KalypsoModel1D2DDebug.SIMULATIONRESULT.printf("%s", //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.16")); //$NON-NLS-1$ final Runtime runtime = Runtime.getRuntime(); runtime.gc(); final TimeLogger logger = new TimeLogger( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.17")); //$NON-NLS-1$ final File gmlZipResultFile = new File(resultOutputDir, "results.gz"); //$NON-NLS-1$ IStepResultMeta stepResultMeta = m_unitResultMeta.addStepResult(); try { /* GMLWorkspace fr Ergebnisse anlegen */ final GMLWorkspace resultWorkspace = FeatureFactory.createGMLWorkspace(INodeResultCollection.QNAME, gmlZipResultFile.toURI().toURL(), null); final URL lsObsUrl = LengthSectionHandler2d.class .getResource("resources/lengthSectionTemplate.gml"); //$NON-NLS-1$ final String componentID = IWspmDictionaryConstants.LS_COMPONENT_STATION; final LengthSectionHandler1d lsHandler = new LengthSectionHandler1d(componentID, lsObsUrl); /* .2d Datei lesen und GML fllen */ final String crs = KalypsoDeegreePlugin.getDefault().getCoordinateSystem(); final MultiTriangleEater multiEater = new MultiTriangleEater(); if (m_boolDoFullEvaluate) { for (final ResultType parameter : m_parameters) { /* GML(s) */ if (parameter == ResultType.TERRAIN && !ResultMeta1d2dHelper.containsTerrain(stepResultMeta)) { /* create TIN-Dir for FEM terrain model */ // TODO: obscure, why go outside our output dir... TODO: refaktor it! final String calcUnitPath = resultOutputDir.getParent(); final File modelPath = new File(calcUnitPath, "model"); //$NON-NLS-1$ if (!modelPath.exists()) { modelPath.mkdirs(); final File modelTinPath = new File(modelPath, "Tin"); //$NON-NLS-1$ modelTinPath.mkdirs(); final File tinResultFile = new File(modelTinPath, "tin.gz"); //$NON-NLS-1$ final ITriangleEater gmlTriangleEater = NodeResultHelper .createTinEater(tinResultFile, parameter, crs); multiEater.addEater(gmlTriangleEater); } } else { /* create TIN-Dir for results */ final File tinPath = new File(resultOutputDir, "Tin"); //$NON-NLS-1$ tinPath.mkdirs(); final File tinZipResultFile = new File(tinPath, "tin.gz"); //$NON-NLS-1$ final ITriangleEater tinEater = NodeResultHelper.createTinEater(tinZipResultFile, parameter, crs); multiEater.addEater(tinEater); } } } final NodeResultsHandler handler = new NodeResultsHandler(resultWorkspace, multiEater, m_flowModel, m_controlModel, m_discModel, resultMinMaxCatcher, lsHandler, m_mapResults); convTelemac.setModelElementHandler(handler); logger.takeInterimTime(); logger.printCurrentInterim(Messages .getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.54", m_inputFile.getName())); //$NON-NLS-1$ System.out.println(stepDate); int iStep = resolveStepNr(stepDate); convTelemac.feedHandler(iStep); logger.takeInterimTime(); logger.printCurrentInterim( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.56")); //$NON-NLS-1$ if (m_boolDoFullEvaluate) { convTelemac.feedHandlerWithTriangles(); } // finish MultiEater and engage serializer KalypsoModel1D2DDebug.SIMULATIONRESULT.printf("%s", //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.58")); //$NON-NLS-1$ multiEater.finished(); KalypsoModel1D2DDebug.SIMULATIONRESULT.printf("%s", //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.60")); //$NON-NLS-1$ /* Node-GML in Datei schreiben */ GmlSerializer.serializeWorkspace(gmlZipResultFile, resultWorkspace, "UTF-8"); //$NON-NLS-1$UTF-8 /* LengthSection in Datei schreiben */ final ICalculationUnit1D[] calcUnits = lsHandler.getCalcUnits(); for (final ICalculationUnit1D calcUnit : calcUnits) { final File lsObsFile = new File(resultOutputDir, "lengthSection_" + calcUnit.getId() + ".gml"); //$NON-NLS-1$ //$NON-NLS-2$ final IObservation<TupleResult> lsObs = lsHandler.getObservation(calcUnit); final GMLWorkspace lsObsWorkspace = lsHandler.getWorkspace(calcUnit); if (lsObs.getResult().size() > 0) { ObservationFeatureFactory.toFeature(lsObs, lsObsWorkspace.getRootFeature()); GmlSerializer.serializeWorkspace(lsObsFile, lsObsWorkspace, "UTF-8"); //$NON-NLS-1$ /* length section entry in result db */ // TODO: use station range for min max... ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.65") //$NON-NLS-1$ + calcUnit.getName(), Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.66"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.lengthSection, new Path(lsObsFile.getName()), Status.OK_STATUS, new BigDecimal(0), new BigDecimal(0)); } } logger.takeInterimTime(); logger.printCurrentInterim( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.67")); //$NON-NLS-1$ BigDecimal min; BigDecimal max; if (m_boolDoFullEvaluate) { for (final ResultType parameter : m_parameters) { /* GML(s) */ /* result db */ switch (parameter) { case TERRAIN: if (stepResultMeta != null && !ResultMeta1d2dHelper.containsTerrain(stepResultMeta)) { /* check if there exists already an entry for terrainTin */ final ICalcUnitResultMeta calcUnitResult = (ICalcUnitResultMeta) stepResultMeta .getOwner(); min = new BigDecimal(resultMinMaxCatcher.getMinTerrain()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxTerrain()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(calcUnitResult, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.68"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.69"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinTerrain, new Path("model/Tin/tin_TERRAIN.gz"), Status.OK_STATUS, min, max); //$NON-NLS-1$ } break; case DEPTH: // TODO: Handle minimum at infinity min = new BigDecimal(resultMinMaxCatcher.getMinDepth()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxDepth()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.71"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.1"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinDepth, new Path("Tin/tin_DEPTH.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case VELOCITY: min = new BigDecimal(resultMinMaxCatcher.getMinVelocityAbs()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxVelocityAbs()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.74"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.75"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinVelo, new Path("Tin/tin_VELOCITY.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case VELOCITY_X: min = new BigDecimal(resultMinMaxCatcher.getMinVelocityAbs()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxVelocityAbs()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.77"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.78"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinVelo, new Path("Tin/tin_VELOCITY_X.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case VELOCITY_Y: min = new BigDecimal(resultMinMaxCatcher.getMinVelocityAbs()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxVelocityAbs()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.80"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.81"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinVelo, new Path("Tin/tin_VELOCITY_Y.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case WATERLEVEL: min = new BigDecimal(resultMinMaxCatcher.getMinWaterlevel()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxWaterlevel()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.83"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.84"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinWsp, new Path("Tin/tin_WATERLEVEL.gz"), //$NON-NLS-1$ Status.OK_STATUS, min, max); break; case SHEARSTRESS: min = new BigDecimal(resultMinMaxCatcher.getMinShearStress()).setScale(3, BigDecimal.ROUND_HALF_UP); max = new BigDecimal(resultMinMaxCatcher.getMaxShearStress()).setScale(3, BigDecimal.ROUND_HALF_UP); ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.86"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.87"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.tinShearStress, new Path("Tin/tin_SHEARSTRESS.gz"), Status.OK_STATUS, min, max); //$NON-NLS-1$ break; default: throw new UnsupportedOperationException(); } } } // we will set all min max results to the node results meta also ResultMeta1d2dHelper.addDocument(stepResultMeta, Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.89"), //$NON-NLS-1$ Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.90"), //$NON-NLS-1$ IDocumentResultMeta.DOCUMENTTYPE.nodes, new Path("results.gz"), Status.OK_STATUS, //$NON-NLS-1$ resultMinMaxCatcher); // TODO: maybe check if time and stepTime are equal? if (stepResultMeta != null) ResultMeta1d2dHelper.addToResultDB(stepResultMeta, stepDate, resultOutputDir); // return gmlZipResultFile; } // catch( CoreException | IOException | GmlSerializeException | GMLSchemaException e ) catch (Exception e) { e.printStackTrace(); final String msg = "error while reading telemac results"; return new Status(IStatus.ERROR, PluginUtilities.id(KalypsoModel1D2DPlugin.getDefault()), msg, e); } finally { // IOUtils.closeQuietly( is ); logger.takeInterimTime(); logger.printCurrentInterim( Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.92")); //$NON-NLS-1$ runtime.gc(); } } return Status.OK_STATUS; }
From source file:com.ln.gui.Main.java
@SuppressWarnings("unchecked") public Main() {//from w w w.j a v a2s. c om System.gc(); setIconImage(Toolkit.getDefaultToolkit().getImage(Configuration.mydir + "\\resources\\icons\\ln6464.png")); DateFormat dd = new SimpleDateFormat("dd"); DateFormat dh = new SimpleDateFormat("HH"); DateFormat dm = new SimpleDateFormat("mm"); Date day = new Date(); Date hour = new Date(); Date minute = new Date(); dayd = Integer.parseInt(dd.format(day)); hourh = Integer.parseInt(dh.format(hour)); minutem = Integer.parseInt(dm.format(minute)); setTitle("Liquid Notify Revision 2"); Description.setBackground(Color.WHITE); Description.setContentType("text/html"); Description.setEditable(false); Getcalendar.Main(); HyperlinkListener hyperlinkListener = new ActivatedHyperlinkListener(f, Description); Description.addHyperlinkListener(hyperlinkListener); //Add components setContentPane(contentPane); setJMenuBar(menuBar); contentPane.setLayout( new MigLayout("", "[220px:230.00:220,grow][209.00px:n:5000,grow]", "[22px][][199.00,grow][grow]")); eventsbtn.setToolTipText("Displays events currently set to notify"); eventsbtn.setMinimumSize(new Dimension(220, 23)); eventsbtn.setMaximumSize(new Dimension(220, 23)); contentPane.add(eventsbtn, "cell 0 0"); NewsArea.setBackground(Color.WHITE); NewsArea.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.DARK_GRAY, Color.DARK_GRAY)); NewsArea.setMinimumSize(new Dimension(20, 22)); NewsArea.setMaximumSize(new Dimension(10000, 22)); contentPane.add(NewsArea, "cell 1 0,growx,aligny top"); menuBar.add(File); JMenuItem Settings = new JMenuItem("Settings"); Settings.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\settings.png")); Settings.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Settings setup = new Settings(); setup.setVisible(true); setup.setLocationRelativeTo(rootPane); } }); File.add(Settings); File.add(mntmNewMenuItem); Tray.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\ln1616.png")); File.add(Tray); Exit.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\exit.png")); File.add(Exit); menuBar.add(mnNewMenu); Update.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\update.png")); Update.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { URL localURL = new URL("http://jiiks.net23.net/tlnotify/online.html"); URLConnection localURLConnection = localURL.openConnection(); BufferedReader localBufferedReader = new BufferedReader( new InputStreamReader(localURLConnection.getInputStream())); String str = localBufferedReader.readLine(); if (!str.contains("YES")) { String st2221 = "Updates server appears to be offline"; JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION); JDialog dialog1 = pane1.createDialog("Update"); dialog1.setLocationRelativeTo(null); dialog1.setVisible(true); dialog1.setAlwaysOnTop(true); } else if (str.contains("YES")) { URL localURL2 = new URL("http://jiiks.net23.net/tlnotify/latestversion.html"); URLConnection localURLConnection1 = localURL2.openConnection(); BufferedReader localBufferedReader2 = new BufferedReader( new InputStreamReader(localURLConnection1.getInputStream())); String str2 = localBufferedReader2.readLine(); Updatechecker.latestver = str2; if (Integer.parseInt(str2) <= Configuration.version) { String st2221 = "No updates available =("; JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION); JDialog dialog1 = pane1.createDialog("Update"); dialog1.setLocationRelativeTo(null); dialog1.setVisible(true); dialog1.setAlwaysOnTop(true); } else if (Integer.parseInt(str2) > Configuration.version) { String st2221 = "Updates available!"; JOptionPane pane1 = new JOptionPane(st2221, JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION); JDialog dialog1 = pane1.createDialog("Update"); dialog1.setLocationRelativeTo(null); dialog1.setVisible(true); dialog1.setAlwaysOnTop(true); Updatechecker upd = new Updatechecker(); upd.setVisible(true); upd.setLocationRelativeTo(rootPane); upd.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } }); mnNewMenu.add(Update); JMenuItem About = new JMenuItem("About"); About.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\about.png")); About.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { About a = new About(); a.setVisible(true); a.setLocationRelativeTo(rootPane); a.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } }); mnNewMenu.add(About); JMenuItem Github = new JMenuItem("Github"); Github.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\github.png")); Github.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String url = "https://github.com/Jiiks/Liquid-Notify-Rev2"; try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); } catch (IOException e1) { e1.printStackTrace(); } } }); mnNewMenu.add(Github); JMenuItem Thread = new JMenuItem("Thread"); Thread.setIcon(new ImageIcon(Configuration.mydir + "\\resources\\icons\\liquid.png")); Thread.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String url = "http://www.teamliquid.net/forum/viewmessage.php?topic_id=318184"; try { java.awt.Desktop.getDesktop().browse(java.net.URI.create(url)); } catch (IOException e1) { e1.printStackTrace(); } } }); mnNewMenu.add(Thread); Refreshbtn.setToolTipText("Refreshes calendar, please don't spam ^_^"); Refreshbtn.setPreferredSize(new Dimension(90, 20)); Refreshbtn.setMinimumSize(new Dimension(100, 20)); Refreshbtn.setMaximumSize(new Dimension(100, 20)); contentPane.add(Refreshbtn, "flowx,cell 0 1,alignx left"); //Components to secondary panel Titlebox = new JComboBox(); contentPane.add(Titlebox, "cell 1 1,growx,aligny top"); Titlebox.setMinimumSize(new Dimension(20, 20)); Titlebox.setMaximumSize(new Dimension(10000, 20)); //Set other setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 686, 342); contentPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); NewsArea.setEnabled(false); NewsArea.setEditable(false); NewsArea.setText("News: " + News); contentPane.add(panel, "cell 0 2,grow"); panel.setLayout(null); final JCalendar calendar = new JCalendar(); calendar.getMonthChooser().setPreferredSize(new Dimension(120, 20)); calendar.getMonthChooser().setMinimumSize(new Dimension(120, 24)); calendar.getYearChooser().setLocation(new Point(20, 0)); calendar.getYearChooser().setMaximum(100); calendar.getYearChooser().setMaximumSize(new Dimension(100, 2147483647)); calendar.getYearChooser().setMinimumSize(new Dimension(50, 20)); calendar.getYearChooser().setPreferredSize(new Dimension(50, 20)); calendar.getYearChooser().getSpinner().setPreferredSize(new Dimension(100, 20)); calendar.getYearChooser().getSpinner().setMinimumSize(new Dimension(100, 20)); calendar.getMonthChooser().getSpinner().setPreferredSize(new Dimension(119, 20)); calendar.getMonthChooser().getSpinner().setMinimumSize(new Dimension(120, 24)); calendar.getDayChooser().getDayPanel().setFont(new Font("Tahoma", Font.PLAIN, 11)); calendar.setDecorationBordersVisible(true); calendar.setTodayButtonVisible(true); calendar.setBackground(Color.LIGHT_GRAY); calendar.setBounds(0, 0, 220, 199); calendar.getDate(); calendar.setWeekOfYearVisible(false); calendar.setDecorationBackgroundVisible(false); calendar.setMaxDayCharacters(2); calendar.getDayChooser().setFont(new Font("Tahoma", Font.PLAIN, 10)); panel.add(calendar); Descriptionscrollpane.setLocation(new Point(100, 100)); Descriptionscrollpane.setMaximumSize(new Dimension(10000, 10000)); Descriptionscrollpane.setMinimumSize(new Dimension(20, 200)); Description.setLocation(new Point(100, 100)); Description.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.DARK_GRAY, Color.DARK_GRAY)); Description.setMaximumSize(new Dimension(1000, 400)); Description.setMinimumSize(new Dimension(400, 200)); contentPane.add(Descriptionscrollpane, "cell 1 2 1 2,growx,aligny top"); Descriptionscrollpane.setViewportView(Description); verticalStrut.setMinimumSize(new Dimension(12, 20)); contentPane.add(verticalStrut, "cell 0 1"); Notify.setToolTipText("Adds selected event to notify event list."); Notify.setHorizontalTextPosition(SwingConstants.CENTER); Notify.setPreferredSize(new Dimension(100, 20)); Notify.setMinimumSize(new Dimension(100, 20)); Notify.setMaximumSize(new Dimension(100, 20)); contentPane.add(Notify, "cell 0 1,alignx right"); calendar.getMonthChooser().addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { month = calendar.getMonthChooser().getMonth(); Parser.parse(); } }); calendar.getDayChooser().addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent e) { try { int h = calendar.getMonthChooser().getMonth(); @SuppressWarnings("deprecation") int date = calendar.getDate().getDate(); int month = calendar.getMonthChooser().getMonth() + 1; globmonth = calendar.getMonthChooser().getMonth(); sdate = date; datestring = Integer.toString(sdate); monthstring = Integer.toString(month); String[] Hours = Betaparser.Hours; String[] Titles = Betaparser.STitle; String[] Full = new String[Hours.length]; String[] Minutes = Betaparser.Minutes; String[] Des = Betaparser.Description; String[] Des2 = new String[Betaparser.Description.length]; String Seconds = "00"; String gg; int[] IntHours = new int[Hours.length]; int[] IntMins = new int[Hours.length]; int Events = 0; monthday = monthstring + "|" + datestring + "|"; Titlebox.removeAllItems(); for (int a = 0; a != Hours.length; a++) { IntHours[a] = Integer.parseInt(Hours[a]); IntMins[a] = Integer.parseInt(Minutes[a]); } for (int i1 = 0; i1 != Hours.length; i1++) { if (Betaparser.Events[i1].startsWith(monthday)) { Full[i1] = String.format("%02d:%02d", IntHours[i1], IntMins[i1]) + " | " + Titles[i1]; Titlebox.addItem(Full[i1]); } } } catch (Exception e1) { //Catching mainly due to boot property change } } }); Image image = Toolkit.getDefaultToolkit().getImage(Configuration.mydir + "\\resources\\icons\\ln1616.png"); final SystemTray tray = SystemTray.getSystemTray(); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(true); } }; PopupMenu popup = new PopupMenu(); MenuItem defaultItem = new MenuItem(); defaultItem.addActionListener(listener); TrayIcon trayIcon = null; trayIcon = new TrayIcon(image, "LiquidNotify Revision 2", popup); trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { setVisible(true); } });// try { tray.add(trayIcon); } catch (AWTException e) { System.err.println(e); } if (trayIcon != null) { trayIcon.setImage(image); } Tray.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); Titlebox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Descparser.parsedesc(); } }); Refreshbtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Getcalendar.Main(); Descparser.parsedesc(); } }); Notify.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { NOTIFY = Descparser.TTT; NOTIFYD = Descparser.DDD; NOTIFYH = Descparser.HHH; NOTIFYM = Descparser.MMM; int i = events; NOA[i] = NOTIFY; NOD[i] = NOTIFYD; NOH[i] = NOTIFYH; NOM[i] = NOTIFYM; Eventlist[i] = "Starts in: " + Integer.toString(NOD[i]) + " Days " + Integer.toString(NOH[i]) + " Hours " + Integer.toString(NOM[i]) + " Minutes " + " | " + NOA[i]; events = events + 1; Notifylist si = new Notifylist(); si.setVisible(false); si.setBounds(1, 1, 1, 1); si.dispose(); if (thread.getState().name().equals("PENDING")) { thread.execute(); } } }); eventsbtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Notifylist list = new Notifylist(); if (played == 1) { asd.close(); played = 0; } list.setVisible(true); list.setLocationRelativeTo(rootPane); list.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } }); mntmNewMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (thread.getState().name().equals("PENDING")) { thread.execute(); } Userstreams us = new Userstreams(); us.setVisible(true); us.setLocationRelativeTo(rootPane); } }); Exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //Absolute exit JOptionPane.showMessageDialog(rootPane, "Bye bye :(", "Exit", JOptionPane.INFORMATION_MESSAGE); Runtime ln = Runtime.getRuntime(); ln.gc(); final Frame[] allf = Frame.getFrames(); final Window[] allw = Window.getWindows(); for (final Window allwindows : allw) { allwindows.dispose(); } for (final Frame allframes : allf) { allframes.dispose(); System.exit(0); } } }); }
From source file:com.ibm.bluemix.mobilestarterkit.service.ServiceAPI.java
@Path("/autoscaling") @POST/*from ww w . j a v a2s. c o m*/ public String autoScalingByMem(String param) { try { JSONObject meta = new JSONObject(param); Runtime rt = Runtime.getRuntime(); int mem_usage = (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0)); String action = meta.getString("action"); if ("mem_up".equalsIgnoreCase(action)) { // 10M . Out of memory ? ?. for (int i = 0; i < 10; i++) { byte b[] = new byte[1048576]; v.add(b); } } else if ("mem_safe_up".equalsIgnoreCase(action) && mem_usage < 90) { // 90% ? ?, 10M . OOM for (int i = 0; i < 10; i++) { byte b[] = new byte[1048576]; v.add(b); } } else if ("mem_reset".equalsIgnoreCase(action)) { // ? v = new Vector(); rt.gc(); } String msg = "Max " + (rt.maxMemory() / 1000) + " KB Total used : " + (rt.totalMemory() / 1000) + " KB Free : " + (rt.freeMemory() / 1000) + " KB " + (int) ((rt.totalMemory() * 100.0) / (rt.maxMemory() * 1.0)) + " %"; System.out.println(msg); return msg; } catch (JSONException e) { e.getStackTrace(); return "Failed"; } }
From source file:configuration.Util.java
public static void CleanMemory() { Runtime r = Runtime.getRuntime(); r.gc(); }