Example usage for org.apache.commons.lang ArrayUtils contains

List of usage examples for org.apache.commons.lang ArrayUtils contains

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils contains.

Prototype

public static boolean contains(boolean[] array, boolean valueToFind) 

Source Link

Document

Checks if the value is in the given array.

Usage

From source file:gov.nih.nci.cabig.caaers.web.ae.ReviewAndReportTab.java

@Override
public void onBind(HttpServletRequest request, CaptureAdverseEventInputCommand command, Errors errors) {
    super.onBind(request, command, errors);
    ReviewAndReportResult reviewResult = new ReviewAndReportResult();
    command.setReviewResult(reviewResult);

    //set the reporting period id.
    reviewResult.setReportingPeriodId(command.getAdverseEventReportingPeriod().getId());

    Map<Integer, ReportDefinition> rdMap = command.getApplicableReportDefinitions().getReportDefinitionMap();

    try {//from   ww w.java 2  s  .c  om
        //find the aeReport
        Integer aeReportId = ServletRequestUtils.getIntParameter(request, "activeAeReportId");
        reviewResult.setAeReportId(aeReportId);

        //bind the start dates
        List<AdverseEvent> adverseEvents = command.getEvaluationResult().getAllAeMap().get(aeReportId);
        int size = adverseEvents.size();
        for (int i = 0; i < size; i++) {
            AdverseEvent ae = adverseEvents.get(i);
            String startDateParamName = "evaluationResult.allAeMap[" + aeReportId.intValue() + "][" + i
                    + "].startDate";
            if (WebUtils.hasParameter(request, startDateParamName)) {
                String strStartDate = request.getParameter(startDateParamName);
                if (StringUtils.isNotEmpty(strStartDate)) {
                    ae.setStartDate(DateUtils.parseDateString(strStartDate).toDate());
                } else {
                    ae.setStartDate(null);
                }

            }
        }

        String paramName = "rd_" + aeReportId.toString();

        //selected report definition ids
        int[] selectedRdIds = ServletRequestUtils.getIntParameters(request, paramName + "_checked");

        //all report definition ids
        int[] rdIds = ServletRequestUtils.getIntParameters(request, paramName);

        for (int rdId : rdIds) {

            //fetch the manual selection indicator
            String strManualIndicator = ServletRequestUtils.getStringParameter(request,
                    paramName + "_" + rdId + "_manual");
            reviewResult.getManualSelectionIndicatorMap().put(new Integer(rdId),
                    StringUtils.equals("1", strManualIndicator));

            //actual action against each.
            String actualActionName = ServletRequestUtils.getStringParameter(request,
                    paramName + "_" + rdId + "_actualaction");

            if (StringUtils.equalsIgnoreCase(ReportDefinitionWrapper.ActionType.AMEND.name(),
                    actualActionName)) {
                reviewResult.getAmendList().add(rdMap.get(rdId));
                //special case, amend with itself
                if (ArrayUtils.contains(selectedRdIds, rdId)) {
                    reviewResult.getCreateList().add(rdMap.get(rdId));
                }
            }

            if (StringUtils.equalsIgnoreCase(ReportDefinitionWrapper.ActionType.WITHDRAW.name(),
                    actualActionName)) {
                reviewResult.getWithdrawList().add(rdMap.get(rdId));
            }

            if (StringUtils.equalsIgnoreCase(ReportDefinitionWrapper.ActionType.EDIT.name(),
                    actualActionName)) {
                reviewResult.getEditList().add(rdMap.get(rdId));
            }

            if (StringUtils.equalsIgnoreCase(ReportDefinitionWrapper.ActionType.CREATE.name(),
                    actualActionName)) {
                reviewResult.getCreateList().add(rdMap.get(rdId));
            }
        }

        //now find the ae's selected. 
        int[] aeIds = ServletRequestUtils.getIntParameters(request, "ae_" + aeReportId);
        for (int aeId : aeIds) {
            reviewResult.getAeList().add(aeId);
        }

        //find primaryAE
        Integer primaryAEId = ServletRequestUtils.getIntParameter(request, "ae_" + aeReportId + "_primary");
        reviewResult.setPrimaryAdverseEventId(primaryAEId);

        //find the aes, deselected. 
        for (AdverseEvent ae : command.getEvaluationResult().getAllAeMap().get(aeReportId)) {
            if (ArrayUtils.contains(aeIds, ae.getId().intValue()))
                continue;
            reviewResult.getUnwantedAEList().add(ae.getId());
        }

    } catch (ServletRequestBindingException e) {
        log.warn(
                "Error while binding review-and-report page parameters, this is okay sometimes as we click back from reivew page",
                e);
    }
}

From source file:com.dp2345.plugin.unionpay.UnionpayPlugin.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w .ja v a2s . c om*/
public boolean verifyNotify(String sn, NotifyMethod notifyMethod, HttpServletRequest request) {
    PluginConfig pluginConfig = getPluginConfig();
    Payment payment = getPayment(sn);
    if (generateSign(request.getParameterMap()).equals(request.getParameter("signature"))
            && pluginConfig.getAttribute("partner").equals(request.getParameter("merId"))
            && sn.equals(request.getParameter("orderNumber"))
            && CURRENCY.equals(request.getParameter("orderCurrency"))
            && "00".equals(request.getParameter("respCode"))
            && payment.getAmount().multiply(new BigDecimal(100))
                    .compareTo(new BigDecimal(request.getParameter("orderAmount"))) == 0) {
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        parameterMap.put("version", "1.0.0");
        parameterMap.put("charset", "UTF-8");
        parameterMap.put("transType", "01");
        parameterMap.put("merId", pluginConfig.getAttribute("partner"));
        parameterMap.put("orderNumber", sn);
        parameterMap.put("orderTime", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        parameterMap.put("merReserved", "");
        parameterMap.put("signMethod", "MD5");
        parameterMap.put("signature", generateSign(parameterMap));
        String result = post("https://unionpaysecure.com/api/Query.action", parameterMap);
        if (ArrayUtils.contains(result.split("&"), "respCode=00")) {
            return true;
        }
    }
    return false;
}

From source file:com.ecyrd.jspwiki.event.WikiSecurityEvent.java

/**
 * Constructs a new instance of this event type, which signals a security
 * event has occurred. The <code>source</code> parameter is required, and
 * may not be <code>null</code>. When the WikiSecurityEvent is
 * constructed, the security logger {@link #log} is notified.
 * @param src the source of the event, which can be any object: a wiki
 *            page, group or authentication/authentication/group manager.
 * @param type the type of event/*from   w w w  . j  av a  2s  . c  om*/
 * @param principal the subject of the event, which may be <code>null</code>
 * @param target the changed Object, which may be <code>null</code>
 */
public WikiSecurityEvent(Object src, int type, Principal principal, Object target) {
    super(src, type);
    if (src == null) {
        throw new IllegalArgumentException("Argument(s) cannot be null.");
    }
    this.m_principal = principal;
    this.m_target = target;
    if (log.isEnabledFor(Level.ERROR) && ArrayUtils.contains(ERROR_EVENTS, type)) {
        log.error(this);
    } else if (log.isEnabledFor(Level.WARN) && ArrayUtils.contains(WARN_EVENTS, type)) {
        log.warn(this);
    } else if (log.isEnabledFor(Level.INFO) && ArrayUtils.contains(INFO_EVENTS, type)) {
        log.info(this);
    }
    log.debug(this);
}

From source file:com.dushyant.flume.sink.aws.sqs.BatchSQSMsgSenderTest.java

/**
 * Tests {@link BatchSQSMsgSender#createBatches(org.apache.flume.Channel)} method. Tests invalid characters not
 * allowed by the SQS. See [http://docs.aws.amazon
 * .com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html]
 * for list of valid characters allowed by SQS.
 * <p>// www  .ja  va 2 s .  c  om
 * <p>
 * <pre>
 * Inputs:
 *  channel = never empty. with messages containing invalid characters.
 *
 * Expected Output:
 *   The sink messages should not contain invalid characters
 * </pre>
 */
@Test
public void testInvalidCharacters() throws Exception {
    // See
    // http://stackoverflow.com/questions/16688523/aws-sqs-valid-characters
    // http://stackoverflow.com/questions/1169754/amazon-sqs-invalid-binary-character-in-message-body
    // https://forums.aws.amazon.com/thread.jspa?messageID=459090
    // http://stackoverflow.com/questions/16329695/invalid-binary-character-when-transmitting-protobuf-net
    // -messages-over-aws-sqs
    byte invalidCharByte = 0x1C;
    String mockMsg = "Test with some invalid chars at the end 0%2F>^F";
    byte[] origPayloadWithInvalidChars = ArrayUtils.add(mockMsg.getBytes(), invalidCharByte);

    BatchSQSMsgSender sqsMsgSender = new BatchSQSMsgSender("https://some-fake/url", "us-east-1",
            "someAwsAccessKey", "someAwsSecretKey", 1, origPayloadWithInvalidChars.length);

    Event mockEvent = Mockito.mock(Event.class);
    when(mockEvent.getBody()).thenReturn(origPayloadWithInvalidChars);

    Channel mockChannel = Mockito.mock(Channel.class);
    when(mockChannel.take()).thenReturn(mockEvent);

    List<SendMessageBatchRequest> batches = sqsMsgSender.createBatches(mockChannel);

    List<SendMessageBatchRequestEntry> msgEntries = batches.get(0).getEntries();
    assertCorrectPayloadInEntries(new String(origPayloadWithInvalidChars).trim().getBytes(), msgEntries);

    // Make sure that the message being sent by the sink doesn't contain the invalid characters
    for (SendMessageBatchRequestEntry entry : msgEntries) {
        Assert.assertNotNull(entry);
        Assert.assertTrue(
                ArrayUtils.contains(new String(origPayloadWithInvalidChars).getBytes(), invalidCharByte));
        Assert.assertTrue(!ArrayUtils.contains(entry.getMessageBody().getBytes(), invalidCharByte));
    }
}

From source file:com.pureinfo.common.namedvalue.view.function.ShowNamedValueOptionsNewFunctionHandler.java

/**
 * //from  w w  w.  j  ava2 s  . c  o  m
 * @param _sValue
 * @param _bMultiple
 * @param _nValueType
 * @param _bShowHead
 * @param _sStyle
 * @param _sName
 * @return
 */
private String doPerform(String _sValue, boolean _bMultiple, List _nvs, Object _oShowWhat, boolean _bShowHead,
        String _sName) throws PureException {
    String[] arrValues = _sValue == null ? null : _sValue.split(NamedValueHelper.VALUE_SEPARATOR);
    StringBuffer sbuff = new StringBuffer();
    try {
        if (!_bMultiple && _bShowHead) {
            sbuff.append("<option value=\"\"> --  --\n");
        }

        for (Iterator iter = _nvs.iterator(); iter.hasNext();) {
            INamedValue element = (INamedValue) iter.next();
            String sShow = rendShow(_oShowWhat, element);

            String sCode = element.getValue();

            sbuff.append("<option ").append("value='").append(sCode).append('\'');
            if (arrValues != null && ArrayUtils.contains(arrValues, sCode)) {
                sbuff.append(" selected");
            }
            sbuff.append('>').append(sShow).append("</option>\n");
        }
        return sbuff.toString();
    } finally {
        sbuff.setLength(0);
        if (_nvs != null)
            _nvs.clear();
    }
}

From source file:co.cask.cdap.client.util.RESTClient.java

public HttpResponse upload(HttpRequest request, AccessToken accessToken, int... allowedErrorCodes)
        throws IOException, UnauthorizedException, DisconnectedException {

    HttpResponse response = HttpRequests.execute(
            HttpRequest.builder(request).addHeaders(getAuthHeaders(accessToken)).build(),
            clientConfig.getUploadRequestConfig());
    int responseCode = response.getResponseCode();
    if (!isSuccessful(responseCode) && !ArrayUtils.contains(allowedErrorCodes, responseCode)) {
        if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException("Unauthorized status code received from the server.");
        }//from   w w w .ja  v  a  2 s  . co m
        throw new IOException(response.getResponseBodyAsString());
    }
    return response;
}

From source file:mitm.application.djigzo.ca.PFXMailBuilder.java

private void replacePFX(MimeMessage message) throws MessagingException {
    Multipart mp;/*www .j  av a  2 s .  c om*/

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    BodyPart pfxPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart octetStreamPart = null;

    /*
     * Try to find the first attachment with X-Djigzo-Marker attachment header which should be the attachment
     * we should replace (we should replace the content and keep the headers)
     */
    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pfxPart = part;

            break;
        }

        /*
         * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/octet-stream")) {
            octetStreamPart = part;
        }
    }

    if (pfxPart == null) {
        if (octetStreamPart != null) {
            logger.info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pfxPart = octetStreamPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pfxPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pfx, "application/octet-stream")));
}

From source file:com.baasbox.controllers.User.java

@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class })
public static Result getUser(String username) throws SqlInjectionException {
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method Start");
    if (ArrayUtils.contains(
            new String[] { BBConfiguration.getBaasBoxAdminUsername(), BBConfiguration.getBaasBoxUsername() },
            username))//from w  w  w  . j a v a 2  s .  com
        return badRequest(username + " cannot be queried");
    ODocument profile = UserService.getUserProfilebyUsername(username);
    if (profile == null)
        return notFound(username + " not found");
    String result = prepareResponseToJson(profile);
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method End");
    return ok(result);
}

From source file:gov.nih.nci.caarray.validation.UniqueConstraintValidator.java

private boolean declaresConstraint(Class<?> entityClass) {
    Annotation[] annotations = entityClass.getDeclaredAnnotations();
    for (Annotation a : annotations) {
        if (a.equals(uniqueConstraint)) {
            return true;
        } else if (UniqueConstraints.class.equals(a.annotationType())) {
            UniqueConstraints ucs = (UniqueConstraints) a;
            return ArrayUtils.contains(ucs.constraints(), uniqueConstraint);
        }// w  w  w . j  av a  2s.  c o m
    }
    return false;
}

From source file:it.geosolutions.imageio.plugins.nitronitf.ImageIOUtils.java

/**
 * Returns a list of Files contained in the given String array of files or directories. If one of the array contents is a directory, it searches
 * it. Files ending in the extensions provided are returned in the list.
 * /*from w w  w.  j  a v a2 s  . c  o m*/
 * @param filesOrDirs
 * @param extensions
 * @return
 */
public static List<File> getFiles(String[] filesOrDirs, String[] extensions) {
    List<File> files = new ArrayList<File>();
    final String[] exts = extensions;
    for (int i = 0; i < filesOrDirs.length; i++) {
        String arg = filesOrDirs[i];
        File file = new File(arg);
        if (file.isDirectory() && file.exists()) {
            files.addAll(Arrays.asList(file.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return ArrayUtils.contains(exts, FilenameUtils.getExtension(name.toLowerCase()));
                }
            })));
        } else
            files.add(file);
    }
    return files;
}