Example usage for java.lang Boolean toString

List of usage examples for java.lang Boolean toString

Introduction

In this page you can find the example usage for java.lang Boolean toString.

Prototype

public String toString() 

Source Link

Document

Returns a String object representing this Boolean's value.

Usage

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRoute.java

@Override
public void run() {
    try {/*from w ww.  j a  va 2s .co m*/
        /*
         * Setup time
         */
        final Boolean isAfter = routeSearch.arrival == 0;
        long travelTime = isAfter ? routeSearch.departure : routeSearch.arrival;

        /*
         * Begin building url
         */
        StringBuffer urlString = new StringBuffer(Trafikanten.getApiUrl()
                + "/ReisRest/Travel/GetTravelsAdvanced/?walkingFactor=" + WALKINGFACTOR);
        if (travelTime > 0) {
            urlString.append("&time=" + dateFormater.format(travelTime));
        }

        boolean firstInList = true;

        /*
         * Setup from stations
         */
        for (StationData station : routeSearch.fromStation) {
            if (firstInList) {
                urlString.append("&fromStops=");
                firstInList = false;
            } else {
                urlString.append(",");
            }
            urlString.append(station.stationId);
        }

        /*
         * Setup to stations
         */
        firstInList = true;
        for (StationData station : routeSearch.toStation) {
            if (firstInList) {
                urlString.append("&toStops=");
                firstInList = false;
            } else {
                urlString.append(",");
            }
            urlString.append(station.stationId);
        }

        /*
         * Setup whether or not we're arriving before or departing after
         */
        urlString.append("&isAfter=" + isAfter.toString());

        /*
         * Disable advanced options  if they are not visible
         */
        if (!routeSearch.advancedOptionsEnabled) {
            routeSearch.resetAdvancedOptions();
        }

        /*
         * Change margin/change punish/proposals
         */
        String changePunish = new Integer(routeSearch.changePunish).toString();
        String changeMargin = new Integer(routeSearch.changeMargin).toString();
        String proposals = new Integer(routeSearch.proposals).toString();
        CharSequence transportTypes = routeSearch
                .renderTransportTypesApi(routeSearch.getAPITransportArray(context));

        urlString.append("&changeMargin=" + changeMargin + "&changePunish=" + changePunish + "&proposals="
                + proposals + "&transporttypes=" + transportTypes);

        Log.i(TAG, "Searching with url " + urlString);

        final InputStream stream = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString.toString()), false).stream;

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting route data");
        jsonParseRouteProposal(stream);
        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");
    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        e.printStackTrace();
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}

From source file:au.com.gaiaresources.bdrs.controller.test.TestDataCreator.java

public void createTaxonGroups(int count, int rand, boolean createAttributes) throws Exception {
    if (rand > 0) {
        count = count + (random.nextBoolean() ? random.nextInt(rand) : -random.nextInt(rand));
    }/*from ww  w .j  a  va  2 s  .  co  m*/
    log.info(String.format("Creating %d Taxon Groups", count));

    // Look for the directory of images, if found we will use that 
    // otherwise we will use a generated set of images.
    byte[] defaultThumbnail = createImage(250, 140, "Test Taxon Group Thumb");
    byte[] defaultImage = createImage(640, 480, "Test Taxon Group Image");
    Map<String, byte[]> defaultImageMap = new HashMap<String, byte[]>();
    defaultImageMap.put("image", defaultImage);
    defaultImageMap.put("thumbNail", defaultThumbnail);

    Preference testDataDirPref = prefDAO.getPreferenceByKey(TEST_DATA_IMAGE_DIR);

    MockMultipartHttpServletRequest request;
    MockHttpServletResponse response;
    for (int i = 0; i < count; i++) {
        request = new MockMultipartHttpServletRequest();
        response = new MockHttpServletResponse();

        request.setMethod("POST");
        request.setRequestURI("/bdrs/admin/taxongroup/edit.htm");

        request.setParameter("name", TEST_GROUPS[random.nextInt(TEST_GROUPS.length)]);
        request.setParameter("behaviourIncluded", String.valueOf(random.nextBoolean()));
        request.setParameter("firstAppearanceIncluded", String.valueOf(random.nextBoolean()));
        request.setParameter("lastAppearanceIncluded", String.valueOf(random.nextBoolean()));
        request.setParameter("habitatIncluded", String.valueOf(random.nextBoolean()));
        request.setParameter("weatherIncluded", String.valueOf(random.nextBoolean()));
        request.setParameter("numberIncluded", String.valueOf(random.nextBoolean()));

        // Image and Thumbnail
        for (String propertyName : new String[] { "image", "thumbNail" }) {
            String key = String.format("%s_file", propertyName);
            String image_filename = String.format("%s_filename.png", propertyName);

            byte[] imageData = getRandomImage(testDataDirPref, 250, 140);
            imageData = imageData == null ? defaultImageMap.get(propertyName) : imageData;

            MockMultipartFile mockImageFile = new MockMultipartFile(key, image_filename, "image/png",
                    imageData);
            ((MockMultipartHttpServletRequest) request).addFile(mockImageFile);

            request.setParameter(propertyName, image_filename);
        }

        // Attributes
        if (createAttributes) {
            int curWeight = 0;
            String attributeOptions = "Option A, Option B, Option C, Option D";
            String rangeIntOptions = "0, 50";

            int index = 0;
            for (Boolean isTag : new Boolean[] { true, false }) {
                for (AttributeType attrType : AttributeType.values()) {

                    request.addParameter("add_attribute", String.valueOf(index));
                    request.setParameter(String.format("add_weight_%d", index), String.valueOf(curWeight));
                    request.setParameter(String.format("add_name_%d", index),
                            String.format("%s name%s", attrType.getName(), isTag ? " Tag" : ""));
                    request.setParameter(String.format("add_description_%d", index),
                            String.format("%s description%s", attrType.getName(), isTag ? " Tag" : ""));
                    request.setParameter(String.format("add_typeCode_%d", index), attrType.getCode());
                    request.setParameter(String.format("add_tag_%d", index), isTag.toString().toLowerCase());
                    //request.setParameter(String.format("add_scope_%d", index), scope.toString());

                    if (AttributeType.STRING_WITH_VALID_VALUES.equals(attrType)) {
                        request.setParameter(String.format("add_option_%d", index), attributeOptions);
                    } else if (AttributeType.INTEGER_WITH_RANGE.equals(attrType)) {
                        request.setParameter(String.format("add_option_%d", index), rangeIntOptions);
                    }

                    index = index + 1;
                    curWeight = curWeight + 100;
                }
            }
        }

        handle(request, response);
    }
}

From source file:gateway.controller.AlertTriggerController.java

/**
 * Proxies an ElasticSearch DSL query to the Pz-Workflow component to return a list of Alert items.
 * /*w ww .  j av a 2s  .  c o  m*/
 * @see TBD
 * 
 * @return The list of Alert items matching the query.
 */
@RequestMapping(value = "/alert/query", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "Query Alerts in Piazza Workflow", notes = "Sends a complex query message to the Piazza Workflow component, that allow users to search for Alerts. Searching is capable of filtering by keywords or other dynamic information.", tags = {
        "Alert", "Workflow", "Search" })
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "The list of Alert results that match the query string.", response = AlertListResponse.class),
        @ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = ErrorResponse.class),
        @ApiResponse(code = 500, message = "Internal Error", response = ErrorResponse.class) })
public ResponseEntity<PiazzaResponse> searchAlerts(
        @ApiParam(value = "The Query string for the Workflow component.", required = true) @Valid @RequestBody SearchRequest query,
        @ApiParam(value = "Paginating large datasets. This will determine the starting page for the query.") @RequestParam(value = "page", required = false) Integer page,
        @ApiParam(value = "The number of results to be returned per query.") @RequestParam(value = "perPage", required = false) Integer perPage,
        @ApiParam(value = "Indicates ascending or descending order.") @RequestParam(value = "order", required = false) String order,
        @ApiParam(value = "The data field to sort by.") @RequestParam(value = "sortBy", required = false) String sortBy,
        @ApiParam(value = "If this flag is set to true, then Workflow objects otherwise referenced by a single Unique ID will be populated in full.") @RequestParam(value = "inflate", required = false) Boolean inflate,
        Principal user) {
    try {
        // Log the request
        logger.log(String.format("User %s sending a complex query for Workflow.",
                gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO);

        // Send the query to the Pz-Workflow component
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<Object>(query, headers);

        String paramPage = (page == null) ? "" : "page=" + page.toString();
        String paramPerPage = (perPage == null) ? "" : "perPage=" + perPage.toString();
        String paramOrder = (order == null) ? "" : "order=" + order;
        String paramSortBy = (sortBy == null) ? "" : "sortBy=" + sortBy;

        AlertListResponse searchResponse = restTemplate.postForObject(
                String.format("%s/%s/%s?%s&%s&%s&%s&inflate=%s", WORKFLOW_URL, "alert", "query", paramPage,
                        paramPerPage, paramOrder, paramSortBy, inflate != null ? inflate.toString() : false),
                entity, AlertListResponse.class);
        // Respond
        return new ResponseEntity<PiazzaResponse>(searchResponse, HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Error Querying Data by user %s: %s", gatewayUtil.getPrincipalName(user),
                exception.getMessage());
        LOGGER.error(error, exception);
        logger.log(error, PiazzaLogger.ERROR);
        return new ResponseEntity<PiazzaResponse>(new ErrorResponse(error, "Gateway"),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:nzilbb.bas.BAS.java

/**
 * Invoke the general MAUS service, for forced alignment given a WAV file and a phonemic transcription.
 * @param LANGUAGE <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language.
 * @param SIGNAL The signal, in WAV format.
 * @param BPF Phonemic transcription of the utterance to be segmented. Format is a <a href="http://www.bas.uni-muenchen.de/forschung/Bas/BasFormatseng.html">BAS Partitur Format (BPF)</a> file with a KAN tier.
 * @param MINPAUSLEN Controls the behaviour of optional inter-word silence. If set to 1, maus will detect all inter-word silence intervals that can be found (minimum length for a silence interval is then 10 msec = 1 frame). If set to values n&gt;1, the minimum length for an inter-word silence interval to be detected is set to n&times;10 msec.
 * @param STARTWORD If set to a value n&gt;0, this option causes maus to start the segmentation with the word number n (word numbering in BPF starts with 0).
 * @param ENDWORD If set to a value n&lt;999999, this option causes maus to end the segmentation with the word number n (word numbering in BPF starts with 0). 
 * @param RULESET MAUS rule set file; UTF-8 encoded; one rule per line; two different file types defined by the extension: '*.nrul' : phonological rule set without statistical information
 * @param OUTFORMAT Defines the output format:
 *  <ul>//www  .  j  ava2s .c  om
 *   <li>"TextGrid" - a praat compatible TextGrid file</li> 
 *   <li>"par" or "mau-append" - the input BPF file with a new (or replaced) tier MAU</li>
 *   <li>"csv" or "mau" - only the BPF MAU tier (CSV table)</li> 
 *   <li>"legacyEMU" - a file with extension *.EMU that contains in the first part the Emu hlb file (*.hlb) and in the second part the Emu phonetic segmentation (*.phonetic)</li>
 *   <li>emuR - an Emu compatible *_annot.json file</li>
 *  </ul>
 * @param MAUSSHIFT If set to n, this option causes the calculated MAUS segment boundaries to be shifted by n msec (default: 10) into the future.
 * @param INSPROB The option INSPROB influences the probability of deletion of segments. It is a constant factor (a constant value added to the log likelihood score) after each segment. Therefore, a higher value of INSPROB will cause the probability of segmentations with more segments go up, thus decreasing the probability of deletions (and increasing the probability of insertions, which are rarely modelled in the rule sets).
 * @param INSKANTEXTGRID Switch to create an additional tier in the TextGrid output file with a word segmentation labelled with the canonic phonemic transcript.
 * @param INSORTTEXTGRID Switch to create an additional tier ORT in the TextGrid output file with a word segmentation labelled with the orthographic transcript (taken from the input ORT tier)
 * @param USETRN  If set to true, the service searches the input BPF for a TRN tier. The synopsis for a TRN entry is: 'TRN: (start-sample) (duration-sample) (word-link-list) (label)', e.g. 'TRN: 23654 56432 0,1,2,3,4,5,6 sentence1' (the speech within the recording 'sentence1' starts with sample 23654, last for 56432 samples and covers the words 0-6). If only one TRN entry is found, the segmentation is restricted within a time range given by this TRN tier entry.
 * @param OUTSYMBOL Defines the encoding of phonetic symbols in output. 
 *  <ul>
 *   <li>"sampa" - (default), phonetic symbols are encoded in language specific SAM-PA (with some coding differences to official SAM-PA</li>
 *   <li>"ipa" - the service produces UTF-8 IPA output.</li> 
 *   <li>"manner" - the service produces IPA manner of articulation for each segment; possible values are: silence, vowel, diphthong, plosive, nasal, fricative, affricate, approximant, lateral-approximant, ejective.</li>
 *   <li>"place" - the service produces IPA place of articulation for each segment; possible values are: silence, labial, dental, alveolar, post-alveolar, palatal, velar, uvular, glottal, front, central, back.</li> </ul>
 * @param NOINITIALFINALSILENCE Switch to suppress the automatic modeling on a leading/trailing silence interval. 
 * @param WEIGHT weights the influence of the statistical pronunciation model against the acoustical scores. More precisely WEIGHT is multiplied to the pronunciation model score (log likelihood) before adding the score to the acoustical score within the search. Since the pronunciation model in most cases favors the canonical pronunciation, increasing WEIGHT will at some point cause MAUS to choose always the canonical pronunciation; lower values of WEIGHT will favor less probable paths be selected according to acoustic evidence
 * @param MODUS Operation modus of MAUS: 
 *  <ul>
 *   <li>"standard" (default) - the segmentation and labelling using the MAUS technique as described in Schiel ICPhS 1999.</li> 
 *   <li>"align" - a forced alignment is performed on the input SAM-PA string defined in the KAN tier of the BPF.</li>
 * </ul>
 * @return The response to the request.
 * @throws IOException If an IO error occurs.
 * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured.
 */
public BASResponse MAUS(String LANGUAGE, InputStream SIGNAL, InputStream BPF, String OUTFORMAT,
        String OUTSYMBOL, Integer MINPAUSLEN, Integer STARTWORD, Integer ENDWORD, InputStream RULESET,
        Integer MAUSSHIFT, Double INSPROB, Boolean INSKANTEXTGRID, Boolean INSORTTEXTGRID, Boolean USETRN,
        Boolean NOINITIALFINALSILENCE, Double WEIGHT, String MODUS)
        throws IOException, ParserConfigurationException {
    if (OUTSYMBOL == null)
        OUTSYMBOL = "sampa";
    // "40 msec seems to be the border of perceivable silence, we set this option default to 5"
    if (MINPAUSLEN == null)
        MINPAUSLEN = 5;
    HttpPost request = new HttpPost(getMAUSUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("LANGUAGE", languageTagger.tag(LANGUAGE))
            .addBinaryBody("SIGNAL", SIGNAL, ContentType.create("audio/wav"), "BAS.wav")
            .addBinaryBody("BPF", BPF, ContentType.create("text/plain-bas"), "BAS.par")
            .addTextBody("OUTFORMAT", OUTFORMAT).addTextBody("OUTSYMBOL", OUTSYMBOL);
    if (USETRN != null)
        builder.addTextBody("USETRN", USETRN.toString());
    if (MINPAUSLEN != null)
        builder.addTextBody("MINPAUSLEN", MINPAUSLEN.toString());
    if (STARTWORD != null)
        builder.addTextBody("STARTWORD", STARTWORD.toString());
    if (ENDWORD != null)
        builder.addTextBody("ENDWORD", ENDWORD.toString());
    if (RULESET != null)
        builder.addBinaryBody("RULESET", RULESET, ContentType.create("text/plain"), "RULESET.txt");
    if (MAUSSHIFT != null)
        builder.addTextBody("MAUSSHIFT", MAUSSHIFT.toString());
    if (INSPROB != null)
        builder.addTextBody("INSPROB", INSPROB.toString());
    if (INSKANTEXTGRID != null)
        builder.addTextBody("INSKANTEXTGRID", INSKANTEXTGRID.toString());
    if (INSORTTEXTGRID != null)
        builder.addTextBody("INSORTTEXTGRID", INSORTTEXTGRID.toString());
    if (NOINITIALFINALSILENCE != null)
        builder.addTextBody("NOINITIALFINALSILENCE", NOINITIALFINALSILENCE.toString());
    if (WEIGHT != null)
        builder.addTextBody("WEIGHT", WEIGHT.toString());
    if (MODUS != null)
        builder.addTextBody("MODUS", MODUS.toString());
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}

From source file:edu.ucsd.crbs.cws.dao.rest.JobRestDAOImpl.java

@Override
public Job update(long jobId, final String status, Long estCpu, Long estRunTime, Long estDisk, Long submitDate,
        Long startDate, Long finishDate, Boolean submittedToScheduler, final String schedulerJobId,
        final Boolean deleted, final String error, final String detailedError) throws Exception {

    ClientConfig cc = new DefaultClientConfig();
    cc.getClasses().add(StringProvider.class);
    Client client = Client.create(cc);//  www .ja va  2s.  com
    client.addFilter(new HTTPBasicAuthFilter(_user.getLogin(), _user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.JOBS_PATH)
            .path(Long.toString(jobId));

    MultivaluedMap queryParams = _multivaluedMapFactory.getMultivaluedMap(_user);

    if (status != null) {
        queryParams.add(Constants.STATUS_QUERY_PARAM, status);
    }
    if (estCpu != null) {
        queryParams.add(Constants.ESTCPU_QUERY_PARAM, estCpu);
    }
    if (estRunTime != null) {
        queryParams.add(Constants.ESTRUNTIME_QUERY_PARAM, estRunTime);
    }
    if (estDisk != null) {
        queryParams.add(Constants.ESTDISK_QUERY_PARAM, estDisk);
    }
    if (submitDate != null) {
        queryParams.add(Constants.SUBMITDATE_QUERY_PARAM, submitDate.toString());
    }
    if (startDate != null) {
        queryParams.add(Constants.STARTDATE_QUERY_PARAM, startDate.toString());
    }
    if (finishDate != null) {
        queryParams.add(Constants.FINISHDATE_QUERY_PARAM, finishDate.toString());
    }
    if (submittedToScheduler != null) {
        queryParams.add(Constants.SUBMITTED_TO_SCHED_QUERY_PARAM, submittedToScheduler.toString());
    }

    if (schedulerJobId != null) {
        queryParams.add(Constants.SCHEDULER_JOB_ID_QUERY_PARAM, schedulerJobId);
    }

    if (deleted != null) {
        queryParams.add(Constants.DELETED_QUERY_PARAM, deleted.toString());
    }

    if (error != null) {
        queryParams.add(Constants.ERROR_QUERY_PARAM, error);
    }

    if (detailedError != null) {
        queryParams.add(Constants.DETAILED_ERROR_QUERY_PARAM, detailedError);
    }

    String json = resource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON)
            .type(MediaType.APPLICATION_JSON_TYPE).entity("{}").post(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<Job>() {
    });
}

From source file:com.ephesoft.dcma.webservice.service.EphesoftWebService.java

/**
 * To verify valid Ephesoft license is installed or not.
 * @param request {@link HttpServletRequest}
 * @param response {@link HttpServletResponse}
 *///  ww  w  .java  2  s.  co  m
@RequestMapping(value = "/verifyEphesoftLicense", method = RequestMethod.POST)
@ResponseBody
public void verifyEphesoftLicense(final HttpServletRequest request, final HttpServletResponse response) {
    LOGGER.info("Start processing verify Ephesoft License web service");
    Boolean isLicenseInstalled = Boolean.FALSE;
    try {
        recostarService.generateHOCRFiles(null, null);
        isLicenseInstalled = true;
        LOGGER.info("Ephesoft license is installed on this machine.");
    } catch (DCMAException ex) {
        LOGGER.error("An exception is occured. Unable to verify license. ", ex);
    } catch (Exception ex) {
        LOGGER.error("An exception is occured. Unable to verify license. ", ex);
    }
    LOGGER.info(
            "Successfully executed verify Ephesoft License web service. Ephesoft License installed value is "
                    + isLicenseInstalled);
    try {
        response.getWriter().write(isLicenseInstalled.toString());
    } catch (final IOException ioe) {
        LOGGER.error("Exception in sending message to client. Logged the exception for debugging.", ioe);
    } catch (final Exception e) {
        LOGGER.error("Exception in sending message to client. Logged the exception for debugging.", e);
    }
}

From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.DataSourceWSDAOImpl.java

public ResourceList takeDataSourceAction(String actionName, String dataSourcePath, IntrospectionPlan plan,
        boolean runInBackgroundTransaction, String reportDetail, AttributeList dataSourceAttributes,
        String serverId, String pathToServersXML) throws CompositeException {

    // For debugging
    if (logger.isDebugEnabled()) {
        int planSize = 0;
        if (plan != null && plan.getEntries() != null && plan.getEntries().getEntry() != null)
            planSize = plan.getEntries().getEntry().size();
        int attrSize = 0;
        if (dataSourceAttributes != null && dataSourceAttributes.getAttribute() != null)
            attrSize = dataSourceAttributes.getAttribute().size();
        logger.debug(//  www  .j a va  2 s  .c om
                "DataSourceWSDAOImpl.takeDataSourceAction(actionName , dataSourcePath, plan, runInBackgroundTransaction, reportDetail, dataSourceAttributes, serverId, pathToServersXML).  actionName="
                        + actionName + "  dataSourcePath=" + dataSourcePath + "  #plans=" + planSize
                        + "  runInBackgroundTransaction=" + runInBackgroundTransaction + "  reportDetail="
                        + reportDetail + "  #dataSourceAttributes=" + attrSize + "  serverId=" + serverId
                        + "  pathToServersXML=" + pathToServersXML);
    }

    // Declare variables
    ResourceList returnResList = null;
    String command = null;

    // read target server properties from xml and build target server object based on target server name 
    CompositeServer targetServer = WsApiHelperObjects.getServerLogger(serverId, pathToServersXML,
            "DataSourceWSAOImpl.takeDataSourceAction(" + actionName + ")", logger);
    // Ping the Server to make sure it is alive and the values are correct.
    WsApiHelperObjects.pingServer(targetServer, true);

    // Construct the resource port based on target server name
    ResourcePortType port = CisApiFactory.getResourcePort(targetServer);

    try {
        // Make sure the resource exists before executing any actions
        if (DeployManagerUtil.getDeployManager().resourceExists(serverId, dataSourcePath,
                ResourceType.DATA_SOURCE.name(), pathToServersXML)) {
            /*********************************
             *  UPDATE datasource
             *********************************/
            if (actionName.equalsIgnoreCase(DataSourceDAO.action.UPDATE.name())) {
                command = "updateDataSource";

                if (logger.isDebugEnabled()) {
                    int dsAttrSize = 0;
                    String dsAttrString = "";
                    if (dataSourceAttributes != null && dataSourceAttributes.getAttribute() != null) {
                        for (Attribute attr : dataSourceAttributes.getAttribute()) {
                            if (dsAttrString.length() != 0)
                                dsAttrString = dsAttrString + ", ";
                            if (attr.getType().toString().equals("PASSWORD_STRING"))
                                dsAttrString = dsAttrString + attr.getName() + "=********";
                            else
                                dsAttrString = dsAttrString + attr.getName() + "=" + attr.getValue();
                        }
                        dsAttrSize = dataSourceAttributes.getAttribute().size();
                    }
                    logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                            + "\").  Invoking port.updateDataSource(\"" + dataSourcePath
                            + "\", \"FULL\", null, DS_ATTRIBUTES:[\"" + dsAttrString
                            + "]\").  #dataSourceAttributes=" + dsAttrSize);
                }

                // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
                if (CommonUtils.isExecOperation()) {
                    returnResList = port.updateDataSource(dataSourcePath, DetailLevel.FULL, null,
                            dataSourceAttributes);

                    if (logger.isDebugEnabled()) {
                        logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                                + "\").  Success: port.updateDataSource().");
                    }
                } else {
                    logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                            + "] WAS NOT PERFORMED.\n");
                }
            }
            /*********************************
             *  ENABLE datasource
             *********************************/
            else if (actionName.equalsIgnoreCase(DataSourceDAO.action.ENABLE.name())) {
                command = "updateResourceEnabled";

                if (logger.isDebugEnabled()) {
                    logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                            + "\").  Invoking port.updateResourceEnabled(\"" + dataSourcePath
                            + "\", \"DATA_SOURCE\", \"FULL\", true).");
                }

                // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
                if (CommonUtils.isExecOperation()) {
                    returnResList = port.updateResourceEnabled(dataSourcePath, ResourceType.DATA_SOURCE,
                            DetailLevel.FULL, true);

                    if (logger.isDebugEnabled()) {
                        logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                                + "\").  Success: port.updateResourceEnabled().");
                    }
                } else {
                    logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                            + "] WAS NOT PERFORMED.\n");
                }
            }
            /*********************************
             *  REINTROSPECT datasource
             *********************************/
            else if (actionName.equalsIgnoreCase(DataSourceDAO.action.REINTROSPECT.name())) {
                command = "reintrospectDataSource";

                if (logger.isDebugEnabled()) {
                    logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                            + "\").  Invoking port.reintrospectDataSource(\"" + dataSourcePath
                            + "\", true, null, null, null, null).");
                }

                // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
                if (CommonUtils.isExecOperation()) {
                    // Errors were being thrown when attributes were present for dataSourceAttributes.  Setting to null.
                    //port.reintrospectDataSource(dataSourcePath, true, dataSourceAttributes, null, null, null);   
                    port.reintrospectDataSource(dataSourcePath, true, null, null, null, null);

                    if (logger.isDebugEnabled()) {
                        logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                                + "\").  Success: port.reintrospectDataSource().");
                    }
                } else {
                    logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                            + "] WAS NOT PERFORMED.\n");
                }
            }
            /*********************************
             *  INTROSPECT datasource
             *********************************/
            else if (actionName.equalsIgnoreCase(DataSourceDAO.action.INTROSPECT.name())) {
                command = "introspectResourcesTask";

                Holder<String> taskId = new Holder<String>();
                Holder<BigInteger> totalResults = new Holder<BigInteger>();
                Holder<Boolean> completed = new Holder<Boolean>();

                if (logger.isDebugEnabled()) {
                    int dsAttrSize = 0;
                    String dsAttrString = "";
                    if (dataSourceAttributes != null && dataSourceAttributes.getAttribute() != null) {
                        for (Attribute attr : dataSourceAttributes.getAttribute()) {
                            if (dsAttrString.length() != 0)
                                dsAttrString = dsAttrString + ", ";
                            if (attr.getType().toString().equals("PASSWORD_STRING"))
                                dsAttrString = dsAttrString + attr.getName() + "=********";
                            else
                                dsAttrString = dsAttrString + attr.getName() + "=" + attr.getValue();
                        }
                        dsAttrSize = dataSourceAttributes.getAttribute().size();
                    }
                    String planString = "";
                    if (plan != null && plan.getEntries() != null && plan.getEntries().getEntry() != null) {
                        for (IntrospectionPlanEntry entry : plan.getEntries().getEntry()) {
                            if (planString.length() != 0)
                                planString = "], " + planString;
                            planString = planString + "PLAN:[";
                            planString = planString + "action=" + entry.getAction();
                            planString = planString + "path=" + entry.getResourceId().getPath();
                            planString = planString + "type=" + entry.getResourceId().getType();
                            String attrList = "";
                            if (entry.getAttributes() != null && entry.getAttributes().getAttribute() != null) {
                                for (Attribute attr : entry.getAttributes().getAttribute()) {
                                    if (attrList.length() != 0)
                                        attrList = attrList + ", ";
                                    if (attr.getType().toString().equalsIgnoreCase("PASSWORD_STRING"))
                                        attrList = attrList + attr.getName() + "=********";
                                    else
                                        attrList = attrList + attr.getName() + "=" + attr.getValue();
                                }
                            }
                            planString = planString + attrList + "]";
                        }
                    }
                    logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                            + "\").  Invoking port.introspectResourcesTask(\"" + dataSourcePath + "\", \""
                            + planString + "\", \"" + runInBackgroundTransaction + "\", DS_ATTRIBUTES:[\""
                            + dsAttrString + "]\", taskId, totalResults, completed).   #dataSourceAttributes="
                            + dsAttrSize);
                }

                // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
                if (CommonUtils.isExecOperation()) {
                    // Invoke the method to introspect and add, update or remove data source resources
                    port.introspectResourcesTask(dataSourcePath, plan, runInBackgroundTransaction,
                            dataSourceAttributes, taskId, totalResults, completed);

                    if (logger.isDebugEnabled()) {
                        logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                                + "\").  Success: port.introspectResourcesTask().");
                    }

                    Boolean block = true; // Make this a blocking call
                    Page page = new Page();

                    Holder<IntrospectionStatus> status = new Holder<IntrospectionStatus>();

                    if (logger.isDebugEnabled()) {
                        String simpleStatus = "";
                        if (status != null && status.value != null && status.value.getStatus() != null)
                            simpleStatus = status.value.getStatus().value();
                        logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                                + "\").  Invoking port.introspectResourcesResult(\"" + taskId.value.toString()
                                + "\", \"" + block.toString() + "\", page, \"FULL\", \""
                                + totalResults.value.toString() + "\", \"" + completed.value.toString()
                                + "\", \"" + simpleStatus + "\").");
                    }

                    // Since a blocking call is used, a single call to get results is all that is needed
                    port.introspectResourcesResult(taskId, block, page, DetailLevel.FULL, totalResults,
                            completed, status);

                    if (logger.isDebugEnabled()) {
                        logger.debug("DataSourceWSDAOImpl.takeDataSourceAction(\"" + actionName
                                + "\").  Success: port.introspectResourcesResult().");
                    }

                    boolean errorDetected = false;
                    String errorEntryPaths = "";

                    // Check the status and print out the report
                    if (status != null && status.value != null && status.value.getStatus() != null) {
                        String simpleStatus = status.value.getStatus().value();
                        // Print out a status report
                        logger.info("Introspection Report (" + reportDetail + "):");
                        logger.info("          Status=" + simpleStatus);
                        logger.info("      Start Time=" + status.value.getStartTime().toString());
                        logger.info("        End Time=" + status.value.getEndTime().toString());
                        logger.info("           Added=" + status.value.getAddedCount());
                        logger.info("         Removed=" + status.value.getRemovedCount());
                        logger.info("         Updated=" + status.value.getUpdatedCount());
                        logger.info("         Skipped=" + status.value.getSkippedCount());
                        logger.info("       Completed=" + status.value.getTotalCompletedCount());
                        logger.info("         Warning=" + status.value.getWarningCount());
                        logger.info("          Errors=" + status.value.getErrorCount());
                        logger.info("");
                        if (status.value.getReport() != null) {
                            List<IntrospectionChangeEntry> reportEntries = status.value.getReport().getEntry();
                            // Iterate over the report entries
                            for (IntrospectionChangeEntry reportEntry : reportEntries) {
                                // Print out the Resource and Status on 2 separate lines with a blank line separator following
                                if (reportDetail.equals("SIMPLE") || reportDetail.equals("FULL")) {
                                    logger.info("   RESOURCE:  Path=" + reportEntry.getPath() + "   Type="
                                            + reportEntry.getType().value() + "   Subtype="
                                            + reportEntry.getSubtype().value());
                                    logger.info("     STATUS:  Status=" + reportEntry.getStatus().value()
                                            + "   Action=" + reportEntry.getAction().value() + "   Duration="
                                            + reportEntry.getDurationMs());
                                }
                                // Print out the Resource and Status as a single line with no blank lines following
                                if (reportDetail.equals("SIMPLE_COMPRESSED")) {
                                    logger.info("   RESOURCE:  Path=" + reportEntry.getPath() + "   Type="
                                            + reportEntry.getType().value() + "   Subtype="
                                            + reportEntry.getSubtype().value() + "   [STATUS]:  Status="
                                            + reportEntry.getStatus().value() + "   Action="
                                            + reportEntry.getAction().value() + "   Duration="
                                            + reportEntry.getDurationMs());
                                }
                                boolean entryErrorDetected = false;
                                if (reportEntry.getStatus().value().equalsIgnoreCase("ERROR")) {
                                    errorDetected = true;
                                    entryErrorDetected = true;
                                    if (errorEntryPaths.length() > 0)
                                        errorEntryPaths = errorEntryPaths + ", ";
                                    errorEntryPaths = errorEntryPaths + reportEntry.getPath();
                                }
                                if (entryErrorDetected || reportDetail.equals("FULL")) {
                                    if (reportEntry.getMessages() != null) {
                                        List<MessageEntry> messages = reportEntry.getMessages().getEntry();
                                        for (MessageEntry message : messages) {
                                            String severity = "";
                                            String code = "";
                                            String name = "";
                                            String msg = "";

                                            if (message.getSeverity() != null
                                                    && message.getSeverity().value().length() > 0)
                                                severity = "  Severity=" + message.getSeverity().value();
                                            if (message.getCode() != null && message.getCode().length() > 0)
                                                code = "   Code=" + message.getCode();
                                            if (message.getName() != null && message.getName().length() > 0)
                                                name = "   Name=" + message.getName();
                                            if (message.getMessage() != null
                                                    && message.getMessage().length() > 0)
                                                msg = "   Message=" + message.getMessage();
                                            logger.info("   MESSAGES:" + severity + code + name + msg);
                                            if (message.getDetail() != null)
                                                logger.info("   MESSAGES:  Detail=" + message.getDetail());
                                        }
                                    }
                                }
                                if (reportDetail.equals("SIMPLE") || reportDetail.equals("FULL")) {
                                    logger.info("");
                                }
                            }
                        }
                        if (errorDetected) {
                            throw new ApplicationException("Resource action="
                                    + DataSourceDAO.action.INTROSPECT.name()
                                    + " was not successful.  Review the introspection report in the log for more details.  Introspection Entry Paths with errors="
                                    + errorEntryPaths);
                        }
                    } else {
                        // Since the status was null, then assume the server is 6.1 which contains a bug where the status has the wrong namespace.
                        // Based on the input of ADD_OR_UPDATE, ADD_OR_UPDATE_RECURSIVELY, or REMOVE, query the resources to determine if the operation was successful.

                        // Print out a status report
                        logger.info("Introspection Report (" + reportDetail + "):");
                        logger.info("      Start Time=" + status.value.getStartTime().toString());
                        logger.info("        End Time=" + status.value.getEndTime().toString());
                        logger.info("           Added=" + status.value.getAddedCount());
                        logger.info("         Removed=" + status.value.getRemovedCount());
                        logger.info("         Updated=" + status.value.getUpdatedCount());
                        logger.info("         Skipped=" + status.value.getSkippedCount());
                        logger.info("       Completed=" + status.value.getTotalCompletedCount());
                        logger.info("         Warning=" + status.value.getWarningCount());
                        logger.info("          Errors=" + status.value.getErrorCount());
                        logger.info("");

                        List<IntrospectionPlanEntry> planEntries = plan.getEntries().getEntry();
                        for (IntrospectionPlanEntry planEntry : planEntries) {
                            String planAction = planEntry.getAction().value().toString();
                            String resourcePath = dataSourcePath;
                            if (planEntry.getResourceId().getPath() != null
                                    && planEntry.getResourceId().getPath().length() > 0)
                                resourcePath = resourcePath + "/" + planEntry.getResourceId().getPath();
                            String resourceType = null;
                            if (planEntry.getResourceId().getType() != null)
                                resourceType = planEntry.getResourceId().getType().toString();
                            String subtype = null;
                            if (planEntry.getResourceId().getSubtype() != null)
                                subtype = planEntry.getResourceId().getSubtype().toString();
                            String planStatus = "";

                            // Print out the Resource and Status on 2 separate lines with a blank line separator following (this is the first line.)
                            if (reportDetail.equals("SIMPLE") || reportDetail.equals("FULL")) {
                                logger.info("   RESOURCE:  Path=" + resourcePath + "   Type=" + resourceType
                                        + "   Subtype=" + subtype);
                            }

                            //Determine if this plan entry exists
                            if (planAction.equalsIgnoreCase("ADD_OR_UPDATE")) {
                                boolean exists = getResourceDAO().resourceExists(serverId, resourcePath,
                                        resourceType, pathToServersXML);
                                if (!exists) {
                                    throw new ApplicationException(
                                            "Resource action=" + DataSourceDAO.action.INTROSPECT.name()
                                                    + " was not successful.  The resource [" + resourcePath
                                                    + "] does not exist for the requested plan entry action ["
                                                    + planEntry.getAction().value().toString() + "].");
                                }
                                planStatus = "SUCCESS";
                            }
                            //Just get the list of resources for the log. [there is no way to tell whether this was successful or not.]
                            else if (planAction.equalsIgnoreCase("ADD_OR_UPDATE_RECURSIVELY")) {
                                ResourceList resourceList = getResourceDAO().getResourcesFromPath(serverId,
                                        resourcePath, resourceType, null, "SIMPLE", pathToServersXML);
                                if (resourceList != null && resourceList.getResource().size() > 0) {
                                    for (Resource resource : resourceList.getResource()) {
                                        if (resource != null && reportDetail.equals("FULL")) {
                                            logger.info("      CHILD RESOURCE:  Path=" + resource.getPath()
                                                    + "   Type=" + resource.getType() + "   Subtype="
                                                    + resource.getSubtype());
                                        }
                                    }
                                }
                                planStatus = "SUCCESS";
                            }
                            //Determine if this plan has been removed
                            else if (planAction.equalsIgnoreCase("REMOVE")) {
                                boolean exists = getResourceDAO().resourceExists(serverId, resourcePath,
                                        resourceType, pathToServersXML);
                                if (exists) {
                                    throw new ApplicationException(
                                            "Resource action=" + DataSourceDAO.action.INTROSPECT.name()
                                                    + " was not successful.  The resource [" + resourcePath
                                                    + "] was not removed for the requested plan entry action ["
                                                    + planEntry.getAction().value().toString() + "].");
                                }
                                planStatus = "SUCCESS";
                            } else {
                                throw new ApplicationException("Resource action="
                                        + DataSourceDAO.action.INTROSPECT.name()
                                        + " was not successful.  The status field is null and the plan entry action ["
                                        + planEntry.getAction().value().toString() + "] is unknown.");
                            }

                            // Print out the Resource and Status on 2 separate lines with a blank line separator following (this is the second line).
                            if (reportDetail.equals("SIMPLE") || reportDetail.equals("FULL")) {
                                logger.info("     STATUS:  Status=" + planStatus + "   Action=" + planAction);
                            }
                            // Print out the Resource and Status as a single line with no blank lines following
                            if (reportDetail.equals("SIMPLE_COMPRESSED")) {
                                logger.info("   RESOURCE:  Path=" + resourcePath + "   Type=" + resourceType
                                        + "   Subtype=" + subtype + "   [STATUS]:  Status=" + planStatus
                                        + "   Action=" + planAction);
                            }
                            // Print out a blank line when report detail is SIMPLE or FULL
                            if (reportDetail.equals("SIMPLE") || reportDetail.equals("FULL")) {
                                logger.info("");
                            }
                        }
                    }
                } else {
                    logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                            + "] WAS NOT PERFORMED.\n");
                }
            }
            if (logger.isDebugEnabled() && returnResList != null) {
                logger.debug("DataSourceWSDAOImpl.takeDataSourceAction::returnResList.getResource().size()="
                        + returnResList.getResource().size());
            }
        } else {
            throw new ApplicationException("The resource " + dataSourcePath + " does not exist.");
        }

    } catch (UpdateDataSourceSoapFault e) {
        CompositeLogger.logException(e,
                DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                        DataSourceDAO.action.UPDATE.name(), "DataSource", dataSourcePath, targetServer),
                e.getFaultInfo());
        throw new ApplicationException(e.getMessage(), e);

    } catch (UpdateResourceEnabledSoapFault e) {
        CompositeLogger.logException(e,
                DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                        DataSourceDAO.action.ENABLE.name(), "DataSource", dataSourcePath, targetServer),
                e.getFaultInfo());
        throw new ApplicationException(e.getMessage(), e);

    } catch (ReintrospectDataSourceSoapFault e) {
        CompositeLogger.logException(e,
                DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                        DataSourceDAO.action.REINTROSPECT.name(), "DataSource", dataSourcePath, targetServer),
                e.getFaultInfo());
        throw new ApplicationException(e.getMessage(), e);
    } catch (IntrospectResourcesTaskSoapFault e) {
        CompositeLogger.logException(e,
                DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                        DataSourceDAO.action.INTROSPECT.name(), "DataSource", pathToServersXML, targetServer),
                e.getFaultInfo());
        throw new ApplicationException(e.getMessage(), e);
    } catch (IntrospectResourcesResultSoapFault e) {
        CompositeLogger.logException(e,
                DeployUtil.constructMessage(DeployUtil.MessageType.ERROR.name(),
                        DataSourceDAO.action.INTROSPECT.name(), "DataSource", pathToServersXML, targetServer),
                e.getFaultInfo());
        throw new ApplicationException(e.getMessage(), e);
    } catch (Exception e) {
        throw new ApplicationException(e.getMessage(), e);

    }
    return returnResList;
}

From source file:com.vmware.bdd.cli.commands.ClusterCommands.java

private void initInfraConfigs(Map<String, Map<String, String>> infraConfigs, Boolean disableLocalUsersFlag) {
    Map<String, String> userMgmtConfigs = new HashMap<>();
    //disable local account by default.
    userMgmtConfigs.put(UserMgmtConstants.DISABLE_LOCAL_USER_FLAG,
            disableLocalUsersFlag == null ? Boolean.TRUE.toString() : disableLocalUsersFlag.toString());
    infraConfigs.put(UserMgmtConstants.LDAP_USER_MANAGEMENT, userMgmtConfigs);
}

From source file:org.ops4j.pax.web.service.jetty.internal.JettyServerWrapper.java

private void configureJspConfigDescriptor(HttpServiceContext context, ContextModel model) {

    Boolean elIgnored = model.getJspElIgnored();
    Boolean isXml = model.getJspIsXml();
    Boolean scriptingInvalid = model.getJspScriptingInvalid();

    JspPropertyGroup jspPropertyGroup = null;

    if (elIgnored != null || isXml != null || scriptingInvalid != null || model.getJspIncludeCodes() != null
            || model.getJspUrlPatterns() != null || model.getJspIncludePreludes() != null) {
        jspPropertyGroup = new JspPropertyGroup();

        if (model.getJspIncludeCodes() != null) {
            for (String includeCoda : model.getJspIncludeCodes()) {
                jspPropertyGroup.addIncludeCoda(includeCoda);
            }/*  w w w  .  jav  a 2  s .  c  o  m*/
        }

        if (model.getJspUrlPatterns() != null) {
            for (String urlPattern : model.getJspUrlPatterns()) {
                jspPropertyGroup.addUrlPattern(urlPattern);
            }
        }

        if (model.getJspIncludePreludes() != null) {
            for (String prelude : model.getJspIncludePreludes()) {
                jspPropertyGroup.addIncludePrelude(prelude);
            }
        }

        if (elIgnored != null)
            jspPropertyGroup.setElIgnored(elIgnored.toString());
        if (isXml != null)
            jspPropertyGroup.setIsXml(isXml.toString());
        if (scriptingInvalid != null)
            jspPropertyGroup.setScriptingInvalid(scriptingInvalid.toString());

    }

    TagLib tagLibDescriptor = null;

    if (model.getTagLibLocation() != null || model.getTagLibUri() != null) {
        tagLibDescriptor = new TagLib();
        tagLibDescriptor.setTaglibLocation(model.getTagLibLocation());
        tagLibDescriptor.setTaglibURI(model.getTagLibUri());
    }

    if (jspPropertyGroup != null || tagLibDescriptor != null) {
        JspConfig jspConfig = new JspConfig();
        jspConfig.addJspPropertyGroup(jspPropertyGroup);
        jspConfig.addTaglibDescriptor(tagLibDescriptor);
        context.getServletContext().setJspConfigDescriptor(jspConfig);
    }
}

From source file:com.zimbra.qa.unittest.TestCalDav.java

private void setZimbraPrefAppleIcalDelegationEnabled(ZMailbox mbox, Boolean val) throws ServiceException {
    ModifyPrefsRequest modPrefsReq = new ModifyPrefsRequest();
    Pref pref = Pref.createPrefWithNameAndValue(ZAttrProvisioning.A_zimbraPrefAppleIcalDelegationEnabled,
            val.toString().toUpperCase());
    modPrefsReq.addPref(pref);/*  www.j  av a2 s  .c  om*/
    ModifyPrefsResponse modPrefsResp = mbox.invokeJaxb(modPrefsReq);
    assertNotNull("null ModifyPrefs Response for forwarding calendar invites/no auto-add", modPrefsResp);
}