Code example for InputStream

Methods: availablereset

0
	@Override 
	public void prepareForReading(InputStream stream) {
		sourceSize = -1;
		if ((stream instanceof ByteArrayInputStream)) {
			try { 
				sourceSize = stream.available();
			} catch (IOException e) {}
		} 
		 
		if (log.isDebugEnabled()) { 
			saveSourceMessage(stream);
		} 
		 
		super.prepareForReading(stream);
	} 
 
	/** 
	 * Add DEBUG logging for messages that fail to be decoded 
	 */ 
	@Override 
	public Object decodeObject() {
		try { 
			Object result = super.decodeObject();
			if (result != null && result.getClass().equals(EOKeyValueQualifier.class)) {
				EOKeyValueQualifier qual = (EOKeyValueQualifier) result;
				NSSelector<?> selector = qual.selector();
				NSSelector<?> newSelector = FriendlyQualifier.operatorSelectorForSelectorNamed(selector.name());
				EOKeyValueQualifier newResult = new EOKeyValueQualifier(qual.key(), newSelector, qual.value());
				return newResult;
			} 
			return result;
		} catch (RuntimeException e) {
			if (log.isDebugEnabled()) { 
				try { 
					String filename = File.createTempFile("decodeError", "").getCanonicalPath();
					FileOutputStream fileOutputStream = new FileOutputStream(filename);
					sourceMessage.writeToStream(fileOutputStream);
					fileOutputStream.close();
					log.warn("Wrote message that caused exception to file: " + filename);
				} catch (java.io.IOException exception) {
					log.warn("Unable to save message that caused exception: " + exception);
				} 
			} 
			 
			log.error(e.getMessage() + ". Response was " + sourceSize + " bytes long.");
			 
			if (ERDistributionUtils.isTemporaryLockingFailure(e)) {
				throw e;
			} else { 
				throw new MalformedResponseException("The response from the server was invalid" +  
						(sourceSize == 0 ? " (empty)" : "") + ".");
			} 
		} 
	} 
	 
	private void saveSourceMessage(InputStream stream) {
		if (!(stream instanceof ByteArrayInputStream)) {
			sourceMessage = new NSData();
			return; 
		} 
		 
		ByteArrayInputStream byteStream = (ByteArrayInputStream)stream;
		byte[] bytes = new byte[byteStream.available()];
		try { 
			byteStream.read(bytes);
			sourceMessage = new NSData(bytes);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} 
		 
		try { 
			stream.reset();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} 
	}