List of usage examples for java.io ByteArrayInputStream close
public void close() throws IOException
From source file:org.keycloak.testsuite.oauth.ClientAuthSignedJWTTest.java
private void testClientWithGeneratedKeys(String format) throws Exception { ClientRepresentation client = app3;// w ww .j a va 2 s .c o m UserRepresentation user = defaultUser; final String keyAlias = "somekey"; final String keyPassword = "keypwd"; final String storePassword = "storepwd"; // Generate new keystore (which is intended for sending to the user and store in a client app) // with public/private keys; in KC, store the certificate itself KeyStoreConfig keyStoreConfig = new KeyStoreConfig(); keyStoreConfig.setFormat(format); keyStoreConfig.setKeyPassword(keyPassword); keyStoreConfig.setStorePassword(storePassword); keyStoreConfig.setKeyAlias(keyAlias); client = getClient(testRealm.getRealm(), client.getId()).toRepresentation(); final String certOld = client.getAttributes().get(JWTClientAuthenticator.CERTIFICATE_ATTR); // Generate the keystore and save the new certificate in client (in KC) byte[] keyStoreBytes = getClientAttributeCertificateResource(testRealm.getRealm(), client.getId()) .generateAndGetKeystore(keyStoreConfig); ByteArrayInputStream keyStoreIs = new ByteArrayInputStream(keyStoreBytes); KeyStore keyStore = getKeystore(keyStoreIs, storePassword, format); keyStoreIs.close(); client = getClient(testRealm.getRealm(), client.getId()).toRepresentation(); assertCertificate(client, certOld, KeycloakModelUtils.getPemFromCertificate((X509Certificate) keyStore.getCertificate(keyAlias))); // Try to login with the new keys oauth.clientId(client.getClientId()); PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword.toCharArray()); OAuthClient.AccessTokenResponse response = doGrantAccessTokenRequest(user.getUsername(), user.getCredentials().get(0).getValue(), getClientSignedJWT(privateKey, client.getClientId())); assertEquals(200, response.getStatusCode()); AccessToken accessToken = oauth.verifyToken(response.getAccessToken()); RefreshToken refreshToken = oauth.verifyRefreshToken(response.getRefreshToken()); events.expectLogin().client(client.getClientId()).session(accessToken.getSessionState()) .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD).detail(Details.TOKEN_ID, accessToken.getId()) .detail(Details.REFRESH_TOKEN_ID, refreshToken.getId()).detail(Details.USERNAME, user.getUsername()) .detail(Details.CLIENT_AUTH_METHOD, JWTClientAuthenticator.PROVIDER_ID) .removeDetail(Details.CODE_ID).removeDetail(Details.REDIRECT_URI).removeDetail(Details.CONSENT) .assertEvent(); }
From source file:org.sakaiproject.jcr.jackrabbit.RepositoryBuilder.java
public void init() { enabled = serverConfigurationService.getBoolean("jcr.experimental", false); if (!enabled) { log.info("Repository Builder is not enabled"); return;/*from w w w. java 2 s. c o m*/ } /* * Unless the explicit values have been injected into this instance, try * to get the database properties from the Sakai Defaults. */ if (dbDialect == null) { dbDialect = serverConfigurationService.getString(DEFAULT_DBDIALECT_PROP); } if (dbUser == null) { dbUser = serverConfigurationService.getString(DEFAULT_DBUSER_PROP); } if (dbPass == null) { dbPass = serverConfigurationService.getString(DEFAULT_DBPASS_PROP); } if (dbDriver == null) { dbDriver = serverConfigurationService.getString(DEFAULT_DBDRIVER_PROP); } if (dbURL == null) { String theDbURL = serverConfigurationService.getString(DEFAULT_DBURL_PROP); // The seperators need to be escaped since this is going into an XML // Attribute. dbURL = theDbURL.replaceAll("&", "&"); } if (contentOnFilesystem == null) { contentOnFilesystem = "false"; } if (useSharedFSBlobStore == null) { useSharedFSBlobStore = "false"; } if (sharedFSBlobLocation == null) { sharedFSBlobLocation = "jcrblobs"; } /* * Currently Setting the journal location, journalLocation, in * compenents.xml using the sakai.home macro */ dataSourcePersistanceManager = serverConfigurationService.getBoolean(DEFAULT_DSPERSISTMNGR_PROP, false); boolean error = false; try { clusterNodeId = serverConfigurationService.getServerId(); if (dbDialect == null) { dbDialect = vendors.get(sqlService.getVendor()); } if (dbDialect == null) { dbDialect = "default"; } persistanceManagerClass = persistanceManagers.get(dbDialect); if (dataSourcePersistanceManager) { log.info(MessageFormat.format( "\nJCR Repository Config is \n" + "\trepositoryConfig = {0} \n" + "\tDB Using Datasource\n" + "\tdbDialect = {5} \n" + "\trepository Home = {6}\n" + "\tcontentOnFilesystem = {7}\n" + "\tjournalLocation= {8}\n" + "\tpersistanceManageerClass= {9}\n", new Object[] { repositoryConfig, dbURL, dbUser, dbPass, dbDriver, dbDialect, repositoryHome, contentOnFilesystem, journalLocation, persistanceManagerClass })); if ((repositoryConfig == null) || (dbDialect == null) || (repositoryHome == null) || (contentOnFilesystem == null) || (journalLocation == null)) { throw new IllegalStateException("You must set all the services (none can be null): " + "repositoryConfig, dbDialect, repositoryHome, contentOnFilesystem, journalLocation "); } } else { log.info(MessageFormat.format( "\nJCR Repository Config is \n" + "\trepositoryConfig = {0} \n" + "\tdbURL = {1}\n" + "\tdbUser = {2} \n" + "\tdbDriver = {4} \n" + "\tdbDialect = {5} \n" + "\trepository Home = {6}\n" + "\tcontentOnFilesystem = {7}\n" + "\tpersistanceManageerClass= {8}\n", new Object[] { repositoryConfig, dbURL, dbUser, dbPass, dbDriver, dbDialect, repositoryHome, contentOnFilesystem, persistanceManagerClass })); if ((repositoryConfig == null) || (dbURL == null) || (dbUser == null) || (dbPass == null) || (dbDriver == null) || (dbDialect == null) || (repositoryHome == null) || (contentOnFilesystem == null)) { throw new IllegalStateException("You must set all the services (none can be null): " + "repositoryConfig, dbURL, dbUser, dbPass, dbDriver, dbDialect, repositoryHome, contentOnFilesystem "); } } if (namespaces == null) { throw new IllegalStateException("You must set the namespace list"); } StringBuffer content = new StringBuffer(); try { Reader r = new InputStreamReader(this.getClass().getResourceAsStream(repositoryConfig)); char[] c = new char[4096]; for (int i = 0; (i = r.read(c)) != -1;) { content.append(c, 0, i); } } catch (Exception ex) { throw new Exception("Failed to load repository config " + repositoryConfig, ex); } String contentStr = content.toString().replaceAll(DB_URL, dbURL); contentStr = contentStr.replaceAll(DB_USER, dbUser); contentStr = contentStr.replaceAll(DB_PASS, dbPass); contentStr = contentStr.replaceAll(DB_DRIVER, dbDriver); contentStr = contentStr.replaceAll(DB_DIALECT, dbDialect); contentStr = contentStr.replaceAll(CONTENT_ID_DB, contentOnFilesystem); contentStr = contentStr.replaceAll(USE_SHARED_FS_BLOB_STORE, useSharedFSBlobStore); contentStr = contentStr.replaceAll(SHARED_CONTENT_BLOB_LOCATION, sharedFSBlobLocation); contentStr = contentStr.replaceAll(CLUSTER_NODE_ID, clusterNodeId); contentStr = contentStr.replaceAll(JOURNAL_LOCATION, journalLocation); contentStr = contentStr.replaceAll(PERSISTANCE_MANAGER, persistanceManagerClass); if (log.isDebugEnabled()) log.debug("Repositroy Config is \n" + contentStr); ByteArrayInputStream bais = new ByteArrayInputStream(contentStr.getBytes()); try { RepositoryConfig rc = RepositoryConfig.create(bais, repositoryHome); repository = RepositoryImpl.create(rc); setup(); } finally { bais.close(); } } catch (Throwable ex) { log.error("init() failure: " + ex); error = true; } finally { if (error) { throw new RuntimeException( "Fatal error initialising JCRService... (see previous logged ERROR for details)"); } } log.info("Repository Builder passed init "); Runtime.getRuntime().addShutdownHook(new Thread() { /* * (non-Javadoc) * * @see java.lang.Thread#run() */ @Override public void run() { shutdown(); } }); }
From source file:hydrograph.ui.engine.ui.util.UiConverterUtil.java
private Graph unMarshall(File inputFile) throws JAXBException, ParserConfigurationException, SAXException, IOException { LOGGER.debug("Un-Marshaling generated object into target XML"); JAXBContext jaxbContext;/*ww w . j a v a 2 s . co m*/ Graph graph = null; Document document = null; parseXML(inputFile); String inputFileAsString = replaceParametersWithDefaultValues(inputFile); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setExpandEntityReferences(false); builderFactory.setNamespaceAware(true); builderFactory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION, true); DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder(); ByteArrayInputStream byteStream = new ByteArrayInputStream(inputFileAsString.getBytes()); InputSource inputSource = new InputSource(byteStream); document = documentBuilder.parse(inputSource); jaxbContext = JAXBContext.newInstance(Graph.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); graph = (Graph) jaxbUnmarshaller.unmarshal(document); if (graph != null) { componentRepo.genrateComponentRepo(graph); } byteStream.close(); return graph; }
From source file:org.cloudgraph.hbase.io.DefaultEdgeOperation.java
protected void decodeRowKeys(byte[] rowKeys) { ByteArrayInputStream bais = new ByteArrayInputStream(rowKeys); try {//from w w w.j av a2 s.c om RowKeys.Builder result = RowKeys.newBuilder(); result.mergeDelimitedFrom(bais); RowKeys keys = result.build(); this.rowKeys = new ArrayList<>(keys.getRowKeyCount()); for (RowKey rowKey : keys.getRowKeyList()) this.rowKeys.add(new KeyBytes(rowKey.getKey().toByteArray())); } catch (IOException e) { throw new StateException(e); } finally { try { bais.close(); } catch (IOException e) { } } }
From source file:de.scoopgmbh.copper.monitoring.client.context.ApplicationContext.java
public ApplicationContext() { mainStackPane = new StackPane(); mainPane = new BorderPane(); mainPane.setId("background");//important for css mainStackPane.getChildren().add(mainPane); messageProvider = new MessageProvider(ResourceBundle.getBundle("de.scoopgmbh.copper.gui.message")); final Preferences prefs = Preferences.userRoot().node("de.scoopgmbh.coppermonitor"); SettingsModel defaultSettings = new SettingsModel(); AuditralColorMapping newItem = new AuditralColorMapping(); newItem.color.setValue(Color.rgb(255, 128, 128)); newItem.loglevelRegEx.setValue("1"); defaultSettings.auditralColorMappings.add(newItem); byte[] defaultModelbytes; ByteArrayOutputStream os = null; try {/* www. ja va 2 s .c om*/ os = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(os); o.writeObject(defaultSettings); defaultModelbytes = os.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { throw new RuntimeException(e); } } } settingsModelSingleton = defaultSettings; ByteArrayInputStream is = null; try { is = new ByteArrayInputStream(prefs.getByteArray(SETTINGS_KEY, defaultModelbytes)); ObjectInputStream o = new ObjectInputStream(is); Object object = o.readObject(); if (object instanceof SettingsModel) { settingsModelSingleton = (SettingsModel) object; } } catch (Exception e) { logger.error("", e); getIssueReporterSingleton() .reportWarning("Can't load settings from (Preferences: " + prefs + ") use defaults instead", e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { ByteArrayOutputStream os = null; try { os = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(os); o.writeObject(settingsModelSingleton); prefs.putByteArray(SETTINGS_KEY, os.toByteArray()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } })); }
From source file:com.photon.phresco.framework.impl.CIManagerImpl.java
private void validate() throws IOException, InterruptedException { S_LOGGER.debug("Entering Method CIManagerImpl.validate()"); CLI validateCLI = new CLI(new URL("http://localhost:3579/ci/")); List<String> argList = new ArrayList<String>(); argList.add("build"); argList.add("NewJob"); Gson gson = new Gson(); JsonParser parser = new JsonParser(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] data = new byte[4]; ByteArrayInputStream inputStream = new ByteArrayInputStream(data); BufferedInputStream stream = new BufferedInputStream(System.in); int execute = validateCLI.execute(argList, inputStream, baos, baos); validateCLI.close();/* w w w . j ava 2 s .c o m*/ byte[] outData = new byte[2]; int read; while ((read = inputStream.read(outData)) != -1) { System.out.print(new String(outData)); } inputStream.close(); // byte[] byteArray = baos.toByteArray(); // baos.flush(); // baos.close(); }
From source file:J2MESearchMixedRecordDataTypeExample.java
public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true);//from ww w. j av a2 s . c om notifyDestroyed(); } else if (command == start) { try { recordstore = RecordStore.openRecordStore("myRecordStore", true); byte[] outputRecord; String outputString[] = { "A", "B", "M" }; int outputInteger[] = { 15, 10, 5 }; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutputStream outputDataStream = new DataOutputStream(outputStream); for (int x = 0; x < 3; x++) { outputDataStream.writeUTF(outputString[x]); outputDataStream.writeInt(outputInteger[x]); outputDataStream.flush(); outputRecord = outputStream.toByteArray(); recordstore.addRecord(outputRecord, 0, outputRecord.length); outputStream.reset(); } outputStream.close(); outputDataStream.close(); String inputString; byte[] byteInputData = new byte[300]; ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData); DataInputStream inputDataStream = new DataInputStream(inputStream); if (recordstore.getNumRecords() > 0) { filter = new Filter("Mary"); recordEnumeration = recordstore.enumerateRecords(filter, null, false); while (recordEnumeration.hasNextElement()) { recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0); inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt(); alert = new Alert("Reading", inputString, null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } inputStream.close(); recordstore.closeRecordStore(); if (RecordStore.listRecordStores() != null) { RecordStore.deleteRecordStore("myRecordStore"); filter.filterClose(); recordEnumeration.destroy(); } } catch (Exception error) { alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert); } } }
From source file:ReadWriteStreams.java
public void readStream() { try {//w ww.j a v a2 s. co m // Careful: Make sure this is big enough! // Better yet, test and reallocate if necessary byte[] recData = new byte[50]; // Read from the specified byte array ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData); // Read Java data types from the above byte array DataInputStream strmDataType = new DataInputStream(strmBytes); for (int i = 1; i <= rs.getNumRecords(); i++) { // Get data into the byte array rs.getRecord(i, recData, 0); // Read back the data types System.out.println("Record #" + i); System.out.println("UTF: " + strmDataType.readUTF()); System.out.println("Boolean: " + strmDataType.readBoolean()); System.out.println("Int: " + strmDataType.readInt()); System.out.println("--------------------"); // Reset so read starts at beginning of array strmBytes.reset(); } strmBytes.close(); strmDataType.close(); } catch (Exception e) { db(e.toString()); } }
From source file:org.apache.hadoop.yarn.server.resourcemanager.recovery.NDBRMStateStore.java
/** * Retrieve Delegation Tokens from NDB.//from w w w . ja v a2 s . co m * * @param rmState * @throws Exception */ private void loadRMDelegationTokenState(RMState rmState) throws Exception { //Retrieve all DelegatioTokenIds from NDB List<DelegationToken> delTokens = RMUtilities.getDelegationTokens(); if (delTokens != null) { for (DelegationToken hopDelToken : delTokens) { ByteArrayInputStream is = new ByteArrayInputStream(hopDelToken.getRmdtidentifier()); DataInputStream fsIn = new DataInputStream(is); try { RMDelegationTokenIdentifier identifier = new RMDelegationTokenIdentifier(); identifier.readFields(fsIn); long renewDate = fsIn.readLong(); rmState.rmSecretManagerState.delegationTokenState.put(identifier, renewDate); } finally { is.close(); } } } }
From source file:edu.unc.lib.dl.services.DigitalObjectManagerImpl.java
/** * Just removes object from container, does not log this event. MUST finish operation or dump rollback info and * rethrow exception.//from ww w . j a v a2 s .co m * * @param pid * the PID of the object to remove * @return the PID of the old container * @throws FedoraException */ private PID removeFromContainer(PID pid) throws FedoraException { boolean relsextDone = false; PID parent = this.getTripleStoreQueryService().fetchContainer(pid); if (parent == null) { // Block removal of repo object if (ContentModelHelper.Administrative_PID.REPOSITORY.getPID().equals(pid)) return null; throw new NotFoundException("Found an object without a parent that is not the REPOSITORY"); } log.debug("removeFromContainer called on PID: " + parent.getPid()); try { // remove ir:contains statement to RELS-EXT relsextDone = this.getManagementClient().purgeObjectRelationship(parent, ContentModelHelper.Relationship.contains.getURI().toString(), pid); if (relsextDone == false) { log.error("failed to purge relationship: " + parent + " contains " + pid); } // if the parent is a container, then make it orderly List<URI> cmtypes = this.getTripleStoreQueryService().lookupContentModels(parent); if (cmtypes.contains(ContentModelHelper.Model.CONTAINER.getURI())) { // edit Contents XML of parent container to append/insert try { Document newXML; Document oldXML; MIMETypedStream mts = this.getAccessClient().getDatastreamDissemination(parent, "MD_CONTENTS", null); ByteArrayInputStream bais = new ByteArrayInputStream(mts.getStream()); oldXML = new SAXBuilder().build(bais); bais.close(); newXML = ContainerContentsHelper.remove(oldXML, pid); this.getManagementClient().modifyInlineXMLDatastream(parent, "MD_CONTENTS", false, "removing child object from this container", new ArrayList<String>(), "List of Contents", newXML); } catch (NotFoundException e) { // MD_CONTENTS was not found, so we will assume this is an unordered container } } } catch (JDOMException e) { IllegalRepositoryStateException irs = new IllegalRepositoryStateException( "Invalid XML for container MD_CONTENTS: " + parent.getPid(), parent, e); log.error(irs); throw irs; } catch (IOException e) { throw new Error("Should not get IOException for reading byte array input", e); } return parent; }