List of usage examples for org.apache.commons.lang StringUtils defaultIfEmpty
public static String defaultIfEmpty(String str, String defaultStr)
Returns either the passed in String, or if the String is empty or null
, the value of defaultStr
.
From source file:org.apache.flume.sink.kafka.KafkaSink.java
public Status process() throws EventDeliveryException { Status status = null;/*from w w w . ja v a2 s . co m*/ Channel channel = getChannel(); Transaction tx = channel.getTransaction(); tx.begin(); try { Event event = channel.take(); if (event == null) { tx.commit(); return Status.READY; } String partitionKey = (String) parameters.get(KafkaFlumeConstants.PARTITION_KEY_NAME); String encoding = StringUtils.defaultIfEmpty( (String) this.parameters.get(KafkaFlumeConstants.ENCODING_KEY_NAME), KafkaFlumeConstants.DEFAULT_ENCODING); String topic = Preconditions.checkNotNull( (String) this.parameters.get(KafkaFlumeConstants.CUSTOME_TOPIC_KEY_NAME), "custom.topic.name is required"); String eventData = new String(event.getBody(), encoding); KeyedMessage<String, String> data; if (StringUtils.isEmpty(partitionKey)) { data = new KeyedMessage<String, String>(topic, eventData); } else { data = new KeyedMessage<String, String>(topic, partitionKey, eventData); } producer.send(data); log.trace("Message: {}", event.getBody()); tx.commit(); status = Status.READY; } catch (Exception e) { tx.rollback(); log.error("KafkaSink Exception:{}", e); status = Status.BACKOFF; } finally { tx.close(); } return status; }
From source file:org.apache.jackrabbit.core.query.lucene.JahiaSearchIndex.java
/** * Schedules the re-indexing of the repository content in a background job. *//*from w w w .j av a 2 s .c om*/ public void scheduleReindexing() { if (!prepareReindexing()) { return; } JobDetail jobDetail = BackgroundJob.createJahiaJob("Re-indexing of the " + StringUtils.defaultIfEmpty(getContext().getWorkspace(), "system") + " workspace content", ReindexJob.class); JobDataMap jobDataMap = jobDetail.getJobDataMap(); jobDataMap.put("index", this); try { ServicesRegistry.getInstance().getSchedulerService().scheduleJobNow(jobDetail, true); } catch (SchedulerException e) { log.error("Unable to schedule background job for re-indexing", e); } }
From source file:org.apache.jackrabbit.core.query.lucene.JahiaSearchIndex.java
synchronized void reindexAndSwitch() throws RepositoryException, IOException { long startTime = System.currentTimeMillis(); File dest = new File(getPath() + ".old." + System.currentTimeMillis()); FileUtils.deleteQuietly(new File(newIndex.getPath())); String workspace = StringUtils.defaultIfEmpty(getContext().getWorkspace(), "system"); log.info("Start initializing new index for {} workspace", workspace); newIndex.newIndexInit();//from www . ja v a 2s . co m log.info("New index for workspace {} initialized in {} ms", workspace, System.currentTimeMillis() - startTime); newIndex.replayDelayedUpdates(newIndex); log.info("Reindexing has finished for {} workspace, switching to new index...", workspace); long startTimeIntern = System.currentTimeMillis(); try { switching = true; quietClose(newIndex); quietClose(this); if (!new File(getPath()).renameTo(dest)) { throw new IOException("Unable to rename the existing index folder " + getPath()); } if (!new File(newIndex.getPath()).renameTo(new File(getPath()))) { // rename the index back log.info("Restored original index"); dest.renameTo(new File(getPath())); throw new IOException("Unable to rename the newly created index folder " + newIndex.getPath()); } log.info("New index deployed, reloading {}", getPath()); init(fs, getContext()); newIndex.replayDelayedUpdates(this); log.info("New index ready"); } finally { newIndex = null; switching = false; } log.info("Switched to newly created index in {} ms", System.currentTimeMillis() - startTimeIntern); FileUtils.deleteQuietly(dest); SpellChecker spellChecker = getSpellChecker(); if (spellChecker instanceof CompositeSpellChecker) { ((CompositeSpellChecker) spellChecker).updateIndex(false); log.info("Triggered update of the spellchecker index"); } log.info("Re-indexing operation is completed for {} workspace in {}", workspace, DateUtils.formatDurationWords(System.currentTimeMillis() - startTime)); }
From source file:org.apache.jetspeed.portlets.spaces.PageNavigator.java
@Override public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String name = actionRequest.getParameter("name"); String type = actionRequest.getParameter("type"); String templatePage = StringUtils.defaultString(actionRequest.getParameter("templatePage"), null); SpaceBean space = (SpaceBean) actionRequest.getPortletSession().getAttribute(SpaceNavigator.ATTRIBUTE_SPACE, PortletSession.APPLICATION_SCOPE); if (space == null) { log.warn("Space not found in session."); return;//from w ww . j a v a2 s . com } if (StringUtils.isBlank(name)) { log.warn("Blank name to create a node of type " + type); return; } if (StringUtils.isBlank(type)) { throw new PortletException("Blank node type: " + type); } if ((Page.DOCUMENT_TYPE.equals(type) || (Folder.FOLDER_TYPE.equals(type))) && StringUtils.isBlank(templatePage)) { templatePage = actionRequest.getPreferences().getValue("defaultTemplatePage", null); if (StringUtils.isBlank(templatePage)) { throw new PortletException("Invalid template page: " + templatePage); } } try { RequestContext requestContext = (RequestContext) actionRequest .getAttribute(RequestContext.REQUEST_PORTALENV); ContentPage contentPage = requestContext.getPage(); String spacePath = space.getPath(); String contentPagePath = contentPage.getPath(); String contentFolderPath = StringUtils .defaultIfEmpty(StringUtils.substringBeforeLast(contentPagePath, "/"), "/"); String nodeName = name.replace(' ', '_'); String nodePath = null; if (contentFolderPath.startsWith(spacePath)) { nodePath = StringUtils.removeEnd(contentFolderPath, "/") + "/" + StringUtils.removeStart(nodeName, "/"); } else { nodePath = StringUtils.removeEnd(spacePath, "/") + "/" + StringUtils.removeStart(nodeName, "/"); } if (Page.DOCUMENT_TYPE.equals(type)) { String path = nodePath + Page.DOCUMENT_TYPE; Page source = pageManager.getPage(templatePage); Page newPage = pageManager.copyPage(source, path, false); newPage.setTitle(name); pageManager.updatePage(newPage); requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null); String redirect = admin.getPortalURL(actionRequest, actionResponse, path); actionResponse.sendRedirect(redirect); } else if (Folder.FOLDER_TYPE.equals(type)) { String path = nodePath; Folder folder = pageManager.newFolder(path); folder.setTitle(name); pageManager.updateFolder(folder); String defaultPagePath = folder.getPath() + "/" + Folder.FALLBACK_DEFAULT_PAGE; Page source = pageManager.getPage(templatePage); Page newPage = pageManager.copyPage(source, defaultPagePath, false); pageManager.updatePage(newPage); requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null); } else if (Link.DOCUMENT_TYPE.equals(type)) { String path = nodePath + Link.DOCUMENT_TYPE; Link link = pageManager.newLink(path); link.setTitle(name); pageManager.updateLink(link); requestContext.setSessionAttribute(PORTAL_SITE_SESSION_CONTEXT_ATTR_KEY, null); } } catch (Exception e) { log.error("Failed to update page.", e); } }
From source file:org.apache.ofbiz.common.CommonEvents.java
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) { try {/*from ww w .jav a 2 s .c om*/ Delegator delegator = (Delegator) request.getAttribute("delegator"); final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default"); final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "captcha." + captchaSizeConfigName, delegator); final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|"); final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored final int fontSize = Integer.parseInt(captchaSizeConfigs[0]); final int height = Integer.parseInt(captchaSizeConfigs[1]); final int width = Integer.parseInt(captchaSizeConfigs[2]); final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha", "captcha.code_length", 6); final char[] availableChars = EntityUtilProperties .getPropertyValue("captcha", "captcha.characters", delegator).toCharArray(); //It is possible to pass the font size, image width and height with the request as well Color backgroundColor = Color.gray; Color borderColor = Color.DARK_GRAY; Color textColor = Color.ORANGE; Color circleColor = new Color(160, 160, 160); Font textFont = new Font("Arial", Font.PLAIN, fontSize); int circlesToDraw = 6; float horizMargin = 20.0f; double rotationRange = 0.7; // in radians BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setColor(backgroundColor); g.fillRect(0, 0, width, height); //Generating some circles for background noise g.setColor(circleColor); for (int i = 0; i < circlesToDraw; i++) { int circleRadius = (int) (Math.random() * height / 2.0); int circleX = (int) (Math.random() * width - circleRadius); int circleY = (int) (Math.random() * height - circleRadius); g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2); } g.setColor(textColor); g.setFont(textFont); FontMetrics fontMetrics = g.getFontMetrics(); int maxAdvance = fontMetrics.getMaxAdvance(); int fontHeight = fontMetrics.getHeight(); String captchaCode = RandomStringUtils.random(6, availableChars); float spaceForLetters = -horizMargin * 2 + width; float spacePerChar = spaceForLetters / (charsToPrint - 1.0f); for (int i = 0; i < captchaCode.length(); i++) { // this is a separate canvas used for the character so that // we can rotate it independently int charWidth = fontMetrics.charWidth(captchaCode.charAt(i)); int charDim = Math.max(maxAdvance, fontHeight); int halfCharDim = (charDim / 2); BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB); Graphics2D charGraphics = charImage.createGraphics(); charGraphics.translate(halfCharDim, halfCharDim); double angle = (Math.random() - 0.5) * rotationRange; charGraphics.transform(AffineTransform.getRotateInstance(angle)); charGraphics.translate(-halfCharDim, -halfCharDim); charGraphics.setColor(textColor); charGraphics.setFont(textFont); int charX = (int) (0.5 * charDim - 0.5 * charWidth); charGraphics.drawString("" + captchaCode.charAt(i), charX, ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent())); float x = horizMargin + spacePerChar * (i) - charDim / 2.0f; int y = ((height - charDim) / 2); g.drawImage(charImage, (int) x, y, charDim, charDim, null, null); charGraphics.dispose(); } // Drawing the image border g.setColor(borderColor); g.drawRect(0, 0, width - 1, height - 1); g.dispose(); response.setContentType("image/jpeg"); ImageIO.write(bufferedImage, "jpg", response.getOutputStream()); HttpSession session = request.getSession(); Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_")); if (captchaCodeMap == null) { captchaCodeMap = new HashMap<String, String>(); session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap); } captchaCodeMap.put(captchaCodeId, captchaCode); } catch (Exception ioe) { Debug.logError(ioe.getMessage(), module); } return "success"; }
From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java
public static Map<String, Object> uspsPriorityMailInternationalLabel(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId"); String resource = (String) context.get("configProps"); GenericValue shipmentRouteSegment = (GenericValue) context.get("shipmentRouteSegment"); Locale locale = (Locale) context.get("locale"); // Start the document Document requestDocument;// ww w . j a v a 2 s . c om boolean certify = false; String test = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "test", resource, "shipment.usps.test"); if (!"Y".equalsIgnoreCase(test)) { requestDocument = createUspsRequestDocument("PriorityMailIntlRequest", false, delegator, shipmentGatewayConfigId, resource); } else { requestDocument = createUspsRequestDocument("PriorityMailIntlCertifyRequest", false, delegator, shipmentGatewayConfigId, resource); certify = true; } Element rootElement = requestDocument.getDocumentElement(); // Retrieve from/to address and package details GenericValue originAddress = null; GenericValue originTelecomNumber = null; GenericValue destinationAddress = null; GenericValue destinationProvince = null; GenericValue destinationCountry = null; GenericValue destinationTelecomNumber = null; List<GenericValue> shipmentPackageRouteSegs = null; try { originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false); originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false); destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false); if (destinationAddress != null) { destinationProvince = destinationAddress.getRelatedOne("StateProvinceGeo", false); destinationCountry = destinationAddress.getRelatedOne("CountryGeo", false); } destinationTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false); shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, null, false); } catch (GenericEntityException e) { Debug.logError(e, module); } if (originAddress == null || originTelecomNumber == null) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelOriginAddressMissing", locale)); } // Origin Info // USPS wants a separate first name and last, best we can do is split the string on the white space, if that doesn't work then default to putting the attnName in both fields String fromAttnName = originAddress.getString("attnName"); String fromFirstName = StringUtils.defaultIfEmpty(StringUtils.substringBefore(fromAttnName, " "), fromAttnName); String fromLastName = StringUtils.defaultIfEmpty(StringUtils.substringAfter(fromAttnName, " "), fromAttnName); UtilXml.addChildElementValue(rootElement, "FromFirstName", fromFirstName, requestDocument); UtilXml.addChildElementValue(rootElement, "FromLastName", fromLastName, requestDocument); UtilXml.addChildElementValue(rootElement, "FromFirm", originAddress.getString("toName"), requestDocument); // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1 UtilXml.addChildElementValue(rootElement, "FromAddress1", originAddress.getString("address2"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromAddress2", originAddress.getString("address1"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromCity", originAddress.getString("city"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromState", originAddress.getString("stateProvinceGeoId"), requestDocument); UtilXml.addChildElementValue(rootElement, "FromZip5", originAddress.getString("postalCode"), requestDocument); // USPS expects a phone number consisting of area code + contact number as a single numeric string String fromPhoneNumber = originTelecomNumber.getString("areaCode") + originTelecomNumber.getString("contactNumber"); fromPhoneNumber = StringUtil.removeNonNumeric(fromPhoneNumber); UtilXml.addChildElementValue(rootElement, "FromPhone", fromPhoneNumber, requestDocument); // Destination Info UtilXml.addChildElementValue(rootElement, "ToName", destinationAddress.getString("attnName"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToFirm", destinationAddress.getString("toName"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToAddress1", destinationAddress.getString("address1"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToAddress2", destinationAddress.getString("address2"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToCity", destinationAddress.getString("city"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToProvince", destinationProvince.getString("geoName"), requestDocument); // TODO: Test these country names, I think we're going to need to maintain a list of USPS names UtilXml.addChildElementValue(rootElement, "ToCountry", destinationCountry.getString("geoName"), requestDocument); UtilXml.addChildElementValue(rootElement, "ToPostalCode", destinationAddress.getString("postalCode"), requestDocument); // TODO: Figure out how to answer this question accurately UtilXml.addChildElementValue(rootElement, "ToPOBoxFlag", "N", requestDocument); String toPhoneNumber = destinationTelecomNumber.getString("countryCode") + destinationTelecomNumber.getString("areaCode") + destinationTelecomNumber.getString("contactNumber"); UtilXml.addChildElementValue(rootElement, "ToPhone", toPhoneNumber, requestDocument); UtilXml.addChildElementValue(rootElement, "NonDeliveryOption", "RETURN", requestDocument); for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) { Document packageDocument = (Document) requestDocument.cloneNode(true); // This is our reference and can be whatever we want. For lack of a better alternative we'll use shipmentId:shipmentPackageSeqId:shipmentRouteSegmentId String fromCustomsReference = shipmentRouteSegment.getString("shipmentId") + ":" + shipmentRouteSegment.getString("shipmentRouteSegmentId"); fromCustomsReference = StringUtils.join(UtilMisc.toList(shipmentRouteSegment.get("shipmentId"), shipmentPackageRouteSeg.get("shipmentPackageSeqId"), shipmentRouteSegment.get("shipmentRouteSegementId")), ':'); UtilXml.addChildElementValue(rootElement, "FromCustomsReference", fromCustomsReference, packageDocument); // Determine the container type for this package String container = "VARIABLE"; String packageTypeCode = null; GenericValue shipmentPackage = null; List<GenericValue> shipmentPackageContents = null; try { shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false); shipmentPackageContents = shipmentPackage.getRelated("ShipmentPackageContent", null, null, false); GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false); if (shipmentBoxType != null) { GenericValue carrierShipmentBoxType = EntityUtil.getFirst(shipmentBoxType .getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "USPS"), null, false)); if (carrierShipmentBoxType != null) { packageTypeCode = carrierShipmentBoxType.getString("packageTypeCode"); // Supported type codes List<String> supportedPackageTypeCodes = UtilMisc.toList("LGFLATRATEBOX", "SMFLATRATEBOX", "FLATRATEBOX", "MDFLATRATEBOX", "FLATRATEENV"); if (supportedPackageTypeCodes.contains(packageTypeCode)) { container = packageTypeCode; } } } } catch (GenericEntityException e) { Debug.logError(e, module); } UtilXml.addChildElementValue(rootElement, "Container", container, packageDocument); // According to the docs sending an empty postage tag will cause the postage to be calculated UtilXml.addChildElementValue(rootElement, "Postage", "", packageDocument); BigDecimal packageWeight = shipmentPackage.getBigDecimal("weight"); String weightUomId = shipmentPackage.getString("weightUomId"); BigDecimal packageWeightPounds = UomWorker.convertUom(packageWeight, weightUomId, "WT_lb", dispatcher); Integer[] packagePoundsOunces = convertPoundsToPoundsOunces(packageWeightPounds); UtilXml.addChildElementValue(rootElement, "GrossPounds", packagePoundsOunces[0].toString(), packageDocument); UtilXml.addChildElementValue(rootElement, "GrossOunces", packagePoundsOunces[1].toString(), packageDocument); UtilXml.addChildElementValue(rootElement, "ContentType", "MERCHANDISE", packageDocument); UtilXml.addChildElementValue(rootElement, "Agreement", "N", packageDocument); UtilXml.addChildElementValue(rootElement, "ImageType", "PDF", packageDocument); // TODO: Try the different layouts UtilXml.addChildElementValue(rootElement, "ImageType", "ALLINONEFILE", packageDocument); UtilXml.addChildElementValue(rootElement, "CustomerRefNo", fromCustomsReference, packageDocument); // Add the shipping contents Element shippingContents = UtilXml.addChildElement(rootElement, "ShippingContents", packageDocument); for (GenericValue shipmentPackageContent : shipmentPackageContents) { Element itemDetail = UtilXml.addChildElement(shippingContents, "ItemDetail", packageDocument); GenericValue product = null; GenericValue originGeo = null; try { GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem", false); product = shipmentItem.getRelatedOne("Product", false); originGeo = product.getRelatedOne("OriginGeo", false); } catch (GenericEntityException e) { Debug.logInfo(e, module); } UtilXml.addChildElementValue(itemDetail, "Description", product.getString("productName"), packageDocument); UtilXml.addChildElementValue(itemDetail, "Quantity", shipmentPackageContent .getBigDecimal("quantity").setScale(0, BigDecimal.ROUND_CEILING).toPlainString(), packageDocument); String packageContentValue = ShipmentWorker.getShipmentPackageContentValue(shipmentPackageContent) .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString(); UtilXml.addChildElementValue(itemDetail, "Value", packageContentValue, packageDocument); BigDecimal productWeight = ProductWorker.getProductWeight(product, "WT_lbs", delegator, dispatcher); Integer[] productPoundsOunces = convertPoundsToPoundsOunces(productWeight); UtilXml.addChildElementValue(itemDetail, "NetPounds", productPoundsOunces[0].toString(), packageDocument); UtilXml.addChildElementValue(itemDetail, "NetOunces", productPoundsOunces[1].toString(), packageDocument); UtilXml.addChildElementValue(itemDetail, "HSTariffNumber", "", packageDocument); UtilXml.addChildElementValue(itemDetail, "CountryOfOrigin", originGeo.getString("geoName"), packageDocument); } // Send the request Document responseDocument = null; String api = certify ? "PriorityMailIntlCertify" : "PriorityMailIntl"; try { responseDocument = sendUspsRequest(api, requestDocument, delegator, shipmentGatewayConfigId, resource, locale); } catch (UspsRequestException e) { Debug.logInfo(e, module); return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelSendingError", UtilMisc.toMap("errorString", e.getMessage()), locale)); } Element responseElement = responseDocument.getDocumentElement(); // TODO: No mention of error returns in the docs String labelImageString = UtilXml.childElementValue(responseElement, "LabelImage"); if (UtilValidate.isEmpty(labelImageString)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementLabelImage", locale)); } shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes())); String trackingCode = UtilXml.childElementValue(responseElement, "BarcodeNumber"); if (UtilValidate.isEmpty(trackingCode)) { return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementBarcodeNumber", locale)); } shipmentPackageRouteSeg.set("trackingCode", trackingCode); try { shipmentPackageRouteSeg.store(); } catch (GenericEntityException e) { Debug.logError(e, module); } } return ServiceUtil.returnSuccess(); }
From source file:org.apache.sling.hc.core.impl.servlet.HealthCheckExecutorServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String tagsStr = StringUtils.defaultIfEmpty(StringUtils.substringBeforeLast(request.getPathInfo(), "."), "") .replace("/", ""); if (StringUtils.isBlank(tagsStr)) { // if not provided via path use parameter or default tagsStr = StringUtils.defaultIfEmpty(request.getParameter(PARAM_TAGS.name), ""); }//from w ww .j av a2s.c om final String[] tags = tagsStr.split("[, ;]+"); String format = StringUtils.substringAfterLast(request.getPathInfo(), "."); if (StringUtils.isBlank(format)) { // if not provided via extension use parameter or default format = StringUtils.defaultIfEmpty(request.getParameter(PARAM_FORMAT.name), FORMAT_HTML); } final Boolean includeDebug = Boolean.valueOf(request.getParameter(PARAM_INCLUDE_DEBUG.name)); final Map<Result.Status, Integer> statusMapping = request.getParameter(PARAM_HTTP_STATUS.name) != null ? getStatusMapping(request.getParameter(PARAM_HTTP_STATUS.name)) : null; HealthCheckExecutionOptions options = new HealthCheckExecutionOptions(); options.setCombineTagsWithOr(Boolean .valueOf(StringUtils.defaultString(request.getParameter(PARAM_COMBINE_TAGS_WITH_OR.name), "true"))); options.setForceInstantExecution(Boolean.valueOf(request.getParameter(PARAM_FORCE_INSTANT_EXECUTION.name))); String overrideGlobalTimeoutVal = request.getParameter(PARAM_OVERRIDE_GLOBAL_TIMEOUT.name); if (StringUtils.isNumeric(overrideGlobalTimeoutVal)) { options.setOverrideGlobalTimeout(Integer.valueOf(overrideGlobalTimeoutVal)); } List<HealthCheckExecutionResult> executionResults = this.healthCheckExecutor.execute(options, tags); Result.Status mostSevereStatus = Result.Status.DEBUG; for (HealthCheckExecutionResult executionResult : executionResults) { Status status = executionResult.getHealthCheckResult().getStatus(); if (status.ordinal() > mostSevereStatus.ordinal()) { mostSevereStatus = status; } } Result overallResult = new Result(mostSevereStatus, "Overall status " + mostSevereStatus); sendNoCacheHeaders(response); if (statusMapping != null) { Integer httpStatus = statusMapping.get(overallResult.getStatus()); response.setStatus(httpStatus); } if (FORMAT_HTML.equals(format)) { sendHtmlResponse(overallResult, executionResults, request, response, includeDebug); } else if (FORMAT_JSON.equals(format)) { sendJsonResponse(overallResult, executionResults, null, response, includeDebug); } else if (FORMAT_JSONP.equals(format)) { String jsonpCallback = StringUtils.defaultIfEmpty(request.getParameter(PARAM_JSONP_CALLBACK.name), JSONP_CALLBACK_DEFAULT); sendJsonResponse(overallResult, executionResults, jsonpCallback, response, includeDebug); } else if (FORMAT_TXT.equals(format)) { sendTxtResponse(overallResult, response); } else { response.setContentType("text/plain"); response.getWriter().println("Invalid format " + format + " - supported formats: html|json|jsonp|txt"); } }
From source file:org.apache.sling.jcr.resource.internal.JcrResourceListener.java
private static String getLongestCommonPrefix(Set<String> paths) { String prefix = null;/*from w ww.j a va2 s. co m*/ Iterator<String> it = paths.iterator(); if (it.hasNext()) { prefix = it.next(); } while (it.hasNext()) { prefix = getCommonPrefix(prefix, it.next()); } return StringUtils.defaultIfEmpty(prefix, "/"); }
From source file:org.apache.sling.scripting.sightly.impl.engine.extension.URIManipulationFilterExtension.java
@Override @SuppressWarnings("unchecked") public Object call(RenderContext renderContext, Object... arguments) { ExtensionUtils.checkArgumentCount(RuntimeFunction.URI_MANIPULATION, arguments, 2); RuntimeObjectModel runtimeObjectModel = renderContext.getObjectModel(); String uriString = runtimeObjectModel.toString(arguments[0]); Map<String, Object> options = runtimeObjectModel.toMap(arguments[1]); StringBuilder sb = new StringBuilder(); PathInfo pathInfo = new PathInfo(uriString); uriAppender(sb, SCHEME, options, pathInfo.getScheme()); if (sb.length() > 0) { sb.append(":"); sb.append(StringUtils.defaultIfEmpty(pathInfo.getBeginPathSeparator(), "//")); }//from w w w. j ava 2 s .c om if (sb.length() > 0) { uriAppender(sb, DOMAIN, options, pathInfo.getHost()); } else { String domain = getOption(DOMAIN, options, pathInfo.getHost()); if (StringUtils.isNotEmpty(domain)) { sb.append("//").append(domain); } } if (pathInfo.getPort() > -1) { sb.append(":").append(pathInfo.getPort()); } String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY); if (prependPath == null) { prependPath = StringUtils.EMPTY; } String path = getOption(PATH, options, pathInfo.getPath()); if (StringUtils.isEmpty(path)) { // if the path is forced to be empty don't remove the path path = pathInfo.getPath(); } if (StringUtils.isNotEmpty(path) && !"/".equals(path)) { if (StringUtils.isNotEmpty(prependPath)) { if (sb.length() > 0 && !prependPath.startsWith("/")) { prependPath = "/" + prependPath; } if (!prependPath.endsWith("/")) { prependPath += "/"; } } String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY); if (appendPath == null) { appendPath = StringUtils.EMPTY; } if (StringUtils.isNotEmpty(appendPath)) { if (!appendPath.startsWith("/")) { appendPath = "/" + appendPath; } } String newPath; try { newPath = new URI(prependPath + path + appendPath).normalize().getPath(); } catch (URISyntaxException e) { newPath = prependPath + path + appendPath; } if (sb.length() > 0 && sb.lastIndexOf("/") != sb.length() - 1 && StringUtils.isNotEmpty(newPath) && !newPath.startsWith("/")) { sb.append("/"); } sb.append(newPath); Set<String> selectors = pathInfo.getSelectors(); handleSelectors(runtimeObjectModel, selectors, options); for (String selector : selectors) { if (StringUtils.isNotBlank(selector) && !selector.contains(" ")) { // make sure not to append empty or invalid selectors sb.append(".").append(selector); } } String extension = getOption(EXTENSION, options, pathInfo.getExtension()); if (StringUtils.isNotEmpty(extension)) { sb.append(".").append(extension); } String prependSuffix = getOption(PREPEND_SUFFIX, options, StringUtils.EMPTY); if (StringUtils.isNotEmpty(prependSuffix)) { if (!prependSuffix.startsWith("/")) { prependSuffix = "/" + prependSuffix; } if (!prependSuffix.endsWith("/")) { prependSuffix += "/"; } } String pathInfoSuffix = pathInfo.getSuffix(); String suffix = getOption(SUFFIX, options, pathInfoSuffix == null ? StringUtils.EMPTY : pathInfoSuffix); if (suffix == null) { suffix = StringUtils.EMPTY; } String appendSuffix = getOption(APPEND_SUFFIX, options, StringUtils.EMPTY); if (StringUtils.isNotEmpty(appendSuffix)) { appendSuffix = "/" + appendSuffix; } String newSuffix = FilenameUtils.normalize(prependSuffix + suffix + appendSuffix, true); if (StringUtils.isNotEmpty(newSuffix)) { if (!newSuffix.startsWith("/")) { sb.append("/"); } sb.append(newSuffix); } } else if ("/".equals(path)) { sb.append(path); } Map<String, Collection<String>> parameters = pathInfo.getParameters(); handleParameters(runtimeObjectModel, parameters, options); if (sb.length() > 0 && !parameters.isEmpty()) { if (StringUtils.isEmpty(path)) { sb.append("/"); } sb.append("?"); for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) { for (String value : entry.getValue()) { sb.append(entry.getKey()).append("=").append(value).append("&"); } } // delete the last & sb.deleteCharAt(sb.length() - 1); } String fragment = getOption(FRAGMENT, options, pathInfo.getFragment()); if (StringUtils.isNotEmpty(fragment)) { sb.append("#").append(fragment); } return sb.toString(); }
From source file:org.apache.sling.scripting.sightly.impl.filter.URIManipulationFilter.java
@Override @SuppressWarnings("unchecked") public Object call(RenderContext renderContext, Object... arguments) { ExtensionUtils.checkArgumentCount(URI_MANIPULATION_FUNCTION, arguments, 2); RenderContextImpl rci = (RenderContextImpl) renderContext; String uriString = rci.toString(arguments[0]); Map<String, Object> options = rci.toMap(arguments[1]); if (uriString == null) { return null; }/*w ww . java 2 s .c om*/ StringBuilder sb = new StringBuilder(); PathInfo pathInfo = new PathInfo(uriString); uriAppender(sb, SCHEME, options, pathInfo.getScheme()); if (sb.length() > 0) { sb.append(":"); sb.append(StringUtils.defaultIfEmpty(pathInfo.getBeginPathSeparator(), "//")); } if (sb.length() > 0) { uriAppender(sb, DOMAIN, options, pathInfo.getHost()); } else { String domain = getOption(DOMAIN, options, pathInfo.getHost()); if (StringUtils.isNotEmpty(domain)) { sb.append("//").append(domain); } } if (pathInfo.getPort() > -1) { sb.append(":").append(pathInfo.getPort()); } String prependPath = getOption(PREPEND_PATH, options, StringUtils.EMPTY); if (prependPath == null) { prependPath = StringUtils.EMPTY; } if (StringUtils.isNotEmpty(prependPath)) { if (sb.length() > 0 && !prependPath.startsWith("/")) { prependPath = "/" + prependPath; } if (!prependPath.endsWith("/")) { prependPath += "/"; } } String path = getOption(PATH, options, pathInfo.getPath()); if (StringUtils.isEmpty(path)) { // if the path is forced to be empty don't remove the path path = pathInfo.getPath(); } String appendPath = getOption(APPEND_PATH, options, StringUtils.EMPTY); if (appendPath == null) { appendPath = StringUtils.EMPTY; } if (StringUtils.isNotEmpty(appendPath)) { if (!appendPath.startsWith("/")) { appendPath = "/" + appendPath; } } String newPath; try { newPath = new URI(prependPath + path + appendPath).normalize().getPath(); } catch (URISyntaxException e) { newPath = prependPath + path + appendPath; } if (sb.length() > 0 && sb.lastIndexOf("/") != sb.length() - 1 && StringUtils.isNotEmpty(newPath) && !newPath.startsWith("/")) { sb.append("/"); } sb.append(newPath); Set<String> selectors = pathInfo.getSelectors(); handleSelectors(rci, selectors, options); for (String selector : selectors) { if (StringUtils.isNotBlank(selector) && !selector.contains(" ")) { // make sure not to append empty or invalid selectors sb.append(".").append(selector); } } String extension = getOption(EXTENSION, options, pathInfo.getExtension()); if (StringUtils.isNotEmpty(extension)) { sb.append(".").append(extension); } String prependSuffix = getOption(PREPEND_SUFFIX, options, StringUtils.EMPTY); if (StringUtils.isNotEmpty(prependSuffix)) { if (!prependSuffix.startsWith("/")) { prependSuffix = "/" + prependSuffix; } if (!prependSuffix.endsWith("/")) { prependSuffix += "/"; } } String pathInfoSuffix = pathInfo.getSuffix(); String suffix = getOption(SUFFIX, options, pathInfoSuffix == null ? StringUtils.EMPTY : pathInfoSuffix); if (suffix == null) { suffix = StringUtils.EMPTY; } String appendSuffix = getOption(APPEND_SUFFIX, options, StringUtils.EMPTY); if (StringUtils.isNotEmpty(appendSuffix)) { appendSuffix = "/" + appendSuffix; } String newSuffix = ResourceUtil.normalize(prependSuffix + suffix + appendSuffix); if (StringUtils.isNotEmpty(newSuffix)) { if (!newSuffix.startsWith("/")) { sb.append("/"); } sb.append(newSuffix); } Map<String, Collection<String>> parameters = pathInfo.getParameters(); handleParameters(rci, parameters, options); if (!parameters.isEmpty()) { sb.append("?"); for (Map.Entry<String, Collection<String>> entry : parameters.entrySet()) { for (String value : entry.getValue()) { sb.append(entry.getKey()).append("=").append(value).append("&"); } } // delete the last & sb.deleteCharAt(sb.length() - 1); } String fragment = getOption(FRAGMENT, options, pathInfo.getFragment()); if (StringUtils.isNotEmpty(fragment)) { sb.append("#").append(fragment); } return sb.toString(); }