List of usage examples for java.io ObjectOutput close
public void close() throws IOException;
From source file:gov.nij.er.ui.EntityResolutionDemo.java
private void saveParameters(File file) { if (file.exists()) { int option = promptParametersFileOverwrite(); if (option == JOptionPane.NO_OPTION || option == JOptionPane.CLOSED_OPTION || option == JOptionPane.CANCEL_OPTION) { return; }//from w w w . j av a2s . c o m } File enhancedFile = file; if (!file.getName().contains(SINGLE_DOT)) { enhancedFile = new File(file.getAbsolutePath() + SINGLE_DOT + PARAMETER_FILE_EXTENSION); } ObjectOutput output = null; try { output = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(enhancedFile))); output.writeObject(parametersTableModel.getAttributeParameters()); LOG.debug("Wrote parameters to file " + enhancedFile.getAbsolutePath()); } catch (IOException ex) { error("Error writing parameters to a file."); ex.printStackTrace(); } finally { try { output.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:org.jfree.data.time.junit.TimeSeriesTest.java
/** * Serialize an instance, restore it, and check for equality. *//*from w w w . j a va 2 s . c om*/ public void testSerialization() { TimeSeries s1 = new TimeSeries("A test"); s1.add(new Year(2000), 13.75); s1.add(new Year(2001), 11.90); s1.add(new Year(2002), null); s1.add(new Year(2005), 19.32); s1.add(new Year(2007), 16.89); TimeSeries s2 = null; try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(buffer); out.writeObject(s1); out.close(); ObjectInput in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); s2 = (TimeSeries) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } assertTrue(s1.equals(s2)); }
From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java
@Override public void dumpSegment(IVectorSegment segment) throws DataSpaceException { stats.startTimerFor(TIMING_DUMP_SEGMENT); try {//from w ww. j a v a 2s. c o m AbstractVectorSegment abstractSegment = (AbstractVectorSegment) segment; SegmentFileInfo fileInfo = new SegmentFileInfo(segment); File file = new File(fileInfo.filePath); File parent = file.getParentFile(); ensureDirExists(parent.getAbsolutePath()); IVectorSegmentBackingArray backingArray = abstractSegment.getBackingArray(); try { OutputStream out = new FileOutputStream(file); try { ObjectOutput objOut = new ObjectOutputStream(new GZIPOutputStream(out)); try { objOut.writeObject(backingArray); } finally { objOut.close(); } } finally { out.close(); } } catch (Exception e) { throw new DataSpaceException( "Exception while saving backing array to " + fileInfo.filePath + ": " + e, e); } markSwappedIn(abstractSegment); } catch (InvalidStateException e) { throw new DataSpaceException("Exception while dumping segment: " + e, e); } finally { stopTimerFor(TIMING_DUMP_SEGMENT); } }
From source file:com.rr.familyPlanning.ui.security.encryptObject.java
/** * Encrypts and encodes the Object and IV for url inclusion * * @param input//from ww w. java 2s.c om * @return * @throws Exception */ public String[] encryptObject(Object obj) throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(stream); try { // Serialize the object out.writeObject(obj); byte[] serialized = stream.toByteArray(); // Setup the cipher and Init Vector Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] iv = new byte[cipher.getBlockSize()]; new SecureRandom().nextBytes(iv); IvParameterSpec ivSpec = new IvParameterSpec(iv); // Hash the key with SHA-256 and trim the output to 128-bit for the key MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(keyString.getBytes()); byte[] key = new byte[16]; System.arraycopy(digest.digest(), 0, key, 0, key.length); SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); // encrypt cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); // Encrypt & Encode the input byte[] encrypted = cipher.doFinal(serialized); byte[] base64Encoded = Base64.encodeBase64(encrypted); String base64String = new String(base64Encoded); String urlEncodedData = URLEncoder.encode(base64String, "UTF-8"); // Encode the Init Vector byte[] base64IV = Base64.encodeBase64(iv); String base64IVString = new String(base64IV); String urlEncodedIV = URLEncoder.encode(base64IVString, "UTF-8"); return new String[] { urlEncodedData, urlEncodedIV }; } finally { stream.close(); out.close(); } }
From source file:org.chiba.xml.xforms.ChibaBean.java
public void writeExternal(ObjectOutput objectOutput) throws IOException { DefaultSerializer serializer = new DefaultSerializer(this); Document serializedForm = serializer.serialize(); StringWriter stringWriter = new StringWriter(); Transformer transformer = null; StreamResult result = new StreamResult(stringWriter); try {/* www. j ava 2 s. c om*/ transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.transform(new DOMSource(serializedForm), result); } catch (TransformerConfigurationException e) { throw new IOException("TransformerConfiguration invalid: " + e.getMessage()); } catch (TransformerException e) { throw new IOException("Error during serialization transform: " + e.getMessage()); } objectOutput.writeUTF(stringWriter.getBuffer().toString()); objectOutput.flush(); objectOutput.close(); }
From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java
/** * request body ?/*from w w w. j a va 2 s .com*/ * * <pre> * * body: * * byte[] data : * * serialize(interface_name, method_name, method_param_desc, method_param_value, attachments_size, attachments_value) * * method_param_desc: for_each (string.append(method_param_interface_name)) * * method_param_value: for_each (method_param_name, method_param_value) * * attachments_value: for_each (attachment_name, attachment_value) * * </pre> * * @param request * @return * @throws IOException */ private byte[] encodeRequest(Channel channel, Request request) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput output = createOutput(outputStream); addMethodInfo(output, request); Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension( channel.getUrl().getParameter(URLParamType.serialize.getName(), URLParamType.serialize.getValue())); if (request.getArguments() != null && request.getArguments().length > 0) { for (Object obj : request.getArguments()) { serialize(output, obj, serialization); } } if (request.getAttachments() == null || request.getAttachments().isEmpty()) { // empty attachments output.writeShort(0); } else { // ?copyattachment????request??? Map<String, String> attachments = copyMap(request.getAttachments()); replaceAttachmentParamsBySign(channel, attachments); addAttachment(output, attachments); } output.flush(); byte[] body = outputStream.toByteArray(); byte flag = MotanConstants.FLAG_REQUEST; output.close(); Boolean usegz = channel.getUrl().getBooleanParameter(URLParamType.usegz.getName(), URLParamType.usegz.getBooleanValue()); int minGzSize = channel.getUrl().getIntParameter(URLParamType.mingzSize.getName(), URLParamType.mingzSize.getIntValue()); return encode(compress(body, usegz, minGzSize), flag, request.getRequestId()); }
From source file:org.polymap.rhei.fulltext.servlet.SearchServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Request: " + request.getQueryString()); String srsParam = request.getParameter("srs"); CoordinateReferenceSystem worldCRS = DEFAULT_WORLD_CRS; if (srsParam != null) { try {/*from w w w. j ava 2s . c o m*/ worldCRS = CRS.decode(srsParam); } catch (Exception e) { worldCRS = DEFAULT_WORLD_CRS; } } log.debug("worldCRS: " + worldCRS); // completion request ***************************** if (request.getParameter("term") != null) { String searchStr = request.getParameter("term"); searchStr = StringEscapeUtils.unescapeHtml4(searchStr); try { JSONArray result = new JSONArray(); for (String record : dispatcher.propose(searchStr, 7, null)) { //result.put( StringEscapeUtils.escapeHtml( record ) ); result.put(record); } log.info("Response: " + result.toString()); response.setContentType("application/json; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.getWriter().println(result.toString()); } catch (Exception e) { log.info("Response: " + "Fehler: " + e.getMessage(), e); response.setContentType("text/html"); response.getWriter().println("Fehler: " + e.getMessage()); } } // content request (GeoRSS/KML/GeoJSON) *********** else if (request.getParameter("search") != null) { String searchStr = request.getParameter("search"); searchStr = URLDecoder.decode(searchStr, "UTF-8"); log.info(" searchStr= " + searchStr); String outputType = request.getParameter("outputType"); int maxResults = request.getParameter("maxResults") != null ? Integer.parseInt(request.getParameter("maxResults")) : DEFAULT_MAX_SEARCH_RESULTS; try { // gzipped response? CountingOutputStream cout = new CountingOutputStream(response.getOutputStream()); OutputStream bout = cout; String acceptEncoding = request.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.toLowerCase().contains("gzip")) { try { bout = new GZIPOutputStream(bout); response.setHeader("Content-Encoding", "gzip"); } catch (NoSuchMethodError e) { // for whatever reason the syncFlush ctor is not always available log.warn(e.toString()); } } ObjectOutput out = null; // KML if ("KML".equalsIgnoreCase(outputType)) { throw new RuntimeException("Not supported currently."); // out = new KMLEncoder( bout ); // response.setContentType( "application/vnd.google-earth.kml+xml; charset=UTF-8" ); // response.setCharacterEncoding( "UTF-8" ); } // JSON else if ("JSON".equalsIgnoreCase(outputType)) { response.setContentType("application/json; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); out = new GeoJsonEncoder(bout, worldCRS); } // RSS else { // XXX figure the real client URL (without reverse proxies) //String baseURL = StringUtils.substringBeforeLast( request.getRequestURL().toString(), "/" ) + "/index.html"; String baseURL = (String) System.getProperties().get("org.polymap.atlas.feed.url"); log.info(" baseURL: " + baseURL); String title = (String) System.getProperties().get("org.polymap.atlas.feed.title"); String description = (String) System.getProperties().get("org.polymap.atlas.feed.description"); out = new GeoRssEncoder(bout, worldCRS, baseURL, title, description); response.setContentType("application/rss+xml; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); } // make sure that empty searchStr *always* results in empty reponse if (searchStr != null && searchStr.length() > 0) { for (JSONObject feature : dispatcher.search(searchStr, maxResults)) { try { out.writeObject(feature); } catch (Exception e) { log.warn("Error during encode: " + e, e); } } } // make sure that streams and deflaters are flushed out.close(); log.info(" written: " + cout.getCount() + " bytes"); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); } } response.flushBuffer(); }
From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java
public void writeExternal(ObjectOutput objectOutput) throws IOException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("serializing XFormsFormsProcessorImpl"); }/*from w w w. ja v a2s.co m*/ try { if (getXForms().getDocumentElement().hasAttribute("bf:serialized")) { objectOutput.writeUTF(DOMUtil.serializeToString(getXForms())); } else { getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:baseURI", getBaseURI()); getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:serialized", "true"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("....::: XForms before writing ::::...."); DOMUtil.prettyPrintDOM(getXForms()); } DefaultSerializer serializer = new DefaultSerializer(this); Document serializedForm = serializer.serialize(); StringWriter stringWriter = new StringWriter(); Transformer transformer = null; StreamResult result = new StreamResult(stringWriter); try { transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.transform(new DOMSource(serializedForm), result); } catch (TransformerConfigurationException e) { throw new IOException("TransformerConfiguration invalid: " + e.getMessage()); } catch (TransformerException e) { throw new IOException("Error during serialization transform: " + e.getMessage()); } objectOutput.writeUTF(stringWriter.getBuffer().toString()); } } catch (XFormsException e) { throw new IOException("baseURI couldn't be set"); } objectOutput.flush(); objectOutput.close(); }
From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java
/** * response body ?//from w ww. j av a2s . co m * * <pre> * * body: * * byte[] : serialize (result) or serialize (exception) * * </pre> * * @param channel * @param value * @return * @throws IOException */ private byte[] encodeResponse(Channel channel, Response value) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutput output = createOutput(outputStream); Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension( channel.getUrl().getParameter(URLParamType.serialize.getName(), URLParamType.serialize.getValue())); byte flag = 0; output.writeLong(value.getProcessTime()); if (value.getException() != null) { output.writeUTF(value.getException().getClass().getName()); serialize(output, value.getException(), serialization); flag = MotanConstants.FLAG_RESPONSE_EXCEPTION; } else if (value.getValue() == null) { flag = MotanConstants.FLAG_RESPONSE_VOID; } else { output.writeUTF(value.getValue().getClass().getName()); serialize(output, value.getValue(), serialization); // v2?responseattachment Map<String, String> attachments = value.getAttachments(); if (attachments != null) { String signed = attachments.get(ATTACHMENT_SIGN); String unSigned = attachments.get(UN_ATTACHMENT_SIGN); attachments.clear(); // attachment???? if (StringUtils.isNotBlank(signed)) { attachments.put(ATTACHMENT_SIGN, signed); } if (StringUtils.isNotBlank(unSigned)) { attachments.put(UN_ATTACHMENT_SIGN, unSigned); } } if (attachments != null && !attachments.isEmpty()) {// ?? addAttachment(output, attachments); } else { // empty attachments output.writeShort(0); } flag = MotanConstants.FLAG_RESPONSE_ATTACHMENT; // v2flag } output.flush(); byte[] body = outputStream.toByteArray(); output.close(); Boolean usegz = channel.getUrl().getBooleanParameter(URLParamType.usegz.getName(), URLParamType.usegz.getBooleanValue()); int minGzSize = channel.getUrl().getIntParameter(URLParamType.mingzSize.getName(), URLParamType.mingzSize.getIntValue()); return encode(compress(body, usegz, minGzSize), flag, value.getRequestId()); }