List of usage examples for java.lang StringBuffer setLength
@Override public synchronized void setLength(int newLength)
From source file:org.jboss.dashboard.ui.config.components.factory.FactoryComponentFormatter.java
protected void serviceProperties(Component component) { Set properties = new TreeSet(); if (component.getScope().equals(Component.SCOPE_GLOBAL) || component.getScope().equals(Component.SCOPE_VOLATILE)) { Object obj = null;//from www .jav a2 s .com try { obj = component.getObject(); } catch (LookupException e) { log.error("Error: ", e); } if (obj instanceof Map) { properties.addAll(((Map) obj).keySet()); } else if (obj instanceof List) { for (int i = 0; i < ((List) obj).size(); i++) { properties.add(new Integer(i)); } } else { Method[] methods = obj.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String propertyName = getPropertyName(method); if (propertyName != null && isGetter(method)) properties.add(propertyName); } Field[] fields = obj.getClass().getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) { properties.add(field.getName()); } } } if (!properties.isEmpty()) { String propertyType = ""; String fullPropertyType = ""; renderFragment("propertiesStart"); int indexStyle = 0; for (Iterator it = properties.iterator(); it.hasNext();) { indexStyle++; Object property = it.next(); Object value = null; if (obj instanceof Map) { value = ((Map) obj).get(property); propertyType = "String"; fullPropertyType = "java.lang.String []"; } else if (obj instanceof List) { value = ((List) obj).get(((Integer) property).intValue()); propertyType = "String"; fullPropertyType = "java.lang.String []"; } else { String propertyName = (String) property; // Find a getter. String propertyAccessorSuffix = Character.toUpperCase(propertyName.charAt(0)) + (propertyName.length() > 1 ? propertyName.substring(1) : ""); String getterName = "get" + propertyAccessorSuffix; String booleanGetterName = "is" + propertyAccessorSuffix; Method getter = null; Class propertyClass = null; try { getter = obj.getClass().getMethod(getterName, new Class[0]); if (getter != null) try { value = getter.invoke(obj, new Object[0]); propertyClass = getter.getReturnType(); } catch (IllegalAccessException e) { log.error("Error:", e); } catch (InvocationTargetException e) { log.error("Error:", e); } } catch (NoSuchMethodException e) { log.debug("No getter " + getterName + " found."); try { getter = obj.getClass().getMethod(booleanGetterName, new Class[0]); if (getter != null) try { value = getter.invoke(obj, new Object[0]); propertyClass = getter.getReturnType(); } catch (IllegalAccessException iae) { log.error("Error:", iae); } catch (InvocationTargetException ite) { log.error("Error:", ite); } } catch (NoSuchMethodException e1) { log.debug("No getter " + booleanGetterName + " found."); } } if (propertyClass == null) { //Find field try { Field field = obj.getClass().getField(propertyName); if (field != null) { value = field.get(obj); propertyClass = field.getType(); } } catch (NoSuchFieldException e) { log.error("Error: ", e); } catch (IllegalAccessException e) { log.error("Error: ", e); } } if (propertyClass.isArray()) { String componentTypeClass = propertyClass.getComponentType().getName(); if (componentTypeClass.indexOf('.') != -1) { propertyType = componentTypeClass.substring(componentTypeClass.lastIndexOf('.') + 1) + "[]"; } else { propertyType = componentTypeClass + " []"; } fullPropertyType = componentTypeClass + " []"; } else if (propertyClass.isPrimitive()) { propertyType = propertyClass.getName(); fullPropertyType = propertyType; } else { if (propertyClass.getName().indexOf('.') != -1) { propertyType = propertyClass.getName() .substring(propertyClass.getName().lastIndexOf('.') + 1); } else { propertyType = propertyClass.getName(); } fullPropertyType = propertyClass.getName(); } } if (value == null) { value = ""; } else if (value instanceof String || value instanceof Integer || value instanceof Short || value instanceof Character || value instanceof Long || value instanceof Byte || value instanceof Boolean || value instanceof Float || value instanceof Double || value.getClass().isPrimitive()) { } else if (value.getClass().isArray()) { int length = Array.getLength(value); String componentType = value.getClass().getComponentType().getName(); value = componentType + " [" + length + "]"; } else { value = value.getClass().getName(); } Map configuredValues = component.getComponentConfiguredProperties(); List configuredValue = (List) configuredValues.get(property); StringBuffer sb = new StringBuffer(); if (configuredValue != null) for (int i = 0; i < configuredValue.size(); i++) { PropertyChangeProcessingInstruction instruction = (PropertyChangeProcessingInstruction) configuredValue .get(i); if (instruction instanceof PropertyAddProcessingInstruction) { sb.append("\n+").append(instruction.getPropertyValue()); } else if (instruction instanceof PropertySubstractProcessingInstruction) { sb.append("\n-").append(instruction.getPropertyValue()); } else if (instruction instanceof PropertySetProcessingInstruction) { sb.setLength(0); sb.append(" ").append(instruction.getPropertyValue()); } } setAttribute("configuredValue", StringUtils.replace(sb.toString(), ",", ", ")); setAttribute("propertyType", propertyType); setAttribute("fullPropertyType", fullPropertyType); setAttribute("propertyName", property); setAttribute("propertyValue", value); setAttribute("estilo", indexStyle % 2 == 0 ? "skn-even_row" : "skn-odd_row"); renderFragment("outputProperty"); } renderFragment("propertiesEnd"); } } }
From source file:com.tremolosecurity.scale.singlerequest.SingleRequestController.java
public void makeRequest() { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();/*from w w w .j a v a 2 s .c o m*/ this.error = ""; if (this.requestReason == null || this.requestReason.isEmpty()) { this.error = "Reason is required"; return; } try { WFCall wfcall = new WFCall(); wfcall.setName(this.singleRequestConfig.getWorkflowName()); wfcall.setReason(this.requestReason); wfcall.setRequestParams(new HashMap<String, Object>()); wfcall.setUidAttributeName(this.singleRequestConfig.getServiceConfiguration().getLookupAttributeName()); TremoloUser user = new TremoloUser(); ArrayList<Attribute> tuAttrs = new ArrayList<Attribute>(); tuAttrs.add(new Attribute(this.singleRequestConfig.getServiceConfiguration().getLookupAttributeName(), request.getRemoteUser())); user.setAttributes(tuAttrs); wfcall.setUser(user); // touch to ensure the session is alive StringBuffer callURL = new StringBuffer(); callURL.append( this.singleRequestConfig.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()) { this.error = "We could not submit your request at this time, please try again later"; System.err.println(pres.getError().getError()); return; } // Execute workflow callURL.setLength(0); callURL.append( this.singleRequestConfig.getServiceConfiguration().getUnisonURL() + "/services/wf/execute"); if (logger.isDebugEnabled()) logger.debug("URL for wf : '" + callURL.toString() + "'"); 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()) { this.error = "We could not submit your request at this time, please try again later"; logger.error(pres.getError().getError()); return; } else { this.singleRequestSubmitted = true; } } catch (Throwable t) { logger.error("Could not submit request", t); this.error = "We could not submit your request at this time, please try again later"; return; } }
From source file:com.tremolosecurity.scale.passwordreset.ResetController.java
public String resetPassword() { this.errors = null; ArrayList<String> lerrors = new ArrayList<String>(); if (!password1.equals(password2)) { lerrors.add("Passwords not equal"); }//from w ww . jav a 2 s.com List<String> valErrors = this.passwordValidationService.getPasswordValidator().validate(password1, this.user); if (valErrors != null) { lerrors.addAll(valErrors); } if (lerrors.size() == 0) { try { TremoloUser user = new TremoloUser(); user.setUid(this.scaleSession.getLogin()); user.getAttributes().add(new Attribute( this.commonConfig.getScaleConfig().getServiceConfiguration().getLookupAttributeName(), this.scaleSession.getLogin())); user.setUserPassword(password1); WFCall wfcall = new WFCall(); wfcall.setUidAttributeName( this.commonConfig.getScaleConfig().getServiceConfiguration().getLookupAttributeName()); wfcall.setUser(user); wfcall.setName(this.resetCfg.getWorkflowName()); // touch to ensure the session is alive StringBuffer callURL = new StringBuffer(); callURL.append(this.commonConfig.getScaleConfig().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(this.commonConfig.getScaleConfig().getServiceConfiguration().getUnisonURL() + "/services/wf/execute"); if (logger.isDebugEnabled()) logger.debug("URL for wf : '" + callURL.toString() + "'"); 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() + "'"); return "There was a problem updating your profile, please contact the system administrator for help"; } } catch (JsonSyntaxException | IllegalStateException | IOException e) { lerrors.add( "There was a problem saving the password, please contact your system administrator for help"); e.printStackTrace(); } } if (lerrors.size() > 0) { this.errors = lerrors; this.resetSubmitted = false; } else { this.resetSubmitted = true; } return ""; }
From source file:com.qpark.maven.plugin.springconfig.ApplicationPropertiesConfigXmlGenerator.java
public void generate() { this.log.debug("+generate"); StringBuffer sb = new StringBuffer(1024); sb.append(this.getXmlDefinition()); sb.append(Util.getGeneratedAtXmlComment(this.getClass(), this.eipVersion)); sb.append("\n"); sb.append(this.getPropertiesDefinition()); sb.append("\n"); sb.append("</beans>\n"); File f = Util.getFile(this.outputDirectory, new StringBuffer(32).append(this.basePackageName).append(".properties-config.xml").toString()); this.log.info(new StringBuffer().append("Write ").append(f.getAbsolutePath())); try {/*ww w . j a v a 2 s .co m*/ Util.writeToFile(f, sb.toString()); } catch (Exception e) { this.log.error(e.getMessage()); e.printStackTrace(); } Properties p = this.getGeneratedProperties(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); f = Util.getFile(this.outputDirectory, "eip.generated.properties"); try { String prefix = Util.capitalizePackageName(this.basePackageName); p.store(baos, "Build time generated properties"); sb.setLength(0); sb.append(new String(baos.toByteArray())); sb.append("\n# Some additional properties that might to be set\n"); sb.append("# Properties of the ").append(prefix).append("DataSourceJdbc default object:\n"); sb.append("#").append(prefix).append(".jdbc.driverClassName=\n"); sb.append("#").append(prefix).append(".jdbc.url=\n"); sb.append("#").append(prefix).append(".jdbc.username=\n"); sb.append("#").append(prefix).append(".jdbc.password=\n"); sb.append("# Properties of the SelfCallingIntegrationConfig.xml\n"); sb.append("#eip.internal.self.calling.username=\n"); sb.append("#eip.internal.self.calling.password=\n"); sb.append("#eip.internal.self.calling.xxx.endpoint=\n"); sb.append("#").append(prefix).append("=\n"); // sb.append("#").append(prefix).append("=\n"); Util.writeToFile(f, sb.toString()); } catch (Exception e) { this.log.error(e.getMessage()); e.printStackTrace(); } this.log.debug("-generate"); }
From source file:org.kuali.rice.kew.actionrequest.ActionRequestFactory.java
/** * Generates an ActionRequest graph for the given KIM Responsibilities. This graph includes any associated delegations. * @param responsibilities//from w w w . j a v a 2s. c o m * @param approvePolicy */ public void addRoleResponsibilityRequest(List<ResponsibilityAction> responsibilities, String approvePolicy) { if (responsibilities == null || responsibilities.isEmpty()) { LOG.warn( "Didn't create action requests for action request description because no responsibilities were defined."); return; } // it's assumed the that all in the list have the same action type code, priority number, etc. String actionTypeCode = responsibilities.get(0).getActionTypeCode(); Integer priority = responsibilities.get(0).getPriorityNumber(); boolean forceAction = responsibilities.get(0).isForceAction(); KimRoleResponsibilityRecipient roleResponsibilityRecipient = new KimRoleResponsibilityRecipient( responsibilities); // Creation of a parent graph entry for ???? ActionRequestValue requestGraph = null; StringBuffer parentAnnotation = null; // set to allow for suppression of duplicate annotations on the parent action request Set<String> uniqueChildAnnotations = null; if (responsibilities.size() > 1) { requestGraph = createActionRequest(actionTypeCode, priority, roleResponsibilityRecipient, "", // description KewApiConstants.MACHINE_GENERATED_RESPONSIBILITY_ID, forceAction, approvePolicy, null, // ruleId null);// annotation requestGraphs.add(requestGraph); parentAnnotation = new StringBuffer(); uniqueChildAnnotations = new HashSet<String>(responsibilities.size()); } StringBuffer annotation = new StringBuffer(); for (ResponsibilityAction responsibility : responsibilities) { if (LOG.isDebugEnabled()) { LOG.debug("Processing Responsibility for action request: " + responsibility); } // KFSMI-2381 - pull information from KIM to populate annotation annotation.setLength(0); Role role = getRoleService().getRole(responsibility.getRoleId()); annotation.append(role.getNamespaceCode()).append(' ').append(role.getName()).append(' '); Map<String, String> qualifier = responsibility.getQualifier(); if (qualifier != null) { for (String key : qualifier.keySet()) { annotation.append(qualifier.get(key)).append(' '); } } if (responsibility.getPrincipalId() != null) { roleResponsibilityRecipient.setTarget(new KimPrincipalRecipient(responsibility.getPrincipalId())); } else if (responsibility.getGroupId() != null) { roleResponsibilityRecipient.setTarget(new KimGroupRecipient(responsibility.getGroupId())); } else { throw new RiceRuntimeException( "Failed to identify a group or principal on the given ResponsibilityResolutionInfo:" + responsibility); } String annotationStr = annotation.toString(); ActionRequestValue request = createActionRequest(responsibility.getActionTypeCode(), responsibility.getPriorityNumber(), roleResponsibilityRecipient, responsibility.getParallelRoutingGroupingCode(), // description responsibility.getResponsibilityId(), responsibility.isForceAction(), // If not nested in a parent action request, ensure that the request // is first approve so delegations of this request do not require // ALL_APPROVE as well (responsibilities.size() == 1) ? ActionRequestPolicy.FIRST.getCode() : approvePolicy, null, // ruleId annotationStr); // if there is only a single request, don't create the nesting structure if (responsibilities.size() > 1) { request.setParentActionRequest(requestGraph); requestGraph.getChildrenRequests().add(request); if (!uniqueChildAnnotations.contains(annotationStr)) { parentAnnotation.append(annotationStr).append(" -- "); uniqueChildAnnotations.add(annotationStr); } } else { requestGraphs.add(request); } generateKimRoleDelegationRequests(responsibility.getDelegates(), request); } if (responsibilities.size() > 1) { requestGraph.setAnnotation(StringUtils.chomp(parentAnnotation.toString(), " -- ")); } }
From source file:org.apache.hadoop.mapreduce.jobhistory.HistoryViewer.java
private void printFailedAttempts(FilteredJob filteredJob) { Map<String, Set<TaskID>> badNodes = filteredJob.getFilteredMap(); StringBuffer attempts = new StringBuffer(); if (badNodes.size() > 0) { attempts.append("\n").append(filteredJob.getFilter()); attempts.append(" task attempts by nodes"); attempts.append("\nHostname\tFailedTasks"); attempts.append("\n==============================="); System.out.println(attempts.toString()); for (Map.Entry<String, Set<TaskID>> entry : badNodes.entrySet()) { String node = entry.getKey(); Set<TaskID> failedTasks = entry.getValue(); attempts.setLength(0); attempts.append(node).append("\t"); for (TaskID t : failedTasks) { attempts.append(t).append(", "); }//from w w w . j av a 2s.c om System.out.println(attempts.toString()); } } }
From source file:com.m2a.struts.M2AActionBase.java
/** * Create an object of the specified class, * throwing a runtime exception if any error occurs. * If method succeeds, then helpers are guaranteed * to exist.//from w ww. j a va 2 s .co m * * @param request The HTTP request we are processing * @param helperClass The name of the class * @throws IllegalArgumentException if helper cannot be * instantiated */ public Object createHelperObject(HttpServletRequest request, String helperClass) { StringBuffer sb = new StringBuffer(); if (isDebug()) { sb.append(Log.HELPER_CREATING); sb.append(helperClass); servlet.log(sb.toString()); } // Try the create Object helper = null; try { helper = Class.forName(helperClass).newInstance(); } catch (Throwable t) { helper = null; // assemble message: {class}: {exception} sb.setLength(0); sb.append(Log.CREATE_OBJECT_ERROR); sb.append(Log.CLASS); sb.append(helperClass); sb.append(Log.SPACE); sb.append(Log.ACTION_EXCEPTION); sb.append(t.toString()); // throw runtime exception throw new IllegalArgumentException(sb.toString()); } if (isDebug()) { sb.setLength(0); sb.append(Log.HELPER_CREATED); sb.append(Log.CLASS); sb.append(helperClass); servlet.log(sb.toString()); } return helper; }
From source file:edu.umd.cfar.lamp.viper.util.StringHelp.java
/** * Converts a comma seperated list of quoted strings * to a list of debackslashified strings. * For example: <code>"one", "two", "three"</code> will * convert to a list containing three strings, each * stripped of quotes./* w w w. j a v a 2s.c o m*/ * * @param str The string containing a list. * @return A list of strings * @see #debackslashify(String str) * @throws BadDataException */ public static List getQuotedList(String str) throws BadDataException { LinkedList strings = new LinkedList(); StringBuffer buff = new StringBuffer(); boolean inside = false; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (!inside && c != '"') { if ((c != ' ') && (c != '\t') && (c != ',')) { throw new BadDataException("Missing quotes in list: '" + c + "'"); } } else { switch (c) { case '\\': if (++i >= str.length()) throw new BadDataException("Error in escape sequence: " + str); switch (str.charAt(i)) { case 'n': buff.append('\n'); break; case '"': buff.append('"'); break; default: buff.append(c); } break; case '"': if (inside == true) { strings.add(buff.toString()); buff.setLength(0); } inside = !inside; break; default: buff.append(c); } } } return strings; }
From source file:com.adito.server.StatsLogger.java
public void run() { FileOutputStream out = null;/*from w w w . j a v a 2 s .co m*/ try { out = new FileOutputStream(new File(ContextHolder.getContext().getLogDirectory(), "stats.csv")); PrintWriter pw = new PrintWriter(out, true); pw.println("connections,connectionsOpen,connectionsOpenMax,connectionsDurationAve," + "connectionsDurationMax,connectionsRequestsAve,connectionsRequestsMax," + "errors,requests,requestsActive,requestsActiveMax,requestsDurectionAve,requestsDurationMax"); StringBuffer sb = new StringBuffer(); while (true) { sb.append(server.getConnections()); sb.append(","); sb.append(server.getConnectionsOpen()); sb.append(","); sb.append(server.getConnectionsOpenMax()); sb.append(","); sb.append(server.getConnectionsDurationAve()); sb.append(","); sb.append(server.getConnectionsDurationMax()); sb.append(","); sb.append(server.getConnectionsRequestsAve()); sb.append(","); sb.append(server.getConnectionsRequestsMax()); sb.append(","); sb.append(server.getErrors()); sb.append(","); sb.append(server.getRequests()); sb.append(","); sb.append(server.getRequestsActive()); sb.append(","); sb.append(server.getRequestsActiveMax()); sb.append(","); sb.append(server.getRequestsDurationAve()); sb.append(","); sb.append(server.getRequestsDurationMax()); pw.println(sb.toString()); sb.setLength(0); Thread.sleep(update); } } catch (Exception e) { log.error("Failed to create stats files.", e); } finally { Util.closeStream(out); } }
From source file:org.hashtrees.test.HashTreesImplTest.java
@Test public void testCompleteRebuild() throws IOException { int rootNodeId = 0; int nodeId = 2; int segId = 1; int noOfSegments = 2; HashTreesStore[] stores = generateInMemoryAndPersistentStores(); try {/* w w w . j av a2 s.c om*/ for (HashTreesStore store : stores) { HTreeComponents components = createHashTree(noOfSegments, false, TREE_ID_PROVIDER, SEG_ID_PROVIDER, store); HashTrees testTree = components.hTree; SimpleMemStore kvStore = components.store; ByteBuffer expectedKey = generateRandomKeyWithPrefix(segId); ByteBuffer expectedValue = ByteBuffer.wrap(randomBytes()); StringBuffer sb = new StringBuffer(); ByteBuffer expectedDigest = ByteBuffer.wrap(ByteUtils.sha1(expectedValue.array())); sb.append(HashTreesImpl.getHexString(expectedKey, expectedDigest) + "\n"); byte[] expectedLeafNodeDigest = ByteUtils.sha1(sb.toString().getBytes()); testTree.hPut(randomByteBuffer(), randomByteBuffer()); kvStore.put(expectedKey.array(), expectedValue.array()); testTree.rebuildHashTree(SimpleTreeIdProvider.TREE_ID, true); SegmentHash segHash = testTree.getSegmentHash(SimpleTreeIdProvider.TREE_ID, nodeId); Assert.assertNotNull(segHash); Assert.assertTrue(Arrays.equals(expectedLeafNodeDigest, segHash.getHash())); sb.setLength(0); sb.append(Hex.encodeHexString(expectedLeafNodeDigest) + "\n"); byte[] expectedRootNodeDigest = ByteUtils.sha1(sb.toString().getBytes()); SegmentHash actualRootNodeDigest = testTree.getSegmentHash(SimpleTreeIdProvider.TREE_ID, rootNodeId); Assert.assertNotNull(actualRootNodeDigest); Assert.assertTrue(Arrays.equals(expectedRootNodeDigest, actualRootNodeDigest.getHash())); } } finally { HashTreesImplTestUtils.closeStores(stores); } }