/** 将0=1/1=1/true的恒等式进行优化 */
  private static IFilter shortestFilter(IFilter root) throws EmptyResultFilterException {
    IFilter filter = FilterUtils.toDNFAndFlat(root);
    List<List<IFilter>> DNFfilter = FilterUtils.toDNFNodesArray(filter);

    List<List<IFilter>> newDNFfilter = new ArrayList<List<IFilter>>();
    for (List<IFilter> andDNFfilter : DNFfilter) {
      boolean isShortest = false;
      List<IFilter> newAndDNFfilter = new ArrayList<IFilter>();
      for (IFilter one : andDNFfilter) {
        if (one.getOperation() == OPERATION.CONSTANT) {
          boolean flag = false;
          if (((IBooleanFilter) one).getColumn() instanceof ISelectable) { // 可能是个not函数
            newAndDNFfilter.add(one); // 不能丢弃
          } else {
            String value = ((IBooleanFilter) one).getColumn().toString();
            if (StringUtils.isNumeric(value)) {
              flag = BooleanUtils.toBoolean(Integer.valueOf(value));
            } else {
              flag = BooleanUtils.toBoolean(((IBooleanFilter) one).getColumn().toString());
            }
            if (!flag) {
              isShortest = true;
              break;
            }
          }
        } else {
          newAndDNFfilter.add(one);
        }
      }

      if (!isShortest) {
        if (newAndDNFfilter.isEmpty()) {
          // 代表出现为true or xxx,直接返回true
          IBooleanFilter f = ASTNodeFactory.getInstance().createBooleanFilter();
          f.setOperation(OPERATION.CONSTANT);
          f.setColumn("1");
          f.setColumnName(ObjectUtils.toString("1"));
          return f;
        } else { // 针对非false的情况
          newDNFfilter.add(newAndDNFfilter);
        }
      }
    }

    if (newDNFfilter.isEmpty()) {
      throw new EmptyResultFilterException("空结果");
    }

    return FilterUtils.DNFToOrLogicTree(newDNFfilter);
  }
Exemple #2
0
 private void ensurePasswordOrPamAuth(Integer usePamAuth, String password) throws FaultException {
   if (!BooleanUtils.toBoolean(usePamAuth, new Integer(1), new Integer(0))
       && StringUtils.isEmpty(password)) {
     throw new FaultException(
         -501, "passwordRequiredOrUsePam", "Password is required if not using PAM authentication");
   }
 }
Exemple #3
0
  public StdioMessageReceiver(
      Connector connector, Service service, InboundEndpoint endpoint, long checkFrequency)
      throws CreateException {
    super(connector, service, endpoint);
    this.setFrequency(checkFrequency);

    this.connector = (StdioConnector) connector;
    String streamName = endpoint.getEndpointURI().getAddress();
    if (StdioConnector.STREAM_SYSTEM_IN.equalsIgnoreCase(streamName)) {
      inputStream = System.in;
    } else {
      inputStream = this.connector.getInputStream();
    }

    // apply connector-specific properties
    if (connector instanceof PromptStdioConnector) {
      PromptStdioConnector ssc = (PromptStdioConnector) connector;

      String promptMessage = (String) endpoint.getProperties().get("promptMessage");
      if (promptMessage != null) {
        ssc.setPromptMessage(promptMessage);
      }
    }

    this.sendStream = BooleanUtils.toBoolean((String) endpoint.getProperties().get("sendStream"));
  }
  /**
   * Will conditionally append the verbose switch if verbose flag is "true".
   *
   * @param verboseFlag String which takes null or "true".
   * @return Rake command builder.
   */
  @SuppressWarnings("unchecked")
  public T addIfVerbose(@Nullable String verboseFlag) {

    if (BooleanUtils.toBoolean(verboseFlag)) {
      getCommandList().add(VERBOSE_ARG);
    }
    return (T) this;
  }
 private static boolean getBoolean(Element element, String name) {
   if (element == null) {
     return false;
   } else {
     String text = element.getChildTextTrim(name);
     return BooleanUtils.toBoolean(text);
   }
 }
Exemple #6
0
 @POST
 @Path("@addContent")
 @Override
 public Response doAddContent() throws ClientException {
   String name = ctx.getForm().getString("name");
   boolean overwrite = BooleanUtils.toBoolean(ctx.getForm().getString("overwritePage"));
   return addContent(name, PageCreationLocation.TOP, overwrite, ctx.getForm());
 }
 /**
  * Returns the value as a {@link Double} value. The returned value will be <code>0</code> or
  * <code>1</code> if the {@link #value} is a boolean value. If {@link #value} can not be converted
  * into a number, a {@link NumberFormatException} is thrown.
  *
  * @return {@link #value} as {@link Double}
  */
 public double getValueAsDouble() {
   if (NumberUtils.isNumber(value)) {
     return NumberUtils.createDouble(value);
   }
   if (isBooleanValue(value)) {
     return BooleanUtils.toBoolean(value) ? 1 : 0;
   }
   throw new NumberFormatException();
 }
Exemple #8
0
  /**
   * Creates a new user
   *
   * @param loggedInUser The current user
   * @param desiredLogin The login for the new user
   * @param desiredPassword The password for the new user
   * @param firstName The first name of the new user
   * @param lastName The last name of the new user
   * @param email The email address for the new user
   * @param usePamAuth Should this user authenticate via PAM?
   * @return Returns 1 if successful (exception otherwise)
   * @throws FaultException A FaultException is thrown if the loggedInUser doesn't have permissions
   *     to create new users in thier org.
   * @xmlrpc.doc Create a new user.
   * @xmlrpc.param #param("string", "sessionKey")
   * @xmlrpc.param #param_desc("string", "desiredLogin", "Desired login name, will fail if already
   *     in use.")
   * @xmlrpc.param #param("string", "desiredPassword")
   * @xmlrpc.param #param("string", "firstName")
   * @xmlrpc.param #param("string", "lastName")
   * @xmlrpc.param #param_desc("string", "email", "User's e-mail address.")
   * @xmlrpc.param #param_desc("int", "usePamAuth", "1 if you wish to use PAM authentication for
   *     this user, 0 otherwise.")
   * @xmlrpc.returntype #return_int_success()
   */
  public int create(
      User loggedInUser,
      String desiredLogin,
      String desiredPassword,
      String firstName,
      String lastName,
      String email,
      Integer usePamAuth)
      throws FaultException {
    // Logged in user must be an org admin and we must be on a sat to do this.
    ensureOrgAdmin(loggedInUser);
    ensurePasswordOrPamAuth(usePamAuth, desiredPassword);

    boolean pamAuth = BooleanUtils.toBoolean(usePamAuth, new Integer(1), new Integer(0));

    if (pamAuth) {
      desiredPassword = getDefaultPasswordForPamAuth();
    }

    CreateUserCommand command = new CreateUserCommand();
    command.setUsePamAuthentication(pamAuth);
    command.setLogin(desiredLogin);
    command.setPassword(desiredPassword);
    command.setFirstNames(firstName);
    command.setLastName(lastName);
    command.setEmail(email);
    command.setOrg(loggedInUser.getOrg());
    command.setCompany(loggedInUser.getCompany());

    // Validate the user to be
    ValidatorError[] errors = command.validate();
    if (errors.length > 0) {
      StringBuilder errorString = new StringBuilder();
      LocalizationService ls = LocalizationService.getInstance();
      // Build a sane error message here
      for (int i = 0; i < errors.length; i++) {
        ValidatorError err = errors[i];
        errorString.append(ls.getMessage(err.getKey(), err.getValues()));
        if (i != errors.length - 1) {
          errorString.append(" :: ");
        }
      }
      // Throw a BadParameterException with our message string
      throw new BadParameterException(errorString.toString());
    }

    command.storeNewUser();
    return 1;
  }
  /**
   * Will conditionally add bundle exec if bundle flag is "true".
   *
   * @param bundleFlag String which takes null or "true".
   * @return T command builder.
   */
  @SuppressWarnings("unchecked")
  public T addIfBundleExec(@Nullable String bundleFlag) {

    if (BooleanUtils.toBoolean(bundleFlag)) {
      getCommandList()
          .add(
              getRvmRubyLocator()
                  .buildExecutablePath(
                      getRubyRuntime().getRubyRuntimeName(),
                      getRubyExecutablePath(),
                      BUNDLE_COMMAND));
      getCommandList().add(BUNDLE_EXEC_ARG);
    }
    return (T) this;
  }
  @Override
  public void writeAttribute(String localName, String value) throws XMLStreamException {
    try {

      if (!objectQueue.isEmpty()) {
        if (StringUtils.equals(CmsConstants.EXPORT_AS_AN_ARRAY_INSTRUCTION, localName)) {
          objectQueue.peek().exportAsAnArray = BooleanUtils.isTrue(BooleanUtils.toBoolean(value));
        } else {
          objectQueue.peek().addAttribute(localName, value);
        }
      }

    } catch (Exception e) {
      throw new XMLStreamException(e);
    }
  }
Exemple #11
0
  public void propertiesUpdated(Map<String, ?> properties) throws Exception {
    log.warn("Properties Reloading: " + properties);

    String userName = (String) properties.get("userName");
    String uri = (String) properties.get("uri");
    String existHome = (String) properties.get("existHome");
    String password = (String) properties.get("password");
    boolean useChangeSets = BooleanUtils.toBoolean((Boolean) properties.get("useChangeSets"));

    this.userName = userName;
    this.uri = uri;
    this.existHome = existHome;
    this.password = password;
    this.useChangeSets = useChangeSets;

    this.afterPropertiesSet();
  }
  private static void validateConfiguration(final PersistedConfigurationAdapter pca)
      throws IOException {
    if (BooleanUtils.toBoolean(
        System.getProperty(ConfigurationFactory.class.getName() + ".skipValidation"))) {
      LOGGER.info("Skipped validation of: " + pca);
      return;
    }

    final Set<String> validationErrors = validate(pca);
    Validate.isTrue(
        validationErrors.isEmpty(),
        "Validation error(s):\n"
            + StringUtils.join(validationErrors, "\n")
            + "\nfound in configuration:\n"
            + pca);
    LOGGER.info("Successfully validated: " + pca);
  }
 public void integrate(Loader loader, Location location, ConfigurationAtom atom, Object focus) {
   if (focus != null && focus instanceof StreamableResourceSource) {
     if ("public-resource".equals(atom.getType())
         || "classpath-public-resource".equals(atom.getType())) {
       StreamableResourcesHandler handler =
           new StreamableResourcesHandler((StreamableResourceSource) focus);
       if (atom instanceof PropertiesAtom) {
         PropertiesAtom propAtom = (PropertiesAtom) atom;
         handler.setShowDirectoryContents(
             BooleanUtils.toBoolean(propAtom.getProperties().get(SHOW_DIRECTORY_CONTENTS)));
         String cacheTime = propAtom.getProperties().get(CACHE_TIME);
         if (StringUtils.isNotBlank(cacheTime)) {
           handler.setCacheTime(Integer.parseInt(cacheTime));
         }
       }
       handlerInvestigator.analyzeObject(handler);
     }
   }
 }
  private Date findPoolEndDate(Entitlement ent) {
    Pool pool = ent.getPool();
    Consumer consumer = ent.getConsumer();

    Date startDate = new Date();

    if (consumer.getCreated() != null) {
      startDate = consumer.getCreated();
    }

    Date oneDayFromRegistration = new Date(startDate.getTime() + (24 * 60 * 60 * 1000));

    boolean isUnmappedGuestPool =
        BooleanUtils.toBoolean(pool.getAttributeValue("unmapped_guests_only"));

    if (isUnmappedGuestPool) {
      return oneDayFromRegistration;
    } else {
      return pool.getEndDate();
    }
  }
  protected static void continueFromCreateCopyCourseOfferingInfo(
      CourseOfferingCreateWrapper coWrapper, CourseInfo course, TermInfo term) {

    ContextInfo contextInfo = ContextUtils.createDefaultContextInfo();
    int firstValue = 0;

    try {
      List<CourseOfferingInfo> courseOfferingInfos =
          CourseOfferingManagementUtil.getCourseOfferingService()
              .getCourseOfferingsByCourseAndTerm(course.getId(), term.getId(), contextInfo);

      coWrapper.setCourse(course);
      coWrapper.setCreditCount(
          CourseOfferingViewHelperUtil.trimTrailing0(
              CourseOfferingManagementUtil.getLrcService()
                  .getResultValue(
                      course
                          .getCreditOptions()
                          .get(firstValue)
                          .getResultValueKeys()
                          .get(firstValue),
                      contextInfo)
                  .getValue()));
      coWrapper.setShowAllSections(true);
      coWrapper.setShowCopyCourseOffering(false);
      coWrapper.setShowTermOfferingLink(true);

      coWrapper.setContextBar(
          CourseOfferingContextBar.NEW_INSTANCE(
              coWrapper.getTerm(),
              coWrapper.getSocInfo(),
              CourseOfferingManagementUtil.getStateService(),
              CourseOfferingManagementUtil.getAcademicCalendarService(),
              contextInfo));

      coWrapper.getExistingTermOfferings().clear();
      coWrapper.getExistingOfferingsInCurrentTerm().clear();

      for (CourseOfferingInfo courseOfferingInfo : courseOfferingInfos) {
        if (StringUtils.equals(
            courseOfferingInfo.getStateKey(), LuiServiceConstants.LUI_CO_STATE_OFFERED_KEY)) {
          CourseOfferingEditWrapper co = new CourseOfferingEditWrapper(courseOfferingInfo);
          co.setGradingOption(
              CourseOfferingManagementUtil.getGradingOption(
                  courseOfferingInfo.getGradingOptionId()));
          coWrapper.getExistingOfferingsInCurrentTerm().add(co);
        }
      }

      // Get past 5 years CO
      Calendar termStart = Calendar.getInstance();
      termStart.setTime(term.getStartDate());
      String termYear = Integer.toString(termStart.get(Calendar.YEAR));
      String termMonth = Integer.toString((termStart.get(Calendar.MONTH) + 1));
      String termDayOfMonth = Integer.toString((termStart.getActualMaximum(Calendar.DAY_OF_MONTH)));

      org.kuali.student.r2.core.search.dto.SearchRequestInfo searchRequest =
          new org.kuali.student.r2.core.search.dto.SearchRequestInfo(
              CourseOfferingHistorySearchImpl.PAST_CO_SEARCH.getKey());
      searchRequest.addParam(
          CourseOfferingHistorySearchImpl.COURSE_ID, coWrapper.getCourse().getId());

      searchRequest.addParam(
          CourseOfferingHistorySearchImpl.TARGET_DAY_OF_MONTH_PARAM, termDayOfMonth);
      searchRequest.addParam(CourseOfferingHistorySearchImpl.TARGET_MONTH_PARAM, termMonth);
      searchRequest.addParam(CourseOfferingHistorySearchImpl.TARGET_YEAR_PARAM, termYear);
      searchRequest.addParam(
          CourseOfferingHistorySearchImpl.SearchParameters.CROSS_LIST_SEARCH_ENABLED,
          BooleanUtils.toStringTrueFalse(true));
      org.kuali.student.r2.core.search.dto.SearchResultInfo searchResult =
          CourseOfferingManagementUtil.getSearchService().search(searchRequest, null);

      List<String> courseOfferingIds = new ArrayList<String>(searchResult.getTotalResults());

      /* Checks whether the course is cross-listed and Set the codes that are cross listed to the cross-listed list */

      for (org.kuali.student.r2.core.search.dto.SearchResultRowInfo row : searchResult.getRows()) {
        for (SearchResultCellInfo cellInfo : row.getCells()) {
          String value = StringUtils.EMPTY;
          if (cellInfo.getValue() != null) {
            value = cellInfo.getValue();
          }
          if (CourseOfferingHistorySearchImpl.SearchResultColumns.CO_ID.equals(cellInfo.getKey())) {
            courseOfferingIds.add(value);
          } else if (CourseOfferingHistorySearchImpl.SearchResultColumns.IS_CROSS_LISTED.equals(
              cellInfo.getValue())) {
            coWrapper.setCrossListedCo(BooleanUtils.toBoolean(value));
          } else if (CourseOfferingHistorySearchImpl.SearchResultColumns.CROSS_LISTED_COURSES
              .equals(cellInfo.getKey())) {
            coWrapper.setAlternateCOCodes(Arrays.asList(StringUtils.split(value, ",")));
          }
        }
      }

      /*
       * Avoid duplicates in case there is a cross Listed
       */
      HashSet hs = new HashSet();
      hs.addAll(courseOfferingIds);
      courseOfferingIds.clear();
      courseOfferingIds.addAll(hs);

      courseOfferingInfos =
          CourseOfferingManagementUtil.getCourseOfferingService()
              .getCourseOfferingsByIds(courseOfferingIds, contextInfo);

      for (CourseOfferingInfo courseOfferingInfo : courseOfferingInfos) {
        CourseOfferingEditWrapper co = new CourseOfferingEditWrapper(courseOfferingInfo);
        TermInfo termInfo =
            CourseOfferingManagementUtil.getAcademicCalendarService()
                .getTerm(courseOfferingInfo.getTermId(), contextInfo);
        co.setTerm(termInfo);
        co.setGradingOption(
            CourseOfferingManagementUtil.getGradingOption(courseOfferingInfo.getGradingOptionId()));
        co.setAlternateCOCodes(coWrapper.getAlternateCOCodes());
        coWrapper.getExistingTermOfferings().add(co);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Exemple #16
0
 private Response updateSite(FormData form) {
   String title = form.getString("dc:title");
   String url = form.getString("webc:url");
   String description = form.getString("dc:description");
   String piwikId = form.getString("piwik:piwikId");
   String siteTemplateStr = form.getString("labssite:siteTemplate");
   String category = form.getString("labssite:category");
   boolean modified = false;
   try {
     if (!StringUtils.isEmpty(title)) {
       site.setTitle(title);
       modified = true;
     }
     if (!StringUtils.isEmpty(description)) {
       site.setDescription(description);
       modified = true;
     }
     if (!StringUtils.isEmpty(category)) {
       site.setCategory(category);
       modified = true;
     }
     String oldUrl = site.getURL();
     url = StringUtils.trim(url);
     if (!StringUtils.isEmpty(url) && !url.equals(oldUrl)) {
       site.setURL(url);
       modified = true;
     }
     String oldPiwikId = site.getPiwikId();
     piwikId = StringUtils.trim(piwikId);
     if (!StringUtils.equals(piwikId, oldPiwikId)) {
       site.setPiwikId(piwikId);
       modified = true;
     }
     boolean isSiteTemplate = BooleanUtils.toBoolean(siteTemplateStr);
     if (site.isElementTemplate() != isSiteTemplate) {
       site.setElementTemplate(isSiteTemplate);
       modified = true;
     }
     if (isSiteTemplate) {
       if (form.isMultipartContent()) {
         Blob preview = form.getBlob("labssite:siteTemplatePreview");
         if (preview != null && !StringUtils.isEmpty(preview.getFilename())) {
           site.setElementPreview(preview);
           modified = true;
         }
       }
     } /* else {
           Blob siteTemplatePreview = null;
           try {
               siteTemplatePreview = site.getSiteTemplatePreview();
           } catch (ClientException e) {
               throw WebException.wrap(e);
           }
           if (siteTemplatePreview != null) {
               site.setElementPreview(null);
               modified = true;
           }
       }*/
     String msgLabel = "label.labssites.edit.noop";
     if (modified) {
       CoreSession session = ctx.getCoreSession();
       getSiteManager().updateSite(session, site);
       session.save();
       msgLabel = "label.labssites.edit.site.updated";
     }
     return redirect(
         ctx.getModulePath()
             + "/"
             + URIUtils.quoteURIPathComponent(site.getURL(), true)
             + "/@views/edit?message_success="
             + msgLabel);
   } catch (SiteManagerException e) {
     return redirect(getPath() + "/@views/edit?message_error=" + e.getMessage());
   } catch (ClientException e) {
     throw WebException.wrap(e);
   }
 }
  @Override
  public void readRep(
      Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases)
      throws KettleException {

    ModelAnnotationGroup modelAnnotationGroup = new ModelAnnotationGroup();
    try {

      setModelAnnotationCategory(rep.getStepAttributeString(id_step, "CATEGORY_NAME"));
      setTargetOutputStep(rep.getStepAttributeString(id_step, "TARGET_OUTPUT_STEP"));

      int nrAnnotations = rep.countNrStepAttributes(id_step, "ANNOTATION_NAME");

      // Read annotations
      for (int i = 0; i < nrAnnotations; i++) {
        String annotationName = rep.getStepAttributeString(id_step, i, "ANNOTATION_NAME");
        String annotationFieldName =
            rep.getStepAttributeString(id_step, i, "ANNOTATION_FIELD_NAME");
        String annotationType = rep.getStepAttributeString(id_step, i, "ANNOTATION_TYPE");

        // Create model annotation
        ModelAnnotation<?> modelAnnotation =
            ModelAnnotationGroupXmlReader.create(annotationType, annotationFieldName);
        if (StringUtils.isNotBlank(annotationName)) {
          modelAnnotation.setName(annotationName);
        }

        if (StringUtils.isNotBlank(annotationType)) {
          // Populate annotation properties
          Map<String, Serializable> map = new HashMap<String, Serializable>();
          for (String key : modelAnnotation.getAnnotation().getModelPropertyIds()) {
            try {
              String value = rep.getStepAttributeString(id_step, i, "PROPERTY_VALUE_" + key);
              if (StringUtils.isNotBlank(value)) {
                map.put(key, value);
              }
            } catch (KettleException ke) {
              // Ignore - not found
            }
          }
          modelAnnotation.populateAnnotation(map);
        }

        // Add to group
        modelAnnotationGroup.add(modelAnnotation);
      }

      modelAnnotationGroup.setSharedDimension(
          BooleanUtils.toBoolean(rep.getStepAttributeString(id_step, "SHARED_DIMENSION")));
      sharedDimension = modelAnnotationGroup.isSharedDimension();
      modelAnnotationGroup.setDescription(rep.getStepAttributeString(id_step, "DESCRIPTION"));

      List<DataProvider> dataProviders = new ArrayList<DataProvider>();
      int nrDataProviders = rep.countNrStepAttributes(id_step, "DP_NAME");
      for (int i = 0; i < nrDataProviders; i++) {

        DataProvider dataProvider = new DataProvider();

        dataProvider.setName(rep.getStepAttributeString(id_step, i, "DP_NAME"));
        dataProvider.setSchemaName(rep.getStepAttributeString(id_step, i, "DP_SCHEMA_NAME"));
        dataProvider.setTableName(rep.getStepAttributeString(id_step, i, "DP_TABLE_NAME"));
        dataProvider.setDatabaseMetaNameRef(
            rep.getStepAttributeString(id_step, i, "DP_DATABASE_META_NAME_REF"));

        List<ColumnMapping> columnMappings = new ArrayList<ColumnMapping>();
        long nrColumnMappings =
            rep.getStepAttributeString(id_step, "CM_COUNT_" + i) != null
                ? Long.valueOf(rep.getStepAttributeString(id_step, "CM_COUNT_" + i))
                : 0;
        for (int j = 0; j < nrColumnMappings; j++) {

          ColumnMapping columnMapping = new ColumnMapping();

          columnMapping.setName(rep.getStepAttributeString(id_step, i, "CM_NAME_" + j));
          columnMapping.setColumnName(
              rep.getStepAttributeString(id_step, i, "CM_COLUMN_NAME_" + j));
          String dataType = rep.getStepAttributeString(id_step, i, "CM_DATA_TYPE_" + j);
          if (StringUtils.isNotBlank(dataType)) {
            columnMapping.setColumnDataType(DataType.valueOf(dataType));
          }

          columnMappings.add(columnMapping);
        }

        dataProvider.setColumnMappings(columnMappings);
        dataProviders.add(dataProvider);
      }
      modelAnnotationGroup.setDataProviders(dataProviders);

    } catch (Exception e) {
      throw new KettleException(
          BaseMessages.getString(
              PKG, "ModelAnnotationMeta.Exception.UnexpectedErrorReadingStepInfoFromRepository"),
          e);
    }

    setModelAnnotations(modelAnnotationGroup);

    // This may override the loaded model annotation group
    if (StringUtils.isNotBlank(getModelAnnotationCategory())) {
      readDataFromMetaStore(metaStore);
    }
  }
Exemple #18
0
  private MuleMessage dispatchMessage(MuleEvent event) throws Exception {
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    Destination replyTo = null;
    boolean transacted = false;
    boolean cached = false;
    boolean remoteSync = useRemoteSync(event);

    if (logger.isDebugEnabled()) {
      logger.debug(
          "dispatching on endpoint: "
              + event.getEndpoint().getEndpointURI()
              + ". MuleEvent id is: "
              + event.getId()
              + ". Outbound transformers are: "
              + event.getEndpoint().getTransformers());
    }

    try {
      session = connector.getSessionFromTransaction();
      if (session != null) {
        transacted = true;

        // If a transaction is running, we can not receive any messages
        // in the same transaction.
        if (remoteSync) {
          throw new IllegalTransactionStateException(
              JmsMessages.connectorDoesNotSupportSyncReceiveWhenTransacted());
        }
      }
      // Should we be caching sessions? Note this is not part of the JMS spec.
      // and is turned off by default.
      else if (event
          .getMessage()
          .getBooleanProperty(
              JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) {
        cached = true;
        if (cachedSession != null) {
          session = cachedSession;
        } else {
          session = connector.getSession(event.getEndpoint());
          cachedSession = session;
        }
      } else {
        session = connector.getSession(event.getEndpoint());
        if (event.getEndpoint().getTransactionConfig().isTransacted()) {
          transacted = true;
        }
      }

      boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true);

      Destination dest = connector.createDestinationMule3858Backport(session, endpoint);
      producer = connector.getJmsSupport().createProducer(session, dest, topic);

      Object message = event.transformMessage();
      if (!(message instanceof Message)) {
        throw new DispatchException(
            JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()),
            event.getMessage(),
            event.getEndpoint());
      }

      Message msg = (Message) message;
      if (event.getMessage().getCorrelationId() != null) {
        msg.setJMSCorrelationID(event.getMessage().getCorrelationId());
      }

      MuleMessage eventMsg = event.getMessage();

      // Some JMS implementations might not support the ReplyTo property.
      if (connector.supportsProperty(JmsConstants.JMS_REPLY_TO)) {
        Object tempReplyTo = eventMsg.removeProperty(JmsConstants.JMS_REPLY_TO);
        if (tempReplyTo == null) {
          // It may be a Mule URI or global endpoint Ref
          tempReplyTo = eventMsg.removeProperty(MuleProperties.MULE_REPLY_TO_PROPERTY);
          if (tempReplyTo != null) {
            if (tempReplyTo.toString().startsWith("jms://")) {
              tempReplyTo = tempReplyTo.toString().substring(6);
            } else {
              EndpointBuilder epb =
                  event
                      .getMuleContext()
                      .getRegistry()
                      .lookupEndpointBuilder(tempReplyTo.toString());
              if (epb != null) {
                tempReplyTo = epb.buildOutboundEndpoint().getEndpointURI().getAddress();
              }
            }
          }
        }
        if (tempReplyTo != null) {
          if (tempReplyTo instanceof Destination) {
            replyTo = (Destination) tempReplyTo;
          } else {
            // TODO AP should this drill-down be moved into the resolver as well?
            boolean replyToTopic = false;
            String reply = tempReplyTo.toString();
            int i = reply.indexOf(":");
            if (i > -1) {
              // TODO MULE-1409 this check will not work for ActiveMQ 4.x,
              // as they have temp-queue://<destination> and temp-topic://<destination> URIs
              // Extract to a custom resolver for ActiveMQ4.x
              // The code path can be exercised, e.g. by a LoanBrokerESBTestCase
              String qtype = reply.substring(0, i);
              replyToTopic = JmsConstants.TOPIC_PROPERTY.equalsIgnoreCase(qtype);
              reply = reply.substring(i + 1);
            }
            replyTo = connector.getJmsSupport().createDestination(session, reply, replyToTopic);
          }
        }
        // Are we going to wait for a return event ?
        if (remoteSync && replyTo == null) {
          replyTo = connector.getJmsSupport().createTemporaryDestination(session, topic);
        }
        // Set the replyTo property
        if (replyTo != null) {
          msg.setJMSReplyTo(replyTo);
        }

        // Are we going to wait for a return event ?
        if (remoteSync) {
          try {
            consumer = connector.getJmsSupport().createConsumer(session, replyTo, topic);
          } catch (Exception e) {
            logger.warn(e);
          }
        }
      }

      // QoS support
      String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY);
      String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY);
      String persistentDeliveryString =
          (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY);

      long ttl =
          StringUtils.isNotBlank(ttlString)
              ? NumberUtils.toLong(ttlString)
              : Message.DEFAULT_TIME_TO_LIVE;
      int priority =
          StringUtils.isNotBlank(priorityString)
              ? NumberUtils.toInt(priorityString)
              : Message.DEFAULT_PRIORITY;
      boolean persistent =
          StringUtils.isNotBlank(persistentDeliveryString)
              ? BooleanUtils.toBoolean(persistentDeliveryString)
              : connector.isPersistentDelivery();

      if (connector.isHonorQosHeaders()) {
        int priorityProp =
            eventMsg.getIntProperty(JmsConstants.JMS_PRIORITY, Connector.INT_VALUE_NOT_SET);
        int deliveryModeProp =
            eventMsg.getIntProperty(JmsConstants.JMS_DELIVERY_MODE, Connector.INT_VALUE_NOT_SET);

        if (priorityProp != Connector.INT_VALUE_NOT_SET) {
          priority = priorityProp;
        }
        if (deliveryModeProp != Connector.INT_VALUE_NOT_SET) {
          persistent = deliveryModeProp == DeliveryMode.PERSISTENT;
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass()));
      }

      if (consumer != null && topic) {
        // need to register a listener for a topic
        Latch l = new Latch();
        ReplyToListener listener = new ReplyToListener(l);
        consumer.setMessageListener(listener);

        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);

        int timeout = event.getTimeout();

        if (logger.isDebugEnabled()) {
          logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
        }

        l.await(timeout, TimeUnit.MILLISECONDS);
        consumer.setMessageListener(null);
        listener.release();
        Message result = listener.getMessage();
        if (result == null) {
          logger.debug("No message was returned via replyTo destination");
          return null;
        } else {
          MessageAdapter adapter = connector.getMessageAdapter(result);
          return new DefaultMuleMessage(
              JmsMessageUtils.toObject(
                  result, connector.getSpecification(), endpoint.getEncoding()),
              adapter);
        }
      } else {
        connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic);
        if (consumer != null) {
          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          }

          Message result = consumer.receive(timeout);
          if (result == null) {
            logger.debug("No message was returned via replyTo destination");
            return null;
          } else {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter);
          }
        }
      }
      return null;
    } finally {
      connector.closeQuietly(producer);
      connector.closeQuietly(consumer);

      // TODO AP check if TopicResolver is to be utilized for temp destinations as well
      if (replyTo != null
          && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) {
        if (replyTo instanceof TemporaryQueue) {
          connector.closeQuietly((TemporaryQueue) replyTo);
        } else {
          // hope there are no more non-standard tricks from JMS vendors
          // here ;)
          connector.closeQuietly((TemporaryTopic) replyTo);
        }
      }

      // If the session is from the current transaction, it is up to the
      // transaction to close it.
      if (session != null && !cached && !transacted) {
        connector.closeQuietly(session);
      }
    }
  }
 public boolean select(String expression, Object selectorContext) {
   boolean test = BooleanUtils.toBoolean(expression);
   return test == ((Boolean) selectorContext).booleanValue();
 }
 /* (non-Javadoc)
  * @see org.eclipse.jface.viewers.CellEditor#doSetValue(java.lang.Object)
  */
 @Override
 protected void doSetValue(Object value) {
   Assert.isTrue(comboBox != null);
   bValue = BooleanUtils.toBoolean(String.valueOf(value));
   comboBox.select(bValue ? 0 : 1);
 }
Exemple #21
0
 public boolean getIsDefault() {
   return BooleanUtils.toBoolean(isDefault);
 }
Exemple #22
0
 public boolean getIsCompiled() {
   return BooleanUtils.toBoolean(isCompiled);
 }
Exemple #23
0
  private MuleMessage dispatchMessage(MuleEvent event) throws Exception {
    Session session = null;
    MessageProducer producer = null;
    MessageConsumer consumer = null;
    Destination replyTo = null;
    boolean transacted = false;
    boolean cached = false;
    boolean useReplyToDestination;

    final Transaction muleTx = TransactionCoordination.getInstance().getTransaction();

    if (logger.isDebugEnabled()) {
      logger.debug(
          "dispatching on endpoint: "
              + event.getEndpoint().getEndpointURI()
              + ". MuleEvent id is: "
              + event.getId()
              + ". Outbound transformers are: "
              + event.getEndpoint().getTransformers());
    }

    // assume session is transacted first, and thus, managed
    boolean sessionManaged = true;
    try {
      session = connector.getSessionFromTransaction();
      if (session != null) {
        transacted = true;
      }
      // Should we be caching sessions? Note this is not part of the JMS spec.
      // and is turned off by default.
      else if (event
          .getMessage()
          .getBooleanProperty(
              JmsConstants.CACHE_JMS_SESSIONS_PROPERTY, connector.isCacheJmsSessions())) {
        sessionManaged = false;
        cached = true;
        if (cachedSession != null) {
          session = cachedSession;
        } else {
          session = connector.getSession(event.getEndpoint());
          cachedSession = session;
        }
      } else {
        // by now we're running with a different connector and connection
        sessionManaged = muleTx != null && muleTx.isXA();

        session = connector.getSession(event.getEndpoint());
        if (event.getEndpoint().getTransactionConfig().isTransacted()) {
          transacted = true;
        }
      }

      // If a transaction is running, we can not receive any messages
      // in the same transaction using a replyTo destination
      useReplyToDestination = returnResponse(event) && !transacted;

      boolean topic = connector.getTopicResolver().isTopic(event.getEndpoint(), true);

      Destination dest = connector.getJmsSupport().createDestination(session, endpoint);
      producer = connector.getJmsSupport().createProducer(session, dest, topic);

      preTransformMessage(event.getMessage());

      Object message = event.transformMessage();
      if (!(message instanceof Message)) {
        throw new DispatchException(
            JmsMessages.checkTransformer("JMS message", message.getClass(), connector.getName()),
            event.getMessage(),
            event.getEndpoint());
      }

      Message msg = (Message) message;

      MuleMessage eventMsg = event.getMessage();

      replyTo = getReplyToDestination(msg, session, event, useReplyToDestination, topic);

      // Set the replyTo property
      if (replyTo != null) {
        msg.setJMSReplyTo(replyTo);
      }

      // Allow overrides to alter the message if necessary
      processMessage(msg, event);

      // QoS support
      String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY);
      String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY);
      String persistentDeliveryString =
          (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY);

      long ttl =
          StringUtils.isNotBlank(ttlString)
              ? NumberUtils.toLong(ttlString)
              : Message.DEFAULT_TIME_TO_LIVE;
      int priority =
          StringUtils.isNotBlank(priorityString)
              ? NumberUtils.toInt(priorityString)
              : Message.DEFAULT_PRIORITY;
      boolean persistent =
          StringUtils.isNotBlank(persistentDeliveryString)
              ? BooleanUtils.toBoolean(persistentDeliveryString)
              : connector.isPersistentDelivery();

      // If we are honouring the current QoS message headers we need to use the ones set on the
      // current message
      if (connector.isHonorQosHeaders()) {
        Object priorityProp = eventMsg.getProperty(JmsConstants.JMS_PRIORITY);
        Object deliveryModeProp = eventMsg.getProperty(JmsConstants.JMS_DELIVERY_MODE);

        if (priorityProp != null) {
          priority = NumberUtils.toInt(priorityProp);
        }
        if (deliveryModeProp != null) {
          persistent = NumberUtils.toInt(deliveryModeProp) == DeliveryMode.PERSISTENT;
        }
      }

      if (logger.isDebugEnabled()) {
        logger.debug("Sending message of type " + ClassUtils.getSimpleName(msg.getClass()));
        logger.debug(
            "Sending JMS Message type "
                + msg.getJMSType()
                + "\n  JMSMessageID="
                + msg.getJMSMessageID()
                + "\n  JMSCorrelationID="
                + msg.getJMSCorrelationID()
                + "\n  JMSDeliveryMode="
                + (persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT)
                + "\n  JMSPriority="
                + priority
                + "\n  JMSReplyTo="
                + msg.getJMSReplyTo());
      }
      connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic, endpoint);

      if (useReplyToDestination && replyTo != null) {
        consumer = createReplyToConsumer(msg, event, session, replyTo, topic);

        if (topic) {
          // need to register a listener for a topic
          Latch l = new Latch();
          ReplyToListener listener = new ReplyToListener(l);
          consumer.setMessageListener(listener);

          connector.getJmsSupport().send(producer, msg, persistent, priority, ttl, topic, endpoint);

          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          }

          l.await(timeout, TimeUnit.MILLISECONDS);
          consumer.setMessageListener(null);
          listener.release();
          Message result = listener.getMessage();
          if (result == null) {
            logger.debug("No message was returned via replyTo destination");
            return new DefaultMuleMessage(NullPayload.getInstance(), connector.getMuleContext());
          } else {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter,
                connector.getMuleContext());
          }
        } else {
          int timeout = event.getTimeout();

          if (logger.isDebugEnabled()) {
            logger.debug("Waiting for return event for: " + timeout + " ms on " + replyTo);
          }

          Message result = consumer.receive(timeout);
          if (result == null) {
            logger.debug("No message was returned via replyTo destination " + replyTo);
            return new DefaultMuleMessage(NullPayload.getInstance(), connector.getMuleContext());
          } else {
            MessageAdapter adapter = connector.getMessageAdapter(result);
            return new DefaultMuleMessage(
                JmsMessageUtils.toObject(
                    result, connector.getSpecification(), endpoint.getEncoding()),
                adapter,
                connector.getMuleContext());
          }
        }
      }

      return new DefaultMuleMessage(
          returnOriginalMessageAsReply ? msg : NullPayload.getInstance(),
          connector.getMuleContext());
    } finally {
      connector.closeQuietly(producer);
      connector.closeQuietly(consumer);

      // TODO AP check if TopicResolver is to be utilized for temp destinations as well
      if (replyTo != null
          && (replyTo instanceof TemporaryQueue || replyTo instanceof TemporaryTopic)) {
        if (replyTo instanceof TemporaryQueue) {
          connector.closeQuietly((TemporaryQueue) replyTo);
        } else {
          // hope there are no more non-standard tricks from JMS vendors
          // here ;)
          connector.closeQuietly((TemporaryTopic) replyTo);
        }
      }

      if (!sessionManaged && transacted && muleTx instanceof TransactionCollection) {
        handleMultiTx(session);
      }

      // If the session is from the current transaction, it is up to the
      // transaction to close it.
      if (session != null && !cached && !transacted) {
        connector.closeQuietly(session);
      }
    }
  }
Exemple #24
0
  public void processInput(CommandLine line, Options options) {
    // automatically generate the help statement

    try {
      // parse the command line arguments

      if (line.getOptions().length < 1) {
        HELP_FORMATTER.printHelp(WINDUP_COMMAND, options);
      } else {
        // Map the environment settings from the input arguments.
        WindupEnvironment settings = new WindupEnvironment();
        if (line.hasOption("javaPkgs")) {
          String javaPkgs = line.getOptionValue("javaPkgs");
          if (javaPkgs != null) {
            String[] javaPkgsArr = javaPkgs.split(":");
            settings.setIncludeJavaPackageSignature(Arrays.asList(javaPkgsArr));
          }
        }
        if (line.hasOption("excludePkgs")) {
          String excludeJavaPkgs = line.getOptionValue("excludePkgs");
          if (excludeJavaPkgs != null) {
            String[] excludeJavaPkgsArr = excludeJavaPkgs.split(":");
            settings.setExcludeJavaPackageSignature(Arrays.asList(excludeJavaPkgsArr));
          }
        }

        if (line.hasOption("targetPlatform")) {
          settings.setTargetPlatform(line.getOptionValue("targetPlatform"));
        }

        if (line.hasOption("fetchRemote")) {
          String fetchRemoteString = line.getOptionValue("fetchRemote");
          if (StringUtils.isBlank(fetchRemoteString)) {
            settings.setFetchRemote(false);
          } else {
            boolean fetchRemote = Boolean.parseBoolean(fetchRemoteString);
            settings.setFetchRemote(fetchRemote);
          }
        }

        String inputLocation = line.getOptionValue("input");
        inputLocation = StringUtils.trim(inputLocation);
        File inputPath = new File(inputLocation);

        File outputPath = null;
        String outputLocation = line.getOptionValue("output");
        outputLocation = StringUtils.trim(outputLocation);
        if (StringUtils.isNotBlank(outputLocation)) {
          outputPath = new File(outputLocation);
        }

        boolean isSource = false;
        if (BooleanUtils.toBoolean(line.getOptionValue("source"))) {
          isSource = true;
        }
        settings.setSource(isSource);

        boolean captureLog = false;
        if (BooleanUtils.toBoolean(line.getOptionValue("captureLog"))) {
          captureLog = true;
        }

        String logLevel = line.getOptionValue("logLevel");
        logLevel = StringUtils.trim(logLevel);

        settings.setCaptureLog(captureLog);
        settings.setLogLevel(logLevel);

        settings.setInputPath(inputPath);
        settings.setOutputPath(outputPath);

        // Run Windup.
        ReportEngine engine = new ReportEngine(settings);
        engine.process();
      }
    } catch (FileNotFoundException e) {
      LOG.error("Input does not exist:" + e.getMessage(), e);
      HELP_FORMATTER.printHelp(WINDUP_COMMAND, options);
    } catch (IOException e) {
      LOG.error("Exception while writing report: " + e.getMessage(), e);
      HELP_FORMATTER.printHelp(WINDUP_COMMAND, options);
    }
  }