List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:se.gothiaforum.controller.actorssearch.ActorsSearchController.java
private void addTheNonHighlightedTags(SolrDocument doc, StringBuilder tagsStr) { Object tags = doc.getFieldValue(Field.ASSET_TAG_NAMES); List<String> allTagsOfArticle = extractTags(tags); for (String tag : allTagsOfArticle) { // Only add those which aren't already existing since they are highlighted. if (tagsStr.indexOf(tag) == -1) { tagsStr.append("," + tag); }// w w w . jav a 2 s . co m } }
From source file:org.hdiv.web.servlet.tags.UrlTagHDIV.java
/** * Build the URL for the tag from the tag attributes and parameters. * @return the URL value as a String// w w w. j a v a 2 s. c o m * @throws JspException */ private String createUrl() throws JspException { HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); HttpServletResponse response = (HttpServletResponse) pageContext.getResponse(); StringBuilder url = new StringBuilder(); if (this.type == UrlType.CONTEXT_RELATIVE) { // add application context to url if (this.context == null) { url.append(request.getContextPath()); } else { url.append(this.context); } } if (this.type != UrlType.RELATIVE && this.type != UrlType.ABSOLUTE && !this.value.startsWith("/")) { url.append("/"); } url.append(replaceUriTemplateParams(this.value, this.params, this.templateParams)); url.append(createQueryString(this.params, this.templateParams, (url.indexOf("?") == -1))); String urlStr = url.toString(); urlStr = HDIVRequestUtils.composeLinkUrl(urlStr, request); // HDIVConfig hdivConfig = (HDIVConfig) HDIVUtil.getHDIVConfig(pageContext.getServletContext()); // // if (!HDIVRequestUtils.hasExtensionToExclude(urlStr, hdivConfig.getExcludedURLExtensions())) // { // if (HDIVRequestUtils.hasActionOrServletExtension(urlStr, hdivConfig.getProtectedURLPatterns())) { // urlStr = HDIVRequestUtils.addHDIVParameterIfNecessary((HttpServletRequest) pageContext.getRequest(), // urlStr, hdivConfig.isValidationInUrlsWithoutParamsActivated()); // } // } if (this.type != UrlType.ABSOLUTE) { // Add the session identifier if needed // (Do not embed the session identifier in a remote link!) urlStr = response.encodeURL(urlStr); } // HTML and/or JavaScript escape, if demanded. urlStr = isHtmlEscape() ? HtmlUtils.htmlEscape(urlStr) : urlStr; urlStr = this.javaScriptEscape ? JavaScriptUtils.javaScriptEscape(urlStr) : urlStr; return urlStr; }
From source file:org.pentaho.di.trans.steps.textfileinput.TextFileInput.java
public static final String[] guessStringsFromLine(VariableSpace space, LogChannelInterface log, String line, TextFileInputMeta inf, String delimiter, String enclosure, String escapeCharacter) throws KettleException { List<String> strings = new ArrayList<String>(); String pol; // piece of line try {// www. j av a 2 s . com if (line == null) { return null; } if (inf.getFileType().equalsIgnoreCase("CSV")) { // Split string in pieces, only for CSV! int pos = 0; int length = line.length(); boolean dencl = false; int len_encl = (enclosure == null ? 0 : enclosure.length()); int len_esc = (escapeCharacter == null ? 0 : escapeCharacter.length()); while (pos < length) { int from = pos; int next; boolean encl_found; boolean contains_escaped_enclosures = false; boolean contains_escaped_separators = false; // Is the field beginning with an enclosure? // "aa;aa";123;"aaa-aaa";000;... if (len_encl > 0 && line.substring(from, from + len_encl).equalsIgnoreCase(enclosure)) { if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRow", line.substring(from, from + len_encl))); } encl_found = true; int p = from + len_encl; boolean is_enclosure = len_encl > 0 && p + len_encl < length && line.substring(p, p + len_encl).equalsIgnoreCase(enclosure); boolean is_escape = len_esc > 0 && p + len_esc < length && line.substring(p, p + len_esc).equalsIgnoreCase(escapeCharacter); boolean enclosure_after = false; // Is it really an enclosure? See if it's not repeated twice or escaped! if ((is_enclosure || is_escape) && p < length - 1) { String strnext = line.substring(p + len_encl, p + 2 * len_encl); if (strnext.equalsIgnoreCase(enclosure)) { p++; enclosure_after = true; dencl = true; // Remember to replace them later on! if (is_escape) { contains_escaped_enclosures = true; } } } // Look for a closing enclosure! while ((!is_enclosure || enclosure_after) && p < line.length()) { p++; enclosure_after = false; is_enclosure = len_encl > 0 && p + len_encl < length && line.substring(p, p + len_encl).equals(enclosure); is_escape = len_esc > 0 && p + len_esc < length && line.substring(p, p + len_esc).equals(escapeCharacter); // Is it really an enclosure? See if it's not repeated twice or escaped! if ((is_enclosure || is_escape) && p < length - 1) { String strnext = line.substring(p + len_encl, p + 2 * len_encl); if (strnext.equals(enclosure)) { p++; enclosure_after = true; dencl = true; // Remember to replace them later on! if (is_escape) { contains_escaped_enclosures = true; // remember } } } } if (p >= length) { next = p; } else { next = p + len_encl; } if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.EndOfEnclosure", "" + p)); } } else { encl_found = false; boolean found = false; int startpoint = from; // int tries = 1; do { next = line.indexOf(delimiter, startpoint); // See if this position is preceded by an escape character. if (len_esc > 0 && next - len_esc > 0) { String before = line.substring(next - len_esc, next); if (escapeCharacter.equals(before)) { // take the next separator, this one is escaped... startpoint = next + 1; // tries++; contains_escaped_separators = true; } else { found = true; } } else { found = true; } } while (!found && next >= 0); } if (next == -1) { next = length; } if (encl_found) { pol = line.substring(from + len_encl, next - len_encl); if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.EnclosureFieldFound", "" + pol)); } } else { pol = line.substring(from, next); if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.NormalFieldFound", "" + pol)); } } if (dencl) { StringBuilder sbpol = new StringBuilder(pol); int idx = sbpol.indexOf(enclosure + enclosure); while (idx >= 0) { sbpol.delete(idx, idx + enclosure.length()); idx = sbpol.indexOf(enclosure + enclosure); } pol = sbpol.toString(); } // replace the escaped enclosures with enclosures... if (contains_escaped_enclosures) { String replace = escapeCharacter + enclosure; String replaceWith = enclosure; pol = Const.replace(pol, replace, replaceWith); } // replace the escaped separators with separators... if (contains_escaped_separators) { String replace = escapeCharacter + delimiter; String replaceWith = delimiter; pol = Const.replace(pol, replace, replaceWith); } // Now add pol to the strings found! strings.add(pol); pos = next + delimiter.length(); } if (pos == length) { if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.EndOfEmptyLineFound")); } strings.add(""); } } else { // Fixed file format: Simply get the strings at the required positions... for (int i = 0; i < inf.getInputFields().length; i++) { TextFileInputField field = inf.getInputFields()[i]; int length = line.length(); if (field.getPosition() + field.getLength() <= length) { strings.add(line.substring(field.getPosition(), field.getPosition() + field.getLength())); } else { if (field.getPosition() < length) { strings.add(line.substring(field.getPosition())); } else { strings.add(""); } } } } } catch (Exception e) { throw new KettleException( BaseMessages.getString(PKG, "TextFileInput.Log.Error.ErrorConvertingLine", e.toString()), e); } return strings.toArray(new String[strings.size()]); }
From source file:org.apache.zeppelin.jdbc.JDBCInterpreter.java
public Connection getConnection(String propertyKey, InterpreterContext interpreterContext) throws ClassNotFoundException, SQLException, InterpreterException, IOException { final String user = interpreterContext.getAuthenticationInfo().getUser(); Connection connection;/*from www .ja v a 2 s . c o m*/ if (propertyKey == null || basePropretiesMap.get(propertyKey) == null) { return null; } JDBCUserConfigurations jdbcUserConfigurations = getJDBCConfiguration(user); setUserProperty(propertyKey, interpreterContext); final Properties properties = jdbcUserConfigurations.getPropertyMap(propertyKey); final String url = properties.getProperty(URL_KEY); if (isEmpty(property.getProperty("zeppelin.jdbc.auth.type"))) { connection = getConnectionFromPool(url, user, propertyKey, properties); } else { UserGroupInformation.AuthenticationMethod authType = JDBCSecurityImpl.getAuthtype(property); switch (authType) { case KERBEROS: if (user == null) { connection = getConnectionFromPool(url, user, propertyKey, properties); } else { if (url.trim().startsWith("jdbc:hive")) { StringBuilder connectionUrl = new StringBuilder(url); Integer lastIndexOfUrl = connectionUrl.indexOf("?"); if (lastIndexOfUrl == -1) { lastIndexOfUrl = connectionUrl.length(); } connectionUrl.insert(lastIndexOfUrl, ";hive.server2.proxy.user=" + user + ";"); connection = getConnectionFromPool(connectionUrl.toString(), user, propertyKey, properties); } else { UserGroupInformation ugi = null; try { ugi = UserGroupInformation.createProxyUser(user, UserGroupInformation.getCurrentUser()); } catch (Exception e) { logger.error("Error in createProxyUser", e); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(e.getMessage()).append("\n"); stringBuilder.append(e.getCause()); throw new InterpreterException(stringBuilder.toString()); } final String poolKey = propertyKey; try { connection = ugi.doAs(new PrivilegedExceptionAction<Connection>() { @Override public Connection run() throws Exception { return getConnectionFromPool(url, user, poolKey, properties); } }); } catch (Exception e) { logger.error("Error in doAs", e); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(e.getMessage()).append("\n"); stringBuilder.append(e.getCause()); throw new InterpreterException(stringBuilder.toString()); } } } break; default: connection = getConnectionFromPool(url, user, propertyKey, properties); } } propertyKeySqlCompleterMap.put(propertyKey, createSqlCompleter(connection)); return connection; }
From source file:org.owasp.benchmark.score.BenchmarkScore.java
private static TestResults readActualResults(File fileToParse) throws Exception { String filename = fileToParse.getName(); TestResults tr = null;/* ww w . j a v a 2s.c o m*/ if (filename.endsWith(".ozasmt")) { tr = new AppScanSourceReader().parse(fileToParse); } else if (filename.endsWith(".json")) { String line1 = getLine(fileToParse, 0); String line2 = getLine(fileToParse, 1); if (line2.contains("Coverity") || line2.contains("formatVersion")) { tr = new CoverityReader().parse(fileToParse); } } else if (filename.endsWith(".txt")) { String line1 = getLine(fileToParse, 0); if (line1.startsWith("Possible ")) { tr = new SourceMeterReader().parse(fileToParse); } } else if (filename.endsWith(".xml")) { // Handle XML results file where the 2nd line indicates the tool type String line1 = getLine(fileToParse, 0); String line2 = getLine(fileToParse, 1); if (line2.startsWith("<pmd")) { tr = new PMDReader().parse(fileToParse); } else if (line2.startsWith("<FusionLiteInsight")) { tr = new FusionLiteInsightReader().parse(fileToParse); } else if (line2.startsWith("<XanitizerFindingsList")) { tr = new XanitizerReader().parse(fileToParse); } else if (line2.startsWith("<BugCollection")) { tr = new FindbugsReader().parse(fileToParse); // change the name of the tool if the filename contains findsecbugs if (fileToParse.getName().contains("findsecbugs")) { tr.setTool("FBwFindSecBugs"); } } else if (line2.startsWith("<ResultsSession")) { tr = new ParasoftReader().parse(fileToParse); } else if (line2.startsWith("<detailedreport")) { tr = new VeracodeReader().parse(fileToParse); } else if (line1.startsWith("<total")) { tr = new SonarQubeReader().parse(fileToParse); } else if (line1.contains("<OWASPZAPReport") || line2.contains("<OWASPZAPReport")) { tr = new ZapReader().parse(fileToParse); } else if (line2.startsWith("<CxXMLResults")) { tr = new CheckmarxReader().parse(fileToParse); } else if (line2.startsWith("<report")) { tr = new ArachniReader().parse(fileToParse); } else if (line2.startsWith("<analysisReportResult")) { tr = new JuliaReader().parse(fileToParse); } else { // Handle XML where we have to look for a specific node to identify the tool type Document doc = getXMLDocument(fileToParse); Node root = doc.getDocumentElement(); if (root.getNodeName().equals("issues")) { tr = new BurpReader().parse(root); } else if (root.getNodeName().equals("XmlReport")) { tr = new AppScanDynamicReader().parse(root); } else if (root.getNodeName().equals("noisycricket")) { tr = new NoisyCricketReader().parse(root); } else if (root.getNodeName().equals("Scan")) { tr = new WebInspectReader().parse(root); } else if (root.getNodeName().equals("ScanGroup")) { tr = new AcunetixReader().parse(root); } else if (root.getNodeName().equals("VulnSummary")) { tr = new Rapid7Reader().parse(root); } else if (root.getNodeName().equals("netsparker")) { tr = new NetsparkerReader().parse(root); } } // end else } // end if endsWith ".xml" else if (filename.endsWith(".fpr")) { // .fpr files are really .zip files. So we have to extract the .fvdl file out of it to process it Path path = Paths.get(fileToParse.getPath()); FileSystem fileSystem = FileSystems.newFileSystem(path, null); File outputFile = File.createTempFile(filename, ".fvdl"); Path source = fileSystem.getPath("audit.fvdl"); Files.copy(source, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); tr = new FortifyReader().parse(outputFile); outputFile.delete(); // Check to see if the results are regular Fortify or Fortify OnDemand results // To check, you have to look at the filtertemplate.xml file inside the .fpr archive // and see if that file contains: "Fortify-FOD-Template" outputFile = File.createTempFile(filename + "-filtertemplate", ".xml"); source = fileSystem.getPath("filtertemplate.xml"); // In older versions of Fortify, like 4.1, the filtertemplate.xml file doesn't exist // So only check it if it exists try { Files.copy(source, outputFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedReader br = new BufferedReader(new FileReader(outputFile)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); // Only read the first 3 lines and the answer is near the top of the file. int i = 1; while (line != null && i++ <= 3) { sb.append(line); line = br.readLine(); } if (sb.indexOf("Fortify-FOD-") > -1) { tr.setTool(tr.getTool() + "-OnDemand"); } } finally { br.close(); } } catch (NoSuchFileException e) { // Do nothing if the filtertemplate.xml file doesn't exist in the .fpr archive } finally { outputFile.delete(); } } else if (filename.endsWith(".log")) { tr = new ContrastReader().parse(fileToParse); } // If the version # of the tool is specified in the results file name, extract it, and set it. // For example: Benchmark-1.1-Coverity-results-v1.3.2661-6720.json (the version # is 1.3.2661 in this example). // This code should also handle: Benchmark-1.1-Coverity-results-v1.3.2661.xml (where the compute time '-6720' isn't specified) int indexOfVersionMarker = filename.lastIndexOf("-v"); if (indexOfVersionMarker != -1) { String restOfFileName = filename.substring(indexOfVersionMarker + 2); int endIndex = restOfFileName.lastIndexOf('-'); if (endIndex == -1) endIndex = restOfFileName.lastIndexOf('.'); String version = restOfFileName.substring(0, endIndex); tr.setToolVersion(version); } return tr; }
From source file:org.pentaho.di.trans.steps.textfileinput.TextFileInput.java
public static final String[] convertLineToStrings(LogChannelInterface log, String line, InputFileMetaInterface inf, String delimiter, String enclosure, String escapeCharacters) throws KettleException { String[] strings = new String[inf.getInputFields().length]; int fieldnr;//from ww w. j a v a 2s.c o m String pol; // piece of line try { if (line == null) { return null; } if (inf.getFileType().equalsIgnoreCase("CSV")) { // Split string in pieces, only for CSV! fieldnr = 0; int pos = 0; int length = line.length(); boolean dencl = false; int len_encl = (enclosure == null ? 0 : enclosure.length()); int len_esc = (escapeCharacters == null ? 0 : escapeCharacters.length()); while (pos < length) { int from = pos; int next; boolean encl_found; boolean contains_escaped_enclosures = false; boolean contains_escaped_separators = false; // Is the field beginning with an enclosure? // "aa;aa";123;"aaa-aaa";000;... if (len_encl > 0 && line.substring(from, from + len_encl).equalsIgnoreCase(enclosure)) { if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.Encloruse", line.substring(from, from + len_encl))); } encl_found = true; int p = from + len_encl; boolean is_enclosure = len_encl > 0 && p + len_encl < length && line.substring(p, p + len_encl).equalsIgnoreCase(enclosure); boolean is_escape = len_esc > 0 && p + len_esc < length && line.substring(p, p + len_esc).equalsIgnoreCase(inf.getEscapeCharacter()); boolean enclosure_after = false; // Is it really an enclosure? See if it's not repeated twice or escaped! if ((is_enclosure || is_escape) && p < length - 1) { String strnext = line.substring(p + len_encl, p + 2 * len_encl); if (strnext.equalsIgnoreCase(enclosure)) { p++; enclosure_after = true; dencl = true; // Remember to replace them later on! if (is_escape) { contains_escaped_enclosures = true; } } } // Look for a closing enclosure! while ((!is_enclosure || enclosure_after) && p < line.length()) { p++; enclosure_after = false; is_enclosure = len_encl > 0 && p + len_encl < length && line.substring(p, p + len_encl).equals(enclosure); is_escape = len_esc > 0 && p + len_esc < length && line.substring(p, p + len_esc).equals(inf.getEscapeCharacter()); // Is it really an enclosure? See if it's not repeated twice or escaped! if ((is_enclosure || is_escape) && p < length - 1) { String strnext = line.substring(p + len_encl, p + 2 * len_encl); if (strnext.equals(enclosure)) { p++; enclosure_after = true; dencl = true; // Remember to replace them later on! if (is_escape) { contains_escaped_enclosures = true; // remember } } } } if (p >= length) { next = p; } else { next = p + len_encl; } if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.EndOfEnclosure", "" + p)); } } else { encl_found = false; boolean found = false; int startpoint = from; // int tries = 1; do { next = line.indexOf(delimiter, startpoint); // See if this position is preceded by an escape character. if (len_esc > 0 && next - len_esc > 0) { String before = line.substring(next - len_esc, next); if (inf.getEscapeCharacter().equals(before)) { // take the next separator, this one is escaped... startpoint = next + 1; // tries++; contains_escaped_separators = true; } else { found = true; } } else { found = true; } } while (!found && next >= 0); } if (next == -1) { next = length; } if (encl_found && ((from + len_encl) <= (next - len_encl))) { pol = line.substring(from + len_encl, next - len_encl); if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.EnclosureFieldFound", "" + pol)); } } else { pol = line.substring(from, next); if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.NormalFieldFound", "" + pol)); } } if (dencl && Const.isEmpty(inf.getEscapeCharacter())) { StringBuilder sbpol = new StringBuilder(pol); int idx = sbpol.indexOf(enclosure + enclosure); while (idx >= 0) { sbpol.delete(idx, idx + enclosure.length()); idx = sbpol.indexOf(enclosure + enclosure); } pol = sbpol.toString(); } // replace the escaped enclosures with enclosures... if (contains_escaped_enclosures) { String replace = inf.getEscapeCharacter() + enclosure; String replaceWith = enclosure; pol = Const.replace(pol, replace, replaceWith); } // replace the escaped separators with separators... if (contains_escaped_separators) { String replace = inf.getEscapeCharacter() + delimiter; String replaceWith = delimiter; pol = Const.replace(pol, replace, replaceWith); } // Now add pol to the strings found! try { strings[fieldnr] = pol; } catch (ArrayIndexOutOfBoundsException e) { // In case we didn't allocate enough space. // This happens when you have less header values specified than there are actual values in the rows. // As this is "the exception" we catch and resize here. // String[] newStrings = new String[strings.length]; for (int x = 0; x < strings.length; x++) { newStrings[x] = strings[x]; } strings = newStrings; } pos = next + delimiter.length(); fieldnr++; } if (pos == length) { if (log.isRowLevel()) { log.logRowlevel(BaseMessages.getString(PKG, "TextFileInput.Log.ConvertLineToRowTitle"), BaseMessages.getString(PKG, "TextFileInput.Log.EndOfEmptyLineFound")); } if (fieldnr < strings.length) { strings[fieldnr] = Const.EMPTY_STRING; } fieldnr++; } } else { // Fixed file format: Simply get the strings at the required positions... for (int i = 0; i < inf.getInputFields().length; i++) { TextFileInputField field = inf.getInputFields()[i]; int length = line.length(); if (field.getPosition() + field.getLength() <= length) { strings[i] = line.substring(field.getPosition(), field.getPosition() + field.getLength()); } else { if (field.getPosition() < length) { strings[i] = line.substring(field.getPosition()); } else { strings[i] = ""; } } } } } catch (Exception e) { throw new KettleException( BaseMessages.getString(PKG, "TextFileInput.Log.Error.ErrorConvertingLine", e.toString()), e); } return strings; }
From source file:org.infoglue.cms.applications.managementtool.actions.ViewListSystemUserAction.java
public String getRolesAndGroups(InfoGluePrincipal principal) { if ((principal.getRoles() == null || principal.getRoles().size() == 1) && (principal.getGroups() == null || principal.getGroups().size() == 0)) { try {/*from w w w . jav a2s . c om*/ principal = UserControllerProxy .getController((Database) principal.getAutorizationModule().getTransactionObject()) .getUser(principal.getName()); } catch (Exception e) { //logger.error(); } } StringBuilder sb = new StringBuilder(""); sb.append("<b>Roles:</b> "); int i = 0; for (InfoGlueRole role : (List<InfoGlueRole>) principal.getRoles()) { if (!role.getName().equals("anonymous") || sb.indexOf("anonymous") == -1) { sb.append((i > 0 ? ", " : "") + role.getDisplayName()); i++; } } sb.append("<br/><b>Groups:</b> "); i = 0; for (InfoGlueGroup group : (List<InfoGlueGroup>) principal.getGroups()) { sb.append((i > 0 ? ", " : "") + group.getDisplayName()); i++; } return sb.toString(); }
From source file:org.objectpocket.storage.FileStore.java
@Override public Map<String, Map<String, String>> readJsonObjects(String typeName) throws IOException { if (typeName == null) { return null; }//from w ww . ja v a2 s. c o m Set<String> filenames = index.getTypeToFilenamesMapping().get(typeName); Map<String, Map<String, String>> objects = new HashMap<String, Map<String, String>>(); if (filenames != null) { for (String filename : filenames) { Map<String, String> objectAndIdMap = new HashMap<String, String>(); // maximum fast file reading StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader br = getBufferedReader(filename)) { String line = null; while ((line = br.readLine()) != null) { stringBuilder.append(line); } } String s = null; // remove first occurrence of "[", as this is the start of the // container array // all other object splitting will work with that! int index = stringBuilder.indexOf("["); if (index > -1) { s = stringBuilder.substring(index + 1, stringBuilder.length()); } else { throw new IOException("The file " + directory + "/" + filename + " does not contain valid JSON. " + getReadErrorMessage()); } List<String> jsonStrings = JsonHelper.splitToTopLevelJsonObjects(s); for (int i = 0; i < jsonStrings.size(); i++) { String[] typeAndIdFromJson = JsonHelper.getTypeAndIdFromJson(jsonStrings.get(i)); if (typeAndIdFromJson[0].equals(typeName)) { objectAndIdMap.put(jsonStrings.get(i), typeAndIdFromJson[1]); } } objects.put(filename, objectAndIdMap); } } else { Logger.getAnonymousLogger().log(Level.WARNING, "File for requested type: " + typeName + " does not exist in data store."); } return objects; }
From source file:com.mediaworx.intellij.opencmsplugin.listeners.OpenCmsModuleFileChangeListener.java
/** * checks if vfsPath is inside an ExportPoint and removes a previously exported file if necessary * @param vfsPath VFS path to check */// w w w . j av a2s. c o m private void deleteExportedFileIfNecessary(String vfsPath) { OpenCmsModuleExportPoint exportPoint = openCmsModules.getExportPointForVfsResource(vfsPath); if (exportPoint != null) { String exportPath = config.getWebappRoot() + "/" + exportPoint.getTargetPathForVfsResource(vfsPath); File exportedFileToBeDeleted = new File(exportPath); if (exportedFileToBeDeleted.exists()) { StringBuilder confirmation = new StringBuilder(); StringBuilder notice = new StringBuilder(); SyncJob.deleteExportedResource(vfsPath, exportPath, confirmation, notice); if (confirmation.indexOf(SyncJob.ERROR_PREFIX) > -1) { console.error(confirmation.toString()); } else { console.info(confirmation.toString()); } if (notice.length() > 0) { console.notice(notice.toString()); } refreshFiles.add(exportedFileToBeDeleted); } } }
From source file:org.kuali.rice.krad.data.jpa.NativeJpaQueryTranslator.java
/** * Fixes the search pattern by converting all non-escaped lookup wildcards ("*" and "?") into their respective JPQL * wildcards ("%" and "_").//from www . j a va 2 s . com * * <p>Any lookup wildcards escaped by a backslash are converted into their non-backslashed equivalents.</p> * * @param value the search pattern to fix. * @return a fixed search pattern. */ protected String fixSearchPattern(String value) { StringBuilder fixedPattern = new StringBuilder(value); // Convert all non-escaped wildcards. for (int i = 0; i < LOOKUP_WILDCARDS.length; i++) { String lookupWildcard = LOOKUP_WILDCARDS[i]; String escapedLookupWildcard = ESCAPED_LOOKUP_WILDCARDS[i]; char jpqlWildcard = JPQL_WILDCARDS[i]; int wildcardIndex = fixedPattern.indexOf(lookupWildcard); int escapedWildcardIndex = fixedPattern.indexOf(escapedLookupWildcard); while (wildcardIndex != -1) { if (wildcardIndex == 0 || escapedWildcardIndex != wildcardIndex - 1) { fixedPattern.setCharAt(wildcardIndex, jpqlWildcard); wildcardIndex = fixedPattern.indexOf(lookupWildcard, wildcardIndex); } else { fixedPattern.replace(escapedWildcardIndex, wildcardIndex + 1, lookupWildcard); wildcardIndex = fixedPattern.indexOf(lookupWildcard, wildcardIndex); escapedWildcardIndex = fixedPattern.indexOf(escapedLookupWildcard, wildcardIndex); } } } return fixedPattern.toString(); }