List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:edu.cmu.lti.f12.hw2.hw2_team01.passage.SentenceBasedPassageCandidateFinder.java
private List<PassageSpan> splitParagraph(String text) { StringBuffer temptext = new StringBuffer(text); List<PassageSpan> rawSpans = new ArrayList<PassageSpan>(); List<PassageSpan> splitedSpans = new ArrayList<PassageSpan>(); List<PassageSpan> sentences = new ArrayList<PassageSpan>(); int start = 0; int startindice = -1; int pstart, pend, textend; while ((startindice = temptext.toString().toLowerCase().indexOf("<p>")) != -1) { temptext.delete(0, startindice + 3); start += (startindice + 3);//from w w w. j a va 2s. com pstart = temptext.toString().toLowerCase().indexOf("<p>"); pend = temptext.toString().toLowerCase().indexOf("</p>"); textend = temptext.toString().toLowerCase().indexOf("</txt>"); if (textend != -1 && textend * pend < pend * pend && textend * pstart < pstart * pstart) { PassageSpan ps = new PassageSpan(start, start + textend); rawSpans.add(ps); temptext = temptext.delete(0, textend + 6); start += (textend + 6); } else if (pend != -1 && pstart > pend) { PassageSpan ps = new PassageSpan(start, start + pend); rawSpans.add(ps); temptext = temptext.delete(0, pend + 4); start += (pend + 4); } else if (pstart != -1) { PassageSpan ps = new PassageSpan(start, start + pstart); rawSpans.add(ps); temptext = temptext.delete(0, pstart + 3); start += pstart + 3; } else { } } String substring = new String(); String subtoken = new String(); String cleanText = new String(); PassageSpan rawps; int substart, subend, psstart, psend, offset; Iterator<PassageSpan> ips = rawSpans.iterator(); while (ips.hasNext()) { sentences.clear(); rawps = ips.next(); //REFINE THE PARAGRAPH //rawps = RefinePassage(rawps); //if(rawps == null)continue; substart = rawps.begin; subend = rawps.end; substring = text.substring(substart, subend); int count = StringUtils.countMatches(substring, " "); if (substring.length() > 20 && count / (double) substring.length() <= 0.4) { cleanText = Jsoup.parse(substring).text().replaceAll("([\177-\377\0-\32]*)", ""); if ((cleanText.length() / (double) substring.length()) >= 0.6) { StringTokenizer tokenizer = new StringTokenizer(substring, ",.?!;"); psstart = substart; psend = psstart; offset = 0; while (tokenizer.hasMoreTokens()) { psstart = psend; subtoken = tokenizer.nextToken(); // offset = noneblankindex(subtoken); // psstart += offset; psend += subtoken.length() + 1; int totallength = subtoken.length(); while (totallength <= 50) { if (tokenizer.hasMoreElements()) { subtoken = tokenizer.nextToken(); totallength += subtoken.length(); psend += subtoken.length() + 1; } else break; } PassageSpan sentence = new PassageSpan(psstart, psend); sentences.add(sentence); } } } Iterator<PassageSpan> isentence = sentences.iterator(); PassageSpan ps1; while (isentence.hasNext()) { ps1 = isentence.next(); splitedSpans.add(ps1); } MergeSentences(substart, subend, sentences, splitedSpans, 2); MergeSentences(substart, subend, sentences, splitedSpans, 3); MergeSentences(substart, subend, sentences, splitedSpans, 4); MergeSentences(substart, subend, sentences, splitedSpans, 5); MergeSentences(substart, subend, sentences, splitedSpans, 6); MergeSentences(substart, subend, sentences, splitedSpans, 7); MergeSentences(substart, subend, sentences, splitedSpans, 8); MergeSentences(substart, subend, sentences, splitedSpans, 9); MergeSentences(substart, subend, sentences, splitedSpans, 10); } return splitedSpans; }
From source file:com.jaspersoft.jasperserver.war.action.repositoryExplorer.ResourceAction.java
public Event copyResource(RequestContext context) { try {// ww w . ja v a2 s.c o m String sourceUri = URLDecoder.decode((String) context.getRequestParameters().get("sourceUri"), "UTF-8"); String destUri = URLDecoder.decode((String) context.getRequestParameters().get("destUri"), "UTF-8"); StringBuffer sb = new StringBuffer(); sb.append('{'); StringTokenizer str = new StringTokenizer(sourceUri, ","); List resourceURIs = new ArrayList(); while (str.hasMoreElements()) { String currentResource = (String) str.nextElement(); // get sourceUri label String sourceLabel = repositoryService.getResource(null, currentResource).getLabel(); // check if the label already exist in the destination folder if (doesObjectLabelExist(destUri, sourceLabel)) { sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } resourceURIs.add(currentResource); } try { repositoryService.copyResources(null, (String[]) resourceURIs.toArray(new String[resourceURIs.size()]), destUri); } catch (Exception e) { log.error("Error copying resources", e); sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } sb.append("\"status\":\"SUCCESS\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); } catch (UnsupportedEncodingException e) { } return success(); }
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Get the consumer token with the given parameters and URL. The determination of whether the retrieved token * is an access token depends on whether a request token is provided. * * @param details The resource details. * @param tokenURL The token URL.// www .j av a 2s. c o m * @param httpMethod The http method. * @param requestToken The request token, or null if none. * @param additionalParameters The additional request parameter. * @return The token. */ protected OAuthConsumerToken getTokenFromProvider(ProtectedResourceDetails details, URL tokenURL, String httpMethod, OAuthConsumerToken requestToken, Map<String, String> additionalParameters) { boolean isAccessToken = requestToken != null; if (!isAccessToken) { //create an empty token to make a request for a new unauthorized request token. requestToken = new OAuthConsumerToken(); } TreeMap<String, String> requestHeaders = new TreeMap<String, String>(); if ("POST".equalsIgnoreCase(httpMethod)) { requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); } InputStream inputStream = readResource(details, tokenURL, httpMethod, requestToken, additionalParameters, requestHeaders); String tokenInfo; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); while (len >= 0) { out.write(buffer, 0, len); len = inputStream.read(buffer); } tokenInfo = new String(out.toByteArray(), "UTF-8"); } catch (IOException e) { throw new OAuthRequestFailedException("Unable to read the token.", e); } StringTokenizer tokenProperties = new StringTokenizer(tokenInfo, "&"); Map<String, String> tokenPropertyValues = new TreeMap<String, String>(); while (tokenProperties.hasMoreElements()) { try { String tokenProperty = (String) tokenProperties.nextElement(); int equalsIndex = tokenProperty.indexOf('='); if (equalsIndex > 0) { String propertyName = OAuthCodec.oauthDecode(tokenProperty.substring(0, equalsIndex)); String propertyValue = OAuthCodec.oauthDecode(tokenProperty.substring(equalsIndex + 1)); tokenPropertyValues.put(propertyName, propertyValue); } else { tokenProperty = OAuthCodec.oauthDecode(tokenProperty); tokenPropertyValues.put(tokenProperty, null); } } catch (DecoderException e) { throw new OAuthRequestFailedException("Unable to decode token parameters."); } } String tokenValue = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token.toString()); if (tokenValue == null) { throw new OAuthRequestFailedException("OAuth provider failed to return a token."); } String tokenSecret = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token_secret.toString()); if (tokenSecret == null) { throw new OAuthRequestFailedException("OAuth provider failed to return a token secret."); } OAuthConsumerToken consumerToken = new OAuthConsumerToken(); consumerToken.setValue(tokenValue); consumerToken.setSecret(tokenSecret); consumerToken.setResourceId(details.getId()); consumerToken.setAccessToken(isAccessToken); if (!tokenPropertyValues.isEmpty()) { consumerToken.setAdditionalParameters(tokenPropertyValues); } return consumerToken; }
From source file:org.mozilla.gecko.GeckoAppShell.java
static String getMimeTypeFromExtensions(String aFileExt) { MimeTypeMap mtm = MimeTypeMap.getSingleton(); StringTokenizer st = new StringTokenizer(aFileExt, "., "); String type = null;/*from ww w. ja va 2 s . co m*/ String subType = null; while (st.hasMoreElements()) { String ext = st.nextToken(); String mt = mtm.getMimeTypeFromExtension(ext); if (mt == null) continue; int slash = mt.indexOf('/'); String tmpType = mt.substring(0, slash); if (!tmpType.equalsIgnoreCase(type)) type = type == null ? tmpType : "*"; String tmpSubType = mt.substring(slash + 1); if (!tmpSubType.equalsIgnoreCase(subType)) subType = subType == null ? tmpSubType : "*"; } if (type == null) type = "*"; if (subType == null) subType = "*"; return type + "/" + subType; }
From source file:com.jaspersoft.jasperserver.war.action.repositoryExplorer.ResourceAction.java
public Event moveResource(RequestContext context) { try {/*from w w w. j av a 2 s . com*/ String sourceUri = URLDecoder.decode((String) context.getRequestParameters().get("sourceUri"), "UTF-8"); String destUri = URLDecoder.decode((String) context.getRequestParameters().get("destUri"), "UTF-8"); StringTokenizer str = new StringTokenizer(sourceUri, ","); StringBuffer sb = new StringBuffer(); sb.append('{'); while (str.hasMoreElements()) { String currentResource = (String) str.nextElement(); // get sourceUri label String sourceLabel = repositoryService.getResource(null, currentResource).getLabel(); // check if the label already exist in the destination folder if (doesObjectLabelExist(destUri, sourceLabel)) { sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } } str = new StringTokenizer(sourceUri, ","); while (str.hasMoreElements()) { String currentResource = (String) str.nextElement(); try { repositoryService.moveResource(null, currentResource, destUri); } catch (Exception e) { e.printStackTrace(); sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } } sb.append("\"status\":\"SUCCESS\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); } catch (UnsupportedEncodingException e) { } return success(); }
From source file:gtu._work.ui.RegexDirReplacer.java
private void initGUI() { try {// w ww . j a v a2s. c o m { } BorderLayout thisLayout = new BorderLayout(); getContentPane().setLayout(thisLayout); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { jTabbedPane1 = new JTabbedPane(); getContentPane().add(jTabbedPane1, BorderLayout.CENTER); { jPanel1 = new JPanel(); BorderLayout jPanel1Layout = new BorderLayout(); jPanel1.setLayout(jPanel1Layout); jTabbedPane1.addTab("source", null, jPanel1, null); { jScrollPane1 = new JScrollPane(); jPanel1.add(jScrollPane1, BorderLayout.CENTER); { ListModel srcListModel = new DefaultListModel(); srcList = new JList(); jScrollPane1.setViewportView(srcList); srcList.setModel(srcListModel); { panel = new JPanel(); jScrollPane1.setRowHeaderView(panel); panel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow"), }, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, })); { childrenDirChkbox = new JCheckBox("??"); childrenDirChkbox.setSelected(true); panel.add(childrenDirChkbox, "1, 1"); } { subFileNameText = new JTextField(); panel.add(subFileNameText, "1, 2, fill, default"); subFileNameText.setColumns(10); subFileNameText.setText("(txt|java)"); } { replaceOldFileChkbox = new JCheckBox(""); replaceOldFileChkbox.setSelected(true); panel.add(replaceOldFileChkbox, "1, 3"); } { charsetText = new JTextField(); panel.add(charsetText, "1, 5, fill, default"); charsetText.setColumns(10); charsetText.setText("UTF8"); } } srcList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { JListUtil.newInstance(srcList).defaultMouseClickOpenFile(evt); JPopupMenuUtil.newInstance(srcList).applyEvent(evt)// .addJMenuItem("load files from clipboard", new ActionListener() { public void actionPerformed(ActionEvent arg0) { String content = ClipboardUtil.getInstance().getContents(); DefaultListModel model = (DefaultListModel) srcList.getModel(); StringTokenizer tok = new StringTokenizer(content, "\t\n\r\f", false); for (; tok.hasMoreElements();) { String val = ((String) tok.nextElement()).trim(); model.addElement(new File(val)); } } }).show(); } }); srcList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(srcList).defaultJListKeyPressed(evt); } }); } } { addDirFiles = new JButton(); jPanel1.add(addDirFiles, BorderLayout.NORTH); addDirFiles.setText("add dir files"); addDirFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog() .getApproveSelectedFile(); if (file == null || !file.isDirectory()) { return; } List<File> fileLst = new ArrayList<File>(); String subName = StringUtils.trimToEmpty(subFileNameText.getText()); if (StringUtils.isBlank(subName)) { subName = ".*"; } String patternStr = ".*\\." + subName; if (childrenDirChkbox.isSelected()) { FileUtil.searchFileMatchs(file, patternStr, fileLst); } else { for (File f : file.listFiles()) { if (f.isFile() && f.getName().matches(patternStr)) { fileLst.add(f); } } } DefaultListModel model = new DefaultListModel(); for (File f : fileLst) { model.addElement(f); } srcList.setModel(model); } }); } } { jPanel2 = new JPanel(); BorderLayout jPanel2Layout = new BorderLayout(); jPanel2.setLayout(jPanel2Layout); jTabbedPane1.addTab("param", null, jPanel2, null); { exeucte = new JButton(); jPanel2.add(exeucte, BorderLayout.SOUTH); exeucte.setText("exeucte"); exeucte.setPreferredSize(new java.awt.Dimension(491, 125)); exeucte.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exeucteActionPerformed(evt); } }); } { jPanel3 = new JPanel(); GroupLayout jPanel3Layout = new GroupLayout((JComponent) jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel2.add(jPanel3, BorderLayout.CENTER); { repFromText = new JTextField(); } { repToText = new JTextField(); } jPanel3Layout.setHorizontalGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(25, 25) .addGroup(jPanel3Layout.createParallelGroup() .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repFromText, GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repToText, GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)); jPanel3Layout.setVerticalGroup(jPanel3Layout.createSequentialGroup().addContainerGap() .addComponent(repFromText, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(repToText, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); } { addToTemplate = new JButton(); jPanel2.add(addToTemplate, BorderLayout.NORTH); addToTemplate.setText("add to template"); addToTemplate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { prop.put(repFromText.getText(), repToText.getText()); reloadTemplateList(); } }); } } { jPanel4 = new JPanel(); BorderLayout jPanel4Layout = new BorderLayout(); jPanel4.setLayout(jPanel4Layout); jTabbedPane1.addTab("result", null, jPanel4, null); { jScrollPane2 = new JScrollPane(); jPanel4.add(jScrollPane2, BorderLayout.CENTER); { ListModel newRepListModel = new DefaultListModel(); newRepList = new JList(); jScrollPane2.setViewportView(newRepList); newRepList.setModel(newRepListModel); newRepList.addMouseListener(new MouseAdapter() { static final String tortoiseMergeExe = "TortoiseMerge.exe"; static final String commandFormat = "cmd /c call \"%s\" /base:\"%s\" /theirs:\"%s\""; public void mouseClicked(MouseEvent evt) { if (!JListUtil.newInstance(newRepList).isCorrectMouseClick(evt)) { return; } OldNewFile oldNewFile = (OldNewFile) JListUtil .getLeadSelectionObject(newRepList); String base = oldNewFile.newFile.getAbsolutePath(); String theirs = oldNewFile.oldFile.getAbsolutePath(); String command = String.format(commandFormat, tortoiseMergeExe, base, theirs); System.out.println(command); try { Runtime.getRuntime().exec(command); } catch (IOException e) { JCommonUtil.handleException(e); } } }); newRepList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { Object[] objects = (Object[]) newRepList.getSelectedValues(); if (objects == null || objects.length == 0) { return; } DefaultListModel model = (DefaultListModel) newRepList.getModel(); int lastIndex = model.getSize() - 1; Object swap = null; StringBuilder dsb = new StringBuilder(); for (Object current : objects) { int index = model.indexOf(current); switch (evt.getKeyCode()) { case 38:// up if (index != 0) { swap = model.getElementAt(index - 1); model.setElementAt(swap, index); model.setElementAt(current, index - 1); } break; case 40:// down if (index != lastIndex) { swap = model.getElementAt(index + 1); model.setElementAt(swap, index); model.setElementAt(current, index + 1); } break; case 127:// del OldNewFile current_ = (OldNewFile) current; dsb.append(current_.newFile.getName() + "\t" + (current_.newFile.delete() ? "T" : "F") + "\n"); current_.newFile.delete(); model.removeElement(current); } } if (dsb.length() > 0) { JOptionPaneUtil.newInstance().iconInformationMessage() .showMessageDialog("del result!\n" + dsb, "DELETE"); } } }); } } { replaceOrignFile = new JButton(); jPanel4.add(replaceOrignFile, BorderLayout.SOUTH); replaceOrignFile.setText("replace orign file"); replaceOrignFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { DefaultListModel model = (DefaultListModel) newRepList.getModel(); StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < model.size(); ii++) { OldNewFile file = (OldNewFile) model.getElementAt(ii); boolean delSuccess = false; boolean renameSuccess = false; if (delSuccess = file.oldFile.delete()) { renameSuccess = file.newFile.renameTo(file.oldFile); } sb.append(file.oldFile.getName() + " del:" + (delSuccess ? "T" : "F") + " rename:" + (renameSuccess ? "T" : "F") + "\n"); } JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog(sb, getTitle()); } }); } } { jPanel5 = new JPanel(); BorderLayout jPanel5Layout = new BorderLayout(); jPanel5.setLayout(jPanel5Layout); jTabbedPane1.addTab("template", null, jPanel5, null); { jScrollPane3 = new JScrollPane(); jPanel5.add(jScrollPane3, BorderLayout.CENTER); { templateList = new JList(); reloadTemplateList(); jScrollPane3.setViewportView(templateList); templateList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (templateList.getLeadSelectionIndex() == -1) { return; } Entry<Object, Object> entry = (Entry<Object, Object>) JListUtil .getLeadSelectionObject(templateList); repFromText.setText((String) entry.getKey()); repToText.setText((String) entry.getValue()); } }); templateList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(templateList).defaultJListKeyPressed(evt); } }); } } { scheduleExecute = new JButton(); jPanel5.add(scheduleExecute, BorderLayout.SOUTH); scheduleExecute.setText("schedule execute"); scheduleExecute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { scheduleExecuteActionPerformed(evt); } }); } } } this.setSize(512, 350); JCommonUtil.setFontAll(this.getRootPane()); JCommonUtil.frameCloseDo(this, new WindowAdapter() { public void windowClosing(WindowEvent paramWindowEvent) { if (StringUtils.isNotBlank(repFromText.getText())) { prop.put(repFromText.getText(), repToText.getText()); } try { prop.store(new FileOutputStream(propFile), "regexText"); } catch (Exception e) { JCommonUtil.handleException("properties store error!", e); } setVisible(false); dispose(); } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:de.tor.tribes.util.parser.TroopsParser.java
public boolean parse(String pTroopsString) { StringTokenizer lineTok = new StringTokenizer(pTroopsString, "\n\r"); int villageLines = -1; boolean retValue = false; int foundTroops = 0; //boolean haveVillage = false; Village v = null;/*from ww w . j av a 2s.com*/ TroopAmountFixed ownTroops = null; TroopAmountFixed troopsInVillage = null; TroopAmountFixed troopsOutside = null; TroopAmountFixed troopsOnTheWay = null; TroopsManager.getSingleton().invalidate(); // used to update group on the fly, if not "all" selected String groupName = null; // groups could be multiple lines, detection is easiest for first line (starts with "Gruppen:") boolean groupLines = false; // store visited villages, so we can add em to selected group List<Village> villages = new LinkedList<>(); while (lineTok.hasMoreElements()) { //parse single line for village String line = lineTok.nextToken(); //tokenize line by tab and space // StringTokenizer elemTok = new StringTokenizer(line, " \t"); //parse single line for village if (v != null) { //parse 4 village lines! line = line.trim(); if (line.trim().startsWith(getVariable("troops.own"))) { ownTroops = parseUnits(line.replaceAll(getVariable("troops.own"), "").trim()); } else if (line.trim().startsWith(getVariable("troops.in.village"))) { troopsInVillage = parseUnits(line.replaceAll(getVariable("troops.in.village"), "").trim()); } else if (line.trim().startsWith(getVariable("troops.outside"))) { troopsOutside = parseUnits(line.replaceAll(getVariable("troops.outside"), "").trim()); } else if (line.trim().startsWith(getVariable("troops.on.the.way"))) { troopsOnTheWay = parseUnits(line.replaceAll(getVariable("troops.on.the.way"), "").trim()); } villageLines--; } else { try { Village current = VillageParser.parseSingleLine(line); if (current != null) { v = current; villageLines = 4; // we are not searching for further group names groupLines = false; // add village to list of villages in selected group if (groupName != null) villages.add(v); } else { // Check if current line is first group line. In case it is, store selected group if (line.trim().startsWith(getVariable("overview.groups"))) groupLines = true; // Check if current line contains active group. In case it does, store group name and stop searching if (groupLines && line.matches(".*>.*?<.*")) { groupLines = false; groupName = StringUtils.substringBetween(line, ">", "<"); // = line.replaceAll(".*>|<.*",""); if we stop using Apache Commons } } } catch (Exception e) { v = null; villageLines = 0; // Check if current line is first group line. In case it is, store selected group if (line.trim().startsWith(getVariable("overview.groups"))) groupLines = true; // Check if current line contains active group. In case it does, store group name and stop searching if (groupLines && line.matches(".*>.*?<.*")) { groupLines = false; groupName = StringUtils.substringBetween(line, ">", "<"); // = line.replaceAll(".*>|<.*",""); if we stop using Apache Commons } } } //add troops information if (villageLines == 0) { if (v != null && ownTroops != null && troopsInVillage != null && troopsOutside != null && troopsOnTheWay != null) { //add troops to manager VillageTroopsHolder own = TroopsManager.getSingleton().getTroopsForVillage(v, TroopsManager.TROOP_TYPE.OWN, true); VillageTroopsHolder inVillage = TroopsManager.getSingleton().getTroopsForVillage(v, TroopsManager.TROOP_TYPE.IN_VILLAGE, true); VillageTroopsHolder outside = TroopsManager.getSingleton().getTroopsForVillage(v, TroopsManager.TROOP_TYPE.OUTWARDS, true); VillageTroopsHolder onTheWay = TroopsManager.getSingleton().getTroopsForVillage(v, TroopsManager.TROOP_TYPE.ON_THE_WAY, true); own.setTroops(ownTroops); inVillage.setTroops(troopsInVillage); outside.setTroops(troopsOutside); onTheWay.setTroops(troopsOnTheWay); ownTroops = null; troopsInVillage = null; troopsOutside = null; troopsOnTheWay = null; v = null; foundTroops++; //found at least one village, so retValue is true retValue = true; } else { v = null; ownTroops = null; troopsInVillage = null; troopsOutside = null; troopsOnTheWay = null; } } } if (retValue) { try { DSWorkbenchMainFrame.getSingleton() .showSuccess("DS Workbench hat Truppeninformationen zu " + foundTroops + ((foundTroops == 1) ? " Dorf " : " Drfern ") + " in die Truppenbersicht eingetragen."); } catch (Exception e) { NotifierFrame.doNotification("DS Workbench hat Truppeninformationen zu " + foundTroops + ((foundTroops == 1) ? " Dorf " : " Drfern ") + " in die Truppenbersicht eingetragen.", NotifierFrame.NOTIFY_INFO); } } //update selected group, if any if (groupName != null && !groupName.equals(getVariable("groups.all"))) { HashMap<String, List<Village>> groupTable = new HashMap<>(); groupTable.put(groupName, villages); DSWorkbenchMainFrame.getSingleton().fireGroupParserEvent(groupTable); } TroopsManager.getSingleton().revalidate(retValue); return retValue; }
From source file:nl.nn.adapterframework.parameters.Parameter.java
/** * determines the raw value /*from w ww . j a va2s. c o m*/ * @param alreadyResolvedParameters * @return the raw value as object * @throws IbisException */ public Object getValue(ParameterValueList alreadyResolvedParameters, ParameterResolutionContext prc) throws ParameterException { Object result = null; log.debug("Calculating value for Parameter [" + getName() + "]"); if (!configured) { throw new ParameterException("Parameter [" + getName() + "] not configured"); } TransformerPool pool = getTransformerPool(); if (pool != null) { try { Object transformResult = null; Source source = null; if (StringUtils.isNotEmpty(getValue())) { source = XmlUtils.stringToSourceForSingleUse(getValue(), prc.isNamespaceAware()); } else if (StringUtils.isNotEmpty(getSessionKey())) { String sourceString; Object sourceObject = prc.getSession().get(getSessionKey()); if (TYPE_LIST.equals(getType()) && sourceObject instanceof List) { List<String> items = (List<String>) sourceObject; XmlBuilder itemsXml = new XmlBuilder("items"); for (Iterator<String> it = items.iterator(); it.hasNext();) { String item = it.next(); XmlBuilder itemXml = new XmlBuilder("item"); itemXml.setValue(item); itemsXml.addSubElement(itemXml); } sourceString = itemsXml.toXML(); } else if (TYPE_MAP.equals(getType()) && sourceObject instanceof Map) { Map<String, String> items = (Map<String, String>) sourceObject; XmlBuilder itemsXml = new XmlBuilder("items"); for (Iterator<String> it = items.keySet().iterator(); it.hasNext();) { String item = it.next(); XmlBuilder itemXml = new XmlBuilder("item"); itemXml.addAttribute("name", item); itemXml.setValue(items.get(item)); itemsXml.addSubElement(itemXml); } sourceString = itemsXml.toXML(); } else { sourceString = (String) sourceObject; } if (StringUtils.isNotEmpty(sourceString)) { log.debug("Parameter [" + getName() + "] using sessionvariable [" + getSessionKey() + "] as source for transformation"); source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware()); } else { log.debug("Parameter [" + getName() + "] sessionvariable [" + getSessionKey() + "] empty, no transformation will be performed"); } } else if (StringUtils.isNotEmpty(getPattern())) { String sourceString = format(alreadyResolvedParameters, prc); if (StringUtils.isNotEmpty(sourceString)) { log.debug("Parameter [" + getName() + "] using pattern [" + getPattern() + "] as source for transformation"); source = XmlUtils.stringToSourceForSingleUse(sourceString, prc.isNamespaceAware()); } else { log.debug("Parameter [" + getName() + "] pattern [" + getPattern() + "] empty, no transformation will be performed"); } } else { source = prc.getInputSource(); } if (source != null) { if (transformerPoolRemoveNamespaces != null) { String rnResult = transformerPoolRemoveNamespaces.transform(source, null); source = XmlUtils.stringToSource(rnResult); } transformResult = transform(source, prc); } if (!(transformResult instanceof String) || StringUtils.isNotEmpty((String) transformResult)) { result = transformResult; } } catch (Exception e) { throw new ParameterException( "Parameter [" + getName() + "] exception on transformation to get parametervalue", e); } } else { if (StringUtils.isNotEmpty(getSessionKey())) { result = prc.getSession().get(getSessionKey()); } else if (StringUtils.isNotEmpty(getPattern())) { result = format(alreadyResolvedParameters, prc); } else if (StringUtils.isNotEmpty(getValue())) { result = getValue(); } else { result = prc.getInput(); } } if (result != null) { if (log.isDebugEnabled()) { log.debug("Parameter [" + getName() + "] resolved to [" + (isHidden() ? hide(result.toString()) : result) + "]"); } } else { // if value is null then return specified default value StringTokenizer stringTokenizer = new StringTokenizer(getDefaultValueMethods(), ","); while (result == null && stringTokenizer.hasMoreElements()) { String token = stringTokenizer.nextToken(); if ("defaultValue".equals(token)) { result = getDefaultValue(); } else if ("sessionKey".equals(token)) { result = prc.getSession().get(getSessionKey()); } else if ("pattern".equals(token)) { result = format(alreadyResolvedParameters, prc); } else if ("value".equals(token)) { result = getValue(); } else if ("input".equals(token)) { result = prc.getInput(); } } log.debug("Parameter [" + getName() + "] resolved to defaultvalue [" + (isHidden() ? hide(result.toString()) : result) + "]"); } if (result != null && result instanceof String) { if (getMinLength() >= 0 && !TYPE_NUMBER.equals(getType())) { if (result.toString().length() < getMinLength()) { log.debug("Padding parameter [" + getName() + "] because length [" + result.toString().length() + "] deceeds minLength [" + getMinLength() + "]"); result = StringUtils.rightPad(result.toString(), getMinLength()); } } if (getMaxLength() >= 0) { if (result.toString().length() > getMaxLength()) { log.debug("Trimming parameter [" + getName() + "] because length [" + result.toString().length() + "] exceeds maxLength [" + getMaxLength() + "]"); result = result.toString().substring(0, getMaxLength()); } } if (TYPE_NODE.equals(getType())) { try { result = XmlUtils.buildNode((String) result, prc.isNamespaceAware()); if (log.isDebugEnabled()) log.debug("final result [" + result.getClass().getName() + "][" + result + "]"); } catch (DomBuilderException e) { throw new ParameterException( "Parameter [" + getName() + "] could not parse result [" + result + "] to XML nodeset", e); } } if (TYPE_DOMDOC.equals(getType())) { try { result = XmlUtils.buildDomDocument((String) result, prc.isNamespaceAware(), prc.isXslt2()); if (log.isDebugEnabled()) log.debug("final result [" + result.getClass().getName() + "][" + result + "]"); } catch (DomBuilderException e) { throw new ParameterException( "Parameter [" + getName() + "] could not parse result [" + result + "] to XML document", e); } } if (TYPE_DATE.equals(getType()) || TYPE_DATETIME.equals(getType()) || TYPE_TIMESTAMP.equals(getType()) || TYPE_TIME.equals(getType())) { log.debug("Parameter [" + getName() + "] converting result [" + result + "] to date using formatString [" + getFormatString() + "]"); DateFormat df = new SimpleDateFormat(getFormatString()); try { result = df.parseObject((String) result); } catch (ParseException e) { throw new ParameterException("Parameter [" + getName() + "] could not parse result [" + result + "] to Date using formatString [" + getFormatString() + "]", e); } } if (TYPE_XMLDATETIME.equals(getType())) { log.debug("Parameter [" + getName() + "] converting result [" + result + "] from xml dateTime to date"); result = DateUtils.parseXmlDateTime((String) result); } if (TYPE_NUMBER.equals(getType())) { log.debug("Parameter [" + getName() + "] converting result [" + result + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator() + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]"); DecimalFormat df = new DecimalFormat(); df.setDecimalFormatSymbols(decimalFormatSymbols); try { Number n = df.parse((String) result); result = n; } catch (ParseException e) { throw new ParameterException( "Parameter [" + getName() + "] could not parse result [" + result + "] to number decimalSeparator [" + decimalFormatSymbols.getDecimalSeparator() + "] groupingSeparator [" + decimalFormatSymbols.getGroupingSeparator() + "]", e); } if (getMinLength() >= 0 && result.toString().length() < getMinLength()) { log.debug("Adding leading zeros to parameter [" + getName() + "]"); result = StringUtils.leftPad(result.toString(), getMinLength(), '0'); } } if (TYPE_INTEGER.equals(getType())) { log.debug("Parameter [" + getName() + "] converting result [" + result + "] to integer"); try { Integer i = Integer.parseInt((String) result); result = i; } catch (NumberFormatException e) { throw new ParameterException( "Parameter [" + getName() + "] could not parse result [" + result + "] to integer", e); } } } if (result != null) { if (getMinInclusive() != null || getMaxInclusive() != null) { if (getMinInclusive() != null) { if (((Number) result).floatValue() < minInclusive.floatValue()) { log.debug("Replacing parameter [" + getName() + "] because value [" + result + "] exceeds minInclusive [" + getMinInclusive() + "]"); result = minInclusive; } } if (getMaxInclusive() != null) { if (((Number) result).floatValue() > maxInclusive.floatValue()) { log.debug("Replacing parameter [" + getName() + "] because value [" + result + "] exceeds maxInclusive [" + getMaxInclusive() + "]"); result = maxInclusive; } } } } return result; }
From source file:org.apache.jcs.access.TestCacheAccess.java
License:asdf
/** * This is the main loop called by the main method. *//*from w ww . j a va 2s . com*/ public void runLoop() { try { try { // process user input till done boolean notDone = true; String message = null; // wait to dispose BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); help(); while (notDone) { p("enter command:"); message = br.readLine(); if (message.startsWith("help")) { help(); } else if (message.startsWith("gc")) { System.gc(); } else if (message.startsWith("getAttributeNames")) { long n_start = System.currentTimeMillis(); String groupName = null; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { groupName = t.trim(); } } getAttributeNames(groupName); long n_end = System.currentTimeMillis(); p("---got attrNames for " + groupName + " in " + String.valueOf(n_end - n_start) + " millis ---"); } else if (message.startsWith("shutDown")) { CompositeCacheManager.getInstance().shutDown(); //cache_control.dispose(); notDone = false; //System.exit( -1 ); return; } else ///////////////////////////////////////////////////////////////////// // get multiple from a region if (message.startsWith("getm")) { int num = 0; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { try { num = Integer.parseInt(t.trim()); } catch (NumberFormatException nfe) { p(t + "not a number"); } } else if (tcnt == 3) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get numbertoget show values[true|false]"); } else { getMultiple(num, show); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("getg")) { String key = null; String group = null; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { group = t.trim(); } else if (tcnt == 4) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get key show values[true|false]"); } else { long n_start = System.currentTimeMillis(); try { Object obj = cache_control.getFromGroup(key, group); if (show && obj != null) { p(obj.toString()); } } catch (Exception e) { log.error(e); } long n_end = System.currentTimeMillis(); p("---got " + key + " from group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("getag")) { // get auto from group int num = 0; String group = null; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { num = Integer.parseInt(t.trim()); } else if (tcnt == 3) { group = t.trim(); } else if (tcnt == 4) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get key show values[true|false]"); } else { long n_start = System.currentTimeMillis(); try { for (int a = 0; a < num; a++) { Object obj = cache_control.getFromGroup("keygr" + a, group); if (show && obj != null) { p(obj.toString()); } } } catch (Exception e) { log.error(e); } long n_end = System.currentTimeMillis(); p("---got " + num + " from group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("get")) { // plain old get String key = null; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get key show values[true|false]"); } else { long n_start = System.currentTimeMillis(); try { Object obj = cache_control.get(key); if (show && obj != null) { p(obj.toString()); } } catch (Exception e) { log.error(e); } long n_end = System.currentTimeMillis(); p("---got " + key + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else if (message.startsWith("putg")) { String group = null; String key = null; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { group = t.trim(); } } if (tcnt < 3) { p("usage: putg key group"); } else { long n_start = System.currentTimeMillis(); cache_control.putInGroup(key, group, "data from putg ----asdfasfas-asfasfas-asfas in group " + group); long n_end = System.currentTimeMillis(); p("---put " + key + " in group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else // put automatically if (message.startsWith("putag")) { String group = null; int num = 0; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { num = Integer.parseInt(t.trim()); } else if (tcnt == 3) { group = t.trim(); } } if (tcnt < 3) { p("usage: putag num group"); } else { long n_start = System.currentTimeMillis(); for (int a = 0; a < num; a++) { cache_control.putInGroup("keygr" + a, group, "data " + a + " from putag ----asdfasfas-asfasfas-asfas in group " + group); } long n_end = System.currentTimeMillis(); p("---put " + num + " in group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("putm")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: putm numbertoput"); } else { putMultiple(num); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("pute")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: putme numbertoput"); } else { long n_start = System.currentTimeMillis(); for (int n = 0; n < num; n++) { IElementAttributes attrp = cache_control.getDefaultElementAttributes(); ElementEventHandlerMockImpl hand = new ElementEventHandlerMockImpl(); attrp.addElementEventHandler(hand); cache_control.put("key" + n, "data" + n + " put from ta = junk", attrp); } long n_end = System.currentTimeMillis(); p("---put " + num + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else if (message.startsWith("put")) { String key = null; String val = null; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { val = t.trim(); } } if (tcnt < 3) { p("usage: put key val"); } else { long n_start = System.currentTimeMillis(); cache_control.put(key, val); long n_end = System.currentTimeMillis(); p("---put " + key + " | " + val + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } ///////////////////////////////////////////////////////////////////// if (message.startsWith("removem")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: removem numbertoremove"); } else { removeMultiple(num); } } else if (message.startsWith("removeall")) { cache_control.clear(); p("removed all"); } else if (message.startsWith("remove")) { String key = message.substring(message.indexOf(" ") + 1, message.length()); cache_control.remove(key); p("removed " + key); } else if (message.startsWith("deattr")) { IElementAttributes ae = cache_control.getDefaultElementAttributes(); p("Default IElementAttributes " + ae); } else if (message.startsWith("cloneattr")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: put numbertoput"); } else { IElementAttributes attrp = new ElementAttributes(); long n_start = System.currentTimeMillis(); for (int n = 0; n < num; n++) { attrp.copy(); } long n_end = System.currentTimeMillis(); p("---cloned attr " + num + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else if (message.startsWith("switch")) { String name = message.substring(message.indexOf(" ") + 1, message.length()); setRegion(name); p("switched to cache = " + name); p(cache_control.toString()); } else if (message.startsWith("stats")) { p(cache_control.getStats()); } else if (message.startsWith("gc")) { System.gc(); p("Called system.gc()"); } else if (message.startsWith("random")) if (message.startsWith("random")) { String rangeS = ""; String numOpsS = ""; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { rangeS = t.trim(); } else if (tcnt == 3) { numOpsS = t.trim(); } else if (tcnt == 4) { show = new Boolean(t).booleanValue(); } } String numS = message.substring(message.indexOf(" ") + 1, message.length()); int range = 0; int numOps = 0; try { range = Integer.parseInt(rangeS.trim()); numOps = Integer.parseInt(numOpsS.trim()); } catch (Exception e) { p("usage: random range numOps show"); p("ex. random 100 1000 false"); } if (numS == null) { p("usage: random range numOps show"); p("ex. random 100 1000 false"); } else { random(range, numOps, show); } } } } catch (Exception e) { p(e.toString()); e.printStackTrace(System.out); } } catch (Exception e) { p(e.toString()); e.printStackTrace(System.out); } }
From source file:org.lexevs.system.constants.SystemVariables.java
/** * Inits the.//from www . j ava 2s.co m * * @param logger the logger * @param props the props * * @throws Exception the exception */ private void init(Logger logger, Properties props) throws Exception { // Read in the config file try { configFileLocation_ = props.getProperty("CONFIG_FILE_LOCATION"); sqlServers_ = new Hashtable<String, SQLConnectionInfo>(); indexLocations_ = new HashSet<String>(); logger.debug( "Reading registry, index location and db configuration information from the properties file"); String relPathStart = System.getProperty("LG_BASE_PATH"); if (relPathStart != null && relPathStart.length() > 0) { logger.debug("Relative Path root read from system variable '" + relPathStart + "'"); relativePathStart_ = relPathStart; if (!isPathValid(relativePathStart_)) { logger.error("You provided an invalid relative path root as a system variable. Ignoring."); relativePathStart_ = null; } } if (relativePathStart_ == null) { relPathStart = props.getProperty("LG_BASE_PATH"); if (relPathStart != null && relPathStart.length() > 0) { logger.debug("Relative Path root read from config file '" + relPathStart + "'"); relativePathStart_ = relPathStart; if (!isPathValid(relativePathStart_)) { logger.error("You provided an invalid relative path root in the config file. Ignoring."); relativePathStart_ = null; } } if (relativePathStart_ == null) { // default to the location of the config file. relativePathStart_ = props.getProperty("CONFIG_FILE_LOCATION"); logger.debug("Relative Path root defaulted to " + CONFIG_FILE_NAME + " location '" + relativePathStart_ + "'"); } } String tempJarFileLocation = getProperty(props, "JAR_FILE_LOCATION"); StringTokenizer tokenizer = new StringTokenizer(tempJarFileLocation, ";"); jarFileLocations_ = new String[tokenizer.countTokens()]; int i = 0; while (tokenizer.hasMoreElements()) { jarFileLocations_[i++] = processRelativePath(tokenizer.nextToken()); } autoLoadRegistryPath_ = processRelativePath(getProperty(props, "REGISTRY_FILE")); autoLoadIndexLocation_ = processRelativePath(getProperty(props, "INDEX_LOCATION")); autoLoadDBURL_ = getProperty(props, "DB_URL"); if (getNullableProperty(props, "MAX_IN_VS_CACHE") == null) { max_value_set_cache = 500; } else { max_value_set_cache = getStringPropertyAsInt(props, "MAX_IN_VS_CACHE"); } String tempSingleDb = getNullableProperty(props, "SINGLE_DB_MODE"); autoLoadSingleDBMode = getNullableBoolean(tempSingleDb, true); String tempOverrideSingleDb = getNullableProperty(props, OVERRIDE_SINGLE_DB_PROP); overrideSingleDbMode = getNullableBoolean(tempOverrideSingleDb, false); singleTableMode = getNullableBoolean(getNullableProperty(props, SINGLE_TABLE_MODE_PROP), SINGLE_TABLE_MODE_DEFAULT); autoLoadDBPrefix_ = getProperty(props, "DB_PREFIX"); // this one can be left out autoLoadDBParameters_ = props.getProperty("DB_PARAM"); if (autoLoadDBParameters_ == null) { autoLoadDBParameters_ = ""; } else { autoLoadDBURL_ = getAutoLoadDBURL() + getAutoLoadDBParameters(); } autoLoadDBDriver_ = getProperty(props, "DB_DRIVER"); autoLoadDBUsername_ = getProperty(props, "DB_USER"); autoLoadDBPassword_ = getProperty(props, "DB_PASSWORD"); // graphdbUser = getProperty(props, "GRAPH_DB_USER"); // graphdbpwd = getProperty(props, "GRAPH_DB_PWD"); // graphdbUrl = getProperty(props, "GRAPH_DB_PATH"); mysql_collation = getNullableProperty(props, "MYSQL_COLLATION", DEFAULT_MYSQL_COLLATION); String pwdEncrypted = getNullableProperty(props, "DB_PASSWORD_ENCRYPTED"); if (pwdEncrypted != null && pwdEncrypted.equalsIgnoreCase("true")) autoLoadDBPassword_ = CryptoUtility.decrypt(autoLoadDBPassword_); File temp = new File(autoLoadIndexLocation_); if (!temp.exists()) { temp.mkdir(); } indexLocations_.add(autoLoadIndexLocation_); logger.debug("Reading the Preconfigured SQL Server configurations from the properties file"); loadSqlServerLocations(props); logger.debug("Reading the Prebuilt Lucene index configurations from the properties file"); loadIndexLocations(props); logger.debug("Reading additional variables from the properties file"); logLocation_ = processRelativePath(getProperty(props, "LOG_FILE_LOCATION")); isNormEnabled_ = false; // This has been disabled due to deployment complexity. Can be // re-enabled if necessary. // isNormEnabled_ = new // Boolean(props.getProperty("NORMALIZED_QUERIES_ENABLED")).booleanValue(); // if (isNormEnabled_) // { // normConfigFile_ = // props.getProperty("LVG_NORM_CONFIG_FILE_ABSOLUTE"); // } realDebugEnableValue_ = new Boolean(getProperty(props, "DEBUG_ENABLED")).booleanValue(); if (!isDebugOverridden_) { isDebugEnabled_ = realDebugEnableValue_; } logger.info("Logging debug messages" + (isDebugEnabled_ == true ? " left on." : " turned off.")); logger.setDebugEnabled(isDebugEnabled_); isAPILoggingEnabled = new Boolean(getProperty(props, "API_LOG_ENABLED")).booleanValue(); logger.setAPILoggingEnabled(isAPILoggingEnabled); isMigrateOnStartupEnabled = getNullableBoolean("MOVE_REGISTRY_TO_DATABASE", false); logger.setAPILoggingEnabled(isMigrateOnStartupEnabled); String val = props.getProperty("SQL_LOG_ENABLED"); if (val != null) { isSQLLoggingEnabled = new Boolean(val).booleanValue(); } logger.info("Logging sql messages" + (isSQLLoggingEnabled == true ? " left on." : " turned off.")); try { maxConnectionsPerDB_ = Integer.parseInt(getProperty(props, "MAX_CONNECTIONS_PER_DB")); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for maxConnectionsPerDB - defaulting to 8"); maxConnectionsPerDB_ = 8; } try { iteratorIdleTime_ = Integer.parseInt(getProperty(props, "ITERATOR_IDLE_TIME")); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for ITERATOR_IDLE_TIME - defaulting to 5"); iteratorIdleTime_ = 5; } try { maxResultSize_ = Integer.parseInt(getProperty(props, "MAX_RESULT_SIZE")); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for MAX_RESULT_SIZE - defaulting to 1000"); maxResultSize_ = 1000; } try { cacheSize_ = Integer.parseInt(getProperty(props, "CACHE_SIZE")); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for CACHE_SIZE - defaulting to 200"); cacheSize_ = 200; } try { maxResultSize_ = Integer.parseInt(getProperty(props, "MAX_RESULT_SIZE")); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for MAX_RESULT_SIZE - defaulting to 1000"); maxResultSize_ = 1000; } String luceneMaxClauses = getNullableProperty(props, LUCENE_MAX_CLAUSE_COUNT_PROP); if (luceneMaxClauses != null) { try { this.luceneMaxClauseCount = Integer.parseInt(luceneMaxClauses); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for " + LUCENE_MAX_CLAUSE_COUNT_PROP); } } this.isSingleIndex = BooleanUtils .toBoolean(getNullableProperty(props, LUCENE_SINGLE_INDEX_PROP, LUCENE_SINGLE_INDEX_DEFAULT)); this.primaryKeyStrategy = getNullableProperty(props, PRIMARY_KEY_STRATEGY_PROP, DEFAULT_PRIMARY_KEY_STRATEGY); this.currentPersistenceScheme = getNullableProperty(props, CURRENT_PERSISTENCE_SCHEME_PROP, DEFAULT_PERSISTENCE_SCHEME); emailErrors_ = new Boolean(getNullableProperty(props, "EMAIL_ERRORS", "false")); if (emailErrors_) { SMTPServer_ = getProperty(props, "SMTP_SERVER"); emailTo_ = getProperty(props, "EMAIL_TO"); } try { logChange_ = getProperty(props, "LOG_CHANGE"); if (!logChange_.equals("daily") && !logChange_.equals("weekly") && !logChange_.equals("monthly")) { Integer.parseInt(logChange_); } } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for LOG_CHANGE - defaulting to 5"); logChange_ = "5"; } try { eraseLogsAfter_ = Integer.parseInt(getProperty(props, "ERASE_LOGS_AFTER")); } catch (NumberFormatException e) { logger.error("INVALID VALUE in config file for ERASE_LOGS_AFTER - defaulting to 5"); eraseLogsAfter_ = 5; } if (autoLoadSingleDBMode) historyDBSchema_ = props.getProperty("HISTORY_DB_SCHEMA"); logger.finishLogConfig(this); } catch (Exception e) { logger.fatal("There was a problem reading the properties", e); throw e; } }