List of usage examples for java.lang IllegalStateException getMessage
public String getMessage()
From source file:hello.jaxrs.GreetingsResource.java
@GET @Produces(MediaType.TEXT_HTML)/* ww w. j a v a 2 s .c o m*/ public Response showGreetings(@QueryParam("added") final String added, @QueryParam("errorMissingParameter") final String errorMissingParameter) { // read greetings Collection<String> greetings; try { greetings = getGreetingService().getGreetings(); } catch (final IllegalStateException e) { // no service is available; lets report that properly return Response.status(Status.SERVICE_UNAVAILABLE).type(MediaType.TEXT_PLAIN_TYPE) .entity(e.getMessage()).build(); } catch (final Exception e) { // this looks like an issue deeper in some underlying code; we should log this properly return Response.serverError().type(MediaType.TEXT_PLAIN_TYPE) .entity(ExceptionUtils.getFullStackTrace(e)).build(); } // render HTML final StringWriter stringWriter = new StringWriter(); final PrintWriter writer = new PrintWriter(stringWriter); printHeader(writer); if (null != added) { printAddedMessage(writer); } if (null != errorMissingParameter) { printErrorMessage(writer, "Please enter a non-empty greeting prior to submitting the form!"); } printAddGreetingForm(writer); printGreetings(writer, greetings); printFooter(writer); return Response.ok(stringWriter.toString(), MediaType.TEXT_HTML_TYPE).build(); }
From source file:org.apache.phoenix.mapreduce.index.IndexTool.java
@Override public int run(String[] args) throws Exception { Connection connection = null; try {// w w w . j a v a 2s . c om CommandLine cmdLine = null; try { cmdLine = parseOptions(args); } catch (IllegalStateException e) { printHelpAndExit(e.getMessage(), getOptions()); } final Configuration configuration = HBaseConfiguration.addHbaseResources(getConf()); final String schemaName = cmdLine.getOptionValue(SCHEMA_NAME_OPTION.getOpt()); final String dataTable = cmdLine.getOptionValue(DATA_TABLE_OPTION.getOpt()); final String indexTable = cmdLine.getOptionValue(INDEX_TABLE_OPTION.getOpt()); final String qDataTable = SchemaUtil.getTableName(schemaName, dataTable); final String qIndexTable = SchemaUtil.getTableName(schemaName, indexTable); connection = ConnectionUtil.getInputConnection(configuration); if (!isValidIndexTable(connection, qDataTable, indexTable)) { throw new IllegalArgumentException( String.format(" %s is not an index table for %s ", qIndexTable, qDataTable)); } final PTable pdataTable = PhoenixRuntime.getTable(connection, qDataTable); final PTable pindexTable = PhoenixRuntime.getTable(connection, qIndexTable); // this is set to ensure index tables remains consistent post population. long indxTimestamp = pindexTable.getTimeStamp(); configuration.set(PhoenixConfigurationUtil.CURRENT_SCN_VALUE, Long.toString(indxTimestamp + 1)); // check if the index type is LOCAL, if so, derive and set the physicalIndexName that is // computed from the qDataTable name. String physicalIndexTable = qIndexTable; if (IndexType.LOCAL.equals(pindexTable.getIndexType())) { physicalIndexTable = MetaDataUtil.getLocalIndexTableName(qDataTable); } final PhoenixConnection pConnection = connection.unwrap(PhoenixConnection.class); final PostIndexDDLCompiler ddlCompiler = new PostIndexDDLCompiler(pConnection, new TableRef(pdataTable)); ddlCompiler.compile(pindexTable); final List<String> indexColumns = ddlCompiler.getIndexColumnNames(); final String selectQuery = ddlCompiler.getSelectQuery(); final String upsertQuery = QueryUtil.constructUpsertStatement(qIndexTable, indexColumns, Hint.NO_INDEX); configuration.set(PhoenixConfigurationUtil.UPSERT_STATEMENT, upsertQuery); PhoenixConfigurationUtil.setPhysicalTableName(configuration, physicalIndexTable); PhoenixConfigurationUtil.setOutputTableName(configuration, indexTable); PhoenixConfigurationUtil.setUpsertColumnNames(configuration, indexColumns.toArray(new String[indexColumns.size()])); final List<ColumnInfo> columnMetadataList = PhoenixRuntime.generateColumnInfo(connection, qIndexTable, indexColumns); ColumnInfoToStringEncoderDecoder.encode(configuration, columnMetadataList); final Path outputPath = new Path(cmdLine.getOptionValue(OUTPUT_PATH_OPTION.getOpt()), physicalIndexTable); FileSystem.get(configuration).delete(outputPath, true); final String jobName = String.format(INDEX_JOB_NAME_TEMPLATE, dataTable, indexTable); final Job job = Job.getInstance(configuration, jobName); job.setJarByClass(IndexTool.class); job.setMapOutputKeyClass(ImmutableBytesWritable.class); FileOutputFormat.setOutputPath(job, outputPath); PhoenixMapReduceUtil.setInput(job, PhoenixIndexDBWritable.class, qDataTable, selectQuery); TableMapReduceUtil.initCredentials(job); boolean useDirectApi = cmdLine.hasOption(DIRECT_API_OPTION.getOpt()); if (useDirectApi) { job.setMapperClass(PhoenixIndexImportDirectMapper.class); configureSubmittableJobUsingDirectApi(job, outputPath, cmdLine.hasOption(RUN_FOREGROUND_OPTION.getOpt())); } else { job.setMapperClass(PhoenixIndexImportMapper.class); configureRunnableJobUsingBulkLoad(job, outputPath); // finally update the index state to ACTIVE. IndexToolUtil.updateIndexState(connection, qDataTable, indexTable, PIndexState.ACTIVE); } return 0; } catch (Exception ex) { LOG.error(" An exception occured while performing the indexing job : " + ExceptionUtils.getStackTrace(ex)); return -1; } finally { try { if (connection != null) { connection.close(); } } catch (SQLException sqle) { LOG.error(" Failed to close connection ", sqle.getMessage()); throw new RuntimeException("Failed to close connection"); } } }
From source file:fr.free.nrw.commons.upload.UploadPresenter.java
/** * Sets the list of licences and the default license. *///from w ww . j a v a 2 s. c om private void updateLicenses() { String selectedLicense = directKvStore.getString(Prefs.DEFAULT_LICENSE, Prefs.Licenses.CC_BY_SA_4);//CC_BY_SA_4 is the default one used by the commons web app try {//I have to make sure that the stored default license was not one of the deprecated one's Utils.licenseNameFor(selectedLicense); } catch (IllegalStateException exception) { Timber.e(exception.getMessage()); selectedLicense = Prefs.Licenses.CC_BY_SA_4; directKvStore.putString(Prefs.DEFAULT_LICENSE, Prefs.Licenses.CC_BY_SA_4); } view.updateLicenses(uploadModel.getLicenses(), selectedLicense); view.updateLicenseSummary(selectedLicense, uploadModel.getCount()); }
From source file:com.cedarsoftware.ncube.NCubeManager.java
/** * Move ncubes matching the passed in version and APP_CD from SNAPSHOT to RELEASE * state. All ncubes move version at the same time. This is by design so that the * cube join commands do not need to mess with determining what ncube versions * they join with./*from w w w.j a v a 2 s. c om*/ * * @param connection JDBC connection * @param version String version to move from SNAPSHOT to RELEASE * @return int count of ncubes that were released */ public static int releaseCubes(Connection connection, String app, String version) { validate(connection, app, version); synchronized (cubeList) { PreparedStatement stmt1 = null; PreparedStatement stmt2 = null; try { stmt1 = connection.prepareStatement( "SELECT n_cube_id FROM n_cube WHERE app_cd = ? AND version_no_cd = ? AND status_cd = '" + ReleaseStatus.RELEASE + "'"); stmt1.setString(1, app); stmt1.setString(2, version); ResultSet rs = stmt1.executeQuery(); if (rs.next()) { throw new IllegalStateException("A RELEASE version " + version + " already exists. Have system admin renumber your SNAPSHOT version."); } stmt2 = connection.prepareStatement("UPDATE n_cube SET update_dt = ?, status_cd = '" + ReleaseStatus.RELEASE + "' WHERE app_cd = ? AND version_no_cd = ? AND status_cd = '" + ReleaseStatus.SNAPSHOT + "'"); stmt2.setDate(1, new java.sql.Date(System.currentTimeMillis())); stmt2.setString(2, app); stmt2.setString(3, version); return stmt2.executeUpdate(); } catch (IllegalStateException e) { throw e; } catch (Exception e) { String s = "Unable to release NCubes for app: " + app + ", version: " + version + ", due to an error: " + e.getMessage(); LOG.error(s, e); throw new RuntimeException(s, e); } finally { jdbcCleanup(stmt1); jdbcCleanup(stmt2); } } }
From source file:io.tilt.minka.spectator.PublishSubscribeQueue.java
protected void readMessages(final boolean onlyMoveOffset, final CuratorFramework client) { final Stat parentStat = new Stat(); final String parentPath = Queues.QUEUE_PREFIX + name; try {/*from ww w .j a v a2 s .c om*/ final List<String> childrenNodePaths = client.getChildren().storingStatIn(parentStat) .forPath(parentPath); if (!childrenNodePaths.isEmpty() && parentStat.getNumChildren() > 0) { // get them all List<MessageMetadata> objects = getUnreadMessages(client, parentPath, childrenNodePaths, onlyMoveOffset); if (logger.isDebugEnabled() && objects != null) { logger.debug("{}: ({}) New messages on queue: {} for listener: {}, now: (ever size: {})", getClass().getSimpleName(), logId, name, userListener.hashCode(), objects.size(), parentStat.getNumChildren()); } // pass em for (final MessageMetadata meta : objects) { userListener.accept(meta); } } else if (!onlyMoveOffset) { logger.error("{}: ({}) Node changed event on Name: {} without children (?) ", getClass().getSimpleName(), logId, name); } } catch (IllegalStateException ise) { // no problem machine is going down logger.warn("{}: ({}) Node going down while consuming topic messages ({})", getClass().getSimpleName(), logId, ise.getMessage()); } catch (Exception e) { logger.error("{}: ({}) Unexpected error while reading queue: {}, children path: {}", getClass().getSimpleName(), logId, name, parentPath, e); } }
From source file:com.ebay.pulsar.analytics.cache.MemcachedCache.java
@Override public byte[] get(NamedKey key) { Future<Object> future; long start = System.nanoTime(); try {/*from w w w. j a v a 2s.co m*/ future = client.asyncGet(computeKeyHash(memcachedPrefix, key)); } 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 null; } try { byte[] bytes = (byte[]) future.get(timeout, TimeUnit.MILLISECONDS); cacheGetTime.addAndGet(System.nanoTime() - start); if (bytes != null) { getBytes.addAndGet(bytes.length); hitCount.incrementAndGet(); } else { missCount.incrementAndGet(); } return bytes == null ? null : deserializeValue(key, bytes); } catch (TimeoutException e) { timeoutCount.incrementAndGet(); future.cancel(false); return null; } 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 null; } }
From source file:com.haulmont.cuba.web.gui.data.OptionsDsWrapper.java
@Override public Collection getItemIds() { if (executeAutoRefreshInvalid) { if (UI.getCurrent().getConnectorTracker().isWritingResponse()) { try { CollectionDsHelper.autoRefreshInvalid(datasource, autoRefresh); } catch (IllegalStateException ex) { if (StringUtils.contains(ex.getMessage(), "A connector should not be marked as dirty while a response is being written")) { // explain exception String message = String.format( "Some datasource listener has modified the component while it is in rendering state. Please refresh datasource '%s' explicitly", datasource.getId()); throw new IllegalStateException(message, ex); }//from w w w .j a v a 2s . com throw ex; } } else { CollectionDsHelper.autoRefreshInvalid(datasource, autoRefresh); } } return datasource.getItems(); }
From source file:com.mimo.service.api.MimoOauth2Client.java
/** * This function calls the Mimo Server along with the client info and server * authenticates the client and returns a valid access_token * // w w w . j av a 2 s . c o m * @param p_code * : code received from the Mimo Server * * @return <b>m_token</b> : is the access token returned from the server **/ private String requesttoken(String p_code) { String m_loadUrl = m_api.requesttoken(p_code); DefaultHttpClient m_httpClient = new DefaultHttpClient(); HttpPost m_post = new HttpPost(m_loadUrl); // String m_authString = "mimo:mimo"; String m_authString = MimoAPIConstants.USERNAME + ":" + MimoAPIConstants.PASSWORD; String m_authStringEnc = Base64.encodeToString(m_authString.getBytes(), Base64.NO_WRAP); m_post.addHeader(MimoAPIConstants.HEADER_TEXT_AUTHORIZATION, MimoAPIConstants.HEADER_TEXT_BASIC + m_authStringEnc); HttpResponse m_response = null; String m_token = null; try { m_response = m_httpClient.execute(m_post); JSONObject m_jsonResp; try { m_jsonResp = new JSONObject(convertStreamToString(m_response.getEntity().getContent())); // m_token = m_jsonResp.getString("access_token"); m_token = m_jsonResp.getString(MimoAPIConstants.GET_ACCESS_TOKEN); if (MimoAPIConstants.DEBUG) { Log.d(TAG + "Access Token", m_token); } return m_token; } catch (IllegalStateException p_e) { if (MimoAPIConstants.DEBUG) { Log.e(TAG, p_e.getMessage()); } } catch (JSONException p_e) { if (MimoAPIConstants.DEBUG) { Log.e(TAG, p_e.getMessage()); } } } catch (ClientProtocolException p_e) { if (MimoAPIConstants.DEBUG) { Log.e(TAG, p_e.getMessage()); } } catch (IOException p_e) { if (MimoAPIConstants.DEBUG) { Log.e(TAG, p_e.getMessage()); } } return ""; }
From source file:org.apache.ambari.view.slider.rest.client.AmbariHttpClient.java
public AmbariCluster getCluster(AmbariClusterInfo clusterInfo) { if (clusterInfo != null) { try {// w w w . ja v a2s . c o m JsonElement jsonElement = doGetJson("/api/v1/clusters/" + clusterInfo.getName() + "?fields=services/ServiceInfo,hosts,Clusters"); if (jsonElement != null) { AmbariCluster cluster = new AmbariCluster(); // desired configs Map<String, String> desiredConfigs = new HashMap<String, String>(); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject clustersJsonObject = jsonObject.get("Clusters").getAsJsonObject(); JsonObject desiredConfigsObj = clustersJsonObject.get("desired_configs").getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : desiredConfigsObj.entrySet()) { desiredConfigs.put(entry.getKey(), entry.getValue().getAsJsonObject().get("tag").getAsString()); } cluster.setDesiredConfigs(desiredConfigs); cluster.setName(clustersJsonObject.get("cluster_name").getAsString()); cluster.setVersion(clustersJsonObject.get("version").getAsString()); // services List<AmbariServiceInfo> services = new ArrayList<AmbariServiceInfo>(); for (JsonElement svcJson : jsonObject.get("services").getAsJsonArray()) { AmbariServiceInfo si = new AmbariServiceInfo(); si.setId(svcJson.getAsJsonObject().get("ServiceInfo").getAsJsonObject().get("service_name") .getAsString()); si.setStarted("STARTED".equals(svcJson.getAsJsonObject().get("ServiceInfo") .getAsJsonObject().get("state").getAsString())); services.add(si); } cluster.setServices(services); // hosts List<AmbariHostInfo> hosts = new ArrayList<AmbariHostInfo>(); for (JsonElement hostJson : jsonObject.get("hosts").getAsJsonArray()) { AmbariHostInfo hi = new AmbariHostInfo(); hi.setHostName(hostJson.getAsJsonObject().get("Hosts").getAsJsonObject().get("host_name") .getAsString()); hosts.add(hi); } cluster.setHosts(hosts); return cluster; } } catch (IllegalStateException e) { logger.warn("Unable to determine Ambari cluster details - " + clusterInfo.getName(), e); throw new RuntimeException(e.getMessage(), e); } catch (HttpException e) { logger.warn("Unable to determine Ambari cluster details - " + clusterInfo.getName(), e); throw createRuntimeException(e); } catch (IOException e) { logger.warn("Unable to determine Ambari cluster details - " + clusterInfo.getName(), e); throw new RuntimeException(e.getMessage(), e); } } return null; }
From source file:net.daboross.bukkitdev.skywars.world.providers.ProtobufStorageProvider.java
@Override public void loadArena(final SkyArenaConfig arena, final boolean forceReload) throws IOException { if (forceReload || cache.containsKey(arena.getArenaName())) { plugin.getLogger().log(Level.WARNING, "Updating arena blocks cache for arena ''{0}''.", arena.getArenaName());/* w ww. j a va 2 s. c o m*/ } boolean createdNewCache = false; Path cachePath = plugin.getArenaPath().resolve(arena.getArenaName() + ".blocks"); BlockStorage.BlockArea area = null; if (!forceReload) { try (InputStream inputStream = new FileInputStream(cachePath.toFile())) { try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) { area = BlockStorage.BlockArea.parseFrom(gzipInputStream); } } catch (FileNotFoundException ignored) { } } if (area == null) { try { area = createCache(arena); createdNewCache = true; } catch (IllegalStateException ex1) { if (ex1.getMessage().contains("Origin location not listed in configuration")) { try (InputStream inputStream = plugin .getResourceAsStream("arenas/" + arena.getArenaName() + ".blocks")) { try (GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream)) { area = BlockStorage.BlockArea.parseFrom(gzipInputStream); } plugin.getLogger().log(Level.INFO, "Loaded pre-built blocks cache file for arena {0}.", arena.getArenaName()); } catch (FileNotFoundException ex) { throw new IOException( "No origin listed in configuration, but no blocks file found in SkyWars jar file either!", ex); } } else { throw ex1; } } try (OutputStream outputStream = new FileOutputStream(cachePath.toFile())) { try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) { area.writeTo(gzipOutputStream); } } } // We turn the BlockStorage.BlockArea into a StoredBlockArea here, not above, because StoredBlockArea can't write to a file. MemoryBlockArea memoryBlockArea = new MemoryBlockArea(area); if (createdNewCache || arena.getChestConfiguration() == null) { loadChests(arena, memoryBlockArea); } cache.put(arena.getArenaName(), memoryBlockArea); }