@Override
  public List<DataElementOperand> validateRequiredComments(
      DataSet dataSet,
      Period period,
      OrganisationUnit organisationUnit,
      DataElementCategoryOptionCombo attributeOptionCombo) {
    List<DataElementOperand> violations = new ArrayList<>();

    if (dataSet.isNoValueRequiresComment()) {
      for (DataElement de : dataSet.getDataElements()) {
        for (DataElementCategoryOptionCombo co : de.getCategoryCombo().getOptionCombos()) {
          DataValue dv =
              dataValueService.getDataValue(de, period, organisationUnit, co, attributeOptionCombo);

          boolean missingValue = dv == null || StringUtils.trimToNull(dv.getValue()) == null;
          boolean missingComment = dv == null || StringUtils.trimToNull(dv.getComment()) == null;

          if (missingValue && missingComment) {
            violations.add(new DataElementOperand(de, co));
          }
        }
      }
    }

    return violations;
  }
  /**
   * Builds {@link Predicate} of a not-existing column on table.
   *
   * @param tableName The name of table
   * @param columnName the name of column
   * @return The predicate for row builder
   */
  public static Predicate<DataRow.Builder> notExistingColumn(String tableName, String columnName) {
    String safeTableName = StringUtils.trimToNull(tableName);
    String safeColumnName = StringUtils.trimToNull(columnName);

    Validate.notNull(safeTableName, "Need viable name of table");
    Validate.notNull(safeColumnName, "Need viable name of column");

    return rowBuilder ->
        safeTableName.equals(rowBuilder.getTableName())
            && !rowBuilder.getDataField(safeColumnName).isPresent();
  }
  @Override
  public String execute() {
    Constant constant = constantService.getConstant(id);

    constant.setName(StringUtils.trimToNull(name));
    constant.setShortName(StringUtils.trimToNull(shortName));
    constant.setCode(StringUtils.trimToNull(code));
    constant.setDescription(StringUtils.trimToNull(description));
    constant.setValue(Double.parseDouble(value));

    constantService.updateConstant(constant);

    return SUCCESS;
  }
 @RequestMapping(value = "/status")
 public String status(
     Model model, @RequestParam(value = "status", required = false) String status) {
   if (StringUtils.trimToNull(status) != null) model.addAttribute("status", status);
   else if (!model.containsAttribute("status")) model.addAttribute("status", "");
   return "status";
 }
Example #5
0
 @Override
 public ActionForward process(
     ActionMapping pActionMapping,
     ActionForm pActionForm,
     HttpServletRequest pHttpServletRequest,
     HttpServletResponse pHttpServletResponse) {
   LoginForm lLoginForm = (LoginForm) pActionForm;
   String lSubmitAction = StringUtils.trimToNull(lLoginForm.getSubmitAction());
   if (lSubmitAction != null) {
     if (SubmitActions.LOGIN.toString().equals(lSubmitAction)) {
       String lLoginName = lLoginForm.getLoginName();
       String lPassword = lLoginForm.getPassword();
       if (!mLoginService.doesUserExist(lLoginName)) {
         ActionMessages lActionMessages = new ActionMessages();
         lActionMessages.add(
             ActionMessages.GLOBAL_MESSAGE,
             new ActionMessage(LOGIN_ERROR_KEY_PREFIX + ".loginname.notexists"));
         this.saveErrors(pHttpServletRequest, lActionMessages);
         lLoginForm.setNextPage(NavigateActions.DisplayLogin.toString());
         return pActionMapping.findForward(NavigateActions.DisplayLogin.toString());
       }
       boolean lAuthenticated = mLoginService.isUserAuthenticated(lLoginName, lPassword);
       if (lAuthenticated) {
         LOGGER.debug("Login Successful");
         User lUser = mLoginService.loadUserByLoginName(lLoginName);
         pHttpServletRequest.getSession().setAttribute(LOGGED_IN_USER, lUser);
         lLoginForm.setNextPage("DisplayHomePage");
       }
       lLoginForm.setNextPage(NavigateActions.DisplayHomePage.toString());
     }
   }
   return pActionMapping.findForward(NavigateActions.DisplayLogin.toString());
 }
 /**
  * From String to LocalDateTime
  *
  * @param v to convert
  * @return DateTime
  * @throws Exception
  */
 public LocalDateTime unmarshal(String v) throws Exception {
   v = StringUtils.trimToNull(v);
   if (v == null) {
     return null;
   }
   return new LocalDateTime(v);
 }
Example #7
0
  protected boolean localizeDataObjectElements(
      List<ValuedDataObject> dataObjects, ObjectNode infoNode) {
    boolean localizationValuesChanged = false;
    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService =
        commandContext.getProcessEngineConfiguration().getDynamicBpmnService();

    for (ValuedDataObject dataObject : dataObjects) {
      List<ExtensionElement> localizationElements =
          dataObject.getExtensionElements().get("localization");
      if (localizationElements != null) {
        for (ExtensionElement localizationElement : localizationElements) {
          if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(
              localizationElement.getNamespacePrefix())) {
            String locale = localizationElement.getAttributeValue(null, "locale");
            String name = localizationElement.getAttributeValue(null, "name");
            String documentation = null;

            List<ExtensionElement> documentationElements =
                localizationElement.getChildElements().get("documentation");
            if (documentationElements != null) {
              for (ExtensionElement documentationElement : documentationElements) {
                documentation = StringUtils.trimToNull(documentationElement.getElementText());
                break;
              }
            }

            if (name != null
                && isEqualToCurrentLocalizationValue(
                        locale,
                        dataObject.getName(),
                        DynamicBpmnConstants.LOCALIZATION_NAME,
                        name,
                        infoNode)
                    == false) {
              dynamicBpmnService.changeLocalizationName(
                  locale, dataObject.getName(), name, infoNode);
              localizationValuesChanged = true;
            }

            if (documentation != null
                && isEqualToCurrentLocalizationValue(
                        locale,
                        dataObject.getName(),
                        DynamicBpmnConstants.LOCALIZATION_DESCRIPTION,
                        documentation,
                        infoNode)
                    == false) {

              dynamicBpmnService.changeLocalizationDescription(
                  locale, dataObject.getName(), documentation, infoNode);
              localizationValuesChanged = true;
            }
          }
        }
      }
    }

    return localizationValuesChanged;
  }
Example #8
0
  protected void createLocalizationValues(String processDefinitionId, Process process) {
    if (process == null) return;

    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService =
        commandContext.getProcessEngineConfiguration().getDynamicBpmnService();
    ObjectNode infoNode = dynamicBpmnService.getProcessDefinitionInfo(processDefinitionId);

    boolean localizationValuesChanged = false;
    List<ExtensionElement> localizationElements =
        process.getExtensionElements().get("localization");
    if (localizationElements != null) {
      for (ExtensionElement localizationElement : localizationElements) {
        if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(
            localizationElement.getNamespacePrefix())) {
          String locale = localizationElement.getAttributeValue(null, "locale");
          String name = localizationElement.getAttributeValue(null, "name");
          String documentation = null;
          List<ExtensionElement> documentationElements =
              localizationElement.getChildElements().get("documentation");
          if (documentationElements != null) {
            for (ExtensionElement documentationElement : documentationElements) {
              documentation = StringUtils.trimToNull(documentationElement.getElementText());
              break;
            }
          }

          String processId = process.getId();
          if (isEqualToCurrentLocalizationValue(locale, processId, "name", name, infoNode)
              == false) {
            dynamicBpmnService.changeLocalizationName(locale, processId, name, infoNode);
            localizationValuesChanged = true;
          }

          if (documentation != null
              && isEqualToCurrentLocalizationValue(
                      locale, processId, "description", documentation, infoNode)
                  == false) {
            dynamicBpmnService.changeLocalizationDescription(
                locale, processId, documentation, infoNode);
            localizationValuesChanged = true;
          }

          break;
        }
      }
    }

    boolean isFlowElementLocalizationChanged =
        localizeFlowElements(process.getFlowElements(), infoNode);
    boolean isDataObjectLocalizationChanged =
        localizeDataObjectElements(process.getDataObjects(), infoNode);
    if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
      localizationValuesChanged = true;
    }

    if (localizationValuesChanged) {
      dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, infoNode);
    }
  }
  /**
   * Given a raw taxon rank and name, finds the matching Linnean rank (if any) and builds a Taxon
   * object with the rank and name.
   */
  public Taxon parseTaxon(String rawTaxonRank, String taxonName) {
    Taxon taxon = null;
    String processedTaxonRank = StringUtils.trimToNull(rawTaxonRank);
    if (processedTaxonRank != null && !StringUtils.equals(processedTaxonRank, "null")) {
      processedTaxonRank = processedTaxonRank.replaceAll(" ", "").toUpperCase();
      String rawRank = taxonRankMapping.getProperty(processedTaxonRank);
      if (rawRank == null) {
        LOG.info("Could not process taxon ranking of [{}], skipping.", processedTaxonRank);
      } else {
        int rank = Integer.valueOf(rawRank.trim());
        LOG.debug("ProcessedTaxonRank [{}] gives numeric rank [{}]", processedTaxonRank, rank);
        switch (rank) {
          case 1000:
            taxon = new Taxon(TaxonRankEnum.KINGDOM, taxonName);
            break;
          case 2000:
            taxon = new Taxon(TaxonRankEnum.PHYLUM, taxonName);
            break;
          case 3000:
            taxon = new Taxon(TaxonRankEnum.CLASS, taxonName);
            break;
          case 4000:
            taxon = new Taxon(TaxonRankEnum.ORDER, taxonName);
            break;
          case 5000:
            taxon = new Taxon(TaxonRankEnum.FAMILY, taxonName);
            break;
        }
      }
    }

    return taxon;
  }
 /**
  * Get the request sequence number from an incoming request.
  *
  * @param request incoming
  * @return request sequence number, or -1 if missing
  */
 public static long getRequestSequence(Document request) {
   final Element sequenceElement =
       request.getRootElement().element(XFormsConstants.XXFORMS_SEQUENCE_QNAME);
   assert sequenceElement != null;
   final String text = StringUtils.trimToNull(sequenceElement.getTextTrim());
   return (text != null) ? Long.parseLong(text) : -1; // allow for empty value for non-Ajax cases
 }
 public static Vermarktungsart parse(String value) {
   value = StringUtils.trimToNull(value);
   if (value == null) return null;
   for (Vermarktungsart s : Vermarktungsart.values()) {
     if (String.valueOf(s.value).equalsIgnoreCase(value)) return s;
   }
   return null;
 }
Example #12
0
 public void put(ConfigurationItem configurationItem, String value) {
   value = StringUtils.trimToNull(value);
   if (value == null) {
     map.remove(configurationItem);
   } else {
     map.put(configurationItem, value);
   }
 }
Example #13
0
  public String getEditorTheme() {
    if (editorTheme == null) {
      this.editorTheme =
          StringUtils.trimToNull(configuration.getString("appearances.editor-theme"));
    }

    return editorTheme;
  }
Example #14
0
  /**
   * @see AbstractPropertyEditor#setValue(PropertyDescriptor,
   *     org.pivot4j.ui.property.RenderPropertyList, java.lang.Object)
   */
  @Override
  public void setValue(PropertyDescriptor descriptor, RenderPropertyList properties, Object value) {
    String stringValue = StringUtils.trimToNull((String) value);

    if (stringValue != null && stringValue.matches("[a-fA-F0-9]+")) {
      stringValue = "#" + stringValue;
    }

    super.setValue(descriptor, properties, stringValue);
  }
  static HashMap<String, String> getFeaturedItem() {
    HashMap<String, String> returnMap = null;

    // configuration file location -> ${dspace.dir}/var/featured-content/current.properties
    String featuredItemFile = FeaturedContentController.getFeaturedItemFile();
    if (featuredItemFile == null) {
      return null;
    }

    Properties props = new Properties();
    InputStream is = null;

    try {
      // file location ->  ${dspace.src}/dspace/config/modules/uow-aspects.cfg
      File propFile = new File(featuredItemFile);
      is = new FileInputStream(propFile);
      props.load(is);

      String img_location = StringUtils.trimToNull(props.getProperty("img_location"));
      String link_target = StringUtils.trimToNull(props.getProperty("link_target"));
      String caption = StringUtils.trimToNull(props.getProperty("caption"));

      if ((img_location != null) && (link_target != null) && (caption != null)) {
        returnMap = new HashMap<>();

        returnMap.put("img_location", img_location);
        returnMap.put("link_target", link_target);
        returnMap.put("caption", caption);
      }

    } catch (IOException e) {
      log.warn("Problem reading featured content information from file: " + e.getMessage(), e);
    } finally {
      try {
        if (is != null) {
          is.close();
        }
      } catch (IOException e) {
        log.warn("Problem closing InputStream: " + e.getMessage(), e);
      }
    }
    return returnMap;
  }
  public RequestParameters extractParameters(Document request, boolean isInitialState) {

    // Get UUID
    final String uuid = getRequestUUID(request);
    assert uuid != null;

    // Get static state if any
    final String encodedStaticState;
    {
      final Element staticStateElement =
          request.getRootElement().element(XFormsConstants.XXFORMS_STATIC_STATE_QNAME);
      encodedStaticState =
          (staticStateElement != null)
              ? StringUtils.trimToNull(staticStateElement.getTextTrim())
              : null;
    }

    // Get dynamic state if any
    final String encodedDynamicState;
    {
      final QName qName =
          isInitialState
              ? XFormsConstants.XXFORMS_INITIAL_DYNAMIC_STATE_QNAME
              : XFormsConstants.XXFORMS_DYNAMIC_STATE_QNAME;
      final Element dynamicStateElement = request.getRootElement().element(qName);
      encodedDynamicState =
          (dynamicStateElement != null)
              ? StringUtils.trimToNull(dynamicStateElement.getTextTrim())
              : null;
    }

    assert (encodedStaticState != null && encodedDynamicState != null)
        || (encodedStaticState == null && encodedDynamicState == null);

    // Session must be present if state is not coming with the request
    if (NetUtils.getSession(false) == null && encodedStaticState == null) {
      throw new OXFException("Session has expired. Unable to process incoming request.");
    }

    return new RequestParametersImpl(uuid, encodedStaticState, encodedDynamicState);
  }
 private static String cutParameter(CharacterIterator ci, Map<String, String> patterns) {
   StringBuilder regexBuffer = new StringBuilder();
   int braceCount = 1;
   for (char regexChar = ci.next(); regexChar != CharacterIterator.DONE; regexChar = ci.next()) {
     if (regexChar == OPEN) {
       braceCount++;
     } else if (regexChar == CLOSE) {
       braceCount--;
       if (braceCount == 0) {
         break;
       }
     }
     regexBuffer.append(regexChar);
   }
   if (braceCount != 0) {
     return null;
   }
   String regex = StringUtils.trimToNull(regexBuffer.toString());
   if (regex == null) {
     return null;
   }
   StringBuilder pathBuffer = new StringBuilder();
   pathBuffer.append(OPEN);
   int index = regex.indexOf(COLON);
   if (index != -1) {
     final String name = StringUtils.trimToNull(regex.substring(0, index));
     final String value = StringUtils.trimToNull(regex.substring(index + 1, regex.length()));
     if (name != null) {
       pathBuffer.append(name);
       if (value != null) {
         patterns.put(name, value);
       }
     } else {
       return null;
     }
   } else {
     pathBuffer.append(regex);
   }
   pathBuffer.append(CLOSE);
   return pathBuffer.toString();
 }
 static String getFeaturedItemFile() {
   String featuredItemFile =
       StringUtils.trimToNull(
           ConfigurationManager.getProperty("uow-aspects", "featured-content.datafile"));
   if (featuredItemFile == null) {
     log.warn(
         "Problem reading featured-content configuration.",
         new Exception("Problem reading featured-content configuration."));
     return null;
   }
   return featuredItemFile;
 }
Example #19
0
  /** @see AbstractPropertyEditor#getValue(org.pivot4j.ui.property.SimpleRenderProperty) */
  @Override
  protected Object getValue(SimpleRenderProperty property) {
    String value = StringUtils.trimToNull((String) super.getValue(property));

    if (value != null && value.matches("#[a-fA-F0-9]+")) {
      value = value.substring(1);
    } else {
      value = null;
    }

    return value;
  }
 public void trimToNull() {
   StringUtils.trimToNull(title);
   StringUtils.trimToNull(location);
   StringUtils.trimToNull(notes);
   StringUtils.trimToNull(url);
   StringUtils.trimToNull(recurRule);
   StringUtils.trimToNull(reminder);
 }
  public RequestParameters extractParameters(Document request, boolean isInitialState) {

    // Get UUID
    final String uuid = getRequestUUID(request);
    assert uuid != null;

    // Get static state if any
    final String encodedStaticState;
    {
      final Element staticStateElement =
          request.getRootElement().element(XFormsConstants.XXFORMS_STATIC_STATE_QNAME);
      encodedStaticState =
          (staticStateElement != null)
              ? StringUtils.trimToNull(staticStateElement.getTextTrim())
              : null;
    }

    // Get dynamic state if any
    final String encodedDynamicState;
    {
      final QName qName =
          isInitialState
              ? XFormsConstants.XXFORMS_INITIAL_DYNAMIC_STATE_QNAME
              : XFormsConstants.XXFORMS_DYNAMIC_STATE_QNAME;
      final Element dynamicStateElement = request.getRootElement().element(qName);
      encodedDynamicState =
          (dynamicStateElement != null)
              ? StringUtils.trimToNull(dynamicStateElement.getTextTrim())
              : null;
    }

    assert (encodedStaticState != null && encodedDynamicState != null)
        || (encodedStaticState == null && encodedDynamicState == null);

    return new RequestParametersImpl(uuid, encodedStaticState, encodedDynamicState);
  }
 public <T extends java.util.Collection<? super Packet>> T acquireFromHttpRequest(
     T argCollection, javax.servlet.http.HttpServletRequest argRequest, String argParameterName) {
   org.apache.commons.lang3.Validate.notNull(argCollection);
   org.apache.commons.lang3.Validate.notNull(argRequest);
   org.apache.commons.lang3.Validate.notEmpty(argParameterName);
   String[] lclValues = argRequest.getParameterValues(argParameterName);
   if (lclValues == null || lclValues.length == 0) {
     return argCollection;
   }
   for (String lclValueUntrimmed : lclValues) {
     String lclValue = org.apache.commons.lang3.StringUtils.trimToNull(lclValueUntrimmed);
     if (lclValue == null) {
       continue;
     }
     java.lang.Integer lclId = java.lang.Integer.valueOf(lclValue);
     Packet lclResult = forId(lclId);
     org.apache.commons.lang3.Validate.notNull(
         lclResult, "'" + lclValue + "' is not a valid Id for any Packet");
     argCollection.add(lclResult);
   }
   return argCollection;
 }
Example #23
0
 /** Adds a property to this set. */
 public void addProperty(String property) {
   String candidate = StringUtils.trimToNull(property);
   if (candidate != null) {
     properties_.add(property);
   }
 }
  @Override
  public String execute() throws Exception {
    OptionSet optionSet = optionService.getOptionSet(optionSetId);

    valueType =
        optionSet != null && optionSet.getValueType() != null
            ? optionSet.getValueType()
            : valueType;

    TrackedEntityAttribute trackedEntityAttribute =
        trackedEntityAttributeService.getTrackedEntityAttribute(id);

    trackedEntityAttribute.setName(StringUtils.trimToNull(name));
    trackedEntityAttribute.setShortName(StringUtils.trimToNull(shortName));
    trackedEntityAttribute.setCode(StringUtils.trimToNull(code));
    trackedEntityAttribute.setDescription(StringUtils.trimToNull(description));
    trackedEntityAttribute.setValueType(valueType);
    trackedEntityAttribute.setAggregationType(AggregationType.fromValue(aggregationType));
    trackedEntityAttribute.setExpression(expression);
    trackedEntityAttribute.setDisplayOnVisitSchedule(false);
    trackedEntityAttribute.setOptionSet(optionSet);

    unique = unique != null;
    trackedEntityAttribute.setUnique(unique);

    inherit = inherit != null;
    trackedEntityAttribute.setInherit(inherit);

    confidential = confidential != null;
    trackedEntityAttribute.setConfidential(confidential);

    if (unique) {
      boolean orgunitScope = false;
      boolean programScope = false;

      if (Objects.equals(scope, SCOPE_ORGUNIT) || Objects.equals(scope, SCOPE_PROGRAM_IN_ORGUNIT)) {
        orgunitScope = true;
      }

      if (Objects.equals(scope, SCOPE_PROGRAM) || Objects.equals(scope, SCOPE_PROGRAM_IN_ORGUNIT)) {
        programScope = true;
      }

      trackedEntityAttribute.setOrgunitScope(orgunitScope);
      trackedEntityAttribute.setProgramScope(programScope);
    } else if (ValueType.TRACKER_ASSOCIATE == valueType) {
      trackedEntityAttribute.setTrackedEntity(
          trackedEntityService.getTrackedEntity(trackedEntityId));
    }

    if (legendSetId != null) {
      trackedEntityAttribute.setLegendSet(legendService.getLegendSet(legendSetId));
    }

    if (jsonAttributeValues != null) {
      AttributeUtils.updateAttributeValuesFromJson(
          trackedEntityAttribute.getAttributeValues(), jsonAttributeValues, attributeService);
    }

    trackedEntityAttributeService.updateTrackedEntityAttribute(trackedEntityAttribute);

    return SUCCESS;
  }
Example #25
0
  protected boolean localizeFlowElements(
      Collection<FlowElement> flowElements, ObjectNode infoNode) {
    boolean localizationValuesChanged = false;

    if (flowElements == null) return localizationValuesChanged;

    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService =
        commandContext.getProcessEngineConfiguration().getDynamicBpmnService();

    for (FlowElement flowElement : flowElements) {
      if (flowElement instanceof UserTask || flowElement instanceof SubProcess) {
        List<ExtensionElement> localizationElements =
            flowElement.getExtensionElements().get("localization");
        if (localizationElements != null) {
          for (ExtensionElement localizationElement : localizationElements) {
            if (BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX.equals(
                localizationElement.getNamespacePrefix())) {
              String locale = localizationElement.getAttributeValue(null, "locale");
              String name = localizationElement.getAttributeValue(null, "name");
              String documentation = null;
              List<ExtensionElement> documentationElements =
                  localizationElement.getChildElements().get("documentation");
              if (documentationElements != null) {
                for (ExtensionElement documentationElement : documentationElements) {
                  documentation = StringUtils.trimToNull(documentationElement.getElementText());
                  break;
                }
              }

              String flowElementId = flowElement.getId();
              if (isEqualToCurrentLocalizationValue(locale, flowElementId, "name", name, infoNode)
                  == false) {
                dynamicBpmnService.changeLocalizationName(locale, flowElementId, name, infoNode);
                localizationValuesChanged = true;
              }

              if (documentation != null
                  && isEqualToCurrentLocalizationValue(
                          locale, flowElementId, "description", documentation, infoNode)
                      == false) {
                dynamicBpmnService.changeLocalizationDescription(
                    locale, flowElementId, documentation, infoNode);
                localizationValuesChanged = true;
              }

              break;
            }
          }
        }

        if (flowElement instanceof SubProcess) {
          SubProcess subprocess = (SubProcess) flowElement;
          boolean isFlowElementLocalizationChanged =
              localizeFlowElements(subprocess.getFlowElements(), infoNode);
          boolean isDataObjectLocalizationChanged =
              localizeDataObjectElements(subprocess.getDataObjects(), infoNode);
          if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
            localizationValuesChanged = true;
          }
        }
      }
    }

    return localizationValuesChanged;
  }
Example #26
0
 public String getName() {
   return StringUtils.trimToNull(
       StringUtils.trimToEmpty(firstname) + " " + StringUtils.trimToEmpty(lastname));
 }
Example #27
0
 /** Called in login page, redirected to on failed logins. */
 public String getNameWithEmail() {
   return StringUtils.trimToNull(getName() + " <" + email + ">");
 }
 /**
  * Get the document UUID from an incoming request.
  *
  * @param request incoming
  * @return document UUID
  */
 public static String getRequestUUID(Document request) {
   final Element uuidElement =
       request.getRootElement().element(XFormsConstants.XXFORMS_UUID_QNAME);
   assert uuidElement != null;
   return StringUtils.trimToNull(uuidElement.getTextTrim());
 }
Example #29
0
  @PostConstruct
  protected void initialize() {
    if (logger.isInfoEnabled()) {
      logger.info("Reading configuration parameters.");
    }

    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();

    ProjectStage stage = context.getApplication().getProjectStage();

    String path = StringUtils.trimToNull(externalContext.getInitParameter(APPLICATION_HOME));
    if (path == null) {
      if (logger.isInfoEnabled()) {
        logger.info("Parameter 'applicationHome' is not set. Using the default path.");
      }

      path = System.getProperty("user.home") + File.separator + ".pivot4j";
    } else if (path.endsWith(File.separator)) {
      path = path.substring(0, path.length() - File.separator.length());
    }

    if (logger.isInfoEnabled()) {
      logger.info("Using application home : {}", path);
    }

    this.applicationHome = new File(path);

    if (!applicationHome.exists()) {
      applicationHome.mkdirs();
    }

    InputStream in = null;

    try {
      String configPath = StringUtils.trimToNull(externalContext.getInitParameter(CONFIG_FILE));
      if (configPath == null || stage == ProjectStage.UnitTest) {
        configPath = path + File.separator + "pivot4j-config.xml";

        File configFile = new File(configPath);

        if (!configFile.exists() || stage == ProjectStage.UnitTest) {
          String defaultConfig = "/WEB-INF/pivot4j-config.xml";

          if (logger.isInfoEnabled()) {
            logger.info("Config file does not exist. Using default : " + defaultConfig);
          }

          ServletContext servletContext = (ServletContext) externalContext.getContext();

          String location = servletContext.getRealPath(defaultConfig);

          if (location != null) {
            configFile = new File(location);
          }
        }

        if (!configFile.exists()) {
          String msg = "Unable to read the default config : " + configFile;
          throw new FacesException(msg);
        }

        in = new FileInputStream(configFile);
      } else {
        URL url;

        if (configPath.startsWith("classpath:")) {
          url = new URL(null, configPath, new ClasspathStreamHandler());
        } else {
          url = new URL(configPath);
        }

        in = url.openStream();

        if (in == null) {
          String msg = "Unable to read config from URL : " + url;
          throw new FacesException(msg);
        }
      }

      this.configuration = readConfiguration(context, in);
    } catch (IOException e) {
      String msg = "Failed to read application config : " + e;
      throw new FacesException(msg, e);
    } catch (ConfigurationException e) {
      String msg = "Invalid application config : " + e;
      throw new FacesException(msg, e);
    } finally {
      IOUtils.closeQuietly(in);
    }

    if (logger.isInfoEnabled()) {
      logger.info("Pivot4J Analytics has been initialized successfully.");
    }

    configuration.addConfigurationListener(
        new ConfigurationListener() {

          @Override
          public void configurationChanged(ConfigurationEvent event) {
            onConfigurationChanged(event);
          }
        });
  }
Example #30
0
  /**
   * Load properties, build a MetricCatcher, start catching
   *
   * @param propertiesFile The config file
   * @throws IOException if the properties file cannot be read
   */
  public Loader(File propertiesFile) throws IOException {
    logger.info("Starting metriccatcher");

    logger.info("Loading configuration from: " + propertiesFile.getAbsolutePath());
    Properties properties = new Properties();
    try {
      properties.load(new FileReader(propertiesFile));
      for (Object key : properties.keySet()) { // copy properties into system properties
        System.setProperty((String) key, (String) properties.get(key));
      }
    } catch (IOException e) {
      logger.error("error reading properties file: " + e);
      System.exit(1);
    }

    int reportingInterval = 60;
    String intervalProperty = properties.getProperty(METRICCATCHER_INTERVAL);
    if (intervalProperty != null) {
      try {
        reportingInterval = Integer.parseInt(intervalProperty);
      } catch (NumberFormatException e) {
        logger.warn("Couldn't parse " + METRICCATCHER_INTERVAL + " setting", e);
      }
    }

    boolean disableJvmMetrics = false;
    String disableJvmProperty = properties.getProperty(METRICCATCHER_DISABLE_JVM_METRICS);
    if (disableJvmProperty != null) {
      disableJvmMetrics = BooleanUtils.toBoolean(disableJvmProperty);
      if (disableJvmMetrics) {
        logger.info("Disabling JVM metric reporting");
      }
    }

    boolean reportingEnabled = false;
    // Start a Ganglia reporter if specified in the config
    String gangliaHost = properties.getProperty(METRICCATCHER_GANGLIA_HOST);
    String gangliaPort = properties.getProperty(METRICCATCHER_GANGLIA_PORT);
    if (gangliaHost != null && gangliaPort != null) {
      logger.info("Creating Ganglia reporter pointed at " + gangliaHost + ":" + gangliaPort);
      GangliaReporter gangliaReporter =
          new GangliaReporter(gangliaHost, Integer.parseInt(gangliaPort));
      gangliaReporter.printVMMetrics = !disableJvmMetrics;
      gangliaReporter.start(reportingInterval, TimeUnit.SECONDS);
      reportingEnabled = true;
    }

    // Start a Graphite reporter if specified in the config
    String graphiteHost = properties.getProperty(METRICCATCHER_GRAPHITE_HOST);
    String graphitePort = properties.getProperty(METRICCATCHER_GRAPHITE_PORT);
    if (graphiteHost != null && graphitePort != null) {
      String graphitePrefix = properties.getProperty(METRICCATCHER_GRAPHITE_PREFIX);
      if (graphitePrefix == null) {
        graphitePrefix = InetAddress.getLocalHost().getHostName();
      }
      logger.info(
          "Creating Graphite reporter pointed at "
              + graphiteHost
              + ":"
              + graphitePort
              + " with prefix '"
              + graphitePrefix
              + "'");
      GraphiteReporter graphiteReporter =
          new GraphiteReporter(
              graphiteHost, Integer.parseInt(graphitePort), StringUtils.trimToNull(graphitePrefix));
      graphiteReporter.printVMMetrics = !disableJvmMetrics;
      graphiteReporter.start(reportingInterval, TimeUnit.SECONDS);
      reportingEnabled = true;
    }

    String reporterConfigFile = properties.getProperty(METRICCATCHER_REPORTER_CONFIG);
    if (reporterConfigFile != null) {
      logger.info("Trying to load reporterConfig from file: {}", reporterConfigFile);
      try {
        ReporterConfig.loadFromFileAndValidate(reporterConfigFile).enableAll();
      } catch (Exception e) {
        logger.error(
            "Failed to load metrics-reporter-config, metric sinks will not be activated", e);
      }
      reportingEnabled = true;
    }

    if (!reportingEnabled) {
      logger.error("No reporters enabled.  MetricCatcher can not do it's job");
      throw new RuntimeException("No reporters enabled");
    }

    int maxMetrics = Integer.parseInt(properties.getProperty(METRICCATCHER_MAX_METRICS, "500"));
    logger.info("Max metrics: " + maxMetrics);
    Map<String, Metric> lruMap = new LRUMap<String, Metric>(10, maxMetrics);

    int port = Integer.parseInt(properties.getProperty(METRICCATCHER_UDP_PORT, "1420"));
    logger.info("Listening on UDP port " + port);
    DatagramSocket socket = new DatagramSocket(port);

    metricCatcher = new MetricCatcher(socket, lruMap);
    metricCatcher.start();

    // Register a shutdown hook and wait for termination
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread() {
              @Override
              public void run() {
                shutdown();
              };
            });
  }