Example usage for java.lang IllegalStateException getMessage

List of usage examples for java.lang IllegalStateException getMessage

Introduction

In this page you can find the example usage for java.lang IllegalStateException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:no.abmu.common.excel.BaseExcelParserTest.java

public void testNoFileNameGiven() {
    BaseExcelParser baseExcelParser = new BaseExcelParserImpl();

    try {//  w  w  w  . j  a  va2  s .c  o  m
        baseExcelParser.load();
        fail("Should have thrown exception.");
    } catch (IllegalStateException e) {
        String expectedErrorMessage = "Can't parse Excel document. No filename specified";
        assertEquals(expectedErrorMessage, e.getMessage());

    }
}

From source file:com.ebay.pulsar.analytics.cache.MemcachedCache.java

@Override
public Map<NamedKey, byte[]> getBulk(Iterable<NamedKey> keys) {
    Map<String, NamedKey> keyLookup = Maps.uniqueIndex(keys, new Function<NamedKey, String>() {
        @Override// w w w . ja  v a2s . co  m
        public String apply(NamedKey input) {
            return computeKeyHash(memcachedPrefix, input);
        }
    });

    Map<NamedKey, byte[]> results = Maps.newHashMap();

    BulkFuture<Map<String, Object>> future;
    try {
        future = client.asyncGetBulk(keyLookup.keySet());
    } catch (IllegalStateException e) {
        // operation did not get queued in time (queue is full)
        errorCount.incrementAndGet();
        logger.warn("Unable to queue cache operation: " + e.getMessage());
        return results;
    }

    try {
        Map<String, Object> some = future.getSome(timeout, TimeUnit.MILLISECONDS);

        if (future.isTimeout()) {
            future.cancel(false);
            timeoutCount.incrementAndGet();
        }
        missCount.addAndGet(keyLookup.size() - some.size());
        hitCount.addAndGet(some.size());

        for (Map.Entry<String, Object> entry : some.entrySet()) {
            final NamedKey key = keyLookup.get(entry.getKey());
            final byte[] value = (byte[]) entry.getValue();
            results.put(key, value == null ? null : deserializeValue(key, value));
        }
        return results;
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw Throwables.propagate(e);
    } catch (ExecutionException e) {
        errorCount.incrementAndGet();
        logger.warn("Exception pulling item from cache: " + e.getMessage());
        return results;
    }
}

From source file:org.apache.phoenix.mapreduce.AbstractBulkLoadTool.java

@Override
public int run(String[] args) throws Exception {

    Configuration conf = HBaseConfiguration.create(getConf());

    CommandLine cmdLine = null;/*from w  w  w .  ja  v  a 2 s  .c om*/
    try {
        cmdLine = parseOptions(args);
    } catch (IllegalStateException e) {
        printHelpAndExit(e.getMessage(), getOptions());
    }
    return loadData(conf, cmdLine);
}

From source file:com.blackducksoftware.integration.hub.bamboo.tasks.HubScanTask.java

private HubServerConfig getHubServerConfig(final IntLogger logger) {
    try {/*from w w w  .  j  av a 2  s.  com*/
        final String hubUrl = getPersistedValue(HubConfigKeys.CONFIG_HUB_URL);
        final String hubUser = getPersistedValue(HubConfigKeys.CONFIG_HUB_USER);
        final String hubPass = getPersistedValue(HubConfigKeys.CONFIG_HUB_PASS);
        final String hubPassLength = getPersistedValue(HubConfigKeys.CONFIG_HUB_PASS_LENGTH);
        final String hubProxyUrl = getPersistedValue(HubConfigKeys.CONFIG_PROXY_HOST);
        final String hubProxyPort = getPersistedValue(HubConfigKeys.CONFIG_PROXY_PORT);
        final String hubProxyNoHost = getPersistedValue(HubConfigKeys.CONFIG_PROXY_NO_HOST);
        final String hubProxyUser = getPersistedValue(HubConfigKeys.CONFIG_PROXY_USER);
        final String hubProxyPass = getPersistedValue(HubConfigKeys.CONFIG_PROXY_PASS);
        final String hubProxyPassLength = getPersistedValue(HubConfigKeys.CONFIG_PROXY_PASS_LENGTH);

        final HubServerConfig result = HubBambooUtils.getInstance().buildConfigFromStrings(hubUrl, hubUser,
                hubPass, hubPassLength, hubProxyUrl, hubProxyPort, hubProxyNoHost, hubProxyUser, hubProxyPass,
                hubProxyPassLength);
        return result;
    } catch (final IllegalStateException e) {
        logger.error(e.getMessage());
        logger.debug("", e);
    }
    return null;
}

From source file:org.openregistry.core.web.resources.SystemOfRecordPeopleResource.java

@POST
@Consumes(MediaType.APPLICATION_XML)//from   w  w  w.jav a 2s .  com
public Response processIncomingPerson(final PersonRequestRepresentation personRequestRepresentation,
        @PathParam("sorSourceId") final String sorSourceId, @QueryParam("force") final String forceAdd) {
    personRequestRepresentation.systemOfRecordId = sorSourceId;
    Response response = null;

    final ReconciliationCriteria reconciliationCriteria = PeopleResourceUtils.buildReconciliationCriteriaFrom(
            personRequestRepresentation, this.reconciliationCriteriaObjectFactory, this.referenceRepository);
    logger.info("Trying to add incoming person...");

    if (FORCE_ADD_FLAG.equals(forceAdd)) {
        logger.warn("Multiple people found, but doing a 'force add'");
        try {
            final ServiceExecutionResult<Person> result = this.personService
                    .forceAddPerson(reconciliationCriteria);
            final Person forcefullyAddedPerson = result.getTargetObject();
            final URI uri = buildPersonResourceUri(forcefullyAddedPerson);
            response = Response.created(uri)
                    .entity(buildPersonActivationKeyRepresentation(forcefullyAddedPerson))
                    .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).build();
            logger.info(String.format(
                    "Person successfully created (with 'force add' option). The person resource URI is %s",
                    uri.toString()));
        } catch (final IllegalStateException e) {
            response = Response.status(409)
                    .entity(new ErrorsResponseRepresentation(Arrays.asList(e.getMessage())))
                    .type(MediaType.APPLICATION_XML).build();
        }
        return response;
    }

    try {
        final ServiceExecutionResult<Person> result = this.personService.addPerson(reconciliationCriteria);

        if (!result.succeeded()) {
            logger.info("The incoming person payload did not pass validation. Validation errors: "
                    + result.getValidationErrors());
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorsResponseRepresentation(
                            ValidationUtils.buildValidationErrorsResponseAsList(result.getValidationErrors())))
                    .type(MediaType.APPLICATION_XML).build();
        }

        final Person person = result.getTargetObject();
        final URI uri = buildPersonResourceUri(person);
        response = Response.created(uri).entity(buildPersonActivationKeyRepresentation(person))
                .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).build();
        logger.info(
                String.format("Person successfully created. The person resource URI is %s", uri.toString()));
    } catch (final ReconciliationException e) {
        switch (e.getReconciliationType()) {
        case MAYBE:
            final List<PersonMatch> conflictingPeopleFound = e.getMatches();
            response = Response.status(409).entity(buildLinksToConflictingPeopleFound(conflictingPeopleFound))
                    .type(MediaType.APPLICATION_XHTML_XML).build();
            logger.info("Multiple people found: " + response.getEntity());
            break;

        case MISMATCH:
            response = Response.status(409)
                    .entity(new ErrorsResponseRepresentation(Arrays.asList(e.getMessage())))
                    .type(MediaType.APPLICATION_XML).build();
            break;
        }
    } catch (final SorPersonAlreadyExistsException e) {
        response = Response.status(409).entity(new ErrorsResponseRepresentation(Arrays.asList(e.getMessage())))
                .type(MediaType.APPLICATION_XML).build();
    }
    return response;
}

From source file:com.sababado.network.AsyncServiceCallTask.java

private Bundle parseResponse(HttpResponse result) {
    Bundle responseBundle = new Bundle();
    if (result != null) {
        if (result.getStatusLine().getStatusCode() != 200) {
            //something is wrong
            int statusCd = result.getStatusLine().getStatusCode();
            responseBundle.putString(EXTRA_ERR_MSG, "Service Failed: " + statusCd + ": "
                    + result.getStatusLine().getReasonPhrase() + ": " + mService.getUrl());
            responseBundle.putInt(EXTRA_ERR_CODE, statusCd);
            return responseBundle;
        }// w  w w.  j a v a  2s .  com
        try {
            Bundle bundle = new Bundle();
            bundle.putSerializable(EXTRA_SERVICE_RESULT,
                    mService.parseResults(result.getEntity().getContent()));
            return bundle;
        } catch (IllegalStateException e) {
            responseBundle.putString(EXTRA_ERR_MSG, "IllegalStateException: " + e.getMessage());
            responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_PARSE_ILLEGAL_STATE);
            return responseBundle;
        } catch (IOException e) {
            responseBundle.putString(EXTRA_ERR_MSG, "IOException: " + e.getMessage());
            responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_PARSE_IOEXCEPTION);
            return responseBundle;
        } catch (XmlPullParserException e) {
            responseBundle.putString(EXTRA_ERR_MSG, "XmlPullParserException: " + e.getMessage());
            responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_XML_PULLPARSER_EXCEPTION);
            return responseBundle;
        }
    } else {
        responseBundle.putString(EXTRA_ERR_MSG, "No result from service call.");
        responseBundle.putInt(EXTRA_ERR_CODE, ERR_CODE_NO_RESULTS);
        return responseBundle;
    }
}

From source file:com.ailk.oci.ocnosql.tools.load.csvbulkload.CsvBulkLoadTool.java

@Override
public int run(String[] args) throws Exception {

    HBaseConfiguration.addHbaseResources(getConf());
    Configuration conf = getConf();
    String quorum = conf.get("hbase.zookeeper.quorum");
    String clientPort = conf.get("hbase.zookeeper.property.clientPort");
    LOG.info("hbase.zookeeper.quorum=" + quorum);
    LOG.info("hbase.zookeeper.property.clientPort=" + clientPort);
    LOG.info("phoenix.query.dateFormat=" + conf.get("phoenix.query.dateFormat"));

    CommandLine cmdLine = null;/*from  w  ww. j a v  a2 s  . c  o m*/
    try {
        cmdLine = parseOptions(args);
        LOG.info("JdbcUrl=" + getJdbcUrl(quorum + ":" + clientPort));
    } catch (IllegalStateException e) {
        printHelpAndExit(e.getMessage(), getOptions());
    }
    Class.forName(DriverManager.class.getName());
    Connection conn = DriverManager.getConnection(getJdbcUrl(quorum + ":" + clientPort));
    String tableName = cmdLine.getOptionValue(TABLE_NAME_OPT.getOpt());
    String schemaName = cmdLine.getOptionValue(SCHEMA_NAME_OPT.getOpt());
    String qualifiedTableName = getQualifiedTableName(schemaName, tableName);
    List<ColumnInfo> importColumns = buildImportColumns(conn, cmdLine, qualifiedTableName);

    LOG.info("tableName=" + tableName);
    LOG.info("schemaName=" + schemaName);
    LOG.info("qualifiedTableName=" + qualifiedTableName);

    configureOptions(cmdLine, importColumns, getConf());

    try {
        validateTable(conn, schemaName, tableName);
    } finally {
        conn.close();
    }

    Path inputPath = new Path(cmdLine.getOptionValue(INPUT_PATH_OPT.getOpt()));
    Path outputPath = null;
    if (cmdLine.hasOption(OUTPUT_PATH_OPT.getOpt())) {
        outputPath = new Path(cmdLine.getOptionValue(OUTPUT_PATH_OPT.getOpt()));
    } else {
        outputPath = new Path("/tmp/" + UUID.randomUUID());
    }
    LOG.info("Configuring HFile output path to {}", outputPath);

    Job job = new Job(getConf(),
            "Phoenix MapReduce import for " + getConf().get(PhoenixCsvToKeyValueMapper.TABLE_NAME_CONFKEY));

    // Allow overriding the job jar setting by using a -D system property at startup
    if (job.getJar() == null) {
        job.setJarByClass(PhoenixCsvToKeyValueMapper.class);
    }
    job.setInputFormatClass(TextInputFormat.class);
    FileInputFormat.addInputPath(job, inputPath);

    FileSystem.get(getConf());
    FileOutputFormat.setOutputPath(job, outputPath);

    job.setMapperClass(PhoenixCsvToKeyValueMapper.class);
    job.setMapOutputKeyClass(ImmutableBytesWritable.class);
    job.setMapOutputValueClass(KeyValue.class);

    HTable htable = new HTable(getConf(), qualifiedTableName);

    // Auto configure partitioner and reducer according to the Main Data table
    HFileOutputFormat.configureIncrementalLoad(job, htable);

    LOG.info("Running MapReduce import job from {} to {}", inputPath, outputPath);
    boolean success = job.waitForCompletion(true);
    if (!success) {
        LOG.error("Import job failed, check JobTracker for details");
        return 1;
    }

    LOG.info("Loading HFiles from {}", outputPath);
    LoadIncrementalHFiles loader = new LoadIncrementalHFiles(getConf());
    loader.doBulkLoad(outputPath, htable);
    htable.close();

    LOG.info("Incremental load complete");

    LOG.info("Removing output directory {}", outputPath);
    if (!FileSystem.get(getConf()).delete(outputPath, true)) {
        LOG.error("Removing output directory {} failed", outputPath);
    }

    return 0;
}

From source file:org.apache.maven.dotnet.UnPackMojo.java

/**
 * Launches the MOJO action. <br/>
 * This method downloads pom.xml and packages dependencies and build AssemblySearchPaths file
 * //  ww w  .  j a  v  a 2 s  .  c  o m
 * @throws MojoExecutionException
 * @throws MojoFailureException
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    dllDirs.clear();

    if (StringUtils.isEmpty(unPackRoot)) {
        unPackRoot = localRepository.getBasedir() + File.separator + DOTNET_DIR_NAME + File.separator
                + LOCAL_DIR_NAME;
    }

    if (offset == null) {
        offset = "";
    }

    Iterator<Artifact> it = this.project.getArtifacts().iterator();
    while (it.hasNext()) {
        Artifact artifact = it.next();

        File packagePath = new File(unPackRoot + File.separator + localRepository.pathOf(artifact));
        if (!packagePath.getParentFile().exists()) {
            unZipPackage(artifact, localRepository.pathOf(artifact));
        } else {
            getLog().info("UpToDate " + packagePath.getParentFile().getPath());

            WatchedDirectoryWalkListener watchedDirectoryWalkListener = new WatchedDirectoryWalkListener(
                    dllDirs, offset);

            DirectoryWalker dw = new DirectoryWalker();
            dw.setBaseDir(new File(packagePath.getParentFile().getPath()));
            dw.addDirectoryWalkListener(watchedDirectoryWalkListener);

            try {
                dw.scan();
            } catch (IllegalStateException e) {
                throw new MojoExecutionException(packagePath.getParentFile().getPath() + " : " + e.getMessage(),
                        e);
            }
        }
    }

    if (csprojvars != null) {
        getLog().info("writing variables into file " + csprojvars);

        ByteArrayOutputStream baOut = new ByteArrayOutputStream();
        PrintStream psOut = new PrintStream(baOut);

        psOut.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        psOut.println(
                "  <Project ToolsVersion=\"3.5\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">");
        psOut.println("  <!-- Generated by DOTNET PLUGIN !-->");
        psOut.println("  <PropertyGroup>");
        psOut.println("  <AssemblySearchPaths>");
        psOut.print("  $(AssemblySearchPaths)");

        Iterator<String> iter = dllDirs.iterator();
        while (iter.hasNext()) {
            psOut.println(";");
            psOut.print("  " + iter.next());
        }
        psOut.println("");
        psOut.println("  </AssemblySearchPaths>");
        psOut.println("  </PropertyGroup>");
        psOut.println("</Project>");

        FileOutputStream fileOutputStreamOrder = null;
        try {
            fileOutputStreamOrder = new FileOutputStream(new File(csprojvars));
            fileOutputStreamOrder.write(baOut.toByteArray());
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Troubles during writing variables", e);
        } catch (IOException e) {
            throw new MojoExecutionException("Troubles during writing variables", e);
        } finally {
            if (fileOutputStreamOrder != null) {
                try {
                    fileOutputStreamOrder.close();
                } catch (IOException e) {
                    getLog().info(e);
                }
            }
        }
    }
}

From source file:org.meerkat.services.WebServiceApp.java

/**
 * checkWebAppStatus//w  w  w. j a  v a  2  s .  c  om
 */
public final WebAppResponse checkWebAppStatus() {
    // Set the response at this point to empty in case of no response at all
    setCurrentResponse("");
    int statusCode = 0;

    // Create a HttpClient
    MeerkatHttpClient meerkatClient = new MeerkatHttpClient();
    DefaultHttpClient httpClient = meerkatClient.getHttpClient();

    HttpResponse httpresponse = null;

    WebAppResponse response = new WebAppResponse();
    XMLComparator xmlCompare;
    response.setResponseWebService();
    String responseFromPostXMLRequest;

    // Get target URL
    String strURL = this.getUrl();

    // Prepare HTTP post
    HttpPost httpPost = new HttpPost(strURL);

    StringEntity strEntity = null;
    try {
        strEntity = new StringEntity(postXML, "UTF-8");
    } catch (UnsupportedEncodingException e3) {
        log.error("UnsupportedEncodingException: " + e3.getMessage());
    }
    httpPost.setEntity(strEntity);

    // Set Headers
    httpPost.setHeader("Content-type", "text/xml; charset=ISO-8859-1");

    // Set the SOAP Action if specified
    if (!soapAction.equalsIgnoreCase("")) {
        httpPost.setHeader("SOAPAction", this.soapAction);
    }

    // Measure the request time
    Counter c = new Counter();
    c.startCounter();

    // Get headers
    // Header[] headers = httpPost.getAllHeaders();
    // int total = headers.length;
    // log.info("\nHeaders");
    // for(int i=0;i<total;i++){
    // log.info(headers[i]);
    // }

    // Execute the request
    try {
        httpresponse = httpClient.execute(httpPost);
        // Set status code
        statusCode = httpresponse.getStatusLine().getStatusCode();
    } catch (Exception e) {
        log.error("WebService Exception: " + e.getMessage() + " [URL: " + this.getUrl() + "]");
        httpClient.getConnectionManager().shutdown();
        c.stopCounter();
        response.setPageLoadTime(c.getDurationSeconds());
        setCurrentResponse(e.getMessage());
        return response;
    }

    response.setHttpStatus(statusCode);

    // Get the response
    BufferedReader br = null;
    try {
        // Read in UTF-8
        br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(), "UTF-8"));
    } catch (IllegalStateException e1) {
        log.error("IllegalStateException in http buffer: " + e1.getMessage());
    } catch (IOException e1) {
        log.error("IOException in http buffer: " + e1.getMessage());
    }

    String readLine;
    String responseBody = "";
    try {
        while (((readLine = br.readLine()) != null)) {
            responseBody += "\n" + readLine;
        }
    } catch (IOException e) {
        log.error("IOException in http response: " + e.getMessage());
    }

    try {
        br.close();
    } catch (IOException e1) {
        log.error("Closing BufferedReader: " + e1.getMessage());
    }

    response.setHttpTextResponse(responseBody);
    setCurrentResponse(responseBody);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpClient.getConnectionManager().shutdown();

    // Stop the counter
    c.stopCounter();
    response.setPageLoadTime(c.getDurationSeconds());

    if (statusCode != HttpStatus.SC_OK) {
        log.warn("Httpstatus code: " + statusCode + " | Method failed: " + httpresponse.getStatusLine());
        // Set the response to the error if none present
        if (this.getCurrentResponse().equals("")) {
            setCurrentResponse(httpresponse.getStatusLine().toString());
        }
    }

    // Prepare to compare with expected response
    responseFromPostXMLRequest = responseBody;

    // Format both request response and response file XML
    String responseFromPostXMLRequestFormatted = "";
    String xmlResponseExpected = "";
    XmlFormatter formatter = new XmlFormatter();

    try {
        responseFromPostXMLRequestFormatted = formatter.format(responseFromPostXMLRequest.trim());
        xmlResponseExpected = formatter.format(responseXML);
    } catch (Exception e) {
        log.error("Error parsing XML: " + e.getMessage());
    }

    try {
        // Compare the XML response file with the response XML
        xmlCompare = new XMLComparator(xmlResponseExpected, responseFromPostXMLRequestFormatted);
        if (xmlCompare.areXMLsEqual()) {
            response.setContainsWebServiceExpectedResponse(true);
        }
    } catch (Exception e) {
        log.error("Error parsing XML for comparison: " + e.getMessage());
    }

    return response;
}

From source file:ca.rmen.android.palidamuerte.app.poem.detail.PoemDetailActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_poem_detail);
    getActionBar().setDisplayShowCustomEnabled(true);
    getActionBar().setCustomView(R.layout.poem_number);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    mTextViewPageNumber = (TextView) getActionBar().getCustomView();
    ActionBar.setCustomFont(this);
    mViewPager = (ViewPager) findViewById(R.id.pager);

    // If this is the first time we open the activity, we will use the poem id provided in the intent.
    // If we are recreating the activity (because of a device rotation, for example), we will display the poem that the user 
    // had previously swiped to, using the ViewPager.
    final long poemId;
    if (savedInstanceState != null)
        poemId = savedInstanceState.getLong(PoemDetailFragment.ARG_ITEM_ID);
    else//  w  w  w.  j  a v  a  2  s. c  o  m
        poemId = getIntent().getLongExtra(PoemDetailFragment.ARG_ITEM_ID, -1);

    new AsyncTask<Void, Void, PoemPagerAdapter>() {

        private String mActivityTitle;

        @Override
        protected PoemPagerAdapter doInBackground(Void... params) {
            mActivityTitle = Poems.getActivityTitle(PoemDetailActivity.this, getIntent());
            PoemSelection poemSelection = Poems.getPoemSelection(PoemDetailActivity.this, getIntent());
            return new PoemPagerAdapter(PoemDetailActivity.this, poemSelection, getSupportFragmentManager());
        }

        @Override
        protected void onPostExecute(PoemPagerAdapter result) {
            if (isFinishing())
                return;
            try {
                mPoemPagerAdapter = result;
                mViewPager.setAdapter(mPoemPagerAdapter);
                mViewPager.setOnPageChangeListener(mOnPageChangeListener);
                findViewById(R.id.activity_loading).setVisibility(View.GONE);
                int position = mPoemPagerAdapter.getPositionForPoem(poemId);
                mViewPager.setCurrentItem(position);
                getActionBar().setTitle(mActivityTitle);
                String pageNumber = getString(R.string.page_number, position + 1, mPoemPagerAdapter.getCount());
                mTextViewPageNumber.setText(pageNumber);
                invalidateOptionsMenu();
            } catch (IllegalStateException e) {
                // Don't have time to investigate the root cause now
                //https://groups.google.com/forum/#!topic/android-developers/Zpb8YSzTltA 
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }.execute();

    // Show the Up button in the action bar.
    getActionBar().setDisplayHomeAsUpEnabled(true);
}