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 static String toString(boolean b) 

Source Link

Document

Returns a String object representing the specified boolean.

Usage

From source file:agk.chatbot.web.BotServer.java

/**
 * Handles GET and POST requests from users and sends back a JSON object
 * containing a status and result./*  www . j  a  v  a 2  s.  c  o m*/
 */
@Override
public void handle(HttpExchange t) throws IOException {
    int status = 200;
    String result = "";
    OutputStream os = t.getResponseBody();
    JSONObject json = new JSONObject();
    Headers responseHeaders = t.getResponseHeaders();
    Headers requestHeaders = t.getRequestHeaders();
    responseHeaders.add("Content-Type", "application/json");

    if (t.getRequestMethod().equals("GET")) {
        System.out.println("GET request recieved");
        result = Boolean.toString(initialised);
        status = 200;
    } else if (t.getRequestMethod().equals("POST")) {
        System.out.println("POST request recieved");
        if (initialised) {
            StringWriter strWriter = new StringWriter();
            org.apache.commons.io.IOUtils.copy(t.getRequestBody(), strWriter, Charset.forName("UTF-8"));
            Map<String, String> map = queryToMap(strWriter.toString());
            String chat = map.get("c");

            if (requestHeaders.getFirst("Content-Type").startsWith("application/x-www-form-urlencoded")) {
                if (chat.length() == 0 || chat.length() > 140) {
                    status = 400;
                    result = "Bad request. Invalid chat message.";
                } else {
                    try {
                        CBRQuery query = bot.strToQuery(chat);
                        bot.cycle(query);
                        ChatResponse resp = bot.getLastResponse();
                        status = 200;
                        result = resp.getText().toString();
                    } catch (ExecutionException e) {
                        status = 500;
                        result = "An error occurred.";
                        e.printStackTrace();
                    }
                }
            } else {
                result = "Bad request. Requires Content-Type: application/x-www-form-urlencoded";
                status = 400;
            }
        } else {
            status = 503;
            result = "Bot is still initialising.";
        }
    } else {
        status = 501;
        result = "Method not implemented.";
    }

    try {
        json.put("status", status);
        json.put("result", result);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String response = json.toString();
    t.sendResponseHeaders(status, response.length());
    os.write(response.getBytes());
    os.close();
}

From source file:net.sourceforge.fenixedu.dataTransferObject.inquiries.CoordinatorInquiryBean.java

public String validateInquiry() {
    String validationResult = null;
    for (InquiryBlockDTO inquiryBlockDTO : getCoordinatorInquiryBlocks()) {
        validationResult = inquiryBlockDTO.validateMandatoryConditions(getCoordinatorInquiryBlocks());
        if (!Boolean.valueOf(validationResult)) {
            return validationResult;
        }//from  w  w w.  j a  va 2 s  .  co  m
    }
    return Boolean.toString(true);
}

From source file:org.ng200.openolympus.controller.api.VerdictJSONController.java

@RequestMapping("/api/verdict")
public @ResponseBody Map<String, Object> showVerdict(@RequestParam(value = "id") final Verdict verdict,
        final Locale locale) {
    if (this.contestService.getRunningContest() != null && !verdict.isViewableWhenContestRunning()) {
        throw new ForbiddenException("security.contest.cantAccessDuringContest");
    }/*from   w  w w . j  ava  2 s . c  om*/
    Assertions.resourceExists(verdict);
    final HashMap<String, Object> response = new HashMap<>();
    response.put("id", Long.toString(verdict.getId()));
    response.put("score", verdict.getScore().toString());
    response.put("maximumScore", verdict.getMaximumScore().toString());
    response.put("cpuTime", verdict.getCpuTime() >= 0 ? Long.toString(verdict.getCpuTime()) : "-");
    response.put("realTime", verdict.getRealTime() >= 0 ? Long.toString(verdict.getRealTime()) : "-");
    response.put("memoryPeak",
            verdict.getMemoryPeak() >= 0 ? NumberFormat.getInstance(locale).format(verdict.getMemoryPeak())
                    : "-");
    response.put("message",
            this.messageSource.getMessage(verdict.getMessage(),
                    new Object[] { verdict.getAdditionalInformation(), verdict.getUnauthorisedSyscall() },
                    "TRANSLATION ERROR", locale));
    response.put("tested", Boolean.toString(verdict.isTested()));
    response.put("success", Boolean.toString(verdict.getScore().signum() > 0));
    return response;
}

From source file:com.bluexml.side.util.libs.eclipse.pages.PageControlsHelper.java

public Button createBooleanFieldControl(Composite composite, final String label, final String id,
        boolean initialValue, final Map<String, Object> values) {
    values.put(id, Boolean.toString(initialValue));

    final Button button = new Button(composite, SWT.CHECK);
    button.setSelection(initialValue);// ww w .ja v  a 2s  .  c  o m
    button.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(final SelectionEvent e) {
            values.put(id, Boolean.toString(button.getSelection()));
            page.checkPageComplite();
        }
    });

    GridData newLayoutData = StylingUtil.getNewLayoutData();
    newLayoutData.horizontalSpan = 3;
    Label artifactIdLabel = new Label(composite, SWT.NONE);
    artifactIdLabel.setText(label);
    artifactIdLabel.setLayoutData(newLayoutData);
    return button;
}

From source file:fr.paris.lutece.plugins.workflow.modules.rest.service.formatters.ActionFormatterJson.java

/**
 * {@inheritDoc }/*from   w  ww .  j  a v a2 s  . c o m*/
 */
@Override
public String format(Action action) {
    JSONObject jsonObject = new JSONObject();

    jsonObject.element(WorkflowRestConstants.TAG_ID_ACTION, action.getId());
    jsonObject.element(WorkflowRestConstants.TAG_NAME, action.getName());
    jsonObject.element(WorkflowRestConstants.TAG_DESCRIPTION, action.getDescription());
    jsonObject.element(WorkflowRestConstants.TAG_ID_WORKFLOW, action.getWorkflow().getId());
    jsonObject.element(WorkflowRestConstants.TAG_ID_STATE_BEFORE, action.getStateBefore().getId());
    jsonObject.element(WorkflowRestConstants.TAG_ID_STATE_AFTER, action.getStateAfter().getId());
    jsonObject.element(WorkflowRestConstants.TAG_IS_AUTOMATIC_STATE,
            Boolean.toString(action.isAutomaticState()));
    jsonObject.element(WorkflowRestConstants.TAG_IS_MASS_ACTION, Boolean.toString(action.isMassAction()));

    return jsonObject.toString();
}

From source file:gobblin.writer.jdbc.JdbcWriterInitializerTest.java

public void skipStagingTable() throws SQLException {
    this.state.setProp(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "partial");
    this.state.setProp(ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL, Boolean.toString(false));

    this.initializer.initialize();
    this.initializer.close();
    Assert.assertEquals(DEST_TABLE, this.workUnit.getProp(ConfigurationKeys.WRITER_STAGING_TABLE));
    verify(this.commands, never()).createTableStructure(anyString(), anyString(), anyString());
    verify(this.commands, never()).truncate(anyString(), anyString());
    verify(this.commands, never()).drop(anyString(), anyString());
}

From source file:com.norconex.collector.http.sitemap.impl.StandardSitemapResolverFactory.java

@Override
public void saveToXML(Writer out) throws IOException {
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    try {//from  ww w .  j  av  a2 s  .c om
        XMLStreamWriter writer = factory.createXMLStreamWriter(out);
        writer.writeStartElement("sitemapResolverFactory");
        writer.writeAttribute("class", getClass().getCanonicalName());
        writer.writeAttribute("lenient", Boolean.toString(lenient));
        if (sitemapLocations != null) {
            for (String location : sitemapLocations) {
                writer.writeStartElement("location");
                writer.writeCharacters(location);
                writer.writeEndElement();
            }
        }
        writer.writeEndElement();
        writer.flush();
        writer.close();
    } catch (XMLStreamException e) {
        throw new IOException("Cannot save as XML.", e);
    }
}

From source file:org.lanark.jsr303js.ValidationJavaScriptGenerator.java

/**
 * Translates the provided set of JSR303 constraints into JavaScript
 * code capable of validating an HTML form and outputs the translated
 * code into the provided writer.//from   ww w .  ja v a  2 s .c o  m
 *
 * @param writer              the writer to output the JavaScript code into
 * @param name                the name of the command that is being validated
 * @param installSelfWithForm should the generated JavaScript attempt to install
 *                            its self with the form on creation
 * @param configJson          a JSON object with other configuration such as date formats
 * @param rules               the collection of <code>ValidationMetaData</code> to translate
 * @param messageSource       the message source accessor that will be used to resolve validation
 *                            messages
 * @throws java.io.IOException if there is an io exception
 */
public void generateJavaScript(Writer writer, String name, boolean installSelfWithForm, String configJson,
        List<ValidationMetaData> rules, MessageSourceAccessor messageSource) throws IOException {
    try {
        setWriter(writer);
        append("new JSR303JSValidator(");
        appendJsString(name);
        append(',');
        append(Boolean.toString(installSelfWithForm));
        append(',');
        if (configJson != null && !configJson.trim().isEmpty()) {
            append(configJson);
        } else {
            append("{}");
        }
        append(',');
        appendArrayValidators(rules, messageSource);
        append(')');
    } finally {
        clearWriter();
    }
}

From source file:com.koda.integ.hbase.test.BlockCachePersistenceTest.java

@Override
public void setUp() throws Exception {
    //    ConsoleAppender console = new ConsoleAppender(); // create appender
    //    // configure the appender
    //    String PATTERN = "%d [%p|%c|%C{1}] %m%n";
    //    console.setLayout(new PatternLayout(PATTERN));
    //    console.setThreshold(Level.ERROR);
    ///*www . j av  a 2  s. c o  m*/
    //    console.activateOptions();
    //    // add appender to any Logger (here is root)
    //    Logger.getRootLogger().removeAllAppenders();
    //    Logger.getRootLogger().addAppender(console);
    Configuration conf = UTIL.getConfiguration();

    conf.set("hbase.zookeeper.useMulti", "false");

    // Cache configuration
    conf.set(OffHeapBlockCache.BLOCK_CACHE_MEMORY_SIZE, "1000000000");
    //conf.set(CacheConfiguration.EVICTION_POLICY, "LRU");

    conf.set(OffHeapBlockCache.BLOCK_CACHE_COMPRESSION, "LZ4");

    // set persistent cache
    conf.set(OffHeapBlockCache.BLOCK_CACHE_PERSISTENT, Boolean.toString(true));
    conf.set(OffHeapBlockCache.BLOCK_CACHE_DATA_ROOTS, "/tmp/ramdisk/data");
    File file = new File("/tmp/ramdisk/data/block-cache.dat");
    if (file.exists()) {
        loadOnStartup = true;
    }

    // Enable snapshot
    UTIL.startMiniCluster(1);

    // Row Cache
    if (data != null)
        return;
    data = generateData(N);
    cluster = UTIL.getMiniHBaseCluster();
    createTables(VERSIONS);
    createHBaseTables();

}