List of usage examples for java.lang StringBuffer setLength
@Override public synchronized void setLength(int newLength)
From source file:com.pureinfo.dolphinview.function.dolphin.ShowRelativesFunctionHandler.java
/** * @see com.pureinfo.dolphinview.parser.function.FunctionHandlerDVImplBase#perform(java.lang.Object[], * com.pureinfo.dolphinview.context.model.IDVContext) *///from w ww . ja v a 2 s .c om public Object perform(Object[] _args, IDVContext _context) throws PureException { FunctionHandlerUtil.validateArgsNum(_args, MIN_ARG_NUM); //1. to read parameters String sAlias = (String) _args[ARG_ALIAS]; String sProperty = (String) _args[ARG_PROPERTY_NAME]; String sDelim = (String) _args[ARG_DELIM]; String sOrderBy; if (_args.length > ARG_ORDERBY) { sOrderBy = (String) _args[ARG_ORDERBY]; } else { sOrderBy = null; } int nFrom = 0; int nMaxSize = 0; if (_args.length > ARG_POS_FROM) { nFrom = FunctionHandlerUtil.getIntArg(_args, ARG_POS_FROM, 0); if (nFrom < 0) { nFrom = 0; } if (_args.length > ARG_MAX_SIZE) { nMaxSize = FunctionHandlerUtil.getIntArg(_args, ARG_MAX_SIZE, 0); if (nMaxSize < 0) { nMaxSize = 0; } } } //2. to find the relative object StringBuffer sbuff = null; List params = null; IStatement query = null; IObjects objs = null; QueryFilter filter = new QueryFilter(); try { // 2.1 to render query SQL DolphinObject object = _context.getObject(); Class relativeClass = RelativeUtil.renderFilter(object, sAlias, filter); if (StringUtils.isEmpty(filter.getSelect())) { filter.setSelect("{" + sAlias + "." + sProperty + "}"); } if (sOrderBy != null && (sOrderBy = sOrderBy.trim()).length() > 0) { filter.setOrder(sOrderBy); } // 2.2 to prepare query params = new ArrayList(); String strSQL = filter.toSQL(params); logger.debug("SQL: " + strSQL); // 2.3 to execute query ISession session = LocalContextHelper.currentSession(); query = session.createQuery(strSQL, relativeClass, nMaxSize > 0 ? nFrom + nMaxSize : 0); filter.registerEntitiesInQuery(query); query.setParameters(0, params); objs = query.executeQuery(false); if (nFrom > 0) { objs.skip(nFrom); } // 2.4 to render the view content sbuff = new StringBuffer(); while ((object = objs.next()) != null) { if (sbuff.length() > 0) { sbuff.append(sDelim); } sbuff.append(object.getProperty(sProperty)); } return sbuff.toString(); } finally { DolphinHelper.clear(objs, query); if (sbuff != null) sbuff.setLength(0); if (params != null) params.clear(); } }
From source file:com.pureinfo.srm.patent.domain.impl.PatentMgrImpl.java
/** * @see com.pureinfo.srm.patent.domain.IPatentMgr#sendEmailForCheck(com.pureinfo.srm.patent.model.Patent, * boolean)/*w w w . j a va2 s . c o m*/ */ public void sendEmailForCheck(Patent _patent, boolean bIsPass) throws PureException { SRMUser inputUser = _patent.getInputUser(); if (inputUser != null) { if (inputUser.getEmail() != null) { StringBuffer sbuff = new StringBuffer(); try { sbuff.append(inputUser.getTrueName()).append("\n "); if (bIsPass) { sbuff.append(""); } else { sbuff.append(""); } sbuff.append("").append(_patent.getName()).append(""); if (bIsPass) { sbuff.append(""); } else { sbuff.append("\n"); sbuff.append(" :\n\n ").append(_patent.getCheckSuggestion()); } String sFromAddress = PureSystem.getRequiredProperty("mail.system.user"); ISender sender = SenderHelper.getSender(SenderHelper.TYPE_MAIL); sender.send(sFromAddress, "", inputUser.getEmail(), inputUser.getTrueName(), "" + _patent.getName() + "", sbuff.toString()); } catch (PureException ex) { ex.printStackTrace(); } finally { sbuff.setLength(0); } } } }
From source file:com.adaptris.core.services.splitter.SimpleRegexpMessageSplitter.java
@Override protected ArrayList<String> split(String messagePayload) throws Exception { String batch = messagePayload; compiledSplitPattern = compile(compiledSplitPattern, splitPattern); Matcher splitMatcher = compiledSplitPattern.matcher(batch); Matcher compareMatcher = null; if (compareToPreviousMatch()) { compiledMatchPattern = compile(compiledMatchPattern, matchPattern); compareMatcher = compiledMatchPattern.matcher(batch); }/*from w ww. jav a 2 s .c o m*/ ArrayList<String> splitMessages = new ArrayList(); int splitStart = 0; int splitEnd = 0; StringBuffer currentSplitMsg = new StringBuffer(); String currentMatch = null; if (compareToPreviousMatch()) { try { // do not check for a match first - we want to throw an exception if // no match found. compareMatcher.find(); // lgtm currentMatch = compareMatcher.group(1); } catch (Exception e) { throw new Exception("Could not match record comparator [" + e.getMessage() + "]", e); } } while (splitMatcher.find(splitEnd)) { splitEnd = splitMatcher.end(); String thisRecord = batch.substring(splitStart, splitEnd); if (compareToPreviousMatch()) { compareMatcher = compiledMatchPattern.matcher(thisRecord); // We may get an empty line, in which case the compare.start() and // compare.end() methods will throw an IllegalStateException String newMatch = ""; if (compareMatcher.find()) { newMatch = compareMatcher.group(1); } if (currentMatch.equals(newMatch)) { // lgtm // Still in the same message currentSplitMsg.append(thisRecord); } else { // The current thisRecord value is actually the start of the next // message, so we should store the last record and start again // with this one. splitMessages.add(currentSplitMsg.toString()); // ******** currentSplitMsg.setLength(0); currentSplitMsg.append(thisRecord); currentMatch = newMatch; } } else { splitMessages.add(thisRecord); } splitStart = splitEnd; } // last message - might be an empty String String thisRecord = batch.substring(splitStart); if (compareToPreviousMatch()) { compareMatcher = compiledMatchPattern.matcher(thisRecord); // We may get an empty line, in which case the compare.start() and // compare.end() methods will throw an IllegalStateException String newMatch = ""; if (compareMatcher.find()) { newMatch = compareMatcher.group(1); } if (currentMatch.equals(newMatch)) { // lgtm // Still in the same message currentSplitMsg.append(thisRecord); splitMessages.add(currentSplitMsg.toString()); } else { // The current thisRecord value is actually the start of the next // message, so we should store the last record and start again // with this one. splitMessages.add(currentSplitMsg.toString()); currentSplitMsg.setLength(0); // Must be a single line record - write it out (unless empty) if (thisRecord.trim().length() > 0) { splitMessages.add(thisRecord); } } } else { // Must be a single line record - write it out (unless empty) if (thisRecord.trim().length() > 0) { splitMessages.add(thisRecord); } } if (ignoreFirstSubMessage()) { splitMessages.remove(0); } return splitMessages; }
From source file:com.tasktop.internal.hp.qc.core.model.comments.mylyn3_8.HtmlStreamTokenizer_m3_8.java
/** * Replaces (in-place) HTML escapes in a StringBuffer with their corresponding characters. * /* w ww .j a v a 2 s . c o m*/ * @deprecated use {@link StringEscapeUtils#unescapeHtml(String)} instead */ @Deprecated public static StringBuffer unescape(StringBuffer sb) { int i = 0; // index into the unprocessed section of the buffer int j = 0; // index into the processed section of the buffer while (i < sb.length()) { char ch = sb.charAt(i); if (ch == '&') { int start = i; String escape = null; for (i = i + 1; i < sb.length(); i++) { ch = sb.charAt(i); if (!Character.isLetterOrDigit(ch) && !(ch == '#' && i == (start + 1))) { escape = sb.substring(start + 1, i); break; } } if (i == sb.length() && i != (start + 1)) { escape = sb.substring(start + 1); } if (escape != null) { Character character = parseReference(escape); if (character != null && !((0x0A == character || 0x0D == character || 0x09 == ch) || (character >= 0x20 && character <= 0xD7FF) || (character >= 0xE000 && character <= 0xFFFD) || (character >= 0x10000 && character <= 0x10FFFF))) { // Character is an invalid xml character // http://www.w3.org/TR/REC-xml/#charsets character = null; } if (character != null) { ch = character.charValue(); } else { // not an HTML escape; rewind i = start; ch = '&'; } } } sb.setCharAt(j, ch); i++; j++; } sb.setLength(j); return sb; }
From source file:com.tremolosecurity.scale.user.ScaleSession.java
public UnisonUserData loadUserFromUnison(String loginID, AttributeData attributeData) throws UnsupportedEncodingException, IOException, ClientProtocolException { UserObj userObj = new UserObj(attributeData); StringBuffer callURL = new StringBuffer(); callURL.append(this.commonConfig.getScaleConfig().getServiceConfiguration().getUnisonURL() + "/services/wf/search?filter=") .append(URLEncoder.encode( "(" + this.commonConfig.getScaleConfig().getServiceConfiguration().getLookupAttributeName() + "=" + loginID + ")", "UTF-8")); HttpGet httpget = new HttpGet(callURL.toString()); HttpResponse response = http.execute(httpget); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = null;/*w w w . j av a 2s . co m*/ StringBuffer json = new StringBuffer(); while ((line = in.readLine()) != null) { json.append(line); } Gson gson = new Gson(); ProvisioningResult pres = gson.fromJson(json.toString(), ProvisioningResult.class); if (!pres.isSuccess()) { logger.error("Could not load user : '" + pres.getError().getError() + "'"); return null; } TremoloUser user = pres.getUser(); for (Attribute attr : user.getAttributes()) { if (attr.getName() .equalsIgnoreCase(this.commonConfig.getScaleConfig().getUiConfig().getDisplayNameAttribute())) { userObj.setDisplayName(attr.getValues().get(0)); } if (attributeData.getLabels().containsKey(attr.getName())) { userObj.getAttrs().put(attr.getName(), new ScaleAttribute(attr.getName(), attributeData.getLabels().get(attr.getName()), attr.getValues().get(0))); } } //determine executed workflows callURL.setLength(0); callURL.append(this.commonConfig.getScaleConfig().getServiceConfiguration().getUnisonURL() + "/services/wf/executed?user=").append(loginID); httpget = new HttpGet(callURL.toString()); response = http.execute(httpget); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = null; json.setLength(0); while ((line = in.readLine()) != null) { json.append(line); } pres = gson.fromJson(json.toString(), ProvisioningResult.class); if (!pres.isSuccess()) { return null; } userObj.getExecutedWorkflows().addAll(pres.getWorkflowIds()); return new UnisonUserData(userObj, user); }
From source file:com.concursive.connect.web.modules.wiki.utils.WikiPDFUtils.java
private static boolean parseLine(WikiPDFContext context, String line, Paragraph main, Connection db, ArrayList<Integer> wikiListTodo, float cellWidth, PdfPCell cell) throws Exception { LOG.debug("PARSING LINE: " + line); // Context Objects Project project = context.getProject(); WikiExportBean exportBean = context.getExportBean(); HashMap<String, ImageInfo> imageList = context.getImageList(); String fileLibrary = context.getFileLibrary(); boolean needsCRLF = true; boolean bold = false; boolean italic = false; boolean bolditalic = false; StringBuffer subject = new StringBuffer(); StringBuffer data = new StringBuffer(); int linkL = 0; int linkR = 0; int attr = 0; int underlineAttr = 0; // parse characters for (int i = 0; i < line.length(); i++) { char c1 = line.charAt(i); String c = String.valueOf(c1); // False attr/links if (!"'".equals(c) && attr == 1) { data.append("'").append(c); attr = 0;//from ww w .ja v a 2 s .c o m continue; } if (!"_".equals(c) && underlineAttr == 1) { data.append("_").append(c); underlineAttr = 0; continue; } if (!"[".equals(c) && linkL == 1) { data.append("[").append(c); linkL = 0; continue; } if (!"]".equals(c) && linkR == 1) { data.append("]").append(c); linkR = 0; continue; } // Links if ("[".equals(c)) { ++linkL; continue; } if ("]".equals(c)) { ++linkR; if (linkL == 2 && linkR == 2) { LOG.debug("main.add(new Chunk(data.toString()))"); main.add(new Chunk(data.toString())); data.setLength(0); // Different type of links... String link = subject.toString().trim(); if (link.startsWith("Image:") || link.startsWith("image:")) { // @note From WikiImageLink.java String image = link.substring(6); String title = null; int frame = -1; int thumbnail = -1; int left = -1; int right = -1; int center = -1; int none = -1; int imageLink = -1; int alt = -1; if (image.indexOf("|") > 0) { // the image is first image = image.substring(0, image.indexOf("|")); // any directives are next frame = link.indexOf("|frame"); thumbnail = link.indexOf("|thumb"); left = link.indexOf("|left"); right = link.indexOf("|right"); center = link.indexOf("|center"); none = link.indexOf("|none"); imageLink = link.indexOf("|link="); alt = link.indexOf("|alt="); // the optional caption is last int last = link.lastIndexOf("|"); if (last > frame && last > thumbnail && last > left && last > right && last > center && last > none && last > imageLink && last > alt) { title = link.substring(last + 1); } } //A picture, including alternate text: //[[Image:Wiki.png|The logo for this Wiki]] //You can put the image in a frame with a caption: //[[Image:Wiki.png|frame|The logo for this Wiki]] // Access some image details int width = 0; int height = 0; ImageInfo imageInfo = imageList.get(image + (thumbnail > -1 ? "-TH" : "")); if (imageInfo != null) { width = imageInfo.getWidth(); height = imageInfo.getHeight(); } // Alt String altText = null; if (alt > -1) { int startIndex = alt + 4; int endIndex = link.indexOf("|", startIndex); if (endIndex == -1) { endIndex = link.length(); } altText = link.substring(startIndex, endIndex); } // Looks like the image needs a link (which is always last) String url = null; if (imageLink > -1) { // Get the entered link int startIndex = imageLink + 6; int endIndex = link.length(); String href = link.substring(startIndex, endIndex); // Treat as a wikiLink to validate and to create a proper url WikiLink wikiLink = new WikiLink(project.getId(), (altText != null ? href + " " + altText : href)); url = wikiLink.getUrl(""); if (!url.startsWith("http://") && !url.startsWith("https://")) { // @todo Use a local link // @todo Use an external link } } // Determine if local or external image if ((image.startsWith("http://") || image.startsWith("https://"))) { // retrieve external image String imageUrl = null; try { URL imageURL = new URL(image); imageUrl = image; } catch (Exception e) { } } else { // local image try { // @todo image alignment and links Image thisImage = Image.getInstance( getImageFilename(db, fileLibrary, project, image, (thumbnail > -1))); LOG.debug("Drawing image for area: " + cellWidth); if (cellWidth > 0f) { LOG.debug(" Image is embedded in cell"); // Guess the size of the cell float cellPixels = (500f * (cellWidth / 100f)); if (cellPixels > 0f && (float) width > cellPixels) { // Shrink image to fit the cell LOG.debug(" Scaling to fit"); thisImage.scaleToFit(cellPixels, 500f); } else { // Align image to left instead of scaling it to fit thisImage.setAlignment(Image.LEFT); } LOG.debug("cell.addElement(thisImage)"); cell.addElement(thisImage); } else { LOG.debug(" Image is inline"); if (width > 500) { LOG.debug(" Scaling to fit"); thisImage.scaleToFit(500f, 500f); } LOG.debug("main.add(thisImage)"); main.add(thisImage); } // thisImage.setAlignment(); // thisImage.Alignment = Image.TEXTWRAP | Image.ALIGN_RIGHT; // main.add(thisImage); } catch (FileNotFoundException fnfe) { LOG.warn("WikiPDFUtils-> Image was not found in the FileLibrary (" + getImageFilename(db, fileLibrary, project, image, (thumbnail > -1)) + ")... will continue."); } } /* if (frame > -1 || thumbnail > -1) { sb.append("</div>"); sb.append("<div id=\"caption\" style=\"margin-bottom: 5px; margin-left: 5px; margin-right: 5px; text-align: left;\">"); } if (thumbnail > -1) { sb.append("<div style=\"float:right\"><a target=\"_blank\" href=\"ProjectManagementWiki.do?command=Img&pid=" + wiki.getProjectId() + "&subject=" + StringUtils.replace(StringUtils.jsEscape(image), "%20", "+") + "\"><img src=\"images/magnify-clip.png\" width=\"15\" height=\"11\" alt=\"Enlarge\" border=\"0\" /></a></div>"); } if (frame > -1 || thumbnail > -1) { if (title != null) { sb.append(StringUtils.toHtml(title)); } sb.append( " </div>\n" + "</div>"); } */ /* if (none > -1) { sb.append("<br clear=\"all\">"); } */ if (i + 1 == line.length() && (right > -1 || left > -1) || none > -1) { needsCRLF = false; } } else { // This is most likely a Wiki link String title = subject.toString().trim(); if (link.indexOf("|") > 0) { link = link.substring(0, link.indexOf("|")).trim(); title = title.substring(title.indexOf("|") + 1); } if (link.indexOf("http://") > -1 || link.indexOf("https://") > -1) { String label = link; if (link.indexOf(" ") > 0) { label = link.substring(link.indexOf(" ") + 1); link = link.substring(0, link.indexOf(" ")); } Anchor anchor1 = new Anchor(label, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE, new Color(0, 0, 255))); anchor1.setReference(link); anchor1.setName("top"); main.add(anchor1); } else { // Place a wiki link if (exportBean.getFollowLinks()) { // See if target link exists before creating a link to it int linkedWikiId = -1; if (StringUtils.hasText(title) && !title.startsWith("|")) { Wiki subwiki = WikiList.queryBySubject(db, title, project.getId()); if (subwiki.getId() > -1) { linkedWikiId = subwiki.getId(); } } // Display the linked item if (linkedWikiId > -1) { // Display as an anchor Anchor linkToWiki = new Anchor(title, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 255))); linkToWiki.setReference("#" + title.toLowerCase()); LOG.debug("Link to: #" + title.toLowerCase()); main.add(linkToWiki); LOG.debug(" main.add(linkToWiki)"); // main.add(new Chunk(title, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 255))).setLocalGoto(link)); // Add this wiki to the to do list... if (!wikiListTodo.contains(linkedWikiId)) { wikiListTodo.add(linkedWikiId); } } else { // Display without the link main.add(new Chunk(title, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 255)))); } } else { // Not following links, so display... perhaps as an external link someday main.add(new Chunk(title, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.NORMAL, new Color(0, 0, 255)))); } } } subject.setLength(0); linkL = 0; linkR = 0; } continue; } if (!"[".equals(c) && linkL == 2 && !"]".equals(c)) { subject.append(c); continue; } // Attribute properties if ("'".equals(c)) { ++attr; continue; } if (!"'".equals(c) && attr > 1) { if (attr == 2) { if (!italic) { main.add(new Chunk(data.toString())); data.setLength(0); data.append(c); italic = true; } else { data.append(c); main.add(new Chunk(data.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.ITALIC, new Color(0, 0, 0)))); data.setLength(0); italic = false; } attr = 0; continue; } if (attr == 3) { if (!bold) { main.add(new Chunk(data.toString())); data.setLength(0); data.append(c); bold = true; } else { data.append(c); main.add(new Chunk(data.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(0, 0, 0)))); data.setLength(0); bold = false; } attr = 0; continue; } if (attr == 5) { if (!bolditalic) { main.add(new Chunk(data.toString())); data.setLength(0); data.append(c); bolditalic = true; } else { data.append(c); main.add(new Chunk(data.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLDITALIC, new Color(0, 0, 0)))); data.setLength(0); bolditalic = false; } attr = 0; continue; } } data.append(c); } for (int x = 0; x < linkR; x++) { data.append("]"); } for (int x = 0; x < linkL; x++) { data.append("["); } if (attr == 1) { data.append("'"); } if (italic) { main.add(new Chunk(data.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.ITALIC, new Color(0, 0, 0)))); } else if (bold) { main.add(new Chunk(data.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(0, 0, 0)))); } else if (bolditalic) { main.add(new Chunk(data.toString(), FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLDITALIC, new Color(0, 0, 0)))); } else { main.add(new Chunk(data.toString())); } data.setLength(0); return needsCRLF; }
From source file:com.ikanow.infinit.e.harvest.enrichment.custom.UnstructuredAnalysisHarvester.java
/** * cleanseText/*from ww w. j ava 2 s. co m*/ * * @param source * @param documents * @return */ private void cleanseText(List<SimpleTextCleanserPojo> simpleTextCleanser, DocumentPojo document) { // Store these since can re-generate them by concatenation StringBuffer fullTextBuilder = null; StringBuffer descriptionBuilder = null; StringBuffer titleBuilder = null; // (note no support for metadata concatenation, replace only) // Iterate over the cleanser functions that need to run on each feed for (SimpleTextCleanserPojo s : simpleTextCleanser) { boolean bConcat = (null != s.getFlags()) && s.getFlags().contains("+"); boolean bUsingJavascript = ((null != s.getScriptlang()) && s.getScriptlang().equalsIgnoreCase("javascript")); if (s.getField().equalsIgnoreCase("fulltext")) { if ((null != document.getFullText()) || bUsingJavascript) { StringBuffer myBuilder = fullTextBuilder; if ((!bConcat) && (null != myBuilder) && (myBuilder.length() > 0)) { document.setFullText(myBuilder.toString()); myBuilder.setLength(0); } //TESTED String res = cleanseField(document.getFullText(), s.getScriptlang(), s.getScript(), s.getFlags(), s.getReplacement(), document); if (bConcat) { if (null == myBuilder) { fullTextBuilder = myBuilder = new StringBuffer(); } myBuilder.append(res).append('\n'); } else { document.setFullText(res); } } } //TESTED else if (s.getField().equalsIgnoreCase("description")) { if ((null != document.getDescription()) || bUsingJavascript) { StringBuffer myBuilder = descriptionBuilder; if ((!bConcat) && (null != myBuilder) && (myBuilder.length() > 0)) { document.setDescription(myBuilder.toString()); myBuilder.setLength(0); } //TESTED String res = cleanseField(document.getDescription(), s.getScriptlang(), s.getScript(), s.getFlags(), s.getReplacement(), document); if (bConcat) { if (null == myBuilder) { descriptionBuilder = myBuilder = new StringBuffer(); } myBuilder.append(res).append('\n'); } else { document.setDescription(res); } } } //TESTED else if (s.getField().equalsIgnoreCase("title")) { if ((null != document.getTitle()) || bUsingJavascript) { StringBuffer myBuilder = titleBuilder; if ((!bConcat) && (null != myBuilder) && (myBuilder.length() > 0)) { document.setTitle(myBuilder.toString()); myBuilder.setLength(0); } //TESTED String res = cleanseField(document.getTitle(), s.getScriptlang(), s.getScript(), s.getFlags(), s.getReplacement(), document); if (bConcat) { if (null == myBuilder) { titleBuilder = myBuilder = new StringBuffer(); } myBuilder.append(res).append('\n'); } else { document.setTitle(res); } } } //TESTED else if (s.getField().startsWith("metadata.")) { // (note no support for metadata concatenation, replace only) String metaField = s.getField().substring(9); // (9 for"metadata.") Object[] meta = document.getMetadata().get(metaField); if ((null != meta) && (meta.length > 0)) { Object[] newMeta = new Object[meta.length]; for (int i = 0; i < meta.length; ++i) { Object metaValue = meta[i]; if (metaValue instanceof String) { newMeta[i] = (Object) cleanseField((String) metaValue, s.getScriptlang(), s.getScript(), s.getFlags(), s.getReplacement(), document); } else { newMeta[i] = metaValue; } } // Overwrite the old fields document.addToMetadata(metaField, newMeta); } } // This is sufficient fields for the moment } // (end loop over fields) // Handle any left over cases: if ((null != fullTextBuilder) && (fullTextBuilder.length() > 0)) { document.setFullText(fullTextBuilder.toString()); } //TESTED if ((null != descriptionBuilder) && (descriptionBuilder.length() > 0)) { document.setDescription(descriptionBuilder.toString()); } //TESTED if ((null != titleBuilder) && (titleBuilder.length() > 0)) { document.setTitle(titleBuilder.toString()); } //TESTED }
From source file:com.tremolosecurity.scale.user.ScaleUser.java
public String saveRequests() { SaveResult res = new SaveResult(); HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();// w w w . j a v a 2 s .c o m req.setAttribute("executeWorkflows", res); ArrayList<String> toRemoveFromCart = new ArrayList<String>(); for (String key : this.cart.keySet()) { WorkflowRequest wfr = this.cart.get(key); // check if there's a reason if (!wfr.hasReason()) { res.getErrors().add("No reason specified for '" + wfr.getWf().getLabel() + "'"); res.setError(true); } else { try { // touch to ensure the session is alive StringBuffer callURL = new StringBuffer(); callURL.append(scaleConfig.getRawConfig().getServiceConfiguration().getUnisonURL() + "/services/wf/login"); HttpGet httpget = new HttpGet(callURL.toString()); HttpResponse response = scaleSession.getHttp().execute(httpget); BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = null; StringBuffer json = new StringBuffer(); while ((line = in.readLine()) != null) { json.append(line); } httpget.abort(); Gson gson = new Gson(); ProvisioningResult pres = gson.fromJson(json.toString(), ProvisioningResult.class); if (!pres.isSuccess()) { return "Could not connect to Unison"; } // Execute workflow callURL.setLength(0); callURL.append(scaleConfig.getRawConfig().getServiceConfiguration().getUnisonURL() + "/services/wf/execute"); if (logger.isDebugEnabled()) logger.debug("URL for wf : '" + callURL.toString() + "'"); TremoloUser user = new TremoloUser(); user.setUid(this.getLogin()); user.getAttributes().add(new Attribute( this.getScaleConfig().getRawConfig().getServiceConfiguration().getLookupAttributeName(), this.getLogin())); WFCall wfcall = new WFCall(); wfcall.setUidAttributeName(this.getScaleConfig().getRawConfig().getServiceConfiguration() .getLookupAttributeName()); wfcall.setUser(user); wfcall.setName(key); wfcall.setReason(wfr.getReason()); String sjson = gson.toJson(wfcall); HttpPost post = new HttpPost(callURL.toString()); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("wfcall", sjson)); post.setEntity(new UrlEncodedFormEntity(urlParameters)); response = scaleSession.getHttp().execute(post); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); line = null; json.setLength(0); while ((line = in.readLine()) != null) { json.append(line); } pres = gson.fromJson(json.toString(), ProvisioningResult.class); if (!pres.isSuccess()) { logger.error("Error : '" + pres.getError().getError() + "'"); res.setError(true); res.getErrors().add("Could not submit '" + wfr.getWf().getLabel() + "'"); } else { res.setSaved(true); res.getSavedRequests().add("Request '" + wfr.getWf().getLabel() + "' submitted"); toRemoveFromCart.add(key); } } catch (Exception e) { e.printStackTrace(); res.setError(true); res.getErrors().add("Could not submit '" + wfr.getWf().getLabel() + "'"); } } } for (String key : toRemoveFromCart) { this.cart.remove(key); } return ""; }
From source file:com.sec.ose.osi.report.standard.data.BillOfMaterialsRowGenerator.java
private ArrayList<BillOfMaterialsRow> getBillOfMaterialsRows(String projectName, ArrayList<BOMEnt> boms, ArrayList<IdentifiedFilesRow> IdentifiedFilesRowList, boolean isAllFileListUp, ArrayList<String> filePathListUpComponent) { ArrayList<BillOfMaterialsRow> BillOfMaterialsRowList = new ArrayList<BillOfMaterialsRow>(); HashMap<String, ArrayList<IdentifiedFilesRow>> fileEntMap = toComponentFileEntHashMap( IdentifiedFilesRowList);// w w w . j a v a 2 s . c o m ArrayList<String> keyListForDup = new ArrayList<String>(); for (int i = 0; i < boms.size(); i++) { BOMEnt curBOM = boms.get(i); // 0. gen key (component name + license name) String componentName = curBOM.getComponentName().trim(); log.debug(projectName + "'s BoM info " + " (" + i + "/" + boms.size() + ") : " + componentName); if (componentName.equals(projectName)) continue; String componentLicense = curBOM.getLicense().trim(); String key = componentName + "#" + componentLicense; if (keyListForDup.contains(key)) continue; else keyListForDup.add(key); // 1. extract component info String componentVersion = curBOM.getComponentVersion(); String componentComment = curBOM.getComment(); String matchedFiles = ""; Integer matchedFileCounts = 0; StringBuffer componentCommentBuf = new StringBuffer(""); StringBuffer fileCommentBuf = new StringBuffer(""); if ((componentComment != null) && (componentComment.length() != 0) && (componentComment.equals("null") == false) && (componentComment.equals("null\nnull") == false) && (componentComment .equals("null<" + componentName + " - " + componentVersion + ">\nnull") == false)) { componentCommentBuf.append("[Compoment Comment]\n" + componentComment + "\n\n"); } log.debug("- Component Comment: " + componentCommentBuf.toString()); BillOfMaterialsRow sheetRow = null; // 2. extract file info - component log.debug("- get FileInfo start"); if (fileEntMap.containsKey(key) == true) { ArrayList<IdentifiedFilesRow> fileEntList = fileEntMap.get(key); log.debug("- File # : " + fileEntList.size()); ArrayList<String> categorySet = getCategorySet(fileEntList); if (categorySet == null) continue; // 3. Top folder for (String topFolder : categorySet) { ArrayList<IdentifiedFilesRow> fileEntListForRow = getFileEntListForRow(topFolder, fileEntList); if (fileEntListForRow != null) { // matchedFileCount matchedFileCounts = fileEntListForRow.size(); // comments fileCommentBuf.setLength(0); for (IdentifiedFilesRow curFileEnt : fileEntListForRow) { curFileEnt.setLicense(componentLicense); String fileComment = curFileEnt.getComment(); if ((fileComment != null) && (fileComment.length() != 0)) { fileCommentBuf .append("## " + curFileEnt.getFullPath() + "\n" + fileComment + "\n\n"); } } // fileList if (isAllFileListUp == true || (filePathListUpComponent != null && filePathListUpComponent.contains(componentName))) { matchedFiles = getFullPaths(fileEntListForRow); } else { matchedFiles = getFileCountForFolders(fileEntListForRow); } } sheetRow = new BillOfMaterialsRow(topFolder, matchedFiles, matchedFileCounts, componentName, componentLicense, componentCommentBuf.toString() + fileCommentBuf.toString()); BillOfMaterialsRowList.add(sheetRow); } log.debug("- getFileInfo end"); } else { log.debug("- getFileInfo ent - no file info"); sheetRow = new BillOfMaterialsRow("", matchedFiles, matchedFileCounts, componentName, componentLicense, componentCommentBuf.toString()); BillOfMaterialsRowList.add(sheetRow); } } // end of for log.debug("IdentifiedRowSize: " + BillOfMaterialsRowList.size()); if (BillOfMaterialsRowList.size() == 0) { BillOfMaterialsRow xSheetRow = new BillOfMaterialsRow("", "No component is identified for this project.", 0, "", "", ""); BillOfMaterialsRowList.add(xSheetRow); } return BillOfMaterialsRowList; }
From source file:com.clustercontrol.infra.view.action.DisableInfraManagementAction.java
@Override public Object execute(ExecutionEvent event) throws ExecutionException { this.window = HandlerUtil.getActiveWorkbenchWindow(event); // In case this action has been disposed if (null == this.window || !isEnabled()) { return null; }/* w ww.j a v a 2 s .c om*/ // ??? this.viewPart = HandlerUtil.getActivePart(event); if (!(viewPart instanceof InfraManagementView)) { return null; } InfraManagementView infraManagementView = null; try { infraManagementView = (InfraManagementView) viewPart.getAdapter(InfraManagementView.class); } catch (Exception e) { m_log.info("execute " + e.getMessage()); return null; } if (infraManagementView == null) { m_log.info("execute: view is null"); return null; } StructuredSelection selection = null; if (infraManagementView.getComposite().getTableViewer().getSelection() instanceof StructuredSelection) { selection = (StructuredSelection) infraManagementView.getComposite().getTableViewer().getSelection(); } if (selection == null) { return null; } List<?> sList = (List<?>) selection.toList(); Map<String, List<String>> managementIdMap = new ConcurrentHashMap<String, List<String>>(); for (Object obj : sList) { List<?> list = (List<?>) obj; String managerName = null; if (list == null) { continue; } managerName = (String) list.get(GetInfraManagementTableDefine.MANAGER_NAME); if (managementIdMap.get(managerName) == null) { managementIdMap.put(managerName, new ArrayList<String>()); } } StringBuffer idbuf = new StringBuffer(); int size = 0; for (Object obj : sList) { List<?> list = (List<?>) obj; String managementId = null; String managerName = null; if (list != null) { managementId = (String) list.get(GetInfraManagementTableDefine.MANAGEMENT_ID); managerName = (String) list.get(GetInfraManagementTableDefine.MANAGER_NAME); managementIdMap.get(managerName).add(managementId); if (size > 0) { idbuf.append(", "); } idbuf.append(managementId); size++; } } if (MessageDialog.openConfirm(null, Messages.getString("confirmed"), Messages.getString("message.infra.confirm.action", new Object[] { Messages.getString("infra.management.id"), Messages.getString("infra.disable.setting"), idbuf.toString() })) == false) { return null; } StringBuffer sucManagementIds = new StringBuffer(); StringBuffer failManagementIds = new StringBuffer(); for (Map.Entry<String, List<String>> entry : managementIdMap.entrySet()) { String managerName = entry.getKey(); InfraEndpointWrapper wrapper = InfraEndpointWrapper.getWrapper(managerName); for (String managementId : entry.getValue()) { try { InfraManagementInfo info = wrapper.getInfraManagement(managementId); info.setValidFlg(false); try { wrapper.modifyInfraManagement(info); sucManagementIds.append(managementId + "(" + managerName + "), "); } catch (InvalidSetting_Exception | NotifyDuplicate_Exception | HinemosUnknown_Exception | InvalidRole_Exception | InvalidUserPass_Exception | InfraManagementNotFound_Exception | InfraManagementDuplicate_Exception e) { m_log.debug("execute modifyInfraManagement, " + e.getMessage()); failManagementIds.append(managementId + ", "); } } catch (HinemosUnknown_Exception | InvalidRole_Exception | InvalidUserPass_Exception | NotifyNotFound_Exception | InfraManagementNotFound_Exception e) { m_log.debug("execute getInfraManagement, " + e.getMessage()); failManagementIds.append(managementId + ", "); } } } //????? if (sucManagementIds.length() > 0) { sucManagementIds.setLength(sucManagementIds.length() - 2); MessageDialog.openInformation(null, Messages.getString("successful"), Messages.getString("message.infra.action.result", new Object[] { Messages.getString("infra.management.id"), Messages.getString("infra.disable.setting"), Messages.getString("successful"), sucManagementIds })); } //???? if (failManagementIds.length() > 0) { failManagementIds.setLength(failManagementIds.length() - 2); MessageDialog.openError(null, Messages.getString("failed"), Messages.getString("message.infra.action.result", new Object[] { Messages.getString("infra.management.id"), Messages.getString("infra.disable.setting"), Messages.getString("failed"), failManagementIds })); } infraManagementView.update(); return null; }