List of usage examples for org.apache.commons.lang ObjectUtils toString
public static String toString(Object obj)
Gets the toString
of an Object
returning an empty string ("") if null
input.
ObjectUtils.toString(null) = "" ObjectUtils.toString("") = "" ObjectUtils.toString("bat") = "bat" ObjectUtils.toString(Boolean.TRUE) = "true"
From source file:de.fhg.iais.asc.ui.parts.TransformersPanel.java
/** * helper method for transfering the metadatamapping information to the context. *///ww w . j av a 2s . c o m private String generateMetadataFormatProcessingString() { StringBuilder builder = new StringBuilder( ObjectUtils.toString(this.sourceMetadataComboBox.getSelectedItem())); builder.append(","); appendMetadataFormatPart(builder, this.domainComboBox); builder.append(","); appendMetadataFormatPart(builder, this.providermappingComboBox); builder.append(","); appendMetadataFormatPart(builder, this.collectionmappingComboBox); builder.append(","); builder.append(ObjectUtils.toString(this.versionComboBox.getSelectedItem())); String mdformatstring = builder.toString(); LOG.debug("Generated Metadataformat-String is: md_format = " + mdformatstring); //$NON-NLS-1$ return mdformatstring; }
From source file:it.analysis.IssuesModeTest.java
@Test public void load_user_name_in_json_report() throws Exception { restoreProfile("one-issue-per-line.xml"); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator.getServer().associateProjectToQualityProfile("sample", "xoo", "one-issue-per-line"); // First run (publish mode) SonarScanner runner = configureRunner("shared/xoo-sample"); orchestrator.executeBuild(runner);/*from ww w . j ava 2 s . c o m*/ SonarClient client = orchestrator.getServer().adminWsClient(); Issues issues = client.issueClient().find(IssueQuery.create()); Issue issue = issues.list().get(0); UserParameters creationParameters = UserParameters.create().login("julien").name("Julien H") .password("password").passwordConfirmation("password"); client.userClient().create(creationParameters); // Assign issue client.issueClient().assign(issue.key(), "julien"); // Issues runner = configureRunnerIssues("shared/xoo-sample", null, "sonar.login", "julien", "sonar.password", "password"); BuildResult result = orchestrator.executeBuild(runner); JSONObject obj = ItUtils.getJSONReport(result); Map<String, String> userNameByLogin = Maps.newHashMap(); final JSONArray users = (JSONArray) obj.get("users"); if (users != null) { for (Object user : users) { String login = ObjectUtils.toString(((JSONObject) user).get("login")); String name = ObjectUtils.toString(((JSONObject) user).get("name")); userNameByLogin.put(login, name); } } assertThat(userNameByLogin.get("julien")).isEqualTo("julien"); for (Object issueJson : (JSONArray) obj.get("issues")) { JSONObject jsonObject = (JSONObject) issueJson; if (issue.key().equals(jsonObject.get("key"))) { assertThat(jsonObject.get("assignee")).isEqualTo("julien"); return; } } fail("Issue not found"); }
From source file:de.fhg.iais.asc.ui.parts.HarvesterPanel.java
@Override public void transferUIToConfiguration(AscConfiguration config) { config.put(STRATEGY, this.harvestingStrategyComboBox.getSelectedItem().toString()); config.put(OAI_SOURCE, this.oaipmhTextField.getText()); String oaipmhMetadata = ObjectUtils.toString(this.oaipmhMetadataComboBox.getSelectedItem()); config.put(SOURCE_FOLDER, oaipmhMetadata); if (this.myCortexModel.isHarvestingSelected()) { config.put(META_DATA_FORMAT, oaipmhMetadata); }/*w ww .ja v a2s .c o m*/ config.put(OAI_SET, this.setsTextField.getText()); config.put(HARVESTING_FROM_DATE, this.fromDateTextField.getText()); config.put(HARVESTING_UNTIL_DATE, this.untilDateTextField.getText()); }
From source file:de.codesourcery.eve.skills.ui.components.impl.MarketPriceEditorComponent.java
/** * Populates the context-sensitive popup menu by examining the current table * selection./*w w w .j a va 2s . c o m*/ * * @param event * @param selectedRows * @return <code>true</code> if the updated popup menu hast at least one * menu item */ protected boolean populatePopupMenu(MouseEvent event, int[] selectedRows) { if (log.isDebugEnabled()) { log.debug("maybeShowPopup(): selection = " + ObjectUtils.toString(selectedRows)); } popupMenu.removeAll(); final int column = table.columnAtPoint(event.getPoint()); if (column < 0) { log.warn("maybeShowPopup(): Invalid column at point " + event.getPoint()); return false; } log.debug("maybeShowPopup(): column = " + column); // gather all selected rows final List<TableEntry> data = new ArrayList<TableEntry>(); for (int row : selectedRows) { final TableEntry row2 = tableModel.getRow(row); System.out.println(">>> selected row: " + row2.getItemName()); data.add(row2); } populatePopupMenuFor(column, data); return popupMenu.getComponentCount() > 0; }
From source file:mitm.common.pdf.MessagePDFBuilder.java
public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream) throws DocumentException, MessagingException, IOException { Document document = createDocument(); PdfWriter pdfWriter = createPdfWriter(document, pdfStream); document.open();/* ww w . ja v a 2 s. c om*/ String[] froms = null; try { froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */); } catch (MessagingException e) { logger.warn("From address is not a valid email address."); } if (froms != null) { for (String from : froms) { document.addAuthor(from); } } String subject = null; try { subject = message.getSubject(); } catch (MessagingException e) { logger.error("Error getting subject.", e); } if (subject != null) { document.addSubject(subject); document.addTitle(subject); } String[] tos = null; try { tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO), true /* mime decode */); } catch (MessagingException e) { logger.warn("To is not a valid email address."); } String[] ccs = null; try { ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC), true /* mime decode */); } catch (MessagingException e) { logger.warn("CC is not a valid email address."); } Date sentDate = null; try { sentDate = message.getSentDate(); } catch (MessagingException e) { logger.error("Error getting sent date.", e); } Collection<Part> attachments = new LinkedList<Part>(); String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments); attachments = preprocessAttachments(attachments); if (body == null) { body = MISSING_BODY; } /* * PDF does not have tab support so we convert tabs to spaces */ body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth); PdfPTable headerTable = new PdfPTable(2); headerTable.setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.setWidthPercentage(100); headerTable.setWidths(new int[] { 1, 6 }); headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); Font headerFont = createHeaderFont(); FontSelector headerFontSelector = createHeaderFontSelector(); PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", ")); headerTable.addCell(headerFontSelector.process(decodedFroms)); cell = new PdfPCell(new Paragraph("To:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", ")))); cell = new PdfPCell(new Paragraph("CC:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", ")))); cell = new PdfPCell(new Paragraph("Subject:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject))); cell = new PdfPCell(new Paragraph("Date:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(ObjectUtils.toString(sentDate)); cell = new PdfPCell(new Paragraph("Attachments:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments)))); document.add(headerTable); if (replyURL != null) { addReplyLink(document, replyURL); } /* * Body table will contain the body of the message */ PdfPTable bodyTable = new PdfPTable(1); bodyTable.setWidthPercentage(100f); bodyTable.setSplitLate(false); bodyTable.setSpacingBefore(15f); bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT); addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments); Phrase footer = new Phrase(FOOTER_TEXT); PdfContentByte cb = pdfWriter.getDirectContent(); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0); document.close(); }
From source file:com.smartitengineering.cms.spi.impl.type.ContentTypeObjectConverter.java
@Override public PersistentContentType rowsToObject(Result startRow, ExecutorService executorService) { try {// ww w .j a v a 2 s .c o m PersistableContentType contentType = SmartContentSPI.getInstance().getPersistableDomainFactory() .createPersistableContentType(); PersistentContentType persistentContentType = new PersistentContentType(); /* * Simple fields */ persistentContentType.setMutableContentType(contentType); persistentContentType.setVersion(0l); logger.info("::::::::::::::::::::: Converting rowId to ContentTypeId :::::::::::::::::::::"); contentType.setContentTypeID(getInfoProvider().getIdFromRowId(startRow.getRow())); if (logger.isInfoEnabled()) { logger.info(new StringBuilder("ContentTypeId ").append(contentType.getContentTypeID()).toString()); } Map<byte[], byte[]> simpleValues = startRow.getFamilyMap(FAMILY_SIMPLE); byte[] displayName = simpleValues.remove(CELL_DISPLAY_NAME); if (displayName != null) { logger.debug("Set display name of the content type!"); contentType.setDisplayName(Bytes.toString(displayName)); } byte[] primaryFieldName = simpleValues.remove(CELL_PRIMARY_FIELD_NAME); if (primaryFieldName != null) { final String toString = Bytes.toString(primaryFieldName); if (logger.isDebugEnabled()) { logger.debug("Set primary field name of the content type!" + toString); } contentType.setPrimaryFieldName(toString); } byte[] defTyoe = simpleValues.remove(CELL_DEF_TYPE); if (defTyoe != null) { final String toString = Bytes.toString(defTyoe); if (logger.isDebugEnabled()) { logger.debug("Set primary field name of the content type!" + toString); } contentType.setDefinitionType(ContentType.DefinitionType.valueOf(toString)); } contentType.setEntityTagValue(Bytes.toString(simpleValues.remove(CELL_ENTITY_TAG))); logger.debug("Setting creation and last modified date"); contentType.setCreationDate(Utils.toDate(simpleValues.remove(CELL_CREATION_DATE))); contentType.setLastModifiedDate(Utils.toDate(simpleValues.remove(CELL_LAST_MODIFIED_DATE))); final byte[] parentId = simpleValues.remove(CELL_PARENT_ID); if (parentId != null) { logger.debug("Setting parent id"); contentType.setParent(getInfoProvider().getIdFromRowId(parentId)); } if (!simpleValues.isEmpty()) { String displayNamesPrefix = new StringBuilder(CELL_PARAMETERIZED_DISPLAY_NAME_PREFIX).append(':') .toString(); final byte[] toBytes = Bytes.toBytes(CELL_PARAMETERIZED_DISPLAY_NAME_PREFIX); for (Entry<byte[], byte[]> entry : simpleValues.entrySet()) { if (logger.isDebugEnabled()) { logger.debug("Extra simple fields Key " + Bytes.toString(entry.getKey()) + " " + Bytes.startsWith(entry.getKey(), toBytes)); logger.debug("Extra simple fields Value " + Bytes.toString(entry.getValue())); } if (Bytes.startsWith(entry.getKey(), toBytes)) { String paramKey = Bytes.toString(entry.getKey()).substring(displayNamesPrefix.length()); String paramVal = Bytes.toString(entry.getValue()); contentType.getMutableParameterizedDisplayNames().put(paramKey, paramVal); } } } if (logger.isDebugEnabled()) { final FastDateFormat formatter = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT; logger.debug(String.format("Creation date is %s and last modified date is %s", formatter.format(contentType.getCreationDate()), formatter.format(contentType.getLastModifiedDate()))); logger.debug(String.format("Id is %s and parent id is %s", contentType.getContentTypeID().toString(), ObjectUtils.toString(contentType.getParent()))); } /* * Content status */ logger.debug("Form statuses"); NavigableMap<byte[], byte[]> statusMap = startRow.getFamilyMap(FAMILY_STATUSES); int index = 0; for (byte[] statusName : statusMap.navigableKeySet()) { final String statusNameStr = Bytes.toString(statusName); if (logger.isDebugEnabled()) { logger.debug(new StringBuilder("Forming content status for ").append(statusNameStr).toString()); } //Value not required as both are the same for status MutableContentStatus contentStatus = SmartContentAPI.getInstance().getContentTypeLoader() .createMutableContentStatus(); contentStatus.setContentTypeID(contentType.getContentTypeID()); contentStatus.setId(++index); contentStatus.setName(statusNameStr); contentType.getMutableStatuses().add(contentStatus); } /* * Representations */ logger.debug("Form representations!"); NavigableMap<byte[], byte[]> representationMap = startRow.getFamilyMap(FAMILY_REPRESENTATIONS); Map<String, MutableRepresentationDef> reps = new HashMap<String, MutableRepresentationDef>(); for (byte[] keyBytes : representationMap.navigableKeySet()) { final String key = Bytes.toString(keyBytes); if (logger.isDebugEnabled()) { logger.debug(new StringBuilder("Work with key ").append(key).toString()); } final int indexOfFirstColon = key.indexOf(':'); final String repName = key.substring(0, indexOfFirstColon); final byte[] qualifier = Bytes.toBytes(key.substring(indexOfFirstColon + 1)); if (logger.isDebugEnabled()) { logger.debug(new StringBuilder("Representation name ").append(repName).toString()); logger.debug(new StringBuilder("Representation qualifier ").append(Bytes.toString(qualifier)) .toString()); } MutableRepresentationDef representationDef = reps.get(repName); if (representationDef == null) { logger.debug("Creating new representation def and putting to map"); representationDef = SmartContentAPI.getInstance().getContentTypeLoader() .createMutableRepresentationDef(); reps.put(repName, representationDef); representationDef.setName(repName); } final byte[] value = representationMap.get(keyBytes); fillResourceDef(qualifier, representationDef, value); } contentType.getMutableRepresentationDefs().addAll(reps.values()); /* * Content Co-Processors */ logger.debug("Form Content Co-Processors!"); NavigableMap<byte[], byte[]> ccpMap = startRow.getFamilyMap(FAMILY_CCP); Map<String, MutableContentCoProcessorDef> ccps = new HashMap<String, MutableContentCoProcessorDef>(); for (byte[] keyBytes : ccpMap.navigableKeySet()) { final String key = Bytes.toString(keyBytes); if (logger.isDebugEnabled()) { logger.debug(new StringBuilder("CCP Work with key ").append(key).toString()); } final int indexOfFirstColon = key.indexOf(':'); final String ccpName = key.substring(0, indexOfFirstColon); final byte[] qualifier = Bytes.toBytes(key.substring(indexOfFirstColon + 1)); if (logger.isDebugEnabled()) { logger.debug(new StringBuilder("CCP name ").append(ccpName).toString()); logger.debug(new StringBuilder("CCP qualifier ").append(Bytes.toString(qualifier)).toString()); } MutableContentCoProcessorDef ccpDef = ccps.get(ccpName); if (ccpDef == null) { logger.debug("Creating new content co processor def and putting to map"); ccpDef = SmartContentAPI.getInstance().getContentTypeLoader() .createMutableContentCoProcessorDef(); ccps.put(ccpName, ccpDef); ccpDef.setName(ccpName); } final byte[] value = ccpMap.get(keyBytes); if (Arrays.equals(qualifier, CELL_CCP_PHASE)) { ccpDef.setPhase(ContentType.ContentProcessingPhase.valueOf(Bytes.toString(value))); } else if (Arrays.equals(qualifier, CELL_CCP_PRIORITY)) { ccpDef.setPriority(Bytes.toInt(value)); } else { fillResourceDef(qualifier, ccpDef, value); } } List<MutableContentCoProcessorDef> ccpDefs = new ArrayList<MutableContentCoProcessorDef>(ccps.values()); Collections.sort(ccpDefs, new Comparator<ContentCoProcessorDef>() { public int compare(ContentCoProcessorDef o1, ContentCoProcessorDef o2) { return o1.getPriority() - o2.getPriority(); } }); for (MutableContentCoProcessorDef ccpDef : ccpDefs) { contentType.addContentCoProcessorDef(ccpDef); } /* * Fields */ NavigableMap<byte[], byte[]> fieldMap = startRow.getFamilyMap(FAMILY_FIELDS); //From a map of all cells form a map of cells by field name Map<String, Map<String, byte[]>> fieldsByName = new LinkedHashMap<String, Map<String, byte[]>>(); Utils.organizeByPrefix(fieldMap, fieldsByName, ':'); for (String fieldName : fieldsByName.keySet()) { final MutableFieldDef fieldDef = SmartContentAPI.getInstance().getContentTypeLoader() .createMutableFieldDef(); final Map<String, byte[]> fieldCells = fieldsByName.get(fieldName); populateFieldDef(fieldDef, fieldName, fieldCells); contentType.getMutableFieldDefs().add(fieldDef); } /* * Variants of content type */ Map<byte[], byte[]> variants = startRow.getFamilyMap(FAMILY_TYPE_REPRESENTATIONS); if (variants != null && !variants.isEmpty()) { final Map<MediaType, String> variantMap = new HashMap<MediaType, String>(variants.size()); for (byte[] mediaType : variants.keySet()) { variantMap.put(MediaType.fromString(Bytes.toString(mediaType)), Bytes.toString(variants.get(mediaType))); } contentType.setRepresentations(variantMap); contentType.setFromPersistentStorage(true); } return persistentContentType; } catch (Exception ex) { logger.warn("Error converting result to content type, throwing exception...", ex); throw new RuntimeException(ex); } }
From source file:com.alipay.vbizplatform.web.controller.MyCarManageController.java
/** * ??// w w w.j a v a2 s .c o m * @param request * @param response * @return */ @RequestMapping("/newCarInfo") public String newCarInfo(HttpServletRequest request, HttpServletResponse response) { Map<String, String> pageParam = super.getParametersFromPage(request); // ??? Map<String, Object> vo = null; //?? String manufacturer = null; // ?? String carSeriesName = null; String uId = null; long startTime = System.currentTimeMillis(); try { // Object obj = request.getSession().getAttribute("newVehicleModel"); uId = super.getUserInfo(request).getUid(); String vehicleModelKey = uId + VEHICLE_MODEL_KEY_PREFIX; Object obj = spyMemcachedClient.get(vehicleModelKey); if (obj == null || (pageParam.get("newCarFlag") != null && pageParam.get("newCarFlag").equals("1"))) { vo = new HashMap<String, Object>(); // request.getSession().setAttribute("newVehicleModel", vo); this.spyMemcachedClient.set(vehicleModelKey, Constant.MEMCACHED_SAVETIME_24, vo); } else { vo = (HashMap<String, Object>) obj; } /*****???vo******/ if (StringUtils.isNotEmpty(pageParam.get("carSeriesName"))) { // ?? carSeriesName = URLDecoder.decode(pageParam.get("carSeriesName"), "UTF-8"); if (null != carSeriesName && !(ObjectUtil.toString(vo.get("viSeriesName")).equals(carSeriesName))) { vo.put("viSeriesName", carSeriesName); //? vo.put("viBrandName", URLDecoder.decode(pageParam.get("brandName"), "UTF-8")); //??? vo.put("viBrandLogo", URLDecoder.decode(pageParam.get("picUrl"), "UTF-8")); // vo.put("viLogoUrl", URLDecoder.decode(pageParam.get("modPicUrl"), "UTF-8")); //? vo.put("bgUrl", URLDecoder.decode(pageParam.get("bgUrl"), "UTF-8")); //?? manufacturer = URLDecoder.decode(pageParam.get("manufacturer"), "UTF-8"); vo.put("manufacturer", manufacturer); // vo.put("sweptVolume", ""); vo.put("viStyleName", ""); vo.put("viModelName", ""); vo.put("viModelId", ""); vo.put("engineType", ""); } } //??? List<String> carEngineList = request.getAttribute("carEngineList") == null ? new ArrayList<String>() : (List<String>) request.getAttribute("carEngineList"); String carEngineFlag = pageParam.get("carEngineFlag"); if (!carEngineList.isEmpty() || "false".equals(carEngineFlag)) { String engineType = ""; if (StringUtils.isNotEmpty(pageParam.get("engineType"))) { // ?? engineType = URLDecoder.decode(pageParam.get("engineType"), "UTF-8"); } else { engineType = carEngineList.get(0); } if (null != engineType && !(ObjectUtil.toString(vo.get("engineType")).equals(engineType))) { String sweptVolume = URLDecoder.decode(ObjectUtil.toString(pageParam.get("sweptVolume")), "UTF-8"); String productionYear = URLDecoder.decode(ObjectUtil.toString(pageParam.get("carYearName")), "UTF-8"); String carModelName = URLDecoder.decode(ObjectUtil.toString(pageParam.get("carModelName")), "UTF-8"); //? vo.put("sweptVolume", sweptVolume); // // vo.put("viStyleName", ); // vo.put("productionYear", productionYear); // vo.put("viModelName", carModelName); //?? vo.put("engineType", engineType); Map<String, Object> map = getVihcleInfo(ObjectUtil.toString(vo.get("manufacturer")), ObjectUtil.toString(vo.get("viSeriesName")), sweptVolume, productionYear, carModelName, engineType); // vo.put("viStyleName", ObjectUtil.toString(map.get("style"))); } } else { if (StringUtils.isNotEmpty(pageParam.get("carModelName"))) { // ?? String carModelName = URLDecoder.decode(pageParam.get("carModelName"), "UTF-8"); if (null != carModelName && !(ObjectUtil.toString(vo.get("viModelName")).equals(carModelName))) { String sweptVolume = URLDecoder.decode(ObjectUtil.toString(pageParam.get("sweptVolume")), "UTF-8"); String productionYear = URLDecoder.decode(ObjectUtil.toString(pageParam.get("carYearName")), "UTF-8"); //? vo.put("sweptVolume", sweptVolume); // // vo.put("productionYear", productionYear); // vo.put("viModelName", carModelName); Map<String, Object> map = getVihcleInfo(ObjectUtil.toString(vo.get("manufacturer")), ObjectUtil.toString(vo.get("viSeriesName")), sweptVolume, productionYear, carModelName, "?"); // vo.put("viStyleName", ObjectUtil.toString(map.get("style"))); } } } // cookie? if (StringUtils.isEmpty(ObjectUtils.toString(vo.get("vlCityName")))) { Map<String, String> cityInfo = getCityInfo(request); if (!cityInfo.isEmpty()) { vo.put("vlCityId", cityInfo.get("resident_city_code")); vo.put("vlCityName", cityInfo.get("resident_city_name")); } } // request.getSession().setAttribute("newVehicleModel", vo); this.spyMemcachedClient.set(vehicleModelKey, Constant.MEMCACHED_SAVETIME_24, vo); request.setAttribute("vehicleModel", vo); String viNumber = String.valueOf(vo.get("viNumber")); // if (StringUtils.isNotEmpty(viNumber) && viNumber.length() >= 1) { request.setAttribute("cityAB", viNumber.substring(0, 1)); // request.setAttribute("carNumber", viNumber.substring(1, viNumber.length())); // } else { if (!StringUtils.isEmpty(ObjectUtil.toString(vo.get("vlCityId"))) && (StringUtils.isEmpty(viNumber))) { CityMapModel cityCode = ownerMessage.queryCityMapInfo(vo.get("vlCityId").toString()); if (null != cityCode) request.setAttribute("cityAB", cityCode.getCarNoPrefix()); // } } if (vo.get("viStartTime") != null) { // request.setAttribute("viStartTime", DateUtil.parserDateToString((Date) vo.get("viStartTime"), DateUtil.DATEFORMAT5)); } String backUrl = "/car/myCarList"; Object backObj = request.getSession().getAttribute("backUrl"); if (backObj != null) { backUrl = backObj.toString(); } request.setAttribute("backUrl", backUrl); //ocs?? List<Map<String, Object>> vehicleList = spyMemcachedClient .get(super.getUserInfo(request).getUid() + "_myCarList"); request.setAttribute("carList", JSONObject.toJSON(vehicleList)); //collapse request.setAttribute("collapseFlag", pageParam.get("collapseFlag")); } catch (Exception e) { if (logger.isErrorEnabled()) { logger.error("???", e); } logUtil.log(new Throwable(), "CARINFO", uId, MethodCallResultEnum.EXCEPTION, null, "???", startTime); super.redirectErrorPage("BUSY-ERR", "??", null, null, response); return null; } logUtil.log(new Throwable(), "CARINFO", uId, MethodCallResultEnum.SUCCESS, null, "????", startTime); return "page/cars/completion"; }
From source file:jp.terasoluna.fw.web.struts.taglib.PageLinksTag.java
/** * ?IuWFNgintp?B/*from www. jav a 2 s.co m*/ * * @param obj intIuWFNg * @return l * @throws JspException JSPO */ protected int getInt(Object obj) throws JspException { int retInt = 0; String value = ObjectUtils.toString(obj); if (!"".equals(value)) { try { retInt = Integer.parseInt(value); } catch (NumberFormatException e) { log.error(e.getMessage()); throw new JspException(e); } } return retInt; }
From source file:com.eucalyptus.objectstorage.ObjectStorageGateway.java
@Override public GetObjectExtendedResponseType getObjectExtended(GetObjectExtendedType request) throws S3Exception { ObjectEntity objectEntity = getObjectEntityAndCheckPermissions(request, request.getVersionId()); if (objectEntity.getIsDeleteMarker()) { throw new NoSuchKeyException(request.getKey()); }//from w ww.j a v a 2 s . c o m request.setKey(objectEntity.getObjectUuid()); request.setBucket(objectEntity.getBucket().getBucketUuid()); // Precondition computation. Why do it here instead of delegating it to backends? // 1. AWS Java SDK, used to interact with backend, swallows 412 and 304 responses and returns null objects. // 2. S3 backend may or may not implement the checks for all preconditions // 3. All the metadata required to process preconditions is available in OSG database for now. Using it might save time and or network trip Date ifModifiedSince = request.getIfModifiedSince(); Date ifUnmodifiedSince = request.getIfUnmodifiedSince(); String ifMatch = request.getIfMatch(); String ifNoneMatch = request.getIfNoneMatch(); // Evaluating conditions in the order S3 seems to be evaluating // W3 spec for headers - http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html if (ifMatch != null && !objectEntity.geteTag().equals(ifMatch)) { throw new PreconditionFailedException("If-Match"); } if (DATE_TIME_COMPARATOR.compare(objectEntity.getObjectModifiedTimestamp(), ifUnmodifiedSince) > 0) { throw new PreconditionFailedException("If-Unmodified-Since"); } boolean shortReply = false; // This if-else ladder is for evaluating If-No-Match and If-Modified-Since in conjunction if (ifNoneMatch != null) { if (objectEntity.geteTag().equals(ifNoneMatch)) { if (ifModifiedSince != null) { if (DATE_TIME_COMPARATOR.compare(objectEntity.getObjectModifiedTimestamp(), ifModifiedSince) <= 0) { shortReply = true; } else { // Object was modified since the specified time, return object shortReply = false; } } else { // If-Modified-Since is absent shortReply = true; } } else { // If-None-Match != object etag shortReply = false; } } else if (ifModifiedSince != null && DATE_TIME_COMPARATOR.compare(objectEntity.getObjectModifiedTimestamp(), ifModifiedSince) <= 0) { // If-None-Match // == null shortReply = true; } else { shortReply = false; // return object since If-None-Match and If-Modified are invalid } if (shortReply) { // return 304 Not Modified response to client return generateNotModifiedResponse(request, objectEntity); } // remove all preconditions before forwarding request to backend request.setIfModifiedSince(null); request.setIfUnmodifiedSince(null); request.setIfMatch(null); request.setIfNoneMatch(null); // Byte range computation // Why do it here instead of delegating it to backends? // 1. AWS SDK is used for GET requests to backends. SDK does not let you specify ranges like bytes=-400 or bytes=400- // 2. Backends might not be compatible with S3/RFC behavior. Computing the simplified range unifies OSG behavior across backends while staying // compatible with S3 // Its safe to assume here that range will either be null or positive because of regex used for marshaling the header Long objectSize = objectEntity.getSize(); Long lastIndex = (objectSize - 1) < 0 ? 0 : (objectSize - 1); Long byteRangeStart = request.getByteRangeStart(); Long byteRangeEnd = request.getByteRangeEnd(); if (byteRangeStart != null && byteRangeEnd != null) { // both start and end represent some value if (byteRangeEnd < byteRangeStart) { // check if end is greater than start // invalid byte range. ignore byte range by setting start and end to null byteRangeStart = null; byteRangeEnd = null; } } else if (byteRangeStart == null && byteRangeEnd == null) { // both start and end dont represent any value // ignore byte range } else if (byteRangeStart != null) { // meaning from byteRangeStart to end. example: bytes=400- if (objectSize == 0) { // S3 throws invalid range error for bytes=x-y when size is 0 throw new InvalidRangeException("bytes=" + ObjectUtils.toString(request.getByteRangeStart()) + "-" + ObjectUtils.toString(request.getByteRangeEnd())); } else { byteRangeEnd = lastIndex; } } else { // implies byteRangeEnd != null. meaning last byteRangeEnd number of bytes. example bytes=-400 if (byteRangeEnd == 0) { // S3 throws invalid range error for bytes=-0 throw new InvalidRangeException("bytes=" + ObjectUtils.toString(request.getByteRangeStart()) + "-" + ObjectUtils.toString(request.getByteRangeEnd())); } else { byteRangeStart = (objectSize - byteRangeEnd) > 0 ? (objectSize - byteRangeEnd) : 0; } // end is always object-size-1 as the start is null byteRangeEnd = lastIndex; } // Final checks if (byteRangeStart != null && byteRangeStart > lastIndex) { // check if start byte position is out of range throw new InvalidRangeException("bytes=" + ObjectUtils.toString(request.getByteRangeStart()) + "-" + ObjectUtils.toString(request.getByteRangeEnd())); // Throw error if it is out of range } if (byteRangeEnd != null && byteRangeEnd > lastIndex) { // check if start byte position is out of range byteRangeEnd = lastIndex; // Set the end byte position to object-size-1 } request.setByteRangeStart(byteRangeStart); // Populate the computed byte range before firing request to backend request.setByteRangeEnd(byteRangeEnd); // Populate the computed byte range before firing request to backend try { GetObjectExtendedResponseType response = ospClient.getObjectExtended(request); response.setVersionId(objectEntity.getVersionId()); response.setLastModified(objectEntity.getObjectModifiedTimestamp()); populateStoredHeaders(response, objectEntity.getStoredHeaders()); response.setResponseHeaderOverrides(request.getResponseHeaderOverrides()); response.setStatus(HttpResponseStatus.OK); return response; } catch (S3Exception e) { LOG.warn("CorrelationId: " + Contexts.lookup().getCorrelationId() + " Responding to client with: ", e); throw e; } catch (Exception e) { // Wrap the error from back-end with a 500 error LOG.warn("CorrelationId: " + Contexts.lookup().getCorrelationId() + " Responding to client with 500 InternalError because of:", e); throw new InternalErrorException(request.getBucket() + "/" + request.getKey(), e); } }
From source file:com.yucheng.cmis.pub.util.NewStringUtils.java
/** * <p>Joins the elements of the provided <code>Iterator</code> into * a single String containing the provided elements.</p> * * <p>No delimiter is added before or after the list. Null objects or empty * strings within the iteration are represented by empty strings.</p> * * <p>See the examples here: {@link #join(Object[],char)}. </p> * * @param iterator the <code>Iterator</code> of values to join together, may be null * @param separator the separator character to use * @return the joined String, <code>null</code> if null iterator input * @since 2.0// w w w . j a v a 2s .c om */ public static String join(Iterator iterator, char separator) { // handle null, zero and one elements before building a buffer if (iterator == null) { return null; } if (!iterator.hasNext()) { return EMPTY; } Object first = iterator.next(); if (!iterator.hasNext()) { return ObjectUtils.toString(first); } // two or more elements StringBuffer buf = new StringBuffer(256); // Java default is 16, probably too small if (first != null) { buf.append(first); } while (iterator.hasNext()) { buf.append(separator); Object obj = iterator.next(); if (obj != null) { buf.append(obj); } } return buf.toString(); }