List of usage examples for java.io ObjectOutput close
public void close() throws IOException;
From source file:info.magnolia.cms.core.version.BaseVersionManager.java
/** * Create version of the specified node and all child nodes based on the given <code>Rule</code>. * @param node to be versioned// ww w . j a v a 2s . c o m * @param rule * @param userName * @return newly created version node * @throws UnsupportedOperationException if repository implementation does not support Versions API * @throws javax.jcr.RepositoryException if any repository error occurs */ protected Version createVersion(Node node, Rule rule, String userName) throws UnsupportedRepositoryOperationException, RepositoryException { if (isInvalidMaxVersions()) { log.debug("Ignore create version, MaxVersionIndex < 1"); log.debug("Returning root version of the source node"); return node.getVersionHistory().getRootVersion(); } CopyUtil.getInstance().copyToversion(node, new RuleBasedNodePredicate(rule)); Node versionedNode = this.getVersionedNode(node); checkAndAddMixin(versionedNode); Node systemInfo = this.getSystemNode(versionedNode); // add serialized rule which was used to create this version ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ObjectOutput objectOut = new ObjectOutputStream(out); objectOut.writeObject(rule); objectOut.flush(); objectOut.close(); // PROPERTY_RULE is not a part of MetaData to allow versioning of node types which does NOT support MetaData systemInfo.setProperty(PROPERTY_RULE, new String(Base64.encodeBase64(out.toByteArray()))); } catch (IOException e) { throw new RepositoryException("Unable to add serialized Rule to the versioned content"); } // add all system properties for this version systemInfo.setProperty(ContentVersion.VERSION_USER, userName); systemInfo.setProperty(ContentVersion.NAME, node.getName()); versionedNode.save(); // add version Version newVersion = versionedNode.checkin(); versionedNode.checkout(); try { this.setMaxVersionHistory(versionedNode); } catch (RepositoryException re) { log.error("Failed to limit version history to the maximum configured", re); log.error("New version has already been created"); } return newVersion; }
From source file:com.angrygiant.mule.mqtt.MqttModule.java
/** * Publish processor - used to publish a message to a given topic on the MQTT broker. * <p/>/*from w w w .j a v a 2 s . com*/ * <p/> * {@sample.xml ../../../doc/mqtt-connector.xml.sample mqtt:publish} * * @param topicName topic to publish message to * @param message string message to publish (if blank/null, uses messagePayload) * @param qos qos level to use when publishing message * @param messagePayload injects passed payload into this object (for possible use) * @param outboundHeaders injected outbound headers map so we can set them prior to leaving * @return delivered byte[] payload of MqttMessage */ @Processor public byte[] publish(String topicName, String message, @Optional @Default("1") int qos, @Payload Object messagePayload, @OutboundHeaders Map<String, Object> outboundHeaders) throws MqttException, IOException { byte[] payloadBytes; logger.debug("Connecting to Broker..."); if (!this.client.isConnected()) { this.client.connect(); logger.info( "Connected to " + getBrokerHostName() + " on port " + getBrokerPort() + " as " + getClientId()); } else { logger.debug("Already connected to Broker"); } if (qos < 0 || qos > 2) { logger.warn("QOS is invalid, setting to default value of 2"); qos = 2; } logger.debug("Decipher whether we're using String or Message payload"); if (StringUtils.isNotBlank(message)) { logger.debug("Using the string message..."); payloadBytes = message.getBytes(); } else if (messagePayload instanceof byte[]) { logger.debug("Message payload is a byte array, using it directly..."); payloadBytes = (byte[]) messagePayload; } else { logger.info("Converting message payload to a byte array..."); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); try { out.writeObject(messagePayload); payloadBytes = bos.toByteArray(); } finally { bos.close(); out.close(); } } logger.debug("Retrieving topic '" + topicName + "'"); MqttTopic topic = this.client.getTopic(topicName); logger.debug("Preparing message..."); MqttMessage mqttMessage = new MqttMessage(payloadBytes); mqttMessage.setQos(qos); logger.debug("publishing message to broker..."); MqttDeliveryToken token = topic.publish(mqttMessage); logger.trace("Waiting for default timeout of 5minutes..."); token.waitForCompletion(900000); if (outboundHeaders == null) { outboundHeaders = new HashMap<String, Object>(); } outboundHeaders.put(MqttTopicListener.TOPIC_NAME, topic.getName()); outboundHeaders.put(MqttTopicListener.MESSAGE_DUPLICATE, mqttMessage.isDuplicate()); outboundHeaders.put(MqttTopicListener.MESSAGE_RETAIN, mqttMessage.isRetained()); outboundHeaders.put(MqttTopicListener.MESSAGE_QOS, mqttMessage.getQos()); outboundHeaders.put(MqttTopicListener.CLIENT_ID, this.client.getClientId()); outboundHeaders.put(MqttTopicListener.CLIENT_URI, this.client.getServerURI()); return mqttMessage.getPayload(); }
From source file:com.ethanruffing.preferenceabstraction.AutoPreferences.java
/** * Stores any object in the preferences, overwriting any identically-named * properties.//w w w . j a va2 s.com * <p> * Note: Do not abuse this method. Many backends are not intended for * storing large data chunks and can be severely inhibited by doing so. * * @param key The key to store the object under. * @param value The object to store. */ @Override public void put(String key, Object value) { if (configType == ConfigurationType.SYSTEM) { // Translate to a byte array. ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(value); put(key, bos.toByteArray()); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException ex) { // ignore close exception } try { bos.close(); } catch (IOException ex) { // ignore close exception } } } else { fileConfig.setProperty(key, value); } }
From source file:cybervillains.ca.KeyStoreManager.java
private synchronized void persistCertMap() { try {//from w w w. j av a2s . c om ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, CERTMAP_SER_FILE))); out.writeObject(_certMap); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, this shouldn't happen... e.printStackTrace(); } catch (IOException e) { // big problem! e.printStackTrace(); throw new Error(e); } }
From source file:cybervillains.ca.KeyStoreManager.java
private synchronized void persistSubjectMap() { try {/* w w w . ja v a 2 s. c o m*/ ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, SUBJMAP_SER_FILE))); out.writeObject(_subjectMap); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, this shouldn't happen... e.printStackTrace(); } catch (IOException e) { // big problem! e.printStackTrace(); throw new Error(e); } }
From source file:cybervillains.ca.KeyStoreManager.java
private synchronized void persistPublicKeyMap() { try {/*from w w w . j a v a2 s .co m*/ ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, PUB_KEYMAP_SER_FILE))); out.writeObject(_mappedPublicKeys); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, won't happen e.printStackTrace(); } catch (IOException e) { // very bad e.printStackTrace(); throw new Error(e); } }
From source file:cybervillains.ca.KeyStoreManager.java
private synchronized void persistKeyPairMap() { try {//from w ww. j a v a 2 s . c om ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, KEYMAP_SER_FILE))); out.writeObject(_rememberedPrivateKeys); out.flush(); out.close(); } catch (FileNotFoundException e) { // writing, won't happen. e.printStackTrace(); } catch (IOException e) { // very bad e.printStackTrace(); throw new Error(e); } }
From source file:qauth.djd.qauthclient.main.ContentFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Bundle args = getArguments();/*from w w w . j a v a 2 s .c o m*/ if (args.getCharSequence(KEY_TITLE).toString().equals("Providers")) { View rootView = inflater.inflate(R.layout.providers_view_frag, container, false); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); mLayoutManager = new LinearLayoutManager(getActivity()); mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER; if (savedInstanceState != null) { // Restore saved layout manager type. mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState .getSerializable(KEY_LAYOUT_MANAGER); } setRecyclerViewLayoutManager(mCurrentLayoutManagerType); pAdapter = new ProviderAdapter(pDataset); mRecyclerView.setAdapter(pAdapter); final PackageManager pm = getActivity().getPackageManager(); List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo packageInfo : packages) { //Log.i(TAG, "Installed package :" + packageInfo.packageName); //Log.i(TAG, "Source dir : " + packageInfo.sourceDir); //Log.i(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); if (packageInfo.packageName.equals("qauth.djd.dummyclient")) { Provider provider = new Provider("DummyClient", packageInfo.packageName); pDataset.add(provider); pAdapter.notifyDataSetChanged(); } } //get local package names and cross reference with providers on server ("/provider/available") //display package names in listview //allow user to click on item to activate or deactivate // '-> have check box with progress bar indicating status return rootView; } else { View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); mLayoutManager = new LinearLayoutManager(getActivity()); mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER; if (savedInstanceState != null) { // Restore saved layout manager type. mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState .getSerializable(KEY_LAYOUT_MANAGER); } setRecyclerViewLayoutManager(mCurrentLayoutManagerType); wAdapter = new WatchAdapter(wDataset); mRecyclerView.setAdapter(wAdapter); FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab); fab.attachToRecyclerView(mRecyclerView); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("test", "clicked!"); AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity()); builderSingle.setIcon(R.drawable.ic_launcher); builderSingle.setTitle("Select Bluetooth Device"); final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.select_dialog_singlechoice); new Thread(new Runnable() { public void run() { for (String s : getNodes()) { arrayAdapter.add(s); } } }).start(); builderSingle.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String nodeId = arrayAdapter.getItem(which); String privKey = null; String pubKey = null; try { SecureRandom random = new SecureRandom(); RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC"); generator.initialize(spec, random); KeyPair pair = generator.generateKeyPair(); privKey = Base64.encodeToString(pair.getPrivate().getEncoded(), Base64.DEFAULT); pubKey = Base64.encodeToString(pair.getPublic().getEncoded(), Base64.DEFAULT); } catch (Exception e) { Log.i("generate", "error: " + e); } //Log.i("keys", "priv key : " + privKey); //String privKey = Base64.encodeToString(MainTabsActivity.privKey.getEncoded(), Base64.DEFAULT); //String pubKey = Base64.encodeToString(MainTabsActivity.pubKey.getEncoded(), Base64.DEFAULT); Keys keys = new Keys(privKey, pubKey); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); } catch (Exception e) { } try { out.writeObject(keys); } catch (Exception e) { } byte b[] = bos.toByteArray(); try { out.close(); } catch (Exception e) { } try { bos.close(); } catch (Exception e) { } Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, "REGISTER", b) .setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() { @Override public void onResult(MessageApi.SendMessageResult sendMessageResult) { if (!sendMessageResult.getStatus().isSuccess()) { Log.i("MessageApi", "Failed to send message with status code: " + sendMessageResult.getStatus().getStatusCode()); } else if (sendMessageResult.getStatus().isSuccess()) { Log.i("MessageApi", "onResult successful!"); } } }); } }); builderSingle.show(); } }); mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this) .addOnConnectionFailedListener( new com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult result) { Log.i("mGoogleApiClient", "onConnectionFailed: " + result); } }) // Request access only to the Wearable API .addApi(Wearable.API).build(); mGoogleApiClient.connect(); /*BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); for(BluetoothDevice bt : pairedDevices) Log.i("BluetoothDevice", "pairedDevice: " + bt.toString());*/ return rootView; } }
From source file:com.moscona.dataSpace.persistence.DirectoryDataStore.java
@Override public void dump(DataSpace dataSpace) throws DataSpaceException { stats.startTimerFor(TIMING_DUMP_DATA_SPACE); String file = dataSpaceFileName(); try {//from w w w .j av a2 s.co m OutputStream out = new FileOutputStream(file); try { ObjectOutput objOut = new ObjectOutputStream(out); try { objOut.writeObject(dataSpace); } finally { objOut.close(); } } finally { out.close(); } //dumpDataSpaceSummary(dataSpace); } catch (Exception e) { throw new DataSpaceException("Exception while saving data space " + file + ": " + e, e); } finally { stopTimerFor(TIMING_DUMP_DATA_SPACE); } }
From source file:ddf.catalog.cache.impl.FileSystemPersistenceProvider.java
@Override public void store(String key, Object value) { OutputStream file = null;/*from ww w. j a v a2s. co m*/ ObjectOutput output = null; LOGGER.trace("Entering: store - key: {}", key); try { File dir = new File(getMapStorePath()); if (!dir.exists()) { boolean success = dir.mkdir(); if (!success) { LOGGER.error("Could not make directory: {}", dir.getAbsolutePath()); } } LOGGER.debug("file name: {}{}{}", getMapStorePath(), key, SER); file = new FileOutputStream(getMapStoreFile(key)); OutputStream buffer = new BufferedOutputStream(file); output = new ObjectOutputStream(buffer); output.writeObject(value); } catch (IOException e) { LOGGER.info("IOException storing value in cache with key = {}", key, e); } finally { try { if (output != null) { output.close(); } } catch (IOException e) { // Intentionally ignored } IOUtils.closeQuietly(file); } LOGGER.trace("Exiting: store"); }