List of usage examples for java.io IOException initCause
public synchronized Throwable initCause(Throwable cause)
From source file:org.apache.hama.bsp.BSPPeerImpl.java
@SuppressWarnings("unchecked") public final void initInput() throws IOException { InputSplit inputSplit = null;//from www .j av a2 s .c o m // reinstantiate the split try { if (splitClass != null) { inputSplit = (InputSplit) ReflectionUtils.newInstance(conf.getClassByName(splitClass), conf); } } catch (ClassNotFoundException exp) { IOException wrap = new IOException("Split class " + splitClass + " not found"); wrap.initCause(exp); throw wrap; } if (inputSplit != null) { DataInputBuffer splitBuffer = new DataInputBuffer(); splitBuffer.reset(split.getBytes(), 0, split.getLength()); inputSplit.readFields(splitBuffer); if (in != null) { in.close(); } in = new TrackedRecordReader<K1, V1>(bspJob.getInputFormat().getRecordReader(inputSplit, bspJob), getCounter(BSPPeerImpl.PeerCounter.TASK_INPUT_RECORDS), getCounter(BSPPeerImpl.PeerCounter.IO_BYTES_READ)); this.splitSize = inputSplit.getLength(); } }
From source file:com.granule.json.utils.internal.JSONObject.java
/** * Method to write out the JSON formatted object. * @param writer The writer to use when serializing the JSON structure. * @param indentDepth How far to indent the text for object's JSON format. * @param contentOnly Flag to debnnote whether to assign this as an attribute name, or as a nameless object. Commonly used for serializing an array. The Array itself has the name, The contents are all nameless objects * @param compact Flag to denote to write the JSON in compact form. No indentions or newlines. Setting this value to true will cause indentDepth to be ignored. * @throws IOException Trhown if an error occurs on write. */// ww w.j a v a 2s . c o m public void writeObject(Writer writer, int indentDepth, boolean contentOnly, boolean compact) throws IOException { if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeObject(Writer, int, boolean, boolean)"); if (writer != null) { try { if (isEmptyObject()) { writeEmptyObject(writer, indentDepth, contentOnly, compact); } else if (isTextOnlyObject()) { writeTextOnlyObject(writer, indentDepth, contentOnly, compact); } else { writeComplexObject(writer, indentDepth, contentOnly, compact); } } catch (Exception ex) { IOException iox = new IOException("Error occurred on serialization of JSON text."); iox.initCause(ex); throw iox; } } else { throw new IOException("The writer cannot be null."); } if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeObject(Writer, int, boolean, boolean)"); }
From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java
private void run(Intent intent, final SQLiteDatabase db) throws Exception { final long now = dateAtMidnight(System.currentTimeMillis()); Log.i(TAG, "Initializing statistics before uploading"); final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15); final Set<Long> uploadedStats = new HashSet<>(15); final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS; // Get pending uploads. Cursor pendingUploadsCursor = null; try {//from w ww.ja v a 2s. c o m pendingUploadsCursor = db.query("daily_stat_testing", new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g", "free_mobile_femtocell", "sync" }, "stat_timestamp>=? AND stat_timestamp<?", new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null); while (pendingUploadsCursor.moveToNext()) { final long d = pendingUploadsCursor.getLong(0); final int sync = pendingUploadsCursor.getInt(6); if (SYNC_UPLOADED == sync) { uploadedStats.add(d); } else if (SYNC_PENDING == sync) { final DailyStat s = new DailyStat(); s.orange = pendingUploadsCursor.getInt(1); s.freeMobile = pendingUploadsCursor.getInt(2); s.freeMobile3G = pendingUploadsCursor.getInt(3); s.freeMobile4G = pendingUploadsCursor.getInt(4); s.freeMobileFemtocell = pendingUploadsCursor.getInt(5); stats.put(d, s); } } } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } finally { try { if (pendingUploadsCursor != null) pendingUploadsCursor.close(); } catch (Exception e) { Log.e(TAG, Log.getStackTraceString(e)); } } // Compute missing uploads. final ContentValues cv = new ContentValues(); db.beginTransaction(); try { for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) { if (stats.get(d) == null && !uploadedStats.contains(d)) { final DailyStat s = computeDailyStat(d); cv.put("stat_timestamp", d); cv.put("orange", s.orange); cv.put("free_mobile", s.freeMobile); cv.put("free_mobile_3g", s.freeMobile3G); cv.put("free_mobile_4g", s.freeMobile4G); cv.put("free_mobile_femtocell", s.freeMobileFemtocell); cv.put("sync", SYNC_PENDING); db.insertOrThrow("daily_stat_testing", null, cv); stats.put(d, s); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } // Delete old statistics. if (DEBUG) { Log.d(TAG, "Cleaning up upload database"); } db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) }); // Check if there are any statistics to upload. final int statsLen = stats.size(); if (statsLen == 0) { Log.i(TAG, "Nothing to upload"); return; } // Check if the remote server is up. final HttpClient client = createHttpClient(); try { client.head(createServerUrl(null)).execute(); } catch (HttpClientException e) { Log.w(TAG, "Remote server is not available: cannot upload statistics", e); return; } // Upload statistics. Log.i(TAG, "Uploading statistics"); final JSONObject json = new JSONObject(); final String deviceId = getDeviceId(); final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false); for (int i = 0; i < statsLen; ++i) { final long d = stats.keyAt(i); final DailyStat s = stats.get(d); try { json.put("timeOnOrange", s.orange); json.put("timeOnFreeMobile", s.freeMobile); json.put("timeOnFreeMobile3g", s.freeMobile3G); json.put("timeOnFreeMobile4g", s.freeMobile4G); json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare statistics upload"); ioe.initCause(e); throw ioe; } final String url = createServerUrl( "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d)); if (DEBUG) { Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url); } final byte[] rawJson = json.toString().getBytes("UTF-8"); try { client.post(url).content(rawJson, "application/json") .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND) .to(new HttpResponseHandler() { @Override public void onResponse(HttpResponse response) throws Exception { final int sc = response.getStatusCode(); if (HttpURLConnection.HTTP_NOT_FOUND == sc) { // Check if the device has just been // registered. if (deviceWasRegistered) { throw new IOException("Failed to upload statistics"); } else { // Got 404: the device does not exist. // We need to register this device. registerDevice(deviceId); // Restart this service. startService(new Intent(getApplicationContext(), SyncServiceTesting.class) .putExtra(EXTRA_DEVICE_REG, true)); } } else if (HttpURLConnection.HTTP_OK == sc) { // Update upload database. cv.clear(); cv.put("sync", SYNC_UPLOADED); db.update("daily_stat_testing", cv, "stat_timestamp=?", new String[] { String.valueOf(d) }); if (DEBUG) { Log.d(TAG, "Upload done for " + DateUtils.formatDate(d)); } } } }).execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to send request with statistics"); ioe.initCause(e); throw ioe; } } }
From source file:org.apache.jackrabbit.core.nodetype.NodeTypeManagerImpl.java
/** * Registers the node types defined in the given input stream depending * on the content type specified for the stream. This will also register * any namespaces identified in the input stream if they have not already * been registered./* ww w .ja v a 2 s . co m*/ * * @param in node type XML stream * @param contentType type of the input stream * @param reregisterExisting flag indicating whether node types should be * reregistered if they already exist * @return registered node types * @throws IOException if the input stream could not be read or parsed * @throws RepositoryException if the node types are invalid or another * repository error occurs */ public NodeType[] registerNodeTypes(InputStream in, String contentType, boolean reregisterExisting) throws IOException, RepositoryException { // make sure the editing session is allowed to register node types. context.getAccessManager().checkRepositoryPermission(Permission.NODE_TYPE_DEF_MNGMT); try { Map<String, String> namespaceMap = new HashMap<String, String>(); List<QNodeTypeDefinition> nodeTypeDefs = new ArrayList<QNodeTypeDefinition>(); if (contentType.equalsIgnoreCase(TEXT_XML) || contentType.equalsIgnoreCase(APPLICATION_XML)) { try { NodeTypeReader ntr = new NodeTypeReader(in); Properties namespaces = ntr.getNamespaces(); if (namespaces != null) { Enumeration<?> prefixes = namespaces.propertyNames(); while (prefixes.hasMoreElements()) { String prefix = (String) prefixes.nextElement(); String uri = namespaces.getProperty(prefix); namespaceMap.put(prefix, uri); } } QNodeTypeDefinition[] defs = ntr.getNodeTypeDefs(); nodeTypeDefs.addAll(Arrays.asList(defs)); } catch (NameException e) { throw new RepositoryException("Illegal JCR name", e); } } else if (contentType.equalsIgnoreCase(TEXT_X_JCR_CND)) { try { NamespaceMapping mapping = new NamespaceMapping(context.getSessionImpl()); CompactNodeTypeDefReader<QNodeTypeDefinition, NamespaceMapping> reader = new CompactNodeTypeDefReader<QNodeTypeDefinition, NamespaceMapping>( new InputStreamReader(in), "cnd input stream", mapping, new QDefinitionBuilderFactory()); namespaceMap.putAll(mapping.getPrefixToURIMapping()); for (QNodeTypeDefinition ntDef : reader.getNodeTypeDefinitions()) { nodeTypeDefs.add(ntDef); } } catch (ParseException e) { IOException e2 = new IOException(e.getMessage()); e2.initCause(e); throw e2; } } else { throw new UnsupportedRepositoryOperationException("Unsupported content type: " + contentType); } new NamespaceHelper(context.getSessionImpl()).registerNamespaces(namespaceMap); if (reregisterExisting) { NodeTypeRegistry registry = context.getNodeTypeRegistry(); // split the node types into new and already registered node types. // this way we can register new node types together with already // registered node types which make circular dependencies possible List<QNodeTypeDefinition> newNodeTypeDefs = new ArrayList<QNodeTypeDefinition>(); List<QNodeTypeDefinition> registeredNodeTypeDefs = new ArrayList<QNodeTypeDefinition>(); for (QNodeTypeDefinition nodeTypeDef : nodeTypeDefs) { if (registry.isRegistered(nodeTypeDef.getName())) { registeredNodeTypeDefs.add(nodeTypeDef); } else { newNodeTypeDefs.add(nodeTypeDef); } } ArrayList<NodeType> nodeTypes = new ArrayList<NodeType>(); // register new node types nodeTypes.addAll(registerNodeTypes(newNodeTypeDefs)); // re-register already existing node types for (QNodeTypeDefinition nodeTypeDef : registeredNodeTypeDefs) { registry.reregisterNodeType(nodeTypeDef); nodeTypes.add(getNodeType(nodeTypeDef.getName())); } return nodeTypes.toArray(new NodeType[nodeTypes.size()]); } else { Collection<NodeType> types = registerNodeTypes(nodeTypeDefs); return types.toArray(new NodeType[types.size()]); } } catch (InvalidNodeTypeDefException e) { throw new RepositoryException("Invalid node type definition", e); } }
From source file:com.granule.json.utils.internal.JSONObject.java
/** * Internal method to write out a proper JSON attribute string. * @param writer The writer to use while serializing * @param attrs The attributes in a properties object to write out * @param depth How far to indent the JSON text. * @param compact Whether or not to use pretty indention output, or compact output, format * @throws IOException Trhown if an error occurs on write. *//*from w w w .java2 s .co m*/ private void writeAttributes(Writer writer, Properties attrs, int depth, boolean compact) throws IOException { if (logger.isLoggable(Level.FINER)) logger.entering(className, "writeAttributes(Writer, Properties, int, boolean)"); if (attrs != null) { Enumeration props = attrs.propertyNames(); if (props != null && props.hasMoreElements()) { while (props.hasMoreElements()) { String prop = (String) props.nextElement(); writeAttribute(writer, escapeAttributeNameSpecialCharacters(prop), (String) attrs.get(prop), depth + 1, compact); if (props.hasMoreElements()) { try { if (!compact) { writer.write(",\n"); } else { writer.write(","); } } catch (Exception ex) { IOException iox = new IOException("Error occurred on serialization of JSON text."); iox.initCause(ex); throw iox; } } } } } if (logger.isLoggable(Level.FINER)) logger.exiting(className, "writeAttributes(Writer, Properties, int, boolean)"); }
From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java
@Override public void getGranuleDescriptors(Query query, final GranuleCatalogVisitor visitor) throws IOException { Utilities.ensureNonNull("query", query); final Query q = mergeHints(query); String typeName = q.getTypeName(); final Lock lock = rwLock.readLock(); try {//w w w . j a v a 2 s . co m lock.lock(); checkStore(); // // Load tiles informations, especially the bounds, which will be // reused // final SimpleFeatureSource featureSource = tileIndexStore.getFeatureSource(typeName); if (featureSource == null) { throw new NullPointerException( "The provided SimpleFeatureSource is null, it's impossible to create an index!"); } final SimpleFeatureCollection features = featureSource.getFeatures(q); if (features == null) throw new NullPointerException( "The provided SimpleFeatureCollection is null, it's impossible to create an index!"); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Index Loaded"); // visiting the features from the underlying store final DefaultProgressListener listener = new DefaultProgressListener(); features.accepts(new AbstractFeatureVisitor() { public void visit(Feature feature) { if (feature instanceof SimpleFeature) { // get the feature final SimpleFeature sf = (SimpleFeature) feature; MultiLevelROI footprint = getGranuleFootprint(sf); if (footprint == null || !footprint.isEmpty()) { final GranuleDescriptor granule = new GranuleDescriptor(sf, suggestedRasterSPI, pathType, locationAttribute, parentLocation, footprint, heterogeneous, q.getHints()); visitor.visit(granule, null); } // check if something bad occurred if (listener.isCanceled() || listener.hasExceptions()) { if (listener.hasExceptions()) { throw new RuntimeException(listener.getExceptions().peek()); } else { throw new IllegalStateException( "Feature visitor for query " + q + " has been canceled"); } } } } }, listener); } catch (Throwable e) { final IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } finally { lock.unlock(); } }
From source file:org.cloudata.core.common.ipc.CClient.java
/** * Make a call, passing <code>param</code>, to the IPC server running at * <code>address</code>, returning the value. Throws exceptions if there are * network problems or if the remote code threw an exception. *//*from ww w . ja va2s .c o m*/ public CWritable call(CWritable param, InetSocketAddress address) throws InterruptedException, IOException { Connection connection = getConnection(address); Call call = new Call(param); int retryCount = 0; while (true) { try { connection.sendParam(call); break; } catch (IOException e) { if (retryCount > 5) { LOG.error("SendParam error:" + address + "," + e.getMessage(), e); throw e; } LOG.error("SendParam error:" + address + "," + e.getMessage() + ", but retry:" + retryCount); retryCount++; closeThisConnection(address, connection); // close on error connection = getConnection(address); } } try { int id; try { id = connection.in.readInt(); // try to read an id } catch (SocketTimeoutException e) { throw new SocketTimeoutException( "timed out waiting for rpc response[" + address + "]" + new Date(call.lastActivity)); } boolean isError = connection.in.readBoolean(); // read if error if (isError) { String exceptionClassName = CWritableUtils.readString(connection.in); String exceptionMessage = CWritableUtils.readString(connection.in); this.returnToConnections(address, connection); throw new CRemoteException(exceptionClassName, exceptionMessage); } else { CWritable value = (CWritable) ReflectionUtils.newInstance(valueClass, conf); value.readFields(connection.in); // read value this.returnToConnections(address, connection); return value; } } catch (EOFException eof) { //LOG.warn("EOFException: id : " + connection + ", socket : " + connection.socket, eof); closeThisConnection(address, connection); throw new IOException(eof.getMessage(), eof); } catch (CRemoteException e) { throw e; } catch (SocketTimeoutException e) { throw e; } catch (Exception e) { LOG.error("Error while call:" + connection.address + "," + e.getMessage(), e); IOException err = new IOException(e.getMessage()); err.initCause(e); closeThisConnection(address, connection); throw err; } // try { // synchronized (call) { // connection.sendParam(call); // send the parameter // long wait = timeout; // do { // call.wait(wait); // wait for the result // wait = timeout - (System.currentTimeMillis() - call.lastActivity); // } while (!call.done && wait > 0); // // if (call.error != null) { // throw new NRemoteException(call.errorClass, call.error); // } else if (!call.done) { // // FIXME timeout? ? ? timeout? ? // throw new SocketTimeoutException("timed out waiting for rpc response[" // + address + "]" + new Date(call.lastActivity)); // } else { // return call.value; // } // } // } finally { // connection.decrementRef(); // returnToConnections(address, connection); // } }
From source file:com.gc.iotools.stream.reader.TeeReaderWriter.java
/** * {@inheritDoc}/*from w w w .jav a 2 s. c o m*/ * * <p> * This method is called when the method {@link #close()} is invoked. It * copies all the data eventually remaining in the source * <code>Reader</code> passed in the constructor to the destination * <code>Writer</code>. * </p> * <p> * The standard behavior is to close both the underlying * <code>Reader</code> and <code>Writer(s)</code>. When the class was * constructed with the parameter {@link #closeStreams} * set to false the underlying streams must be closed * externally. * @see #close() */ @Override public void close() throws IOException { IOException e1 = null; try { final char[] buffer = new char[EasyStreamConstants.SKIP_BUFFER_SIZE]; while (read(buffer, 0, buffer.length) > 0) { // empty block: just throw bytes away } } catch (final IOException e) { e1 = new IOException("Incomplete data was written to the destination " + "Writer(s)."); e1.initCause(e); } if (this.closeStreams) { final long startr = System.currentTimeMillis(); this.source.close(); this.readTime += System.currentTimeMillis() - startr; for (int i = 0; i < this.destinations.length; i++) { final long start = System.currentTimeMillis(); this.destinations[i].close(); this.writeTime[i] += System.currentTimeMillis() - start; } } if (e1 != null) { throw e1; } }
From source file:org.apache.hadoop.hbase.util.LoadTestTool.java
/** * When NUM_TABLES is specified, the function starts multiple worker threads * which individually start a LoadTestTool instance to load a table. Each * table name is in format <tn>_<index>. For example, "-tn test -num_tables 2" * , table names will be "test_1", "test_2" * * @throws IOException//from w w w. j av a2s.com */ private int parallelLoadTables() throws IOException { // create new command args String tableName = cmd.getOptionValue(OPT_TABLE_NAME, DEFAULT_TABLE_NAME); String[] newArgs = null; if (!cmd.hasOption(LoadTestTool.OPT_TABLE_NAME)) { newArgs = new String[cmdLineArgs.length + 2]; newArgs[0] = "-" + LoadTestTool.OPT_TABLE_NAME; newArgs[1] = LoadTestTool.DEFAULT_TABLE_NAME; for (int i = 0; i < cmdLineArgs.length; i++) { newArgs[i + 2] = cmdLineArgs[i]; } } else { newArgs = cmdLineArgs; } int tableNameValueIndex = -1; for (int j = 0; j < newArgs.length; j++) { if (newArgs[j].endsWith(OPT_TABLE_NAME)) { tableNameValueIndex = j + 1; } else if (newArgs[j].endsWith(NUM_TABLES)) { // change NUM_TABLES to 1 so that each worker loads one table newArgs[j + 1] = "1"; } } // starting to load multiple tables List<WorkerThread> workers = new ArrayList<WorkerThread>(); for (int i = 0; i < numTables; i++) { String[] workerArgs = newArgs.clone(); workerArgs[tableNameValueIndex] = tableName + "_" + (i + 1); WorkerThread worker = new WorkerThread(i, workerArgs); workers.add(worker); LOG.info(worker + " starting"); worker.start(); } // wait for all workers finish LOG.info("Waiting for worker threads to finish"); for (WorkerThread t : workers) { try { t.join(); } catch (InterruptedException ie) { IOException iie = new InterruptedIOException(); iie.initCause(ie); throw iie; } checkForErrors(); } return EXIT_SUCCESS; }
From source file:org.lockss.filter.html.HtmlFilterInputStream.java
/** Parse the input, apply the transform, generate output string and * InputStream *//* w ww . ja v a 2 s . c om*/ void parse() throws IOException { try { Parser parser = makeParser(); NodeList nl = parser.parse(null); if (nl.size() <= 0) { log.warning("nl.size(): " + nl.size()); out = new ReaderInputStream(new StringReader("")); } if (log.isDebug3()) log.debug3("parsed (" + nl.size() + "):\n" + nodeString(nl)); nl = xform.transform(nl); if (log.isDebug3()) log.debug3("xformed (" + nl.size() + "):\n" + nodeString(nl)); // outCharset == null means the client wants the no-charset // re-encoding behavior; don't look at the input encoding if (outCharset != null && adaptEncoding) { String sourceCharset = isSource.getEncoding(); if (!sourceCharset.equalsIgnoreCase(outCharset)) { log.debug2("Using changed charset: " + sourceCharset); outCharset = sourceCharset; } } if (useFile) { try { setOutToFileInputStream(nl); } catch (IOException ioe) { setOutToReaderInputStream(nl); } } else { setOutToReaderInputStream(nl); } IOUtil.safeClose(in); in = null; } catch (ParserException e) { IOException ioe = new IOException(e.toString()); ioe.initCause(e); throw ioe; } }