List of usage examples for java.lang StringBuffer setLength
@Override public synchronized void setLength(int newLength)
From source file:org.pentaho.di.job.entries.essbase.JobEntryMAXL.java
public Result execute(Result previousResult, int nr) { Result result = previousResult; if (databaseMeta != null) { final EssbaseHelper helper = new EssbaseHelper(databaseMeta); FileObject MAXLfile = null; try {/*from w w w. ja v a2 s. c o m*/ String myMAXL = null; helper.connect(); helper.openMaxlSession(this.getObjectName()); if (maxlfromfile) { if (maxlfilename == null) throw new KettleDatabaseException( BaseMessages.getString(PKG, "JobMAXL.NoMAXLFileSpecified")); try { String realfilename = environmentSubstitute(maxlfilename); MAXLfile = KettleVFS.getFileObject(realfilename, this); if (!MAXLfile.exists()) { logError(BaseMessages.getString(PKG, "JobMAXL.MAXLFileNotExist", realfilename)); throw new KettleDatabaseException( BaseMessages.getString(PKG, "JobMAXL.MAXLFileNotExist", realfilename)); } if (isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMAXL.MAXLFileExists", realfilename)); InputStream IS = KettleVFS.getInputStream(MAXLfile); try { InputStreamReader BIS = new InputStreamReader(new BufferedInputStream(IS, 500)); StringBuffer lineStringBuffer = new StringBuffer(256); lineStringBuffer.setLength(0); BufferedReader buff = new BufferedReader(BIS); String sLine = null; myMAXL = Const.CR; ; while ((sLine = buff.readLine()) != null) { if (Const.isEmpty(sLine)) { myMAXL = myMAXL + Const.CR; } else { myMAXL = myMAXL + Const.CR + sLine; } } } finally { IS.close(); } } catch (Exception e) { throw new KettleDatabaseException( BaseMessages.getString(PKG, "JobMAXL.ErrorRunningMAXLfromFile"), e); } } else { myMAXL = maxl; } if (!Const.isEmpty(myMAXL)) { // let it run if (useVariableSubstitution) myMAXL = environmentSubstitute(myMAXL); if (isDetailed()) logDetailed(BaseMessages.getString(PKG, "JobMAXL.Log.MAXLStatement", myMAXL)); if (sendOneStatement) helper.execStatement(myMAXL); else helper.execStatements(myMAXL); } } catch (Exception e) { result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMAXL.ErrorRunJobEntry", e.getMessage())); } finally { helper.disconnect(); if (MAXLfile != null) { try { MAXLfile.close(); } catch (Exception e) { } } } } else { result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobMAXL.NoDatabaseConnection")); } if (result.getNrErrors() == 0) { result.setResult(true); } else { result.setResult(false); } return result; }
From source file:com.commander4j.util.JUtility.java
public static String removeChar(String s, char c) { StringBuffer r = new StringBuffer(s.length()); r.setLength(s.length()); int current = 0; for (int i = 0; i < s.length(); i++) { char cur = s.charAt(i); if (cur != c) r.setCharAt(current++, cur); }/*from www . j av a 2s . c o m*/ return r.toString(); }
From source file:org.pentaho.di.job.entries.sql.JobEntrySQL.java
public Result execute(Result previousResult, int nr) { Result result = previousResult; if (connection != null) { Database db = new Database(this, connection); FileObject SQLfile = null; db.shareVariablesWith(this); try {/*w w w .java 2s . c om*/ String mySQL = null; db.connect(parentJob.getTransactionId(), null); if (sqlfromfile) { if (sqlfilename == null) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "JobSQL.NoSQLFileSpecified")); } try { String realfilename = environmentSubstitute(sqlfilename); SQLfile = KettleVFS.getFileObject(realfilename, this); if (!SQLfile.exists()) { logError(BaseMessages.getString(PKG, "JobSQL.SQLFileNotExist", realfilename)); throw new KettleDatabaseException( BaseMessages.getString(PKG, "JobSQL.SQLFileNotExist", realfilename)); } if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSQL.SQLFileExists", realfilename)); } InputStream IS = KettleVFS.getInputStream(SQLfile); try { InputStreamReader BIS = new InputStreamReader(new BufferedInputStream(IS, 500)); StringBuffer lineStringBuffer = new StringBuffer(256); lineStringBuffer.setLength(0); BufferedReader buff = new BufferedReader(BIS); String sLine = null; mySQL = Const.CR; while ((sLine = buff.readLine()) != null) { if (Const.isEmpty(sLine)) { mySQL = mySQL + Const.CR; } else { mySQL = mySQL + Const.CR + sLine; } } } finally { IS.close(); } } catch (Exception e) { throw new KettleDatabaseException( BaseMessages.getString(PKG, "JobSQL.ErrorRunningSQLfromFile"), e); } } else { mySQL = sql; } if (!Const.isEmpty(mySQL)) { // let it run if (useVariableSubstitution) { mySQL = environmentSubstitute(mySQL); } if (isDetailed()) { logDetailed(BaseMessages.getString(PKG, "JobSQL.Log.SQlStatement", mySQL)); } if (sendOneStatement) { db.execStatement(mySQL); } else { db.execStatements(mySQL); } } } catch (KettleDatabaseException je) { result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobSQL.ErrorRunJobEntry", je.getMessage())); } finally { db.disconnect(); if (SQLfile != null) { try { SQLfile.close(); } catch (Exception e) { // Ignore errors } } } } else { result.setNrErrors(1); logError(BaseMessages.getString(PKG, "JobSQL.NoDatabaseConnection")); } if (result.getNrErrors() == 0) { result.setResult(true); } else { result.setResult(false); } return result; }
From source file:com.digitalgeneralists.assurance.model.compare.ComparisonEngine.java
private void identifyTargetItemsNotInSource(File source, File target, Scan scan, IFileComparor comparor, IScanOptions options, Collection<FileReference> exclusions, IProgressMonitor monitor) { if (target.isDirectory() && source.isDirectory()) { for (File targetFile : target.listFiles()) { StringBuilder path = new StringBuilder(512); File sourceFile = new File(path.append(source.getPath()).append(File.separator) .append(targetFile.getName()).toString()); path.setLength(0);//from w ww. j a v a 2 s . c om path = null; // If the source file or target file is in the the global // ignore or exclusion list, just bypass it. // Checking both files in case one is null, in which case // we would have a mismatch. if (((!this.fileIsInGlobalIgnore(sourceFile, options)) && (!this.fileIsInGlobalIgnore(targetFile, options))) && ((!this.fileIsInExclusions(sourceFile, exclusions)) && (!this.fileIsInExclusions(targetFile, exclusions)))) { if (!sourceFile.exists()) { ComparisonResult result = new ComparisonResult(sourceFile, targetFile, AssuranceResultReason.SOURCE_DOES_NOT_EXIST, comparor); scan.addResult(result); result = null; StringBuffer message = new StringBuffer(512); logger.info(message.append(sourceFile).append(" does not exist.")); message.setLength(0); logger.info(message.append(sourceFile).append(" does not match ").append(targetFile)); message.setLength(0); message = null; } } sourceFile = null; targetFile = null; } } }
From source file:org.geoserver.wfs.response.DXFOutputFormat.java
/** * Gets output filename./*ww w. j a va2 s.c o m*/ * If the handle attribute is defined on the GetFeature tag it * will be used, else the name is obtained concatenating layer names * with underscore as a separator (up to a maximum name length). */ private String getFileName(Operation operation) { GetFeatureType request = (GetFeatureType) OwsUtils.parameter(operation.getParameters(), GetFeatureType.class); if (request.getHandle() != null) { LOGGER.log(Level.FINE, "Using handle for file name: " + request.getHandle()); return request.getHandle(); } StringBuffer sb = new StringBuffer(); for (Iterator f = request.getQuery().iterator(); f.hasNext();) { QueryType query = (QueryType) f.next(); sb.append(getLayerName(query) + "_"); } sb.setLength(sb.length() - 1); LOGGER.log(Level.FINE, "Using layer names for file name: " + sb.toString()); if (sb.length() > 20) { LOGGER.log(Level.WARNING, "Calculated filename too long. Returing a shorter one: " + sb.toString().substring(0, 20)); return sb.toString().substring(0, 20); } return sb.toString(); }
From source file:com.pureinfo.srm.outlay.model.impl.ZjuOutlayCardCodeGenerator.java
/** * @see com.pureinfo.srm.outlay.model.IOutlayCardCodeGenerator#generateCode(com.pureinfo.srm.project.model.Project, * String)//from w ww .j a v a 2 s .co m */ public String generateCode(Project _prj, String _sOutlayType) throws PureException { StringBuffer sbuff = new StringBuffer(); IIDTableMgr mgr = (IIDTableMgr) ArkContentHelper.getContentMgrOf(IDTable.class); String sIdName = getCodePrefix(_prj, _sOutlayType); try { sbuff.append(sIdName); String sFlowid = numFormatter.format(mgr.getIdValue(sIdName)); sbuff.append(sFlowid); return sbuff.toString(); } finally { sbuff.setLength(0); } }
From source file:annis.administration.AnnisAdminRunner.java
private void printTable(List<Map<String, Object>> table) { // use first element to get metadata (like column names) Map<String, Object> first = table.get(0); List<String> columnNames = new ArrayList<String>(first.keySet()); // determine length of column Map<String, Integer> columnSize = new HashMap<String, Integer>(); for (String column : columnNames) { columnSize.put(column, column.length()); }/*w w w. ja va 2s .c o m*/ for (Map<String, Object> row : table) { for (Map.Entry<String, Object> e : row.entrySet()) { String column = e.getKey(); final Object value = e.getValue(); if (value == null) { continue; } int length = value.toString().length(); if (columnSize.get(column) < length) { columnSize.put(column, length); } } } // print header StringBuffer sb = new StringBuffer(); for (String column : columnNames) { sb.append(pad(column, columnSize.get(column))); sb.append(" | "); } sb.setLength(sb.length() - " | ".length()); System.out.println(sb); // print values for (Map<String, Object> row : table) { sb = new StringBuffer(); for (String column : columnNames) { sb.append(pad(row.get(column), columnSize.get(column))); sb.append(" | "); } sb.setLength(sb.length() - " | ".length()); System.out.println(sb); } }
From source file:gov.nih.nci.sdk.example.generator.WebServiceGenerator.java
public void runCommand(String _command) { try {//from ww w . ja v a2s .c om StringBuffer input = new StringBuffer(); input.setLength(0); // erase input StringBuffer String s; if (_command != null) { Runtime a = Runtime.getRuntime(); java.lang.Process p = a.exec(_command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command // System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { input.append(s); } // read any errors from the attempted command while ((s = stdError.readLine()) != null) { getScriptContext().logInfo(s); } } } catch (Throwable t) { t.printStackTrace(); getScriptContext().logError(t); } }
From source file:com.sec.ose.osi.sdk.protexsdk.discovery.DCStringSearch.java
public void loadFromProtexServer(UIResponseObserver observer, ReportEntityList identifiedFiles, ReportEntityList stringSearch) { PreparedStatement prep = IdentificationDBManager.getStringSearchPreparedStatement(projectName); HashSet<String> StringSearchFileLineSet = new HashSet<String>(); if (stringSearch == null) { System.err.println("Not Founded StringSearch."); return;/*from w w w. ja va2s . c o m*/ } StringBuffer stringSearchLineBuf = new StringBuffer(""); if (identifiedFiles != null) { for (ReportEntity tmpIdentifiedFile : identifiedFiles.getEntityList()) { stringSearchLineBuf.setLength(0); if (tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.DISCOVERY_TYPE) .equals("String Search")) { String stringSearchFilePath = tmpIdentifiedFile .getValue(ReportInfo.IDENTIFIED_FILES.FILE_FOLDER_NAME).substring(1); String stringSearchSearch = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.SEARCH); String stringSearchComponent = tmpIdentifiedFile .getValue(ReportInfo.IDENTIFIED_FILES.COMPONENT); String stringSearchVersion = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.VERSION); String stringSearchLicense = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.LICENSE); String stringSearchTotalLine = tmpIdentifiedFile .getValue(ReportInfo.IDENTIFIED_FILES.TOTAL_LINES); String stringSearchComment = tmpIdentifiedFile.getValue(ReportInfo.IDENTIFIED_FILES.COMMENT); String stringResolutionType = tmpIdentifiedFile .getValue(ReportInfo.IDENTIFIED_FILES.RESOLUTION_TYPE); String stringSearchStartLine = tmpIdentifiedFile .getValue(ReportInfo.IDENTIFIED_FILES.FILE_LINE); stringSearchLineBuf.append(stringSearchFilePath); stringSearchLineBuf.append(stringSearchStartLine); if (stringSearchTotalLine.length() > 0) { int iStringSearchStartLine = Tools.transStringToInteger(stringSearchStartLine); int iStringSearchTotalLine = Tools.transStringToInteger(stringSearchTotalLine); int iStringSearchEndLine = iStringSearchStartLine + iStringSearchTotalLine - 1; stringSearchLineBuf.append(".."); stringSearchLineBuf.append(iStringSearchEndLine); } StringSearchFileLineSet.add(stringSearchLineBuf.toString()); if (stringSearchSearch.length() > 0) { String pendingStatus = String.valueOf(AbstractMatchInfo.STATUS_IDENTIFIED); if ("Declared".equals(stringResolutionType)) pendingStatus = String.valueOf(AbstractMatchInfo.STATUS_DECLARED); try { prep.setString(1, stringSearchFilePath); prep.setString(2, stringSearchSearch); prep.setString(3, stringSearchComponent); prep.setString(4, stringSearchVersion); prep.setString(5, stringSearchLicense); prep.setString(6, pendingStatus); prep.setString(7, stringSearchLineBuf.toString().substring(stringSearchFilePath.length())); prep.setString(8, stringSearchComment); prep.addBatch(); } catch (SQLException e) { log.warn(e); } } } } IdentificationDBManager.execute(prep); } for (ReportEntity entity : stringSearch) { String stringSearchFilePath = entity.getValue(ReportInfo.STRING_SEARCHES.FILE); String stringSearchSearch = entity.getValue(ReportInfo.STRING_SEARCHES.SEARCH); String stringSearchLine = entity.getValue(ReportInfo.STRING_SEARCHES.LINE); if (StringSearchFileLineSet.contains(stringSearchFilePath + stringSearchLine)) continue; if (stringSearchSearch.length() > 0) { try { prep.setString(1, stringSearchFilePath); prep.setString(2, stringSearchSearch); prep.setString(3, null); prep.setString(4, null); prep.setString(5, null); prep.setString(6, String.valueOf(AbstractMatchInfo.STATUS_PENDING)); prep.setString(7, stringSearchLine); prep.setString(8, null); // comment prep.addBatch(); } catch (SQLException e) { log.warn(e); } } } IdentificationDBManager.execute(prep); StringSearchFileLineSet = null; if (prep != null) { try { prep.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:org.apache.nutch.parse.html.HtmlParser.java
public ParseResult getParse(Content content) { HTMLMetaTags metaTags = new HTMLMetaTags(); URL base;/* w w w.j av a2 s . c o m*/ try { base = new URL(content.getBaseUrl()); } catch (MalformedURLException e) { return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf()); } String text = ""; String title = ""; Outlink[] outlinks = new Outlink[0]; Metadata metadata = new Metadata(); // parse the content DocumentFragment root; try { byte[] contentInOctets = content.getContent(); InputSource input = new InputSource(new ByteArrayInputStream(contentInOctets)); EncodingDetector detector = new EncodingDetector(conf); detector.autoDetectClues(content, true); detector.addClue(sniffCharacterEncoding(contentInOctets), "sniffed"); String encoding = detector.guessEncoding(content, defaultCharEncoding); metadata.set(Metadata.ORIGINAL_CHAR_ENCODING, encoding); metadata.set(Metadata.CHAR_ENCODING_FOR_CONVERSION, encoding); input.setEncoding(encoding); if (LOG.isTraceEnabled()) { LOG.trace("Parsing..."); } root = parse(input); } catch (IOException e) { return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf()); } catch (DOMException e) { return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf()); } catch (SAXException e) { return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf()); } catch (Exception e) { e.printStackTrace(LogUtil.getWarnStream(LOG)); return new ParseStatus(e).getEmptyParseResult(content.getUrl(), getConf()); } // get meta directives HTMLMetaProcessor.getMetaTags(metaTags, root, base); if (LOG.isTraceEnabled()) { LOG.trace("Meta tags for " + base + ": " + metaTags.toString()); } // check meta directives if (!metaTags.getNoIndex()) { // okay to index StringBuffer sb = new StringBuffer(); if (LOG.isTraceEnabled()) { LOG.trace("Getting text..."); } utils.getText(sb, root); // extract text text = sb.toString(); sb.setLength(0); if (LOG.isTraceEnabled()) { LOG.trace("Getting title..."); } utils.getTitle(sb, root); // extract title title = sb.toString().trim(); } if (!metaTags.getNoFollow()) { // okay to follow links ArrayList<Outlink> l = new ArrayList<Outlink>(); // extract outlinks URL baseTag = utils.getBase(root); if (LOG.isTraceEnabled()) { LOG.trace("Getting links..."); } utils.getOutlinks(baseTag != null ? baseTag : base, l, root); outlinks = l.toArray(new Outlink[l.size()]); if (LOG.isTraceEnabled()) { LOG.trace("found " + outlinks.length + " outlinks in " + content.getUrl()); } } ParseStatus status = new ParseStatus(ParseStatus.SUCCESS); if (metaTags.getRefresh()) { status.setMinorCode(ParseStatus.SUCCESS_REDIRECT); status.setArgs(new String[] { metaTags.getRefreshHref().toString(), Integer.toString(metaTags.getRefreshTime()) }); } ParseData parseData = new ParseData(status, title, outlinks, content.getMetadata(), metadata); ParseResult parseResult = ParseResult.createParseResult(content.getUrl(), new ParseImpl(text, parseData)); // run filters on parse ParseResult filteredParse = this.htmlParseFilters.filter(content, parseResult, metaTags, root); if (metaTags.getNoCache()) { // not okay to cache for (Map.Entry<org.apache.hadoop.io.Text, Parse> entry : filteredParse) entry.getValue().getData().getParseMeta().set(Nutch.CACHING_FORBIDDEN_KEY, cachingPolicy); } return filteredParse; }