List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile
public static void writeByteArrayToFile(File file, byte[] data) throws IOException
From source file:org.apache.geode.management.internal.cli.commands.ExportImportClusterConfigurationCommands.java
@CliCommand(value = { CliStrings.IMPORT_SHARED_CONFIG }, help = CliStrings.IMPORT_SHARED_CONFIG__HELP) @CliMetaData(interceptor = "org.apache.geode.management.internal.cli.commands.ExportImportClusterConfigurationCommands$ImportInterceptor", relatedTopic = { CliStrings.TOPIC_GEODE_CONFIG }) @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE) @SuppressWarnings("unchecked") public Result importSharedConfig(@CliOption(key = { CliStrings.IMPORT_SHARED_CONFIG__ZIP }, mandatory = true, help = CliStrings.IMPORT_SHARED_CONFIG__ZIP__HELP) String zip) { InternalLocator locator = InternalLocator.getLocator(); if (!locator.isSharedConfigurationRunning()) { ErrorResultData errorData = ResultBuilder.createErrorResultData(); errorData.addLine(CliStrings.SHARED_CONFIGURATION_NOT_STARTED); return ResultBuilder.buildResult(errorData); }// w w w. j a va 2 s. c o m GemFireCacheImpl cache = GemFireCacheImpl.getInstance(); Set<DistributedMember> servers = CliUtil.getAllNormalMembers(cache); Set<String> regionsWithData = servers.stream().map(this::getNonEmptyRegionsOnServer) .flatMap(Collection::stream).collect(toSet()); if (!regionsWithData.isEmpty()) { return ResultBuilder .createGemFireErrorResult("Cannot import cluster configuration with existing data in regions: " + regionsWithData.stream().collect(joining(","))); } byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell(); String zipFileName = CliUtil.bytesToNames(shellBytesData)[0]; byte[] zipBytes = CliUtil.bytesToData(shellBytesData)[0]; Result result; InfoResultData infoData = ResultBuilder.createInfoResultData(); File zipFile = new File(zipFileName); try { ClusterConfigurationService sc = locator.getSharedConfiguration(); // backup the old config for (Configuration config : sc.getEntireConfiguration().values()) { sc.writeConfigToFile(config); } sc.renameExistingSharedConfigDirectory(); FileUtils.writeByteArrayToFile(zipFile, zipBytes); ZipUtils.unzip(zipFileName, sc.getSharedConfigurationDirPath()); // load it from the disk sc.loadSharedConfigurationFromDisk(); infoData.addLine(CliStrings.IMPORT_SHARED_CONFIG__SUCCESS__MSG); } catch (Exception e) { ErrorResultData errorData = ResultBuilder.createErrorResultData(); errorData.addLine("Import failed"); logSevere(e); result = ResultBuilder.buildResult(errorData); // if import is unsuccessful, don't need to bounce the server. return result; } finally { FileUtils.deleteQuietly(zipFile); } // Bounce the cache of each member Set<CliFunctionResult> functionResults = servers.stream().map(this::reCreateCache).collect(toSet()); for (CliFunctionResult functionResult : functionResults) { if (functionResult.isSuccessful()) { infoData.addLine("Successfully applied the imported cluster configuration on " + functionResult.getMemberIdOrName()); } else { infoData.addLine("Failed to apply the imported cluster configuration on " + functionResult.getMemberIdOrName() + " due to " + functionResult.getMessage()); } } result = ResultBuilder.buildResult(infoData); return result; }
From source file:org.apache.geode.management.internal.cli.functions.ImportSharedConfigurationArtifactsFunction.java
@Override public void execute(FunctionContext context) { Object[] args = (Object[]) context.getArguments(); String zipFileName = (String) args[0]; byte[] zipFileData = (byte[]) args[1]; InternalLocator locator = InternalLocator.getLocator(); String memberName = locator.getDistributedSystem().getName(); if (locator.isSharedConfigurationRunning()) { File zippedSharedConfiguration = new File(zipFileName); try {// w w w.j av a 2 s .c o m SharedConfiguration sc = locator.getSharedConfiguration(); sc.renameExistingSharedConfigDirectory(); sc.clearSharedConfiguration(); FileUtils.writeByteArrayToFile(zippedSharedConfiguration, zipFileData); ZipUtils.unzip(zipFileName, sc.getSharedConfigurationDirPath()); CliFunctionResult cliFunctionResult = new CliFunctionResult(memberName, true, CliStrings.IMPORT_SHARED_CONFIG__ARTIFACTS__COPIED); context.getResultSender().lastResult(cliFunctionResult); } catch (Exception e) { CliFunctionResult result = new CliFunctionResult(memberName, e, CliUtil.stackTraceAsString(e)); context.getResultSender().lastResult(result); } finally { FileUtils.deleteQuietly(zippedSharedConfiguration); } } else { CliFunctionResult cliFunctionResult = new CliFunctionResult(memberName, false, CliStrings.SHARED_CONFIGURATION_NOT_STARTED); context.getResultSender().lastResult(cliFunctionResult); } }
From source file:org.apache.geode.management.internal.configuration.ClusterConfigurationServiceEndToEndDUnitTest.java
private void createAsyncEventQueue(final String queueName) throws IOException { String queueCommandsJarName = "testEndToEndSC-QueueCommands.jar"; final File jarFile = new File(queueCommandsJarName); try {//from w w w.java 2 s .co m ClassBuilder classBuilder = new ClassBuilder(); byte[] jarBytes = classBuilder.createJarFromClassContent("com/qcdunit/QueueCommandsDUnitTestListener", "package com.qcdunit;" + "import java.util.List; import java.util.Properties;" + "import org.apache.geode.internal.cache.xmlcache.Declarable2; import org.apache.geode.cache.asyncqueue.AsyncEvent;" + "import org.apache.geode.cache.asyncqueue.AsyncEventListener;" + "public class QueueCommandsDUnitTestListener implements Declarable2, AsyncEventListener {" + "Properties props;" + "public boolean processEvents(List<AsyncEvent> events) { return true; }" + "public void close() {}" + "public void init(final Properties props) {this.props = props;}" + "public Properties getConfig() {return this.props;}}"); FileUtils.writeByteArrayToFile(jarFile, jarBytes); CommandStringBuilder csb = new CommandStringBuilder(CliStrings.DEPLOY); csb.addOption(CliStrings.DEPLOY__JAR, queueCommandsJarName); executeAndVerifyCommand(csb.getCommandString()); csb = new CommandStringBuilder(CliStrings.CREATE_ASYNC_EVENT_QUEUE); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, queueName); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER, "com.qcdunit.QueueCommandsDUnitTestListener"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE, "100"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL, "200"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS, "4"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION, "true"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS, "true"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY, "false"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY, "1000"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY, OrderPolicy.KEY.toString()); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT, "true"); csb.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL, "true"); executeAndVerifyCommand(csb.getCommandString()); } finally { FileUtils.deleteQuietly(jarFile); } }
From source file:org.apache.hadoop.util.TestShell.java
/** * Touch a file; creating parent dirs on demand. * @param path path of file/*from www . j a v a 2 s . co m*/ * @return the file created * @throws IOException on any failure to write */ private File touch(File path) throws IOException { path.getParentFile().mkdirs(); FileUtils.writeByteArrayToFile(path, new byte[] {}); return path; }
From source file:org.apache.jackrabbit.core.data.db.ResettableTempFileInputStreamTest.java
private File createTemporaryFileWithContents(byte[] data) throws IOException { final File tmp = File.createTempFile("test", ".bin"); FileUtils.writeByteArrayToFile(tmp, data); return tmp;/* w ww. j a v a 2s .c om*/ }
From source file:org.apache.jackrabbit.core.data.FileDataStore.java
@Override protected byte[] getOrCreateReferenceKey() throws DataStoreException { File file = new File(directory, "reference.key"); try {/* w w w . j a v a 2s . c o m*/ if (file.exists()) { return FileUtils.readFileToByteArray(file); } else { byte[] key = super.getOrCreateReferenceKey(); FileUtils.writeByteArrayToFile(file, key); return key; } } catch (IOException e) { throw new DataStoreException("Unable to access reference key file " + file.getPath(), e); } }
From source file:org.apache.jackrabbit.oak.plugins.segment.ExternalBlobIT.java
private FileBlob getFileBlob() throws IOException { if (fileBlob == null) { File file = folder.newFile(); byte[] data = new byte[2345]; new Random().nextBytes(data); FileUtils.writeByteArrayToFile(file, data); fileBlob = new FileBlob(file.getPath()); }/*from w w w. ja v a2 s .c o m*/ return fileBlob; }
From source file:org.apache.jmeter.protocol.amf.proxy.AmfRequestHdr.java
private void populateSampler(Map<String, String> pageEncodings, Map<String, String> formEncodings, boolean amf) throws MalformedURLException, UnsupportedEncodingException { sampler.setDomain(serverName());//from w w w. ja v a 2 s . c om if (log.isDebugEnabled()) { log.debug("Proxy: setting server: " + sampler.getDomain()); } sampler.setMethod(method); log.debug("Proxy: setting method: " + sampler.getMethod()); sampler.setPort(serverPort()); if (log.isDebugEnabled()) { log.debug("Proxy: setting port: " + sampler.getPort()); } if (url.indexOf("//") > -1) { String protocol = url.substring(0, url.indexOf(":")); if (log.isDebugEnabled()) { log.debug("Proxy: setting protocol to : " + protocol); } sampler.setProtocol(protocol); } else if (sampler.getPort() == HTTPConstants.DEFAULT_HTTPS_PORT) { sampler.setProtocol(HTTPS); if (log.isDebugEnabled()) { log.debug("Proxy: setting protocol to https"); } } else { if (log.isDebugEnabled()) { log.debug("Proxy setting default protocol to: http"); } sampler.setProtocol(HTTP); } URL pageUrl = null; if (sampler.isProtocolDefaultPort()) { pageUrl = new URL(sampler.getProtocol(), sampler.getDomain(), getPath()); } else { pageUrl = new URL(sampler.getProtocol(), sampler.getDomain(), sampler.getPort(), getPath()); } String urlWithoutQuery = getUrlWithoutQuery(pageUrl); // Check if the request itself tells us what the encoding is String contentEncoding = null; String requestContentEncoding = ConversionUtils.getEncodingFromContentType(getContentType()); if (requestContentEncoding != null) { contentEncoding = requestContentEncoding; } else { // Check if we know the encoding of the page if (pageEncodings != null) { synchronized (pageEncodings) { contentEncoding = pageEncodings.get(urlWithoutQuery); } } // Check if we know the encoding of the form if (formEncodings != null) { synchronized (formEncodings) { String formEncoding = formEncodings.get(urlWithoutQuery); // Form encoding has priority over page encoding if (formEncoding != null) { contentEncoding = formEncoding; } } } } // Get the post data using the content encoding of the request String postData = null; if (log.isDebugEnabled()) { if (contentEncoding != null) { log.debug("Using encoding " + contentEncoding + " for request body"); } else { log.debug("No encoding found, using JRE default encoding for request body"); } } if (contentEncoding != null) { postData = new String(rawPostData, contentEncoding); } else { // Use default encoding postData = new String(rawPostData); } if (contentEncoding != null) { sampler.setPath(getPath(), contentEncoding); } else { // Although the spec says UTF-8 should be used for encoding URL parameters, // most browser use ISO-8859-1 for default if encoding is not known. // We use null for contentEncoding, then the url parameters will be added // with the value in the URL, and the "encode?" flag set to false sampler.setPath(getPath(), null); } if (log.isDebugEnabled()) { log.debug("Proxy: setting path: " + sampler.getPath()); } if (!HTTPConstants.CONNECT.equals(getMethod()) && numberRequests) { requestNumber++; sampler.setName(requestNumber + " " + sampler.getPath()); } else { sampler.setName(sampler.getPath()); } // Set the content encoding if (contentEncoding != null) { sampler.setContentEncoding(contentEncoding); } // If it was a HTTP GET request, then all parameters in the URL // has been handled by the sampler.setPath above, so we just need // to do parse the rest of the request if it is not a GET request if ((!HTTPConstants.CONNECT.equals(getMethod())) && (!HTTPConstants.GET.equals(method))) { // Check if it was a multipart http post request final String contentType = getContentType(); MultipartUrlConfig urlConfig = getMultipartConfig(contentType); if (urlConfig != null) { urlConfig.parseArguments(postData); // Tell the sampler to do a multipart post sampler.setDoMultipartPost(true); // Remove the header for content-type and content-length, since // those values will most likely be incorrect when the sampler // performs the multipart request, because the boundary string // will change getHeaderManager().removeHeaderNamed(CONTENT_TYPE); getHeaderManager().removeHeaderNamed(CONTENT_LENGTH); // Set the form data sampler.setArguments(urlConfig.getArguments()); // Set the file uploads sampler.setHTTPFiles(urlConfig.getHTTPFileArgs().asArray()); // used when postData is pure xml (eg. an xml-rpc call) or for PUT } else if (postData.trim().startsWith("<?") || "PUT".equals(sampler.getMethod())) { sampler.addNonEncodedArgument("", postData, ""); } else if (contentType == null || contentType.startsWith(HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED)) { // It is the most common post request, with parameter name and values // We also assume this if no content type is present, to be most backwards compatible, // but maybe we should only parse arguments if the content type is as expected sampler.parseArguments(postData.trim(), contentEncoding); //standard name=value postData } else if (postData.length() > 0) { if (amf) { // If AMF, try to process the request and store it if (postData != null && postData.length() > 0) { String xml = AmfXmlConverter.convertAmfMessageToXml(rawPostData); sampler.setProperty(AmfRequest.AMFXML, xml); ((AmfRequest) sampler).RawAMF = rawPostData; } } else if (isBinaryContent(contentType)) { try { File tempDir = new File(binaryDirectory); File out = File.createTempFile(method, binaryFileSuffix, tempDir); FileUtils.writeByteArrayToFile(out, rawPostData); HTTPFileArg[] files = { new HTTPFileArg(out.getPath(), "", contentType) }; sampler.setHTTPFiles(files); } catch (IOException e) { log.warn("Could not create binary file: " + e); } } else { // Just put the whole postbody as the value of a parameter sampler.addNonEncodedArgument("", postData, ""); //used when postData is pure xml (ex. an xml-rpc call) } } } if (log.isDebugEnabled()) { log.debug("sampler path = " + sampler.getPath()); } }
From source file:org.apache.jmeter.protocol.http.proxy.DefaultSamplerCreatorClassifier.java
/** * Compute sampler informations from Request Header * // w w w . ja va 2 s . c o m * @param sampler * {@link HTTPSamplerBase} * @param request * {@link HttpRequestHdr} * @throws Exception */ protected void computeFromPostBody(HTTPSamplerBaseClassifier sampler, HttpRequestHdrClassifier request) throws Exception { // If it was a HTTP GET request, then all parameters in the URL // has been handled by the sampler.setPath above, so we just need // to do parse the rest of the request if it is not a GET request if ((!HTTPConstants.CONNECT.equals(request.getMethod())) && (!HTTPConstants.GET.equals(request.getMethod()))) { // Check if it was a multipart http post request final String contentType = request.getContentType(); MultipartUrlConfig urlConfig = request.getMultipartConfig(contentType); String contentEncoding = sampler.getContentEncoding(); // Get the post data using the content encoding of the request String postData = null; if (log.isDebugEnabled()) { if (!StringUtils.isEmpty(contentEncoding)) { log.debug("Using encoding " + contentEncoding + " for request body"); } else { log.debug("No encoding found, using JRE default encoding for request body"); } } if (!StringUtils.isEmpty(contentEncoding)) { postData = new String(request.getRawPostData(), contentEncoding); } else { // Use default encoding postData = new String(request.getRawPostData(), PostWriter.ENCODING); } if (urlConfig != null) { urlConfig.parseArguments(postData); // Tell the sampler to do a multipart post sampler.setDoMultipartPost(true); // Remove the header for content-type and content-length, since // those values will most likely be incorrect when the sampler // performs the multipart request, because the boundary string // will change request.getHeaderManager().removeHeaderNamed(HttpRequestHdr.CONTENT_TYPE); request.getHeaderManager().removeHeaderNamed(HttpRequestHdr.CONTENT_LENGTH); // Set the form data sampler.setArguments(urlConfig.getArguments()); // Set the file uploads sampler.setHTTPFiles(urlConfig.getHTTPFileArgs().asArray()); // used when postData is pure xml (eg. an xml-rpc call) or for // PUT } else if (postData.trim().startsWith("<?") || HTTPConstants.PUT.equals(sampler.getMethod()) || isPotentialXml(postData)) { sampler.addNonEncodedArgument("", postData, ""); } else if (contentType == null || (contentType.startsWith(HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED) && !isBinaryContent(contentType))) { // It is the most common post request, with parameter name and // values // We also assume this if no content type is present, to be most // backwards compatible, // but maybe we should only parse arguments if the content type // is as expected sampler.parseArguments(postData.trim(), contentEncoding); // standard // name=value // postData } else if (postData.length() > 0) { if (isBinaryContent(contentType)) { try { File tempDir = new File(getBinaryDirectory()); File out = File.createTempFile(request.getMethod(), getBinaryFileSuffix(), tempDir); FileUtils.writeByteArrayToFile(out, request.getRawPostData()); HTTPFileArg[] files = { new HTTPFileArg(out.getPath(), "", contentType) }; sampler.setHTTPFiles(files); } catch (IOException e) { log.warn("Could not create binary file: " + e); } } else { // Just put the whole postbody as the value of a parameter sampler.addNonEncodedArgument("", postData, ""); // used // when // postData // is // pure // xml // (ex. // an // xml-rpc // call) } } } }
From source file:org.apache.log4j.util.SerializationTestHelper.java
/** * Asserts the serialized form of an object. * * @param witness file name of expected serialization. * @param actual byte array of actual serialization. * @param skip positions to skip comparison. * @param endCompare position to stop comparison. * @throws IOException thrown on IO or serialization exception. *///w w w . j a v a 2 s . c o m public static void assertStreamEquals(final String witness, final byte[] actual, final int[] skip, final int endCompare) throws IOException { final File witnessFile = new File(witness); if (witnessFile.exists()) { int skipIndex = 0; final byte[] expected = FileUtils.readFileToByteArray(witnessFile); final int bytesRead = expected.length; if (bytesRead < endCompare) { assertEquals(bytesRead, actual.length); } int endScan = actual.length; if (endScan > endCompare) { endScan = endCompare; } for (int i = 0; i < endScan; i++) { if ((skipIndex < skip.length) && (skip[skipIndex] == i)) { skipIndex++; } else { if (expected[i] != actual[i]) { assertEquals("Difference at offset " + i, expected[i], actual[i]); } } } } else { // // if the file doesn't exist then // assume that we are setting up and need to write it FileUtils.writeByteArrayToFile(witnessFile, actual); fail("Writing witness file " + witness); } }