List of usage examples for java.util.regex Matcher quoteReplacement
public static String quoteReplacement(String s)
From source file:net.ytbolg.mcxa.MCLaucherXA.java
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened // GameInfo.uuid = UUID.randomUUID().toString().toUpperCase().replace("-", ""); // GameInfo.rb.getBundle(tpf) // jMenu3.setVisible(false); setTitle(MainTitle);//from w w w. j a va 2 s.c o m jLabel2.setText(Lang.getLang("Main_Label_Username")); jCheckBox1.setText(Lang.getLang("Main_CheckBox_zhangben")); jLabel4.setText(Lang.getLang("Main_Label_Memory")); jLabel1.setText(Lang.getLang("Main_Label_Type")); jLabel3.setText(Lang.getLang("Main_Label_Time")); jLabel6.setText(Lang.getLang("Main_Label_BMCLVAPI")); jButton1.setText(Lang.getLang("Main_Button_Lauch")); // jButton2.setText(Lang.getLang("Main_Button_GetAss")); jMenu1.setText(Lang.getLang("Main_Menu_File")); jMenu2.setText(Lang.getLang("Main_Menu_Help")); jMenuItem1.setText(Lang.getLang("Main_Menu_DownVersion")); jMenuItem3.setText(Lang.getLang("Main_Menu_DownForge")); jMenuItem2.setText(Lang.getLang("Main_Menu_Config")); jMenuItem4.setText(Lang.getLang("Main_Menu_Update")); // jMenuItem4.setText(Lang.getLang("Main_Menu_Delete")); jLabel7.setText(Lang.getLang("Main_Label_Update")); jLabel9.setText(Lang.getLang("Main_Label_AppArgs")); jLabel7.setVisible(Updater.NeedUpdate()); JMenuItem ji = jPopupMenu1.add(Lang.getLang("Main_Menu_Delete")); JMenuItem j2 = jPopupMenu1.add(Lang.getLang("Main_Menu_Brush")); JMenuItem j3 = jPopupMenu1.add(Lang.getLang("Main_Button_GetAss")); JMenuItem j4 = jPopupMenu1.add(Lang.getLang("Main_Menu_RedownloadLib")); j2.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mousePressed(MouseEvent e) { jList1.setListData(GameInfoGet.getGameVersions()); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseReleased(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseEntered(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseExited(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); ji.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { //if(e.getComponent().) // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mousePressed(MouseEvent e) { // System.out.println("Right click"); if (e.getButton() == MouseEvent.BUTTON1) { System.out.println( GameInfo.GameDir + tpf + "versions" + tpf + jList1.getSelectedValue().toString()); deleteDir(new File( GameInfo.GameDir + tpf + "versions" + tpf + jList1.getSelectedValue().toString())); jList1.setListData(GameInfoGet.getGameVersions()); } // System.out.println("Right click"); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseReleased(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseExited(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void mouseDragged(MouseEvent e) { } }); j3.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mousePressed(MouseEvent e) { GameInfo.assVersion = jList1.getSelectedValue().toString(); try { GetAss(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } catch (ParserConfigurationException ex) { Logger.getLogger(MCLaucherXA.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void mouseReleased(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseEntered(MouseEvent e) { ///// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseExited(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); j4.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mousePressed(MouseEvent e) { try { Downloader d = new Downloader(); d.setUnzip(false); String al = GameInfoGet .libstotruedir(GameInfoGet.getLibs(jList1.getSelectedValue().toString())); String libs[] = al.split(";"); for (int a = 0; a < libs.length; a++) { libs[a] = libs[a].substring(1, libs[a].length() - 1); } for (String lib : libs) { File f = new File(lib); if (f.exists()) { f.delete(); } d.add(DownLoadURL.getURL(DownLoadURL.LIBRARIES, Integer.valueOf(Config.getConfig("DownSou"))) + lib.replaceFirst(Matcher.quoteReplacement(GameInfo.GameDir + tpf + "libraries"), ""), lib); } d.setVisible(true); d.start(); // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } catch (IOException | JSONException ex) { Logger.getLogger(MCLaucherXA.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void mouseReleased(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseEntered(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseExited(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }); // this.setIconImage(this.getToolkit().getImage(getClass().getResource("/icon_16x16.icon"))); // System.out.println(p.getProperty("zhengbanmima")); jCheckBox1.setSelected(Config.getConfig("iszhengban").equals("true")); jCheckBox1ActionPerformed(null); setLocationRelativeTo(getOwner()); if (!System.getProperty("os.name").contains("Windows")) { jLabel8.setText(Lang.getLang("Main_NotWindows")); // jLabel9.setText(); } this.setResizable(false); jList1.setListData(GameInfoGet.getGameVersions());// TODO add your handling code here: GameInfo.downUrl = Config.getConfig("downUrl"); try { int m = GameInfoGet.getGameVersions().length; vs = new JSONObject[m]; // System.out.println(m); for (int i = 0; i < m; i++) { vs[i] = new JSONObject(ReadFile(GameInfo.GameDir + tpf + "versions" + tpf + GameInfoGet.getGameVersions()[i] + tpf + GameInfoGet.getGameVersions()[i] + ".json")); } jPasswordField1.setText(Config.getConfig("zhengbanmima")); if (Config.getConfig("zhengbanmima").equals("")) { jCheckBox1.setSelected(false); jPasswordField1.setEnabled(false); } jTextField1.setText(Config.getConfig("username")); jTextField2.setText(Config.getConfig("lastmemory")); int i = 0; // System.out.println(p.getProperty("lastgameversion")); i = Integer.parseInt(Config.getConfig("lastgameversion")); if (i < 0) { i = 0; } jList1.setSelectedIndex(i); if (jList1.getModel().getSize() != 0) { BrushLabels(jList1.getSelectedIndex()); } // OutputStream in = new FileOutputStream(GameInfo.Rundir + tpf + "MCXA.cfg"); Config.Save(); // p.store(in, "= ="); if (MakeCmd.isChanged( new ZipFile(GameInfo.GameDir + tpf + "versions" + tpf + jList1.getSelectedValue().toString() + tpf + jList1.getSelectedValue().toString() + ".jar"))) { jComboBox1.setSelectedIndex(0); } } catch (IOException | JSONException e) { } catch (Exception ex) { Logger.getLogger(MCLaucherXA.class.getName()).log(Level.SEVERE, null, ex); } // TODO add your handling code here: }
From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java
public Object[] subsetObjectVector(File tabfile, int column, int varcount, int casecount, int columntype, boolean compatmode) throws IOException { Object[] retVector = null;/* w ww . j av a2 s .c o m*/ boolean isString = false; boolean isDouble = false; boolean isLong = false; boolean isFloat = false; //Locale loc = new Locale("en", "US"); if (columntype == COLUMN_TYPE_STRING) { isString = true; retVector = new String[casecount]; } else if (columntype == COLUMN_TYPE_DOUBLE) { isDouble = true; retVector = new Double[casecount]; } else if (columntype == COLUMN_TYPE_LONG) { isLong = true; retVector = new Long[casecount]; } else if (columntype == COLUMN_TYPE_FLOAT) { isFloat = true; retVector = new Float[casecount]; } else { throw new IOException("Unsupported column type: " + columntype); } File rotatedImageFile = getRotatedImage(tabfile, varcount, casecount); long[] columnEndOffsets = extractColumnOffsets(rotatedImageFile, varcount, casecount); long columnOffset = 0; long columnLength = 0; if (column > 0) { columnOffset = columnEndOffsets[column - 1]; columnLength = columnEndOffsets[column] - columnEndOffsets[column - 1]; } else { columnOffset = varcount * 8; columnLength = columnEndOffsets[0] - varcount * 8; } FileChannel fc = (FileChannel.open(Paths.get(rotatedImageFile.getAbsolutePath()), StandardOpenOption.READ)); fc.position(columnOffset); int MAX_COLUMN_BUFFER = 8192; ByteBuffer in = ByteBuffer.allocate(MAX_COLUMN_BUFFER); if (columnLength < MAX_COLUMN_BUFFER) { in.limit((int) (columnLength)); } long bytesRead = 0; long bytesReadTotal = 0; int caseindex = 0; int byteoffset = 0; byte[] leftover = null; while (bytesReadTotal < columnLength) { bytesRead = fc.read(in); byte[] columnBytes = in.array(); int bytecount = 0; while (bytecount < bytesRead) { if (columnBytes[bytecount] == '\n') { /* String token = new String(columnBytes, byteoffset, bytecount-byteoffset, "UTF8"); if (leftover != null) { String leftoverString = new String (leftover, "UTF8"); token = leftoverString + token; leftover = null; } */ /* * Note that the way I was doing it at first - above - * was not quite the correct way - because I was creating UTF8 * strings from the leftover bytes, and the bytes in the * current buffer *separately*; which means, if a multi-byte * UTF8 character got split in the middle between one buffer * and the next, both chunks of it would become junk * characters, on each side! * The correct way of doing it, of course, is to create a * merged byte buffer, and then turn it into a UTF8 string. * -- L.A. 4.0 */ String token = null; if (leftover == null) { token = new String(columnBytes, byteoffset, bytecount - byteoffset, "UTF8"); } else { byte[] merged = new byte[leftover.length + bytecount - byteoffset]; System.arraycopy(leftover, 0, merged, 0, leftover.length); System.arraycopy(columnBytes, byteoffset, merged, leftover.length, bytecount - byteoffset); token = new String(merged, "UTF8"); leftover = null; merged = null; } if (isString) { if ("".equals(token)) { // An empty string is a string missing value! // An empty string in quotes is an empty string! retVector[caseindex] = null; } else { // Strip the outer quotes: token = token.replaceFirst("^\\\"", ""); token = token.replaceFirst("\\\"$", ""); // We need to restore the special characters that // are stored in tab files escaped - quotes, new lines // and tabs. Before we do that however, we need to // take care of any escaped backslashes stored in // the tab file. I.e., "foo\t" should be transformed // to "foo<TAB>"; but "foo\\t" should be transformed // to "foo\t". This way new lines and tabs that were // already escaped in the original data are not // going to be transformed to unescaped tab and // new line characters! String[] splitTokens = token.split(Matcher.quoteReplacement("\\\\"), -2); // (note that it's important to use the 2-argument version // of String.split(), and set the limit argument to a // negative value; otherwise any trailing backslashes // are lost.) for (int i = 0; i < splitTokens.length; i++) { splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\\""), "\""); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\t"), "\t"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\n"), "\n"); splitTokens[i] = splitTokens[i].replaceAll(Matcher.quoteReplacement("\\r"), "\r"); } // TODO: // Make (some of?) the above optional; for ex., we // do need to restore the newlines when calculating UNFs; // But if we are subsetting these vectors in order to // create a new tab-delimited file, they will // actually break things! -- L.A. Jul. 28 2014 token = StringUtils.join(splitTokens, '\\'); // "compatibility mode" - a hack, to be able to produce // unfs identical to those produced by the "early" // unf5 jar; will be removed in production 4.0. // -- L.A. (TODO: ...) if (compatmode && !"".equals(token)) { if (token.length() > 128) { if ("".equals(token.trim())) { // don't ask... token = token.substring(0, 129); } else { token = token.substring(0, 128); //token = String.format(loc, "%.128s", token); token = token.trim(); //dbgLog.info("formatted and trimmed: "+token); } } else { if ("".equals(token.trim())) { // again, don't ask; // - this replicates some bugginness // that happens inside unf5; token = "null"; } else { token = token.trim(); } } } retVector[caseindex] = token; } } else if (isDouble) { try { // TODO: verify that NaN and +-Inf are // handled correctly here! -- L.A. // Verified: new Double("nan") works correctly, // resulting in Double.NaN; // Double("[+-]Inf") doesn't work however; // (the constructor appears to be expecting it // to be spelled as "Infinity", "-Infinity", etc. if ("inf".equalsIgnoreCase(token) || "+inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Double.POSITIVE_INFINITY; } else if ("-inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Double.NEGATIVE_INFINITY; } else if (token == null || token.equals("")) { // missing value: retVector[caseindex] = null; } else { retVector[caseindex] = new Double(token); } } catch (NumberFormatException ex) { dbgLog.warning("NumberFormatException thrown for " + token + " as Double"); retVector[caseindex] = null; // missing value // TODO: ? } } else if (isLong) { try { retVector[caseindex] = new Long(token); } catch (NumberFormatException ex) { retVector[caseindex] = null; // assume missing value } } else if (isFloat) { try { if ("inf".equalsIgnoreCase(token) || "+inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Float.POSITIVE_INFINITY; } else if ("-inf".equalsIgnoreCase(token)) { retVector[caseindex] = java.lang.Float.NEGATIVE_INFINITY; } else if (token == null || token.equals("")) { // missing value: retVector[caseindex] = null; } else { retVector[caseindex] = new Float(token); } } catch (NumberFormatException ex) { dbgLog.warning("NumberFormatException thrown for " + token + " as Float"); retVector[caseindex] = null; // assume missing value (TODO: ?) } } caseindex++; if (bytecount == bytesRead - 1) { byteoffset = 0; } else { byteoffset = bytecount + 1; } } else { if (bytecount == bytesRead - 1) { // We've reached the end of the buffer; // This means we'll save whatever unused bytes left in // it - i.e., the bytes between the last new line // encountered and the end - in the leftover buffer. // *EXCEPT*, there may be a case of a very long String // that is actually longer than MAX_COLUMN_BUFFER, in // which case it is possible that we've read through // an entire buffer of bytes without finding any // new lines... in this case we may need to add this // entire byte buffer to an already existing leftover // buffer! if (leftover == null) { leftover = new byte[(int) bytesRead - byteoffset]; System.arraycopy(columnBytes, byteoffset, leftover, 0, (int) bytesRead - byteoffset); } else { if (byteoffset != 0) { throw new IOException( "Reached the end of the byte buffer, with some leftover left from the last read; yet the offset is not zero!"); } byte[] merged = new byte[leftover.length + (int) bytesRead]; System.arraycopy(leftover, 0, merged, 0, leftover.length); System.arraycopy(columnBytes, byteoffset, merged, leftover.length, (int) bytesRead); //leftover = null; leftover = merged; merged = null; } byteoffset = 0; } } bytecount++; } bytesReadTotal += bytesRead; in.clear(); if (columnLength - bytesReadTotal < MAX_COLUMN_BUFFER) { in.limit((int) (columnLength - bytesReadTotal)); } } fc.close(); if (caseindex != casecount) { throw new IOException("Faile to read " + casecount + " tokens for column " + column); //System.out.println("read "+caseindex+" tokens instead of expected "+casecount+"."); } return retVector; }
From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java
/** * Load a request from a file, provided by a filename. * /*from www . j a v a2 s.c o m*/ * @param requestFileName The name of the file to load the request from. * @param parametersMap Map of parameters to replace within the parametrized values of the request. * @return String contents of the file. * @throws IOException Thrown on inability to read from the file. */ private String loadRequestFromFile(String requestFileName, Map<String, String> parametersMap) throws IOException { String requestFilePath; String requestData; requestFilePath = pathToRequestsDirectory + requestFileName; requestData = getFileContent(requestFilePath); Properties prop = (Properties) connectorProperties.clone(); if (parametersMap != null) { prop.putAll(parametersMap); } Matcher matcher = Pattern.compile("%s\\(([A-Za-z0-9]*)\\)", Pattern.DOTALL).matcher(requestData); while (matcher.find()) { String key = matcher.group(1); requestData = requestData.replaceAll("%s\\(" + key + "\\)", Matcher.quoteReplacement(prop.getProperty(key))); } return requestData; }
From source file:com.cisco.dvbu.ps.deploytool.dao.jdbcapi.RegressionInputFileJdbcDAOImpl.java
/** * Generates security query XML for a given CIS instance and other input parameters, such as domain, user, published datasource and others. * This method uses the same <newFileParams> structure as "generateInputFile" does and the same rules for getting the Queries, Procedures and Web Services * /*w w w . j ava 2 s.c o m*/ * @param cisServerConfig composite server object used for connections * @param regressionConfig regression config object * @param regressionQueries regression query object * @param regressionSecurityQueries regression security query object * @param mode "OVERWRITE" or "APPEND" to the existing regressionSecurityQueries object * * @return RegressionSecurityQueryType updated regression security object * * @throws CompositeException */ public RegressionSecurityQueriesType generateSecurityQueriesXML(CompositeServer cisServerConfig, RegressionTestType regressionConfig, RegressionQueriesType regressionQueries, RegressionSecurityQueriesType regressionSecurityQueries, String mode) throws CompositeException { RegressionSecurityQueriesType regressionSecurityQueriesReturn = new RegressionSecurityQueriesType(); // Initialize all variables String prefix = "generateSecurityQueryXML"; String rsqId = null; String rsqIds = ""; int rsqIdsCount = 0; totalQueriesGenerated = 0; totalProceduresGenerated = 0; totalWebServicesGenerated = 0; boolean getActualLinkType = true; // Get the DEBUG3 value from the property file setGlobalProperties(); populateConfigValues(regressionConfig, regressionQueries); // If the mode=APPEND, then determine how may many regression security queries Ids (rsqIds) currently exist and create a list of the ids to be used during appending. if (mode.equalsIgnoreCase("APPEND")) { if (regressionSecurityQueries.getRegressionSecurityQuery() != null && regressionSecurityQueries.getRegressionSecurityQuery().size() > 0) { List<RegressionSecurityQueryType> regressionSecurityQueryList = regressionSecurityQueries .getRegressionSecurityQuery(); // Loop over the list of regression security queries for (RegressionSecurityQueryType regressionSecurityQueryListLoop : regressionSecurityQueryList) { if (regressionSecurityQueryListLoop.getId() != null && regressionSecurityQueryListLoop.getId().length() > 0) { rsqIds = rsqIds + regressionSecurityQueryListLoop.getId() + " "; rsqIdsCount++; // Add the existing item to the return variable regressionSecurityQueriesReturn.getRegressionSecurityQuery() .add(regressionSecurityQueryListLoop); } } } } // Begin the input file generation if (this.needQueries) { /** * [QUERY] * database=MYTEST * SELECT count(1) cnt FROM CAT1.SCH1.customers */ RegressionItem[] items = buildQueriesString(cisServerConfig, regressionConfig); // Output the query to the input file for (int i = 0; i < items.length; i++) { // Initialize variables RegressionSecurityQueryType rsq = new RegressionSecurityQueryType(); RegressionItem item = new RegressionItem(); item = items[i]; boolean queryFound = queryExistsInRegressionSecurityList(item, regressionSecurityQueries); if (!queryFound) { // Calculate the rsqId rsqId = ""; while (true) { ++rsqIdsCount; rsqId = "rsq" + rsqIdsCount; if (!rsqIds.toLowerCase().contains(rsqId)) { break; } } // Set the Regression Security Query Type rsq.setQueryType("QUERY"); rsq.setId(rsqId); rsq.setDatasource(item.database); rsq.setQuery(item.input); // patterns: table | schema.table | cat.schema.table rsq.setResourcePath(item.resourcePath); rsq.setResourceType(item.resourceType); // Add the existing item to the return variable regressionSecurityQueriesReturn.getRegressionSecurityQuery().add(rsq); // Add debug statement to log output when debug3=true CommonUtils.writeOutput( "Added query to query list: resource path=" + item.resourcePath + " type=" + item.resourceType + " query=" + item.input, prefix, "-debug3", logger, debug1, debug2, debug3); } } } if (this.needProcs) { if (this.useSelectForProcs) { /** * [PROCEDURE] * database=MYTEST * SELECT * FROM CAT1.SCH1.LookupProduct(1) */ RegressionItem[] items = buildProcsStringSelectSyntax(cisServerConfig, regressionConfig); // Output the query to the input file for (int i = 0; i < items.length; i++) { // Initialize variables RegressionSecurityQueryType rsq = new RegressionSecurityQueryType(); RegressionItem item = new RegressionItem(); item = items[i]; boolean queryFound = queryExistsInRegressionSecurityList(item, regressionSecurityQueries); if (!queryFound) { // Calculate the rsqId rsqId = ""; while (true) { ++rsqIdsCount; rsqId = "rsq" + rsqIdsCount; if (!rsqIds.toLowerCase().contains(rsqId)) { break; } } // Set the Regression Security Query Type rsq.setQueryType("PROCEDURE"); rsq.setId(rsqId); rsq.setDatasource(item.database); rsq.setQuery(item.input); // patterns: table | schema.table | cat.schema.table if (item.outTypes != null && item.outTypes.length > 0) { String outTypes = null; for (int j = 0; j < item.outTypes.length; j++) { if (outTypes == null) { outTypes = ""; } else { outTypes = outTypes + ", "; } outTypes = outTypes + item.outTypes[j]; } rsq.setProcOutTypes(outTypes); } rsq.setResourcePath(item.resourcePath); rsq.setResourceType(item.resourceType); // Add the existing item to the return variable regressionSecurityQueriesReturn.getRegressionSecurityQuery().add(rsq); // Add debug statement to log output when debug3=true CommonUtils.writeOutput( "Added procedure to query list: resource path=" + item.resourcePath + " type=" + item.resourceType + " query=" + item.input, prefix, "-debug3", logger, debug1, debug2, debug3); } } } else { /** * [PROCEDURE] * database=MYTEST * CALL CAT1.SCH1.LookupProduct(1) */ RegressionItem[] items = buildProcsStringCallSyntax(cisServerConfig, regressionConfig); // Output the query to the input file for (int i = 0; i < items.length; i++) { // Initialize variables RegressionSecurityQueryType rsq = new RegressionSecurityQueryType(); RegressionItem item = new RegressionItem(); item = items[i]; boolean queryFound = queryExistsInRegressionSecurityList(item, regressionSecurityQueries); if (!queryFound) { // Calculate the rsqId rsqId = ""; while (true) { ++rsqIdsCount; rsqId = "rsq" + rsqIdsCount; if (!rsqIds.toLowerCase().contains(rsqId)) { break; } } // Set the Regression Security Query Type rsq.setQueryType("PROCEDURE"); rsq.setId(rsqId); rsq.setDatasource(item.database); rsq.setQuery(item.input); // patterns: table | schema.table | cat.schema.table if (item.outTypes != null && item.outTypes.length > 0) { String outTypes = null; for (int j = 0; j < item.outTypes.length; j++) { if (outTypes == null) { outTypes = ""; } else { outTypes = outTypes + ", "; } outTypes = outTypes + item.outTypes[j]; } rsq.setProcOutTypes(outTypes); } rsq.setResourcePath(item.resourcePath); rsq.setResourceType(item.resourceType); // Add the existing item to the return variable regressionSecurityQueriesReturn.getRegressionSecurityQuery().add(rsq); // Add debug statement to log output when debug3=true CommonUtils.writeOutput( "Added call procedure to query list: resource path=" + item.resourcePath + " type=" + item.resourceType + " query=" + item.input, prefix, "-debug3", logger, debug1, debug2, debug3); } } } } if (this.needWs) { /** * [WEB_SERVICE] * database=testWebService00_NoParams_wrapped * path=/soap11/testWebService00_NoParams_wrapped * action=ViewSales * encrypt=false * contentType=text/xml;charset=UTF-8 * <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/"> * <soapenv:Header/> * <soapenv:Body> * <ns1:ViewSales> * <ns1:ViewSalesInput></ns1:ViewSalesInput> * </ns1:ViewSales> * </soapenv:Body> * </soapenv:Envelope> */ RegressionItem[] items = buildWsString(cisServerConfig, regressionConfig, getActualLinkType); // Output the query to the input file for (int i = 0; i < items.length; i++) { // Initialize variables RegressionSecurityQueryType rsq = new RegressionSecurityQueryType(); RegressionItem item = new RegressionItem(); item = items[i]; boolean queryFound = queryExistsInRegressionSecurityList(item, regressionSecurityQueries); if (!queryFound) { // Calculate the rsqId rsqId = ""; while (true) { ++rsqIdsCount; rsqId = "rsq" + rsqIdsCount; if (!rsqIds.toLowerCase().contains(rsqId)) { break; } } // Set the Regression Security Query Type rsq.setQueryType("WEB_SERVICE"); rsq.setId(rsqId); rsq.setDatasource(item.database); rsq.setWsPath(item.path); rsq.setWsAction(item.action); rsq.setWsEncrypt(String.valueOf(item.encrypt)); rsq.setWsContentType(item.contentType); rsq.setQuery(item.input); rsq.setResourcePath(item.resourcePath); rsq.setResourceType(item.resourceType); // Add the existing item to the return variable regressionSecurityQueriesReturn.getRegressionSecurityQuery().add(rsq); // Add debug statement to log output when debug3=true String queryNoLines = item.input.replaceAll(Pattern.quote("\n"), Matcher.quoteReplacement("")); CommonUtils.writeOutput( "Added web service to query list: resource path=" + item.resourcePath + " type=" + item.resourceType + " query=" + queryNoLines, prefix, "-debug3", logger, debug1, debug2, debug3); } } } return regressionSecurityQueriesReturn; }
From source file:com.atlassian.jira.functest.framework.AdministrationImpl.java
private String replaceTokens(String source, final Map<String, String> replacements) { for (final String token : replacements.keySet()) { final int index = source.indexOf(token); if (index < 0) { Assert.fail("Replacement token '" + token + "' not found"); }/*from w ww .j a v a2 s. co m*/ source = source.replaceAll(token, Matcher.quoteReplacement(replacements.get(token))); } return source; }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java
private void decodeData(BufferedReader reader) throws IOException { List<String[]> dataTableList = new ArrayList<String[]>(); List<String[]> dateFormatList = new ArrayList<String[]>(); int[] variableTypeFinal = new int[varQnty]; // create a File object to save the tab-delimited data file File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab"); smd.getFileInformation().put("tabDelimitedDataFileLocation", tabDelimitedDataFile.getAbsolutePath()); FileOutputStream fileOutTab = null; PrintWriter pwout = null;/*from ww w. j ava 2 s .com*/ try { fileOutTab = new FileOutputStream(tabDelimitedDataFile); pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true); variableFormatTypeList = new String[varQnty]; for (int i = 0; i < varQnty; i++) { variableFormatTypeList[i] = SPSSConstants.FORMAT_CATEGORY_TABLE .get(printFormatTable.get(variableNameList.get(i))); formatCategoryTable.put(variableNameList.get(i), variableFormatTypeList[i]); } // contents (variable) checker concering decimals Arrays.fill(variableTypeFinal, 0); // raw-case counter int j = 0; // case // use while instead for because the number of cases (observations) is usually unknown FBLOCK: while (true) { j++; // case(row)-wise storage object; to be updated after each row-reading String[] casewiseRecord = new String[varQnty]; String[] caseWiseDateFormat = new String[varQnty]; String[] casewiseRecordForTabFile = new String[varQnty]; // warning: the above object is later shallow-copied to the // data object for calculating a UNF value/summary statistics // for (int i = 0; i < varQnty; i++) { // check the type of this variable boolean isStringType = variableTypeTable.get(variableNameList.get(i)) > 0 ? true : false; if (isStringType) { // String case variableTypeFinal[i] = -1; StringBuilder sb_StringLengthBase30 = new StringBuilder(""); int stringLengthBase10 = 0; String buffer = ""; char[] tmp = new char[1]; int nint; while ((nint = reader.read(tmp)) > 0) { buffer = Character.toString(tmp[0]); if (buffer.equals("/")) { break; } else if (buffer.equals("Z")) { if (i == 0) { // the reader has passed the last case; subtract 1 from the j counter caseQnty = j - 1; break FBLOCK; } } else { sb_StringLengthBase30.append(buffer); } } if (nint == 0) { // no more data to be read (reached the eof) caseQnty = j - 1; break FBLOCK; } dbgLog.finer( j + "-th case " + i + "=th var:datum length=" + sb_StringLengthBase30.toString()); // this length value should be a positive integer Matcher mtr = pattern4positiveInteger.matcher(sb_StringLengthBase30.toString()); if (mtr.matches()) { stringLengthBase10 = Integer.valueOf(sb_StringLengthBase30.toString(), 30); } else { // reading error case throw new IOException("reading F(data) section: string: length is not integer"); } // read this string-variable's contents after "/" char[] char_datumString = new char[stringLengthBase10]; reader.read(char_datumString); String datum = new String(char_datumString); casewiseRecord[i] = datum; casewiseRecordForTabFile[i] = "\"" + datum.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\""; // end of string case } else { // numeric case StringBuilder sb_datumNumericBase30 = new StringBuilder(""); boolean isMissingValue = false; String datum = null; String datumForTabFile = null; String datumDateFormat = null; String buffer = ""; char[] tmp = new char[1]; int nint; while ((nint = reader.read(tmp)) > 0) { sb_datumNumericBase30.append(buffer); buffer = Character.toString(tmp[0]); if (buffer.equals("/")) { break; } else if (buffer.equals("Z")) { if (i == 0) { // the reader has passed the last case // subtract 1 from the j counter dbgLog.fine("Z-mark was detected"); caseQnty = j - 1; break FBLOCK; } } else if (buffer.equals("*")) { // '*' is the first character of the system missing value datumForTabFile = MissingValueForTextDataFile; datum = null; isMissingValue = true; // read next char '.' as part of the missing value reader.read(tmp); buffer = Character.toString(tmp[0]); break; } } if (nint == 0) { // no more data to be read; reached the eof caseQnty = j - 1; break FBLOCK; } // follow-up process for non-missing-values if (!isMissingValue) { // decode a numeric datum as String String datumNumericBase30 = sb_datumNumericBase30.toString(); Matcher matcher = pattern4Integer.matcher(datumNumericBase30); if (matcher.matches()) { // integer case datum = Long.valueOf(datumNumericBase30, 30).toString(); } else { // double case datum = doubleNumberFormatter.format(base30Tobase10Conversion(datumNumericBase30)); } // now check format (if date or time) String variableFormatType = variableFormatTypeList[i]; if (variableFormatType.equals("date")) { variableTypeFinal[i] = -1; long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET; datum = sdf_ymd.format(new Date(dateDatum)); datumDateFormat = sdf_ymd.toPattern(); } else if (variableFormatType.equals("time")) { variableTypeFinal[i] = -1; int formatDecimalPointPosition = formatDecimalPointPositionList.get(i); if (printFormatTable.get(variableNameList.get(i)).equals("DTIME")) { if (datum.indexOf(".") < 0) { long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_BIAS; datum = sdf_dhms.format(new Date(dateDatum)); // don't save date format for dtime } else { // decimal point included String[] timeData = datum.split("\\."); long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_BIAS; StringBuilder sb_time = new StringBuilder( sdf_dhms.format(new Date(dateDatum))); if (formatDecimalPointPosition > 0) { sb_time.append( "." + timeData[1].substring(0, formatDecimalPointPosition)); } datum = sb_time.toString(); // don't save date format for dtime } } else if (printFormatTable.get(variableNameList.get(i)).equals("DATETIME")) { if (datum.indexOf(".") < 0) { long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET; datum = sdf_ymdhms.format(new Date(dateDatum)); datumDateFormat = sdf_ymdhms.toPattern(); } else { // decimal point included String[] timeData = datum.split("\\."); long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_OFFSET; StringBuilder sb_time = new StringBuilder( sdf_ymdhms.format(new Date(dateDatum))); if (formatDecimalPointPosition > 0) { sb_time.append( "." + timeData[1].substring(0, formatDecimalPointPosition)); } datum = sb_time.toString(); datumDateFormat = sdf_ymdhms.toPattern() + (formatDecimalPointPosition > 0 ? ".S" : ""); } } else if (printFormatTable.get(variableNameList.get(i)).equals("TIME")) { if (datum.indexOf(".") < 0) { long dateDatum = Long.parseLong(datum) * 1000L; datum = sdf_hms.format(new Date(dateDatum)); datumDateFormat = sdf_hms.toPattern(); } else { // decimal point included String[] timeData = datum.split("\\."); long dateDatum = Long.parseLong(timeData[0]) * 1000L; StringBuilder sb_time = new StringBuilder( sdf_hms.format(new Date(dateDatum))); if (formatDecimalPointPosition > 0) { sb_time.append( "." + timeData[1].substring(0, formatDecimalPointPosition)); } datum = sb_time.toString(); datumDateFormat = sdf_hms.toPattern() + (formatDecimalPointPosition > 0 ? ".S" : ""); } } } else if (variableFormatType.equals("other")) { if (printFormatTable.get(variableNameList.get(i)).equals("WKDAY")) { // day of week variableTypeFinal[i] = -1; datum = SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(datum) - 1); } else if (printFormatTable.get(variableNameList.get(i)).equals("MONTH")) { // month variableTypeFinal[i] = -1; datum = SPSSConstants.MONTH_LIST.get(Integer.valueOf(datum) - 1); } } // since value is not missing, set both values to be the same datumForTabFile = datum; // decimal-point check (variable is integer or not) if (variableTypeFinal[i] == 0) { if (datum.indexOf(".") >= 0) { variableTypeFinal[i] = 1; decimalVariableSet.add(i); } } } casewiseRecord[i] = datum; caseWiseDateFormat[i] = datumDateFormat; casewiseRecordForTabFile[i] = datumForTabFile; } // end: if: string vs numeric variable } // end:for-loop-i (variable-wise loop) // print the i-th case; use casewiseRecord to dump the current case to the tab-delimited file pwout.println(StringUtils.join(casewiseRecordForTabFile, "\t")); // store the current case-holder object to the data object for later operations such as UNF/summary statistics dataTableList.add(casewiseRecord); dateFormatList.add(caseWiseDateFormat); } // end: while-block } finally { // close the print writer if (pwout != null) { pwout.close(); } } smd.setDecimalVariables(decimalVariableSet); smd.getFileInformation().put("caseQnty", caseQnty); // store data in column(variable)-wise for calculating variable-wise statistics Object[][] dataTable2 = new Object[varQnty][caseQnty]; String[][] dateFormat = new String[varQnty][caseQnty]; for (int jl = 0; jl < caseQnty; jl++) { for (int jk = 0; jk < varQnty; jk++) { dataTable2[jk][jl] = dataTableList.get(jl)[jk]; dateFormat[jk][jl] = dateFormatList.get(jl)[jk]; } } String[] unfValues = new String[varQnty]; for (int k = 0; k < varQnty; k++) { int variableTypeNumer = variableTypeFinal[k]; unfValues[k] = getUNF(dataTable2[k], dateFormat[k], variableTypeNumer, k); } String fileUnfValue = UNF5Util.calculateUNF(unfValues); porDataSection.setUnf(unfValues); porDataSection.setFileUnf(fileUnfValue); porDataSection.setData(dataTable2); smd.setVariableUNF(unfValues); smd.getFileInformation().put("fileUNF", fileUnfValue); }
From source file:org.azyva.dragom.cliutil.CliUtil.java
/** * Initializes the Java Util Logging framework by implementing replaceable * properties in the configuration file. * * <p>If the java.util.logging.config.file system property is defined, this method * does nothing, leaving the default initialization process be used. * * <p>If the java.util.logging.config.file system property is not defined and the * org.azyva.dragom.JavaUtilLoggingConfigFile system property is defined, this * method calls LogManager.readConfiguration with an InputStream which represents * the file but with property references replaced by the corresponding system * property.// ww w. j a v a2s .c o m * * <p>If none of these two system properties are defined, this method does * nothing. */ public static void initJavaUtilLogging() { String javaUtilLoggingConfigFile; String javaUtilLoggingConfig; Matcher matcher; StringBuffer stringBufferNewJavaUtilLoggingConfig; Util.applyDragomSystemProperties(); if ((System.getProperty("java.util.logging.config.file") == null) && ((javaUtilLoggingConfigFile = System .getProperty(CliUtil.SYS_PROPERTY_JAVA_UTIL_LOGGING_CONFIG_FILE)) != null)) { try { javaUtilLoggingConfig = new String(Files.readAllBytes(Paths.get(javaUtilLoggingConfigFile))); matcher = CliUtil.patternPropertyReference.matcher(javaUtilLoggingConfig); stringBufferNewJavaUtilLoggingConfig = new StringBuffer(); while (matcher.find()) { String property; String value; property = matcher.group(1); value = System.getProperty(property); if (value == null) { throw new RuntimeException("System property " + property + " referenced in " + javaUtilLoggingConfigFile + " is not defined."); } // In a Properties file, \ must be escaped. value = value.replace("\\", "\\\\"); matcher.appendReplacement(stringBufferNewJavaUtilLoggingConfig, Matcher.quoteReplacement(value)); } matcher.appendTail(stringBufferNewJavaUtilLoggingConfig); java.util.logging.LogManager.getLogManager().readConfiguration( new ByteArrayInputStream(stringBufferNewJavaUtilLoggingConfig.toString().getBytes())); } catch (IOException ioe) { throw new RuntimeException(ioe); } } }
From source file:com.github.aliteralmind.codelet.CodeletBaseConfig.java
/** <p>Load configuration and get the instance. Call only once.</p> /*from w w w . ja va2 s . c o m*/ * @param props May not be {@code null}, and must be a valid {@linkplain CodeletBaseConfig Codelet properties} file. * @return #INSTANCE * @exception IllegalStateException If configuration was already loaded. * @see com.github.xbn.util.PropertiesUtil */ static final CodeletBaseConfig loadConfigGetInstance(Properties props, String config_baseDir, Iterator<String> externalJDDocRoot_configLineItr, Iterator<String> rqdDbgLevels_configLineItr, Iterator<String> debugLevels_configLineItr) throws NoSuchFileException, AccessDeniedException, MalformedURLException, IOException, InterruptedException { if (wasLoaded()) { throw new IllegalStateException("wasLoaded() is true."); } String dbgLvlStr = null; try { dbgLvlStr = props.getProperty(GLOBAL_DEBUG_LEVEL, ""); } catch (RuntimeException rx) { throw CrashIfObject.nullOrReturnCause(props, "props", null, rx); } dbgLevel = DebugLevel.getFromStringOff12345(dbgLvlStr, GLOBAL_DEBUG_LEVEL); String dbgAptrStr = props.getProperty(DEBUG_DESTINATION, ""); if (dbgAptrStr.equals("console")) { dbgAptr = TextAppenter.CONSOLE; doDebugToConsole = true; } else { dbgAptr = NewTextAppenterFor.file(dbgAptrStr, AppendOrOverwrite.APPEND); doDebugToConsole = false; } if (dbgLevel.isOn()) { debugln("Loading Codelet configuration"); debugln(" Loading base config"); debugln(" Loading debug level config file..."); } //Named debuggers cannet be used until the named-level map is created! int namedDebugLevelsRqd = 0; Map<String, DebugLevel> rqdDbgLevelNameMap = NamedDebuggers.newMapFromConfigFile(null, rqdDbgLevels_configLineItr, "rqdDbgLevels_configLineItr", null); //debug namedDebugLevelsRqd = rqdDbgLevelNameMap.size(); namedDebugLevels = new NamedDebuggers(rqdDbgLevelNameMap, debugLevels_configLineItr, "rqdDbgLevelNameMap", null); //debug //NOW named debuggers can be used. if (isDebugOn(null, "zzconfiguration.nameddebuglevels.listallafterload")) { debugln("All named debuggers:" + MapUtil.toString(namedDebugLevels.getMap(), null)); } namedDebugLevels.setAllQueriesDebug(getDebugApblIfOn(null, "zzconfiguration.nameddebuglevels.eachquery")); String baseDirBaseRplcmntQuoted = Matcher.quoteReplacement(props.getProperty(BASE_DIR_BASE_DIR, "")); xmplSrcBaseDir = get1stDollarBASERplcd(props.getProperty(EXAMPLE_CLASS_SRC_BASE_DIR, ""), baseDirBaseRplcmntQuoted); String enclosingBaseDirPropVal = props.getProperty(ENCLOSING_CLASS_SRC_BASE_DIRS, ""); enclosingBaseDirs = null; if (enclosingBaseDirPropVal.length() == 0) { throw new IllegalArgumentException( "No values for " + ENCLOSING_CLASS_SRC_BASE_DIRS + ". At least one required."); } else { enclosingBaseDirs = enclosingBaseDirPropVal.split(","); for (int i = 0; i < enclosingBaseDirs.length; i++) { enclosingBaseDirs[i] = get1stDollarBASERplcd(enclosingBaseDirs[i], baseDirBaseRplcmntQuoted); new PathMustBe().existing().readable().getOrCrashIfBad(enclosingBaseDirs[i], "Element " + i + " in " + ENCLOSING_CLASS_SRC_BASE_DIRS); } } enclosingBaseDirList = Collections.unmodifiableList(Arrays.asList(enclosingBaseDirs)); char gapNamePreChar = PropertiesUtil.getWithEmptyDefault(props, GAP_NAME_PREFIX_CHAR, Empty.OK, GapCharConfig.DEFAULT_PREFIX_CHAR); char gapNamePostChar = PropertiesUtil.getWithEmptyDefault(props, GAP_NAME_POSTFIX_CHAR, Empty.OK, GapCharConfig.DEFAULT_POSTFIX_CHAR); String gapLiteralPre = props.getProperty(GAP_NAME_LITERAL_PREFIX, GapCharConfig.DEFAULT_LITERAL_PREFIX); String gapLiteralPost = props.getProperty(GAP_NAME_LITERAL_POSTFIX, GapCharConfig.DEFAULT_LITERAL_POSTFIX); gapCharConfig = new GapCharConfig(gapNamePreChar, gapNamePostChar, gapLiteralPre, gapLiteralPost); String defaultAlterGetterClsNm = props.getProperty(DEFAULT_ALTERERS_CLASS_NAME, ""); if (defaultAlterGetterClsNm.length() == 0) { defaultAlterGetter = new DefaultDefaultAlterGetter(); if (isDebugOn(null, "zzconfiguration.progress")) { debugln(" No default-alter-getter class name provided. Using DefaultDefaultAlterGetter"); } } else { defaultAlterGetter = ReflectRtxUtil.<DefaultAlterGetter>getNewInstanceFromNoParamCnstr( defaultAlterGetterClsNm, DefaultAlterGetter.class, getDebugApblIfOn(null, "zzconfiguration.progress")); } String tmplBaseDir = props.getProperty(DEFAULT_TPML_DIR_PREFIX, ""); defaultSrcTmplPath = get1stDollarBASERplcd(tmplBaseDir + props.getProperty(DEFAULT_SRC_CODE_TMPL_PATH, ""), baseDirBaseRplcmntQuoted); defaultOutTmplPath = get1stDollarBASERplcd(tmplBaseDir + props.getProperty(DEFAULT_DOT_OUT_TMPL_PATH, ""), baseDirBaseRplcmntQuoted); defaultSrcAndOutTmplPath = get1stDollarBASERplcd( tmplBaseDir + props.getProperty(DEFAULT_AND_OUT_TMPL_PATH, ""), baseDirBaseRplcmntQuoted); defaultFileTextTmplPath = get1stDollarBASERplcd( tmplBaseDir + props.getProperty(DEFAULT_FILE_TEXT_TMPL_PATH, ""), baseDirBaseRplcmntQuoted); userExtraGapsClassNm = props.getProperty(USER_EXTRA_GAPS_CLASS_NAME, ""); customTmplDir = get1stDollarBASERplcd(props.getProperty(USER_TEMPLATE_BASE_DIR, ""), baseDirBaseRplcmntQuoted); blackWhiteList = FilenameBlackWhiteList.newFromProperties(props, ",", BLACK_WHITE_LIST_TYPE, BLACK_WHITE_LIST_CASE, BLACK_WHITE_PROPER_LIST, BLACK_WHITE_OVERRIDE_LIST, getDebugApblIfOn(null, "zzconfiguration.blackwhitelist.loading"), getDebugApblIfOn(null, "zzconfiguration.blackwhitelist.usage")); jdTgtClsMapInitCapacity = PropertiesUtil.getWithEmptyDefault(props, UNIQUE_JD_CLASS_TARGET_INIT_CAPACITY, Empty.OK, DEFAULT_JD_TARGET_CLASS_MAP_INIT_CAPACITY); doCrashIfAlterNotMade = PropertiesUtil.getWithEmptyDefault(props, ALTERATION_NOT_MADE_CRASH, "yes", "no", Empty.BAD, false); onlinePkgLstAttemptCount = PropertiesUtil.getWithEmptyDefault(props, PKGLIST_ONLINE_ATTEMPT_COUNT, Empty.OK, DEFAULT_ONLINE_PKGLST_ATTEMPTS); onlinePkgLstAttemptSleepMills = PropertiesUtil.getWithEmptyDefault(props, PKGLIST_ONLINE_ATTEMPT_SLEEP_MILLS, Empty.OK, DEFAULT_ONLINE_PKGLST_SLEEP_MILLS); doCrashIfOnlinePkgLstFails = PropertiesUtil.getWithEmptyDefault(props, PKGLIST_ONLINE_FAILS_BEHAVIOR, "crash", "warn", Empty.BAD, false); doAutoUpdateOfflinePkgLsts = PropertiesUtil.getWithEmptyDefault(props, AUTO_UPDATE_OFFLINE_PACKAGE_LISTS, "yes", "no", Empty.BAD, false); offlinePkgLstNamePost = props.getProperty(PKGLIST_OFFLINE_NAME_POSTFIX, ""); allDocRoots = AllOnlineOfflineDocRoots.newFromConfigLineIterator(externalJDDocRoot_configLineItr, config_baseDir + OFFLINE_PACKAGE_LIST_DIR_NAME + FILE_SEP, offlinePkgLstNamePost, onlinePkgLstAttemptCount, onlinePkgLstAttemptSleepMills, RefreshOffline.getForBoolean(doAutoUpdateOfflinePkgLsts), IfError.getCRASHIfTrue(doCrashIfOnlinePkgLstFails), getDebugApblIfOn(null, "zzconfiguration.progress"), getDebugAptr().getAppendable()); //Required!! if (isDebugOn(null, "zzconfiguration.allvaluessummary")) { debugln(" Codelet base-configuration loaded:"); debugln(" - " + EXAMPLE_CLASS_SRC_BASE_DIR + ": \"" + xmplSrcBaseDir + "\""); debugln(" - " + ENCLOSING_CLASS_SRC_BASE_DIRS + ": \"" + Arrays.toString(enclosingBaseDirList.toArray()) + "\""); debugln(" - " + DEFAULT_ALTERERS_CLASS_NAME + ": " + ((defaultAlterGetter == null) ? null : defaultAlterGetter.getClass().getName())); debugln(" Templates:"); debugln(" - Gap-name character configuration: " + gapCharConfig); debugln(" - " + USER_EXTRA_GAPS_CLASS_NAME + ": \"" + userExtraGapsClassNm + "\""); debugln(" - " + DEFAULT_TPML_DIR_PREFIX + ": \"" + tmplBaseDir + "\""); debugln(" - " + DEFAULT_SRC_CODE_TMPL_PATH + ": \"" + defaultSrcTmplPath + "\""); debugln(" - " + DEFAULT_DOT_OUT_TMPL_PATH + ": \"" + defaultOutTmplPath + "\""); debugln(" - " + DEFAULT_AND_OUT_TMPL_PATH + ": \"" + defaultSrcAndOutTmplPath + "\""); debugln(" - " + DEFAULT_FILE_TEXT_TMPL_PATH + ": \"" + defaultFileTextTmplPath + "\""); debugln(" - " + USER_TEMPLATE_BASE_DIR + ": \"" + customTmplDir + "\""); debugln(" JavaDoc:"); debugln(" - " + UNIQUE_JD_CLASS_TARGET_INIT_CAPACITY + ": " + jdTgtClsMapInitCapacity); debugln(" - " + PKGLIST_ONLINE_ATTEMPT_COUNT + ": " + onlinePkgLstAttemptCount); debugln(" - " + PKGLIST_ONLINE_ATTEMPT_SLEEP_MILLS + ": " + onlinePkgLstAttemptSleepMills); debugln(" - doCrashIfOnlinePackageListFailure(): " + doCrashIfOnlinePkgLstFails); debugln(" - doAutoUpdateOfflinePackageLists(): " + doAutoUpdateOfflinePkgLsts); debugln(" - doAutoUpdateOfflinePackageLists(): " + doAutoUpdateOfflinePkgLsts); debugln(" - doCrashIfAlterNotMade(): " + doCrashIfAlterNotMade); debugln(" - " + PKGLIST_OFFLINE_NAME_POSTFIX + ": \"" + offlinePkgLstNamePost + "\""); debugln(" - getAllJavaDocRoots(): " + allDocRoots); debugln(" Debugging:"); debugln(" - " + GLOBAL_DEBUG_LEVEL + ": " + dbgLevel); debugln(" - " + DEBUG_DESTINATION + ": " + dbgAptr); debugln(" - Black/white list: " + blackWhiteList); debugln(" - Named debuggers: " + namedDebugLevels.getMap().size() + " (" + namedDebugLevelsRqd + " required)"); debugln(" (done--ready to load CodeletTemplateConfig)"); } wasLoaded = true; return INSTANCE; }
From source file:org.openddr.simpleapi.oddr.ODDRService.java
public PropertyValues getPropertyValues(Evidence evdnc, PropertyRef[] prs) throws NameException { Device deviceFound = null;//from w w w .j a v a 2 s . c om Browser browserFound = null; OperatingSystem osFound = null; boolean deviceIdentified = false; boolean browserIdentified = false; boolean osIdentified = false; UserAgent deviceUA = null; UserAgent browserUA = null; JexlEngine jexl = new JexlEngine(); ODDRPropertyValues ret = new ODDRPropertyValues(); Map<String, Vocabulary> vocabularies = vocabularyHolder.getVocabularies(); for (PropertyRef propertyRef : prs) { VocabularyProperty vocabularyProperty = vocabularyHolder.existProperty( propertyRef.getLocalPropertyName(), propertyRef.getAspectName(), propertyRef.getNamespace()); Vocabulary vocabulary = vocabularies.get(propertyRef.getNamespace()); if (ASPECT_DEVICE.equals(propertyRef.getAspectName())) { if (!deviceIdentified) { if (deviceUA == null) { deviceUA = UserAgentFactory.newDeviceUserAgent(evdnc); } if (evdnc instanceof BufferedODDRHTTPEvidence) { deviceFound = ((BufferedODDRHTTPEvidence) evdnc).getDeviceFound(); } if (deviceFound == null) { deviceFound = deviceIdentificator.get(deviceUA, this.threshold); } if (evdnc instanceof BufferedODDRHTTPEvidence) { ((BufferedODDRHTTPEvidence) evdnc).setDeviceFound(deviceFound); } deviceIdentified = true; } String property = null; if (deviceFound != null) { property = deviceFound.get(propertyRef.getLocalPropertyName()); ret.addProperty(new ODDRPropertyValue(property, vocabularyProperty.getType(), propertyRef)); } else { ret.addProperty(new ODDRPropertyValue(null, vocabularyProperty.getType(), propertyRef)); } continue; } else if (ASPECT_WEB_BROWSER.equals(propertyRef.getAspectName())) { //TODO: evaluate ua-pixels header in evidence if (!browserIdentified) { if (browserUA == null) { browserUA = UserAgentFactory.newBrowserUserAgent(evdnc); } if (evdnc instanceof BufferedODDRHTTPEvidence) { browserFound = ((BufferedODDRHTTPEvidence) evdnc).getBrowserFound(); } if (browserFound == null) { browserFound = browserIdentificator.get(browserUA, this.threshold); } if (evdnc instanceof BufferedODDRHTTPEvidence) { ((BufferedODDRHTTPEvidence) evdnc).setBrowserFound(browserFound); } browserIdentified = true; } String property = null; if (browserFound != null) { property = browserFound.get(propertyRef.getLocalPropertyName()); ret.addProperty(new ODDRPropertyValue(property, vocabularyProperty.getType(), propertyRef)); } else { ret.addProperty(new ODDRPropertyValue(null, vocabularyProperty.getType(), propertyRef)); } continue; } else if (ASPECT_OPERATIVE_SYSTEM.equals(propertyRef.getAspectName())) { //TODO: evaluate ua-os header in evidence if (!osIdentified) { if (deviceUA == null) { deviceUA = UserAgentFactory.newDeviceUserAgent(evdnc); } if (evdnc instanceof BufferedODDRHTTPEvidence) { osFound = ((BufferedODDRHTTPEvidence) evdnc).getOsFound(); } if (osFound == null) { osFound = osIdentificator.get(deviceUA, this.threshold); } if (evdnc instanceof BufferedODDRHTTPEvidence) { ((BufferedODDRHTTPEvidence) evdnc).setOsFound(osFound); } osIdentified = true; } String property = null; if (osFound != null) { property = osFound.get(propertyRef.getLocalPropertyName()); ret.addProperty(new ODDRPropertyValue(property, vocabularyProperty.getType(), propertyRef)); } else { ret.addProperty(new ODDRPropertyValue(null, vocabularyProperty.getType(), propertyRef)); } continue; } else if (ASPECT_GROUP.equals(propertyRef.getAspectName())) { try { String jexlExp = vocabularyProperty.getExpr(); Matcher m = groupRegexprPattern.matcher(jexlExp); while (m.find()) { String id = m.group(1); String propertyValueString = null; PropertyValue propertyValue = getPropertyValue(evdnc, vocabulary.getVocabularyVariables().get(id).getName(), vocabulary.getVocabularyVariables().get(id).getAspect(), vocabulary.getVocabularyVariables().get(id).getVocabulary()); propertyValueString = (propertyValue.exists() ? propertyValue.getString() : "-"); String toReplace = "$" + id; jexlExp = jexlExp.replaceAll(Matcher.quoteReplacement(toReplace), "'" + propertyValueString + "'"); } Expression e = jexl.createExpression(jexlExp); JexlContext jc = new MapContext(); Object o = e.evaluate(jc); ret.addProperty(new ODDRPropertyValue(o.toString(), vocabularyProperty.getType(), propertyRef)); } catch (Exception ex) { throw new RuntimeException(ex); } } } return ret; }
From source file:com.cisco.dvbu.ps.common.util.CommonUtils.java
/** * Encode CIS paths by replacing real values with encoded values. * Modify CommonConstants.pathCodes to modify the array of encoded values and real values. * /* ww w . j a va 2s .co m*/ * @param path * @return */ public static String encodePath(String path) { for (int i = 0; i < CommonConstants.pathCodes.length; i++) { String symbol = CommonConstants.pathCodes[i][0]; String encodedValue = CommonConstants.pathCodes[i][1]; // Encode "symbol" with "encodedValue" if (path.contains(symbol)) path = path.replaceAll(Matcher.quoteReplacement(symbol), Matcher.quoteReplacement(encodedValue)); } return path; }