Example usage for java.util ArrayList contains

List of usage examples for java.util ArrayList contains

Introduction

In this page you can find the example usage for java.util ArrayList contains.

Prototype

public boolean contains(Object o) 

Source Link

Document

Returns true if this list contains the specified element.

Usage

From source file:it.cnr.icar.eric.server.query.CompressContentQueryFilterPlugin.java

protected Collection<ExtrinsicObjectType> getAllImportedEOs(ExtrinsicObjectType targetEO,
        ServerRequestContext serverContext, int depth) throws RegistryException {
    ArrayList<ExtrinsicObjectType> eoList = new ArrayList<ExtrinsicObjectType>();
    try {/*from  www .  j a va2 s  .c  o m*/
        ReferenceResolver refResolver = new ReferenceResolverImpl();
        // Support this parameter: urn:oasis:names:tc:ebxml-regrep:rs:depthParameter
        Collection<?> objRefs = refResolver.getReferencedObjects(serverContext, targetEO, depth);
        if (objRefs != null) {
            Iterator<?> objRefItr = objRefs.iterator();
            while (objRefItr.hasNext()) {
                Object obj = objRefItr.next();
                if (obj instanceof ExtrinsicObjectType) {
                    ExtrinsicObjectType dependentEO = (ExtrinsicObjectType) obj;
                    if (!eoList.contains(dependentEO)) {
                        eoList.add(dependentEO);
                    }
                }
            }
        }
    } catch (Throwable t) {
        throw new RegistryException(t);
    }
    return eoList;
}

From source file:edu.illinois.imunit.examples.apache.collections.TestBlockingBuffer.java

/**
 * Tests interrupted {@link BlockingBuffer#get()}.
 *//*from   w  w w  .j  a  va  2 s.com*/
@Test
@Schedules({ @Schedule(name = "InterruptedGet", value = "[beforeGet:afterGet]@readThread->beforeInterrupt@main,"
        + "finishAddException@readThread->afterInterrupt@main") })
public void testInterruptedGet() throws InterruptedException {
    Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer());
    Object obj = new Object();

    // spawn a read thread to wait on the empty buffer
    ArrayList exceptionList = new ArrayList();
    Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "InterruptedGet", "readThread");
    thread.start();

    try {
        //Thread.sleep(100); //INS-SLEEP
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    // Interrupting the thread should cause it to throw BufferUnderflowException
    fireEvent("beforeInterrupt");
    thread.interrupt();

    // Chill, so thread can throw and add message to exceptionList
    // Thread.sleep(100);
    fireEvent("afterInterrupt");

    assertTrue("InterruptedGet", exceptionList.contains("BufferUnderFlow"));
    // assertFalse("InterruptedGet", thread.isAlive());
    //    if( thread.isAlive() ) {
    //      fail( "Read thread has hung." );
    //    }

}

From source file:com.segma.trim.InAppBillingUtilities.InAppBillingHelper.java

int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
        throws RemoteException, JSONException {
    logDebug("Querying SKU details.");
    ArrayList<String> skuList = new ArrayList<String>();
    skuList.addAll(inv.getAllOwnedSkus(itemType));
    if (moreSkus != null) {
        for (String sku : moreSkus) {
            if (!skuList.contains(sku)) {
                skuList.add(sku);//from   ww w.  j a va 2 s  .  c o m
            }
        }
    }

    if (skuList.size() == 0) {
        logDebug("queryPrices: nothing to do because there are no SKUs.");
        return BILLING_RESPONSE_RESULT_OK;
    }

    // Split the sku list in blocks of no more than 20 elements.
    ArrayList<ArrayList<String>> packs = new ArrayList<ArrayList<String>>();
    ArrayList<String> tempList;
    int n = skuList.size() / 20;
    int mod = skuList.size() % 20;
    for (int i = 0; i < n; i++) {
        tempList = new ArrayList<String>();
        for (String s : skuList.subList(i * 20, i * 20 + 20)) {
            tempList.add(s);
        }
        packs.add(tempList);
    }
    if (mod != 0) {
        tempList = new ArrayList<String>();
        for (String s : skuList.subList(n * 20, n * 20 + mod)) {
            tempList.add(s);
        }
        packs.add(tempList);
    }

    for (ArrayList<String> skuPartList : packs) {
        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuPartList);
        Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus);

        if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
            int response = getResponseCodeFromBundle(skuDetails);
            if (response != BILLING_RESPONSE_RESULT_OK) {
                logDebug("getSkuDetails() failed: " + getResponseDesc(response));
                return response;
            } else {
                logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
                return IABHELPER_BAD_RESPONSE;
            }
        }

        ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);

        for (String thisResponse : responseList) {
            StockKeepingUnitDetails d = new StockKeepingUnitDetails(itemType, thisResponse);
            logDebug("Got sku details: " + d);
            inv.addSkuDetails(d);
        }
    }

    return BILLING_RESPONSE_RESULT_OK;
}

From source file:com.smartmobilesoftware.util.IabHelper.java

int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus)
        throws RemoteException, JSONException {
    logDebug("Querying SKU details.");
    ArrayList<String> skuList = new ArrayList<String>();
    skuList.addAll(inv.getAllOwnedSkus(itemType));
    if (moreSkus != null) {
        logDebug("moreSkus: Building SKUs List");
        for (String sku : moreSkus) {
            logDebug("moreSkus: " + sku);
            if (!skuList.contains(sku)) {
                skuList.add(sku);//from w  w w  .  j  a  v a 2s. c  o  m
            }
        }
    }

    if (skuList.size() == 0) {
        logDebug("queryPrices: nothing to do because there are no SKUs.");
        return BILLING_RESPONSE_RESULT_OK;
    }

    // Split the SKUs into slices of maximum 20 entries before querying them to prevent 
    // "Input Error: skusBundle array associated with key ITEM_ID_LIST cannot contain more than 20 items."
    while (skuList.size() > 0) {
        ArrayList<String> skuSubList = new ArrayList<String>(skuList.subList(0, Math.min(19, skuList.size())));
        skuList.removeAll(skuSubList);

        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuSubList);
        Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus);

        if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) {
            int response = getResponseCodeFromBundle(skuDetails);
            if (response != BILLING_RESPONSE_RESULT_OK) {
                logDebug("getSkuDetails() failed: " + getResponseDesc(response));
                return response;
            } else {
                logError("getSkuDetails() returned a bundle with neither an error nor a detail list.");
                return ERR_BAD_RESPONSE;
            }
        }

        ArrayList<String> responseList = skuDetails.getStringArrayList(RESPONSE_GET_SKU_DETAILS_LIST);

        for (String thisResponse : responseList) {
            SkuDetails d = new SkuDetails(itemType, thisResponse);
            logDebug("Got sku details: " + d);
            inv.addSkuDetails(d);
        }
    }
    return BILLING_RESPONSE_RESULT_OK;
}

From source file:gsn.webservice.standard.GSNWebServiceSkeleton.java

/**
 * Auto generated method signature/*  w  w  w  .  j  a v  a2  s.  c  o m*/
 *
 * @param getMultiData
 */

public gsn.webservice.standard.GetMultiDataResponse getMultiData(
        gsn.webservice.standard.GetMultiData getMultiData) {
    //throw new java.lang.UnsupportedOperationException("Please implement " + this.getClass().getName() + "#getMultiData");
    //
    User user = getUserForAC(getMultiData.getAcDetails());
    //
    GetMultiDataResponse response = new GetMultiDataResponse();
    //
    Map<String, String[]> requestParameters = new HashMap<String, String[]>();

    // virtual sensor and field selection

    HashMap<String, ArrayList<String>> vsAndFields = buildSelection(getMultiData.getFieldSelector());

    ArrayList<String> vsnames = new ArrayList<String>();
    for (Map.Entry<String, ArrayList<String>> entry : vsAndFields.entrySet()) {
        if (!Main.getContainerConfig().isAcEnabled()
                || (user != null && (user.hasReadAccessRight(entry.getKey()) || user.isAdmin()))) {
            StringBuilder sb = new StringBuilder();
            sb.append(entry.getKey());
            for (String elt : entry.getValue()) {
                sb.append(":").append(elt);
            }
            vsnames.add(sb.toString());
        }
    }
    requestParameters.put("vsname", vsnames.toArray(new String[] {}));

    // time format

    String timeFormat = getMultiData.getTimeFormat();
    if (timeFormat != null)
        requestParameters.put("timeformat", new String[] { timeFormat });

    ArrayList<String> critFields = new ArrayList<String>();

    //from / to
    long from = getMultiData.getFrom();
    long to = getMultiData.getTo();
    for (String vsname : vsAndFields.keySet()) {
        if (from != java.lang.Long.MIN_VALUE)
            critFields.add("and::" + vsname + ":timed:ge:" + from);
        if (to != java.lang.Long.MIN_VALUE)
            critFields.add("and::" + vsname + ":timed:leq:" + to);
    }

    // conditions

    StandardCriterion[] standardCriteria = getMultiData.getConditions();
    if (standardCriteria != null) {
        for (StandardCriterion criterion : standardCriteria) {
            HashMap<String, ArrayList<String>> selection = new HashMap<String, ArrayList<String>>();
            if ("ALL".equalsIgnoreCase(criterion.getVsname())) {
                if ("ALL".equalsIgnoreCase(criterion.getField())) {
                    // We add this criterion for all the virtual sensors and all their fields
                    selection = vsAndFields;
                } else {
                    //ArrayList<String> vss = fieldToVs.get(criterion.getField());
                    ArrayList<String> crit = new ArrayList<String>();
                    crit.add(criterion.getField());
                    for (Map.Entry<String, ArrayList<String>> entry : vsAndFields.entrySet()) {
                        if (entry.getValue() != null && entry.getValue().contains(criterion.getField())) {
                            selection.put(entry.getKey(), crit);
                        }
                    }
                }
            } else {
                ArrayList<String> _fields = vsAndFields.get(criterion.getVsname());
                if (_fields != null) {
                    if ("ALL".equalsIgnoreCase(criterion.getField())) {
                        selection.put(criterion.getVsname(), _fields);
                    } else {
                        if (_fields.contains(criterion.getField())) {
                            ArrayList<String> values = new ArrayList<String>();
                            values.add(criterion.getField());
                            selection.put(criterion.getVsname(), values);
                        }
                    }
                }
            }
            for (Map.Entry<String, ArrayList<String>> entry : selection.entrySet()) {
                String vsname = entry.getKey();
                for (String field : entry.getValue()) {
                    //<critJoin>:<negation>:<vsname>:<field>:<operator>:<value>
                    StringBuilder sb = new StringBuilder();
                    sb.append(criterion.getCritJoin());
                    sb.append(":");
                    sb.append(criterion.getNegation());
                    sb.append(":");
                    sb.append(vsname);
                    sb.append(":");
                    sb.append(field);
                    sb.append(":");
                    sb.append(criterion.getOperator());
                    sb.append(":");
                    sb.append(criterion.getValue());
                    //
                    critFields.add(sb.toString());
                }
            }
        }
    }

    requestParameters.put("critfield", critFields.toArray(new String[] {}));

    // nb

    /*long nb = getMultiData.getNb();
    if (nb != java.lang.Long.MIN_VALUE) // check if nb is set
    requestParameters.put("nb", new String[]{"0:" + nb});
    */
    int userNb = getMultiData.getNb();
    if (userNb == java.lang.Integer.MIN_VALUE)
        userNb = java.lang.Integer.MAX_VALUE;
    else if (userNb < 0)
        userNb = 0;

    // aggregation

    AggregationCriterion aggregation = getMultiData.getAggregation();
    if (aggregation != null) {
        aggregation.getTimeRange();
        requestParameters.put("groupby", new String[] { new StringBuilder().append(aggregation.getTimeRange())
                .append(":").append(aggregation.getGroupOperator()).toString() });
    }

    //
    try {
        QueriesBuilder qbuilder = new QueriesBuilder(requestParameters);
        for (Map.Entry<String, AbstractQuery> entry : qbuilder.getSqlQueries().entrySet()) {
            //
            QuerySession session = generateSession(entry.getValue(), entry.getKey(), userNb);
            //
            GSNWebService_QueryResult result = getResult(session);
            //
            response.addQueryResult(result);
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
    }

    //
    return response;
}

From source file:com.google.wireless.speed.speedometer.measurements.PingTask.java

private MeasurementResult executePingCmdTask() throws MeasurementError {
    Log.i(SpeedometerApp.TAG, "Starting executePingCmdTask");
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult measurementResult = null;
    // TODO(Wenjie): Add a exhaustive list of ping locations for different Android phones
    pingTask.pingExe = parent.getString(R.string.ping_executable);
    try {/*  www  . j a v  a 2s  .c o m*/
        String command = Util.constructCommand(pingTask.pingExe, "-i",
                Config.DEFAULT_INTERVAL_BETWEEN_ICMP_PACKET_SEC, "-s", pingTask.packetSizeByte, "-w",
                pingTask.pingTimeoutSec, "-c", Config.PING_COUNT_PER_MEASUREMENT, targetIp);
        Log.i(SpeedometerApp.TAG, "Running: " + command);
        pingProc = Runtime.getRuntime().exec(command);

        // Grab the output of the process that runs the ping command
        InputStream is = pingProc.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;
        int lineCnt = 0;
        ArrayList<Double> rrts = new ArrayList<Double>();
        ArrayList<Integer> receivedIcmpSeq = new ArrayList<Integer>();
        double packetLoss = Double.MIN_VALUE;
        int packetsSent = Config.PING_COUNT_PER_MEASUREMENT;
        // Process each line of the ping output and store the rrt in array rrts.
        while ((line = br.readLine()) != null) {
            // Ping prints a number of 'param=value' pairs, among which we only need the 
            // 'time=rrt_val' pair
            String[] extractedValues = Util.extractInfoFromPingOutput(line);
            if (extractedValues != null) {
                int curIcmpSeq = Integer.parseInt(extractedValues[0]);
                double rrtVal = Double.parseDouble(extractedValues[1]);

                // ICMP responses from the system ping command could be duplicate and out of order
                if (!receivedIcmpSeq.contains(curIcmpSeq)) {
                    rrts.add(rrtVal);
                    receivedIcmpSeq.add(curIcmpSeq);
                }
            }

            this.progress = 100 * ++lineCnt / Config.PING_COUNT_PER_MEASUREMENT;
            this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
            broadcastProgressForUser(progress);
            // Get the number of sent/received pings from the ping command output 
            int[] packetLossInfo = Util.extractPacketLossInfoFromPingOutput(line);
            if (packetLossInfo != null) {
                packetsSent = packetLossInfo[0];
                int packetsReceived = packetLossInfo[1];
                packetLoss = 1 - ((double) packetsReceived / (double) packetsSent);
            }

            Log.i(SpeedometerApp.TAG, line);
        }
        // Use the output from the ping command to compute packet loss. If that's not
        // available, use an estimation.
        if (packetLoss == Double.MIN_VALUE) {
            packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        }
        measurementResult = constructResult(rrts, packetLoss, packetsSent);
        Log.i(SpeedometerApp.TAG, MeasurementJsonConvertor.toJsonString(measurementResult));
    } catch (IOException e) {
        Log.e(SpeedometerApp.TAG, e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (SecurityException e) {
        Log.e(SpeedometerApp.TAG, e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (NumberFormatException e) {
        Log.e(SpeedometerApp.TAG, e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (InvalidParameterException e) {
        Log.e(SpeedometerApp.TAG, e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } finally {
        // All associated streams with the process will be closed upon destroy()
        cleanUp(pingProc);
    }

    if (measurementResult == null) {
        Log.e(SpeedometerApp.TAG, "Error running ping: " + errorMsg);
        throw new MeasurementError(errorMsg);
    }
    return measurementResult;
}

From source file:com.clustercontrol.jobmanagement.session.JobRunManagementBean.java

/**
 * /*from ww  w. j  a  va  2s  .c o  m*/
 * facilityID???????
 * 
 * @param monitorTypeId
 * @param facilityId
 * @return ??
 * @throws HinemosUnknown
 * @throws MonitorNotFound
 * 
 */
public HashMap<RunInstructionInfo, MonitorInfo> getMonitorJobMap(String monitorTypeId, String facilityId)
        throws HinemosUnknown {
    HashMap<RunInstructionInfo, MonitorInfo> ret = new HashMap<>();
    JpaTransactionManager jtm = null;
    try {
        jtm = new JpaTransactionManager();
        jtm.begin();

        Map<RunInstructionInfo, MonitorInfo> monitorJobMap = MonitorJobWorker.getMonitorJobMap(monitorTypeId);
        for (Map.Entry<RunInstructionInfo, MonitorInfo> entry : monitorJobMap.entrySet()) {
            // ?ID?
            JobSessionJobEntity sessionJob = QueryUtil.getJobSessionJobPK(entry.getKey().getSessionId(),
                    entry.getKey().getJobunitId(), entry.getKey().getJobId());
            // ??ID????
            ArrayList<String> facilityIdList = new RepositoryControllerBean()
                    .getExecTargetFacilityIdList(entry.getKey().getFacilityId(), sessionJob.getOwnerRoleId());
            if (facilityIdList != null && facilityIdList.contains(facilityId)) {
                ret.put(entry.getKey(), entry.getValue());
            }
        }

        jtm.commit();
    } catch (HinemosUnknown e) {
        jtm.rollback();
        throw e;
    } catch (Exception e) {
        m_log.warn("getMonitorJobMap() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
        if (jtm != null)
            jtm.rollback();
        throw new HinemosUnknown(e.getMessage(), e);
    } finally {
        if (jtm != null)
            jtm.close();
    }

    return ret;
}

From source file:edu.illinois.imunit.examples.apache.collections.TestBlockingBuffer.java

/**
 * Tests interrupted remove.//  w w w  .j ava 2 s.  c o m
 */
@Test
@Schedules({
        @Schedule(name = "InterruptedRemove", value = "[beforeRemove: afterRemove]@readThread->beforeInterrupt@main,"
                + "finishAddException@readThread->afterInterrupt@main") })
public void testInterruptedRemove() throws InterruptedException {
    Buffer blockingBuffer = BlockingBuffer.decorate(new MyBuffer());
    Object obj = new Object();

    // spawn a read thread to wait on the empty buffer
    ArrayList exceptionList = new ArrayList();
    Thread thread = new ReadThread(blockingBuffer, obj, exceptionList, "remove", "InterruptedRemove",
            "readThread");
    thread.start();
    try {
        //Thread.sleep(100); //INS-SLEEP
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    // Interrupting the thread should cause it to throw BufferUnderflowException
    fireEvent("beforeInterrupt");
    thread.interrupt();
    // Chill, so thread can throw and add message to exceptionList
    // Thread.sleep(100);
    fireEvent("afterInterrupt");
    assertTrue("InterruptedRemove", exceptionList.contains("BufferUnderFlow"));
    //assertFalse("InterruptedRemove",thread.isAlive());
    //if( thread.isAlive() ) {
    //fail( "Read thread has hung." );
    //}

}

From source file:com.mobiperf_library.measurements.PingTask.java

private MeasurementResult executePingCmdTask(int ipByteLen) throws MeasurementError {
    Logger.i("Starting executePingCmdTask");
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult measurementResult = null;
    // TODO(Wenjie): Add a exhaustive list of ping locations for different Android phones
    pingTask.pingExe = Util.pingExecutableBasedOnIPType(ipByteLen, parent);
    Logger.i("Ping executable is " + pingTask.pingExe);
    if (pingTask.pingExe == null) {
        Logger.e("Ping executable not found");
        throw new MeasurementError("Ping executable not found");
    }/*from  w  ww . j a  v  a 2  s.c  o m*/
    try {
        String command = Util.constructCommand(pingTask.pingExe, "-i",
                Config.DEFAULT_INTERVAL_BETWEEN_ICMP_PACKET_SEC, "-s", pingTask.packetSizeByte, "-w",
                pingTask.pingTimeoutSec, "-c", Config.PING_COUNT_PER_MEASUREMENT, targetIp);
        Logger.i("Running: " + command);
        pingProc = Runtime.getRuntime().exec(command);

        // Grab the output of the process that runs the ping command
        InputStream is = pingProc.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;
        int lineCnt = 0;
        ArrayList<Double> rrts = new ArrayList<Double>();
        ArrayList<Integer> receivedIcmpSeq = new ArrayList<Integer>();
        double packetLoss = Double.MIN_VALUE;
        int packetsSent = Config.PING_COUNT_PER_MEASUREMENT;
        // Process each line of the ping output and store the rrt in array rrts.
        while ((line = br.readLine()) != null) {
            // Ping prints a number of 'param=value' pairs, among which we only need the 
            // 'time=rrt_val' pair
            String[] extractedValues = Util.extractInfoFromPingOutput(line);
            if (extractedValues != null) {
                int curIcmpSeq = Integer.parseInt(extractedValues[0]);
                double rrtVal = Double.parseDouble(extractedValues[1]);

                // ICMP responses from the system ping command could be duplicate and out of order
                if (!receivedIcmpSeq.contains(curIcmpSeq)) {
                    rrts.add(rrtVal);
                    receivedIcmpSeq.add(curIcmpSeq);
                }
            }

            this.progress = 100 * ++lineCnt / Config.PING_COUNT_PER_MEASUREMENT;
            this.progress = Math.min(Config.MAX_PROGRESS_BAR_VALUE, progress);
            broadcastProgressForUser(progress);
            // Get the number of sent/received pings from the ping command output 
            int[] packetLossInfo = Util.extractPacketLossInfoFromPingOutput(line);
            if (packetLossInfo != null) {
                packetsSent = packetLossInfo[0];
                int packetsReceived = packetLossInfo[1];
                packetLoss = 1 - ((double) packetsReceived / (double) packetsSent);
            }

            Logger.i(line);
        }
        // Use the output from the ping command to compute packet loss. If that's not
        // available, use an estimation.
        if (packetLoss == Double.MIN_VALUE) {
            packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        }
        measurementResult = constructResult(rrts, packetLoss, packetsSent, PING_METHOD_CMD);
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (SecurityException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (NumberFormatException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (InvalidParameterException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } finally {
        // All associated streams with the process will be closed upon destroy()
        cleanUp(pingProc);
    }

    if (measurementResult == null) {
        Logger.e("Error running ping: " + errorMsg);
        throw new MeasurementError(errorMsg);
    }
    return measurementResult;
}

From source file:io.codeclou.jenkins.githubwebhookbuildtriggerplugin.GithubWebhookBuildTriggerAction.java

@RequirePOST
public HttpResponse doReceive(HttpServletRequest request, StaplerRequest staplerRequest)
        throws IOException, ServletException {
    StringWriter writer = new StringWriter();
    IOUtils.copy(request.getInputStream(), writer, "UTF-8");
    String requestBody = writer.toString();
    Gson gson = new Gson();
    GithubWebhookPayload githubWebhookPayload = gson.fromJson(requestBody, GithubWebhookPayload.class);
    StringBuilder info = new StringBuilder();
    if (githubWebhookPayload == null) {
        return HttpResponses.error(500, this
                .getTextEnvelopedInBanner("   ERROR: payload json is empty at least requestBody is empty!"));
    }/* ww w  .  j a v  a  2 s  .c  o  m*/
    try {
        //
        // WEBHOOK SECRET
        //
        String githubSignature = request.getHeader("x-hub-signature");
        String webhookSecretAsConfiguredByUser = GithubWebhookBuildTriggerPluginBuilder.DescriptorImpl
                .getDescriptor().getWebhookSecret();
        String webhookSecretMessage = "validating webhook payload against wevhook secret.";
        info.append(">> webhook secret validation").append("\n");
        if (webhookSecretAsConfiguredByUser == null || webhookSecretAsConfiguredByUser.isEmpty()) {
            webhookSecretMessage = "   skipping validation since no webhook secret is configured in \n"
                    + "   'Jenkins' -> 'Configure' tab under 'Github Webhook Build Trigger' section.";
        } else {
            Boolean isValid = GitHubWebhookUtility.verifySignature(requestBody, githubSignature,
                    webhookSecretAsConfiguredByUser);
            if (!isValid) {
                info.append(webhookSecretMessage).append("\n");
                return HttpResponses.error(500, this.getTextEnvelopedInBanner(info.toString()
                        + "   ERROR: github webhook secret signature check failed. Check your webhook secret."));
            }
            webhookSecretMessage = "   ok. Webhook secret validates against " + githubSignature + "\n";
        }
        info.append(webhookSecretMessage).append("\n\n");

        //
        // CHECK IF INITIAL REQUEST (see test-webhook-init-payload.json)
        // See: https://developer.github.com/webhooks/#ping-event
        //
        if (githubWebhookPayload.getHook_id() != null) {
            info.append(">> ping request received: your webhook with ID ");
            info.append(githubWebhookPayload.getHook_id());
            info.append(" is working :)\n");
            return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
        }

        //
        // PAYLOAD TO ENVVARS
        //
        EnvironmentContributionAction environmentContributionAction = new EnvironmentContributionAction(
                githubWebhookPayload);

        //
        // TRIGGER JOBS
        //
        String jobNamePrefix = this.normalizeRepoFullName(githubWebhookPayload.getRepository().getFull_name());
        StringBuilder jobsTriggered = new StringBuilder();
        ArrayList<String> jobsAlreadyTriggered = new ArrayList<>();
        StringBuilder causeNote = new StringBuilder();
        causeNote.append("github-webhook-build-trigger-plugin:\n");
        causeNote.append(githubWebhookPayload.getAfter()).append("\n");
        causeNote.append(githubWebhookPayload.getRef()).append("\n");
        causeNote.append(githubWebhookPayload.getRepository().getClone_url());
        Cause cause = new Cause.RemoteCause("github.com", causeNote.toString());
        Collection<Job> jobs = Jenkins.getInstance().getAllItems(Job.class);
        if (jobs.isEmpty()) {
            jobsTriggered.append("   WARNING NO JOBS FOUND!\n");
            jobsTriggered.append("      You either have no jobs or if you are using matrix-based security,\n");
            jobsTriggered.append("      please give the following rights to 'Anonymous':\n");
            jobsTriggered.append("      'Job' -> build, discover, read.\n");
        }
        for (Job job : jobs) {
            if (job.getName().startsWith(jobNamePrefix) && !jobsAlreadyTriggered.contains(job.getName())) {
                jobsAlreadyTriggered.add(job.getName());
                if (job instanceof WorkflowJob) {
                    WorkflowJob wjob = (WorkflowJob) job;
                    if (wjob.isBuildable()) {
                        jobsTriggered.append("   WORKFLOWJOB> ").append(job.getName()).append(" TRIGGERED\n");
                        wjob.scheduleBuild2(0, environmentContributionAction.transform(),
                                new CauseAction(cause));
                    } else {
                        jobsTriggered.append("   WORKFLOWJOB> ").append(job.getName())
                                .append(" NOT BUILDABLE. SKIPPING.\n");
                    }
                } else {
                    AbstractProject projectScheduable = (AbstractProject) job;
                    if (job.isBuildable()) {
                        jobsTriggered.append("   CLASSICJOB>  ").append(job.getName()).append(" TRIGGERED\n");
                        projectScheduable.scheduleBuild(0, cause, environmentContributionAction);
                    } else {
                        jobsTriggered.append("   CLASSICJOB>  ").append(job.getName())
                                .append(" NOT BUILDABLE. SKIPPING.\n");
                    }
                }
            }
        }
        //
        // WRITE ADDITONAL INFO
        //
        info.append(">> webhook content to env vars").append("\n");
        info.append(environmentContributionAction.getEnvVarInfo());
        info.append("\n");
        info.append(">> jobs triggered with name matching '").append(jobNamePrefix).append("*'").append("\n");
        info.append(jobsTriggered.toString());
        return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
    } catch (JsonSyntaxException ex) {
        return HttpResponses.error(500,
                this.getTextEnvelopedInBanner(info.toString() + "   ERROR: github webhook json invalid"));
    }
}