protected boolean getShowLinearCurve() throws IOException { boolean res = false; { ConfigFactory f = DefaultConfigFactory.getInstance(); Config c = f.getConfig(); String configNameLinearCurve = getConfigNameLinearCurve(); boolean configValueDefault = false; // Set 'configValueDefault': { String mode = c.getProperty("mode"); if (mode != null) { if ("Test".equals(mode)) { configValueDefault = true; } } } res = c.getPropertyAsBoolean(configNameLinearCurve, configValueDefault); } return res; }
/** * This function is used to re-run the analyser, and re-create the rows corresponding the its * results. */ private void refreshReviewTable() { reviewPanel.removeAll(); rows.clear(); GridBagLayout gbl = new GridBagLayout(); reviewPanel.setLayout(gbl); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridy = 0; try { Map<String, Long> sums = analyser.processLogFile(config.getLogFilename(), fromDate.getDate(), toDate.getDate()); for (Entry<String, Long> entry : sums.entrySet()) { String project = entry.getKey(); double hours = 1.0 * entry.getValue() / (1000 * 3600); addRow(gbl, gbc, project, hours); } for (String project : main.getProjectsTree().getTopLevelProjects()) if (!rows.containsKey(project)) addRow(gbl, gbc, project, 0); gbc.insets = new Insets(10, 0, 0, 0); addLeftLabel(gbl, gbc, "TOTAL"); gbc.gridx = 1; gbc.weightx = 1; totalLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 3)); gbl.setConstraints(totalLabel, gbc); reviewPanel.add(totalLabel); gbc.weightx = 0; addRightLabel(gbl, gbc); } catch (IOException e) { e.printStackTrace(); } recomputeTotal(); pack(); }
private static String getAbsoluteExecutablePath(final Config config) { if (Strings.isNullOrEmpty(config.getWrapperScript())) { return ""; } return FileUtilities.getAbsoluteFileForExecutables(new File(config.getWrapperScript())) .getPath(); }
protected void init() { // Create link to backing-store: { BackingStore<String, DSLAMProviderRequest, C> backingStore = new DSLAMProviderContextBackingStore(); setBackingStore(backingStore); } // Set renew-time and cache-time: { int renewTime = TIME_RENEW_DEFAULT; int cacheTime = TIME_CACHE_DEFAULT; { try { ConfigFactory f = DefaultConfigFactory.getInstance(); Config c = f.getConfig(); if (c != null) { renewTime = c.getPropertyAsInt("provider.allocator.context-cache.time.renew", renewTime); cacheTime = c.getPropertyAsInt("provider.allocator.context-cache.time.cache", cacheTime); } } catch (IOException ex) { // Ignore! } } setRenewTime(renewTime); setCacheTime(cacheTime); } }
private void switchAccount(boolean login) { if (!login) parentView = StaticData.getInstance().roster; destroyView(); Config cf = Config.getInstance(); cf.accountIndex = cursor; cf.saveToStorage(); Account.loadAccount(login); }
/** * Returns the string to execute, which is determined from the property <code>install.execString * </code>. MessageFormat is used to reformat the string. The first argument is the the install * path, with the remaining arguments the paths to the extracted files that were downloaded. */ private static String getExecuteString(String[] args) { String execString = Config.getExecString(); if (execString == null) { Config.trace("No exec string specified"); return null; } String apply = MessageFormat.format(execString, args); Config.trace("exec string !" + apply + "!"); return apply; }
private AuthToken getAuthTokenForApp( HttpServletRequest req, HttpServletResponse resp, boolean doNotSendHttpError) throws IOException, ServiceException { Config config = Provisioning.getInstance().getConfig(); int adminPort = config.getIntAttr(Provisioning.A_zimbraAdminPort, 0); if (adminPort == req.getLocalPort()) { return getAdminAuthTokenFromCookie(req, resp, doNotSendHttpError); } return getAuthTokenFromCookie(req, resp, doNotSendHttpError); }
public void saveStreams() throws IOException { Config config = Config.getConfiguration("manager.streams"); config.setArray("streams", streams.toArray()); Iterator it = streams.iterator(); while (it.hasNext()) { DataSource ds = (DataSource) it.next(); ds.save(); } config.save(); }
@Override public GridRunner create(final Config config, final DependencyResolver dependencies) { final GridRunner runner = new GridRunner(); runner.setServiceFactory(getServiceFactory()); runner.setEnabled(true); runner.setQueueName(config.getQueueName()); if (config.getMemoryRequirement() != null) { runner.setMemoryRequirement(config.getMemoryRequirement()); } if (config.getNativeSpecification() != null) { runner.setNativeSpecification(config.getNativeSpecification()); } runner.setGridScriptFactory(gridScriptFactory); runner.setManager(gridEngineManager); runner.setWrapperScript(getAbsoluteExecutablePath(config)); runner.setWorkerFactoryConfig(config.getWorkerConfiguration()); runner.setFileTokenFactory(fileTokenFactory); runner.setDaemonLoggerFactory(new DaemonLoggerFactory(new File(config.getLogOutputFolder()))); final DaemonConfig daemonConfig = config.getParentConfig().getParentConfig(); if (daemonConfig.isDumpErrors() && !Strings.isNullOrEmpty(daemonConfig.getDumpFolderPath())) { runner.setFailedJobManager( new FailedJobManager(new File(daemonConfig.getDumpFolderPath()))); } else { runner.setFailedJobManager(new FailedJobManager()); } return runner; }
/** * Returns the language-dependent label with the given key. The search order is to look first in * the extension's <code>label</code> files and if the requested label is not found in the BlueJ * system <code>label</code> files. Extensions' labels are stored in a Property format and must be * jarred together with the extension. The path searched is equivalent to the bluej/lib/[language] * style used for the BlueJ system labels. E.g. to create a set of labels which can be used by * English, Italian and German users of an extension, the following files would need to be present * in the extension's Jar file: * * <pre> * lib/english/label * lib/italian/label * lib/german/label * </pre> * * The files named <code>label</code> would contain the actual label key/value pairs. * * @param key Description of the Parameter * @return The label value */ public String getLabel(String key) { if (!myWrapper.isValid()) throw new ExtensionUnloadedException(); // If there are no label for this extension I can only return the system ones. if (localLabels == null) return Config.getString(key, key); // In theory there are label for this extension let me try to get them String aLabel = localLabels.getProperty(key, null); // Found what I wanted, job done. if (aLabel != null) return aLabel; // ok, the only hope is to get it from the system return Config.getString(key, key); }
/** Inits the. */ public static synchronized void init() { if (inited) { return; } _conf = Config.getConfig(); /** initialize app command */ Command.init(); /** initialize the RSA key, hardcode 2048 bits */ TConn.pub_key = SystemConfig.s("pub_key", null); if (TConn.pub_key == null) { Key k = RSA.generate(2048); TConn.pri_key = k.pri_key; TConn.pub_key = k.pub_key; /** set back in database */ SystemConfig.setConfig("pri_key", TConn.pri_key); SystemConfig.setConfig("pub_key", TConn.pub_key); } else { /** get from the database */ TConn.pri_key = SystemConfig.s("pri_key", null); } inited = true; }
protected List<String> getUserRolesFromConfig(String property) throws IOException { List<String> res = null; { if (property != null) { ConfigFactory f = DefaultConfigFactory.getInstance(); Config c = f.getConfig(); String v = c.getProperty(property); // re-read; marks property read in 'Config'-impl. cache res = parseStringList(v); } } return res; }
private static void main2(String[] args) { Config.cmdline(args); try { javabughack(); } catch (InterruptedException e) { return; } setupres(); MainFrame f = new MainFrame(null); if (Utils.getprefb("fullscreen", false)) f.setfs(); f.mt.start(); try { f.mt.join(); } catch (InterruptedException e) { f.g.interrupt(); return; } dumplist(Resource.remote().loadwaited(), Config.loadwaited); dumplist(Resource.remote().cached(), Config.allused); if (ResCache.global != null) { try { Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8"); try { Resource.dumplist(Resource.remote().used(), w); } finally { w.close(); } } catch (IOException e) { } } System.exit(0); }
private static void readBeanGraphs(Config config) throws IOException { try { for (Iterator it = config.readBeanGraphFiles(); it.hasNext(); ) { File filename = (File) it.next(); InputStream in = new FileInputStream(filename); org.netbeans.modules.schema2beansdev.beangraph.BeanGraph bg = org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.read(in); in.close(); config.addReadBeanGraphs(bg); } } catch (javax.xml.parsers.ParserConfigurationException e) { throw new RuntimeException(e); } catch (org.xml.sax.SAXException e) { throw new RuntimeException(e); } }
/** Creates a new instance of AccountPicker */ public AccountSelect(Display display, boolean enableQuit) { super(); // this.display=display; setTitleItem(new Title(SR.MS_ACCOUNTS)); accountList = new Vector(); Account a; int index = 0; activeAccount = Config.getInstance().accountIndex; do { a = Account.createFromStorage(index); if (a != null) { accountList.addElement(a); a.active = (activeAccount == index); index++; } } while (a != null); if (accountList.isEmpty()) { a = Account.createFromJad(); if (a != null) { // a.updateJidCache(); accountList.addElement(a); rmsUpdate(); } } attachDisplay(display); addCommand(cmdAdd); if (enableQuit) addCommand(cmdQuit); commandState(); setCommandListener(this); }
private void handleOpenArticle( Request request, HttpServletResponse httpServletResponse, String target) throws Exception { try { int k1 = target.indexOf('/', 1); int k2 = target.indexOf('/', k1 + 1); String feedId = target.substring(k1 + 1, k2); String strSeq = target.substring(k2 + 1); int seq = Integer.parseInt(strSeq); Article article = articleDb.get(feedId, seq); LoginInfo loginInfo = userHelpers.getLoginInfo(request); // ttt2 using the link from a non-authenticated browser causes a NPE; maybe do something // better, e.g. sign up ReadArticlesColl readArticlesColl = readArticlesCollDb.get(loginInfo.userId, feedId); if (readArticlesColl == null) { readArticlesColl = new ReadArticlesColl(loginInfo.userId, feedId); } if (!readArticlesColl.isRead(seq)) { readArticlesColl.markRead(seq, Config.getConfig().maxSizeForReadArticles); readArticlesCollDb.add(readArticlesColl); } String s = URIUtil.encodePath(article.url) .replace("%3F", "?") .replace("%23", "#"); // ttt2 see how to do this right httpServletResponse.sendRedirect(s); } catch (Exception e) { WebUtils.showResult( String.format("Failed to get article for path %s. %s", target, e), "/", request, httpServletResponse); } }
public static void zhongbiao(Long id) { Toubiao toubiao = Toubiao.findById(id); toubiao.status = "1"; toubiao.save(); Request request = toubiao.request; request.status = 1; request.zb = true; request.save(); List<Toubiao> toubiaos = Toubiao.find("request.id=? and id!=?", request.id, id).fetch(); for (Toubiao tb : toubiaos) { tb.status = "2"; tb.save(); } Config config = Config.find("1=1").first(); String message = ""; SendMessage m = new SendMessage(); message = "您已中标" + toubiao.request.name + "项目,请按时发货"; if (config.msg_request_invite != null && !"".equals(config.msg_request_invite)) { message = config.msg_request_notification.replace("{request}", toubiao.request.name); } Profile p = toubiao.profile; if (p.contact_phone != null && !"".equals(p.contact_phone)) m.sendSms(p.contact_phone, message, "0000003"); if (p.contact_email != null && !"".equals(p.contact_email)) m.sendMail(p.contact_email, "[" + Messages.get("application.name") + "]中标通知", message); redirect("/admin/requests"); }
public static void initialize() throws Exception { if (Evaluator.evaluator == null) { if (Plan.conf == null) Plan.conf = new Configuration(); conf = Plan.conf; Config.read(Plan.conf); initialize_evaluator(); } }
public OutputStream getStream(String dir, String name, String extension) throws java.io.IOException { String filename = getFilename(dir, name, extension); if (!config.isQuiet()) config.messageOut.println(Common.getMessage("MSG_GeneratingClass", filename)); // NOI18N generatedFiles.add(filename); // return new FileOutputStream(filename); return new WriteIfDifferentOutputStream(filename); }
/** * Mutates the classifier. It mutates the action and the condition. * * @param envState is the current environtment state. It is necessary for the niched mutation. * @return a boolean indicating if the action has been mutated. */ public boolean mutate(double[] envState) { int i; // First, the condition is mutated for (i = 0; i < rep.length; i++) { rep[i].mutate(envState[i]); } // Second, the action is mutated int act = 0; if (Config.rand() < Config.pM) { do { act = (int) (Config.rand() * (double) Config.numberOfActions); } while (action == act); action = act; return true; } return false; } // end mutate
// !!! IDEA reports this as unused, but it is called from JSP public static String getStyle(LoginInfo loginInfo) { StringBuilder bld = new StringBuilder(); bld.append("<style media=\"screen\" type=\"text/css\">\n\n"); if (loginInfo == null) { bld.append(Config.getConfig().defaultStyle); } else { bld.append(loginInfo.style); // ttt3 detect broken styles and return default } bld.append("</style>\n"); return bld.toString(); }
public static Config getInstance() { if (instance == null) { instance = new Config(); instance.loadFromStorage(); FontCache.rosterFontSize = instance.font1; FontCache.msgFontSize = instance.font2; FontCache.resetCache(); } return instance; }
protected String getUserPresentationNameFromConfig(Principal userPrincipal) throws IOException { String res = null; { if (userPrincipal != null) { String userName = PrincipalUtil.getNameStripped(userPrincipal); if (userName != null) { String property = "security.authorization.user." + userName + ".presentation-name"; ConfigFactory f = DefaultConfigFactory.getInstance(); Config c = f.getConfig(); res = c.getProperty(property); } } } return res; }
// Accessors private String getProxyURL(HttpServletRequest httpServletRequest) { // Get the proxy host String stringProxyHostNew = Config.getInstance().getProxyHost(); this.setProxyHost(stringProxyHostNew); // Get the proxy port if specified String stringProxyPortNew = "" + Config.getInstance().getProxyPort(); this.setProxyPort(Integer.parseInt(stringProxyPortNew)); // Get the proxy path if specified String stringProxyPathNew = Config.getInstance().getProxyPath(); if (stringProxyPathNew != null && stringProxyPathNew.length() > 0) { this.setProxyPath(stringProxyPathNew); } // Get the maximum file upload size if specified String stringMaxFileUploadSize = "" + Config.getInstance().getMaxFileUploadSize(); if (stringMaxFileUploadSize != null && stringMaxFileUploadSize.length() > 0) { this.setMaxFileUploadSize(Integer.parseInt(stringMaxFileUploadSize)); } // Set the protocol to HTTP String stringProxyURL = "http://" + this.getProxyHostAndPort(); // Check if we are proxying to a path other that the document root if (!this.getProxyPath().equalsIgnoreCase("")) { stringProxyURL += this.getProxyPath(); } try { // Handle the path given to the servlet stringProxyURL += URIUtil.encodePath(httpServletRequest.getPathInfo()); // Handle the query string if (httpServletRequest.getQueryString() != null) { stringProxyURL += "?" + URIUtil.encodeQuery(httpServletRequest.getQueryString()); } LOG.debug("Proxying " + httpServletRequest.getRequestURL() + " to " + stringProxyURL); return stringProxyURL; } catch (Throwable t) { throw new RuntimeException(t); } }
private void handleSignupPost(Request request, HttpServletResponse httpServletResponse) throws Exception { String userId = request.getParameter(PARAM_USER_ID); String userName = request.getParameter(PARAM_USER_NAME); String email = request.getParameter(PARAM_EMAIL); String stringPassword = request.getParameter(PARAM_PASSWORD); String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM); if (!stringPassword.equals(stringPasswordConfirm)) { WebUtils.redirectToError( "Mismatch between password and password confirmation", request, httpServletResponse); return; } SecureRandom secureRandom = new SecureRandom(); String salt = "" + secureRandom.nextLong(); byte[] password = User.computeHashedPassword(stringPassword, salt); User user = userDb.get(userId); if (user != null) { WebUtils.redirectToError( "There already exists a user with the ID " + userId, request, httpServletResponse); return; } user = new User( userId, userName, password, salt, email, new ArrayList<String>(), Config.getConfig().activateAccountsAtCreation, false); // ttt2 add confirmation by email, captcha, ... List<String> fieldErrors = user.checkFields(); if (!fieldErrors.isEmpty()) { StringBuilder bld = new StringBuilder("Invalid values when trying to create user with ID ") .append(userId) .append("<br/>"); for (String s : fieldErrors) { bld.append(s).append("<br/>"); } WebUtils.redirectToError(bld.toString(), request, httpServletResponse); return; } // ttt2 2 clients can add the same userId simultaneously userDb.add(user); httpServletResponse.sendRedirect("/"); }
/** Invoked when the installer has failed. */ public static void installFailed(final String description, Throwable th) { Config.trace("installFailed: " + description + " " + th); if (SwingUtilities.isEventDispatchThread()) { Config.getInstallService().installFailed(); System.exit(-1); } else { try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { Config.getInstallService().installFailed(); System.exit(-1); } }); } catch (java.lang.reflect.InvocationTargetException ite) { Config.trace("Unexpected exception: " + ite); } catch (InterruptedException ie) { Config.trace("Unexpected exception: " + ie); } } }
/** * Applies crossover. It generates two children. * * @param parent1 is the first parent. * @param parent2 is the second parent * @param child1 is the first child * @param child2 is the second child. */ public void makeCrossover( Classifier parent1, Classifier parent2, Classifier child1, Classifier child2) { int i = 0; // cross1 is a number between [0.. clLength-1] int cross1 = (int) (Config.rand() * (double) Config.clLength); // cross2 is a number between [1..clLenght]. int cross2 = (int) (Config.rand() * (double) Config.clLength) + 1; if (cross1 > cross2) { int aux = cross2; cross2 = cross1; cross1 = aux; // In the else-if condition is not necessary to check if (cross2<clLength) // to increment the point, because cross1 [0..length-1] } else if (cross1 == cross2) cross2++; // All the intervals (real representation) or genes (ternary representation) that // are not in the cross point are crossed. if (!Config.ternaryRep) { for (i = cross1 + 1; i < cross2 - 1; i++) { child2.setAllele(i, parent1); child1.setAllele(i, parent2); } // Now we have to cross the border allele child1.crossAllele(cross1, parent1, parent2); child1.crossAllele(cross2 - 1, parent2, parent1); child2.crossAllele(cross1, parent2, parent1); child2.crossAllele(cross2 - 1, parent1, parent2); } else { for (i = cross1; i < cross2 - 1; i++) { child2.setAllele(i, parent1); child1.setAllele(i, parent2); } } } // end makeCrossover
private String generateOverviewText() throws InsufficientDataException { StringBuilder sb = new StringBuilder(); final String team = config.getTeam(); double total = checkTotal(); final String nl = System.getProperty("line.separator"); for (Entry<String, Row> entry : rows.entrySet()) { double hours = Double.parseDouble(entry.getValue().hoursTF.getText()); double fraction = hours / total; if (fraction < 0.004) continue; String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey(); sb.append(line + nl); } return sb.toString(); }
/** * It crosses a real allele within two parents. If the representation is a ternary representation, * a crossover within intervals is not possible because there is only one gene in each position. * So, in this case, the gene of the second parent will be copied. In case of being a real * representation, a random number is generated to decide where to cross the interval. It it's * crossed within the inteval, the crossAllele method will do it. * * @param parent1 is the first parent classifier. * @param parent2 is the second parent classifier. */ public void crossAllele(int i, Classifier parent1, Classifier parent2) { if (Config.ternaryRep) { rep[i].setAllele(parent2.rep[i]); } else { if (Config.typeOfAttributes[i].equals("ternary")) { rep[i].setAllele(parent2.rep[i]); } else { if (Config.rand() < 0.5) rep[i].setAllele(parent2.rep[i]); else { // The alleles has to be crossed rep[i].setAllele(parent1.rep[i].getLowerAllele(), parent2.rep[i].getUpperAllele()); rep[i].verifyInterval(); } } } } // end crossAllele
public void loadStreams() throws Exception { Config config = Config.getConfiguration("manager.streams"); afterLoadMap = new HashMap(); Object[] names = config.getArray("streams", null); if (names == null) { return; } for (int i = 0; i < names.length; i++) { StreamDataSource sds = new StreamDataSource(names[i].toString()); sds.load(); sds.initiate(); addStreamNoFire(sds); addDefault(sds); } Iterator it = afterLoadMap.keySet().iterator(); while (it.hasNext()) { StreamDataSource sds = (StreamDataSource) it.next(); List sList = (List) afterLoadMap.get(sds); Iterator addIt = sList.iterator(); while (addIt.hasNext()) { Integer serial = (Integer) addIt.next(); StreamDataSource addStream = getStream(serial.intValue()); if (addStream != null) { sds.addStream(addStream); } else { logger.warn("Unable to find source (" + serial + ") for " + sds); } } } afterLoadMap = null; }