List of usage examples for java.io File deleteOnExit
public void deleteOnExit()
From source file:com.ebixio.virtmus.stats.StatsLogger.java
/** * Check for new versions of VirtMus./* w w w.j a v a 2 s . c o m*/ * @param installId The random ID identifying this install. * @param prevVersion The previous version of VirtMus installed. * @param statsEnabled Set to true if the user is participating in stats collection. */ private static void checkForNewVersion(long installId, String prevVersion, UploadStats statsEnabled) { final String urlStr = pref.get(Options.OptCheckVersionUrl, CHECK_VERSION); // Catch redirects. HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() { @Override public void handlePermanentRedirect(HttpRequest request, HttpResponse response, HttpUriRequest redirect) { if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(urlStr)) { pref.put(Options.OptCheckVersionUrl, newUrl); } } }; // TODO: Use http://wiki.fasterxml.com/JacksonHome to avoid warnings? String postData = new JSONStringer().object().key("version").value(MainApp.VERSION) /* installId MUST be sent as string since JS on the server side only has 64-bit float values and can't represent all long int values, leading to truncation of some digits since the JS float mantisa has only 53 bits (not 64). See: http://www.2ality.com/2012/07/large-integers.html */ .key("installId").value(String.valueOf(installId)).key("prevVersion").value(prevVersion) .key("statsEnabled").value(statsEnabled.name()).endObject().toString(); try { CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build(); HttpPost post = new HttpPost(urlStr); addHttpHeaders(post); StringEntity entity = new StringEntity(postData, ContentType.APPLICATION_JSON); post.setEntity(entity); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { // 200 if (statsEnabled == UploadStats.No) { // If the user doesn't want to participate, he probably doesn't // want to be checking for new releases either, so disable it. pref.putBoolean(Options.OptCheckVersion, false); } // This is used to notify the user that a newer version is available HttpEntity rspEntity = response.getEntity(); if (rspEntity != null && statsEnabled != UploadStats.No) { File f = File.createTempFile("VersionPost", "html"); f.deleteOnExit(); Files.copy(rspEntity.getContent(), f.toPath(), StandardCopyOption.REPLACE_EXISTING); if (f.length() > 0) { URL rspUrl = Utilities.toURI(f).toURL(); HtmlBrowser.URLDisplayer.getDefault().showURL(rspUrl); } } } else { Log.log(Level.INFO, "CheckVersion result: {0}", status); } } catch (MalformedURLException ex) { Log.log(ex); } catch (IOException ex) { Log.log(ex); } }
From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.core.util.FileUtils.java
/** * Make the given URL available as a file. A temporary file is created and * deleted upon a regular shutdown of the JVM. If the parameter {@code * aCache} is {@code true}, the temporary file is remembered in a cache and * if a file is requested for the same URL at a later time, the same file is * returned again. If the previously created file has been deleted * meanwhile, it is recreated from the URL. * * @param aUrl// w ww . ja v a 2 s .c om * the URL. * @param aCache * use the cache or not. * @return a file created from the given URL. * @throws IOException * if the URL cannot be accessed to (re)create the file. */ public static synchronized File getUrlAsFile(URL aUrl, boolean aCache) throws IOException { // If the URL already points to a file, there is not really much to do. if ("file".equals(aUrl.getProtocol())) { return new File(aUrl.getPath()); } // Lets see if we already have a file for this URL in our cache. Maybe // the file has been deleted meanwhile, so we also check if the file // actually still exists on disk. File file = urlFileCache.get(aUrl); if (!aCache || (file == null) || !file.exists()) { // Create a temporary file and try to preserve the file extension String suffix = ".temp"; String name = new File(aUrl.getPath()).getName(); int suffixSep = name.indexOf("."); if (suffixSep != -1) { suffix = name.substring(suffixSep + 1); name = name.substring(0, suffixSep); } // Get a temporary file which will be deleted when the JVM shuts // down. file = File.createTempFile(name, suffix); file.deleteOnExit(); // Now copy the file from the URL to the file. InputStream is = null; OutputStream os = null; try { is = aUrl.openStream(); os = new FileOutputStream(file); IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } // Remember the file if (aCache) { urlFileCache.put(aUrl, file); } } return file; }
From source file:it.marcoberri.mbfasturl.action.Commons.java
/** * /* ww w .j ava 2 s. c o m*/ * @param u * @param dimx * @param dimy * @return * @throws WriterException * @throws IOException */ public static String generateQrcode(Url u, int dimx, int dimy) throws WriterException, IOException { final String proxy = ConfigurationHelper.getProp().getProperty("url.proxy.domain", "http://mbfu.it/"); final GridFS fs = MongoConnectionHelper.getGridFS(); final QRCodeWriter writer = new QRCodeWriter(); final BitMatrix bitMatrix = writer.encode(proxy + "/" + u.getFast(), BarcodeFormat.QR_CODE, dimx, dimy); final File temp = File.createTempFile("tempfile" + System.currentTimeMillis(), ".tmp"); MatrixToImageWriter.writeToFile(bitMatrix, "gif", temp); final GridFSInputFile gfi = fs.createFile(temp); gfi.setFilename(u.getFast() + ".gif"); final BasicDBObject meta = new BasicDBObject(); meta.put("ref_url", u.getId()); meta.put("created", new Date()); gfi.setMetaData(meta); gfi.setContentType("image/gif"); gfi.save(); temp.deleteOnExit(); return gfi.getId().toString(); }
From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java
public static String getDocUploadResponse(RequestModel req, File uploadedFile) { req.getSession().newSigningInstance(DocTypeIdentifier.getDocType(uploadedFile)); SigDocumentType docType = DocTypeIdentifier.getDocType(uploadedFile); switch (docType) { case XML:// ww w . ja v a 2 s . c o m String xmlTest = XmlUtils.getParsedXMLText(uploadedFile); if (xmlTest.length() == 0) { return "Error"; } default: String response = getDocSelectResponse(uploadedFile, req); uploadedFile.deleteOnExit(); return response; } }
From source file:org.xmlactions.common.io.ResourceUtils.java
/** * Returns a tempory folder where tempory files can be stored. This folder * will be marked for deletion when system exits. If the system doesn;t exit * cleanly then the folder will not be deleted. The tempory folder is * created inside the user home//from w ww . ja va 2s . c om * * @param appendFolderName * is the folder to be created inside the tempory folder * location. */ public static File getTempFolder(String appendFolderName) { String folder = System.getProperty("user.home"); File file = new File(ResourceCommon.buildFileName(folder, appendFolderName)); file.mkdirs(); file.deleteOnExit(); return (file); }
From source file:brooklyn.util.os.Os.java
public static File writePropertiesToTempFile(Properties props, File tempDir, String prefix, String suffix) { Preconditions.checkNotNull(props, "Properties required to create temp file for %s*%s", prefix, suffix); File tempFile; try {//w w w. j av a 2 s . co m tempFile = File.createTempFile(prefix, suffix, tempDir); } catch (IOException e) { throw Throwables.propagate(e); } tempFile.deleteOnExit(); OutputStream out = null; try { out = new FileOutputStream(tempFile); props.store(out, "Auto-generated by Brooklyn"); } catch (IOException e) { throw Throwables.propagate(e); } finally { Streams.closeQuietly(out); } return tempFile; }
From source file:eu.stratosphere.core.testing.GenericTestPlan.java
private static String createTemporaryFile(final String suffix, final String prefix) { try {//from w ww.j a v a2 s . com final File tempFile = File.createTempFile(suffix, prefix); tempFile.deleteOnExit(); return tempFile.toURI().toString(); } catch (final IOException e) { throw new IllegalStateException("Cannot create temporary file for prefix " + prefix, e); } }
From source file:eu.trentorise.opendata.josman.Josmans.java
/** * Fetches Javadoc of released artifact and writes it into {@code destFile} * //w ww. j av a 2 s . c om */ public static File fetchJavadoc(String groupId, String artifactId, SemVersion version) { checkNotEmpty(groupId, "Invalid groupId!"); checkNotEmpty(artifactId, "Invalid artifactId!"); checkNotNull(version); File destFile; try { destFile = File.createTempFile(groupId + "-" + artifactId + "-javadoc", ".jar"); destFile.deleteOnExit(); } catch (IOException ex) { throw new RuntimeException("Couldn't create target javadoc file!", ex); } URL url; try { url = new URL("http://repo1.maven.org/maven2/" + groupId.replace(".", "/") + "/" + artifactId + "/" + version + "/" + javadocJarName(artifactId, version)); } catch (MalformedURLException ex) { throw new RuntimeException("Error while forming javadoc URL!", ex); } LOG.log(Level.INFO, "Fetching javadoc from {0} into {1} ...", new Object[] { url, destFile.getAbsolutePath() }); try { FileUtils.copyURLToFile(url, destFile, CONNECTION_TIMEOUT, CONNECTION_TIMEOUT); LOG.log(Level.INFO, "Done copying javadoc."); } catch (IOException ex) { throw new RuntimeException("Error while fetch-and-write javadoc for " + groupId + "/" + artifactId + "-" + version + " into file " + destFile.getAbsoluteFile(), ex); } return destFile; }
From source file:com.microsoft.azure.management.compute.samples.DeployImageFromContainerRegistryToKubernetes.java
/** * Main function which runs the actual sample. * * @param azure instance of the azure client * @param clientId secondary service principal client ID * @param secret secondary service principal secret * @return true if sample runs successfully *//* w ww . j a va2 s. c o m*/ public static boolean runSample(Azure azure, String clientId, String secret) { final String rgName = SdkContext.randomResourceName("rgACR", 15); final String acrName = SdkContext.randomResourceName("acrsample", 20); final String saName = SdkContext.randomResourceName("sa", 20); final String acsName = SdkContext.randomResourceName("acssample", 30); final String rootUserName = "acsuser"; final Region region = Region.US_EAST; final String dockerImageName = "nginx"; final String dockerImageTag = "latest"; final String dockerContainerName = "acrsample-nginx"; String acsSecretName = "mysecret112233"; String acsNamespace = "acrsample"; String acsLbIngressName = "lb-acrsample"; String servicePrincipalClientId = clientId; // replace with a real service principal client id String servicePrincipalSecret = secret; // and corresponding secret SSHShell shell = null; try { //============================================================= // If service principal client id and secret are not set via the local variables, attempt to read the service // principal client id and secret from a secondary ".azureauth" file set through an environment variable. // // If the environment variable was not set then reuse the main service principal set for running this sample. if (servicePrincipalClientId.isEmpty() || servicePrincipalSecret.isEmpty()) { String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); } servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal); } //============================================================= // Create an SSH private/public key pair to be used when creating the container service System.out.println("Creating an SSH private and public key pair"); SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS"); System.out.println("SSH private key value: \n" + sshKeys.getSshPrivateKey()); System.out.println("SSH public key value: \n" + sshKeys.getSshPublicKey()); //============================================================= // Create an Azure Container Service with Kubernetes orchestration System.out.println( "Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)"); Date t1 = new Date(); ContainerService azureContainerService = azure.containerServices().define(acsName).withRegion(region) .withNewResourceGroup(rgName).withKubernetesOrchestration() .withServicePrincipal(servicePrincipalClientId, servicePrincipalSecret).withLinux() .withRootUsername(rootUserName).withSshKey(sshKeys.getSshPublicKey()) .withMasterNodeCount(ContainerServiceMasterProfileCount.MIN) .withMasterLeafDomainLabel("dns-" + acsName).defineAgentPool("agentpool").withVMCount(1) .withVMSize(ContainerServiceVMSizeTypes.STANDARD_D1_V2).withLeafDomainLabel("dns-ap-" + acsName) .attach().create(); Date t2 = new Date(); System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureContainerService.id()); Utils.print(azureContainerService); //============================================================= // Create an Azure Container Registry to store and manage private Docker container images System.out.println("Creating an Azure Container Registry"); t1 = new Date(); Registry azureRegistry = azure.containerRegistries().define(acrName).withRegion(region) .withNewResourceGroup(rgName).withNewStorageAccount(saName).withRegistryNameAsAdminUser() .create(); t2 = new Date(); System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); Utils.print(azureRegistry); //============================================================= // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry RegistryListCredentials acrCredentials = azureRegistry.listCredentials(); DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region, azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.passwords().get(0).value()); //============================================================= // Pull a temp image from public Docker repo and create a temporary container from that image // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR dockerClient.pullImageCmd(dockerImageName).withTag(dockerImageTag).exec(new PullImageResultCallback()) .awaitSuccess(); System.out.println("List local Docker images:"); List<Image> images = dockerClient.listImagesCmd().withShowAll(true).exec(); for (Image image : images) { System.out.format("\tFound Docker image %s (%s)\n", image.getRepoTags()[0], image.getId()); } CreateContainerResponse dockerContainerInstance = dockerClient .createContainerCmd(dockerImageName + ":" + dockerImageTag).withName(dockerContainerName) .withCmd("/hello").exec(); System.out.println("List Docker containers:"); List<Container> dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)\n", container.getImage(), container.getId()); } //============================================================= // Commit the new container String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; String dockerImageId = dockerClient.commitCmd(dockerContainerInstance.getId()) .withRepository(privateRepoUrl).withTag("latest").exec(); // We can now remove the temporary container instance dockerClient.removeContainerCmd(dockerContainerInstance.getId()).withForce(true).exec(); //============================================================= // Push the new Docker image to the Azure Container Registry dockerClient.pushImageCmd(privateRepoUrl).withAuthConfig(dockerClient.authConfig()) .exec(new PushImageResultCallback()).awaitSuccess(); // Remove the temp image from the local Docker host try { dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); } catch (NotFoundException e) { // just ignore if not exist } //============================================================= // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally dockerClient.pullImageCmd(privateRepoUrl).withAuthConfig(dockerClient.authConfig()) .exec(new PullImageResultCallback()).awaitSuccess(); System.out.println( "List local Docker images after pulling sample image from the Azure Container Registry:"); images = dockerClient.listImagesCmd().withShowAll(true).exec(); for (Image image : images) { System.out.format("\tFound Docker image %s (%s)\n", image.getRepoTags()[0], image.getId()); } dockerContainerInstance = dockerClient.createContainerCmd(privateRepoUrl) .withName(dockerContainerName + "-private").withCmd("/hello").exec(); System.out.println( "List Docker containers after instantiating container from the Azure Container Registry sample image:"); dockerContainers = dockerClient.listContainersCmd().withShowAll(true).exec(); for (Container container : dockerContainers) { System.out.format("\tFound Docker container %s (%s)\n", container.getImage(), container.getId()); } //============================================================= // Download the Kubernetes config file from one of the master virtual machines azureContainerService = azure.containerServices().getByResourceGroup(rgName, acsName); System.out.println("Found Kubernetes master at: " + azureContainerService.masterFqdn()); shell = SSHShell.open(azureContainerService.masterFqdn(), 22, rootUserName, sshKeys.getSshPrivateKey().getBytes()); String kubeConfigContent = shell.download("config", ".kube", true); System.out.println("Found Kubernetes config:\n" + kubeConfigContent); //============================================================= // Instantiate the Kubernetes client using the downloaded ".kube/config" file content // The Kubernetes client API requires setting an environment variable pointing at a real file; // we will create a temporary file that will be deleted automatically when the sample exits File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); tempKubeConfigFile.deleteOnExit(); BufferedWriter buffOut = new BufferedWriter(new FileWriter(tempKubeConfigFile)); buffOut.write(kubeConfigContent); buffOut.close(); System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath()); Config config = new Config(); KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); //============================================================= // List all the nodes available in the Kubernetes cluster System.out.println(kubernetesClient.nodes().list()); //============================================================= // Create a namespace where all the sample Kubernetes resources will be created Namespace ns = new NamespaceBuilder().withNewMetadata().withName(acsNamespace) .addToLabels("acr", "sample").endMetadata().build(); try { System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); } catch (Exception ignored) { } Thread.sleep(5000); for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) { System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); } //============================================================= // Create a secret of type "docker-repository" that will be used for downloading the container image from // our Azure private container repo String basicAuth = new String(Base64.encodeBase64( (acrCredentials.username() + ":" + acrCredentials.passwords().get(0).value()).getBytes())); HashMap<String, String> secretData = new HashMap<>(1); String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", azureRegistry.loginServerUrl(), basicAuth, "acrsample@azure.com"); dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); secretData.put(".dockercfg", dockerCfg); SecretBuilder secretBuilder = new SecretBuilder().withNewMetadata().withName(acsSecretName) .withNamespace(acsNamespace).endMetadata().withData(secretData) .withType("kubernetes.io/dockercfg"); System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build())); Thread.sleep(5000); for (Secret kubeS : kubernetesClient.secrets().inNamespace(acsNamespace).list().getItems()) { System.out.println("\tFound secret: " + kubeS); } //============================================================= // Create a replication controller for our image stored in the Azure Container Registry ReplicationController rc = new ReplicationControllerBuilder().withNewMetadata().withName("acrsample-rc") .withNamespace(acsNamespace).addToLabels("acrsample-nginx", "nginx").endMetadata().withNewSpec() .withReplicas(2).withNewTemplate().withNewMetadata().addToLabels("acrsample-nginx", "nginx") .endMetadata().withNewSpec().addNewImagePullSecret(acsSecretName).addNewContainer() .withName("acrsample-pod-nginx").withImage(privateRepoUrl).addNewPort().withContainerPort(80) .endPort().endContainer().endSpec().endTemplate().endSpec().build(); System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc)); Thread.sleep(5000); rc = kubernetesClient.replicationControllers().inNamespace(acsNamespace).withName("acrsample-rc").get(); System.out.println("Found replication controller: " + rc.toString()); for (Pod pod : kubernetesClient.pods().inNamespace(acsNamespace).list().getItems()) { System.out.println("\tFound Kubernetes pods: " + pod.toString()); } //============================================================= // Create a Load Balancer service that will expose the service to the world Service lbService = new ServiceBuilder().withNewMetadata().withName(acsLbIngressName) .withNamespace(acsNamespace).endMetadata().withNewSpec().withType("LoadBalancer").addNewPort() .withPort(80).withProtocol("TCP").endPort().addToSelector("acrsample-nginx", "nginx").endSpec() .build(); System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(acsNamespace).create(lbService)); Thread.sleep(5000); System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get()); //============================================================= // Wait until the external IP becomes available int timeout = 30 * 60 * 1000; // 30 minutes String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"; while (timeout > 0) { try { List<LoadBalancerIngress> lbIngressList = kubernetesClient.services().inNamespace(acsNamespace) .withName(acsLbIngressName).get().getStatus().getLoadBalancer().getIngress(); if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { System.out.println("\tFound ingress IP: " + lbIngressList.get(0).getIp()); timeout = 0; } } catch (Exception ignored) { } if (timeout > 0) { timeout -= 30000; // 30 seconds Thread.sleep(30000); } } // Clean-up kubernetesClient.namespaces().delete(ns); shell.close(); shell = null; return true; } catch (Exception f) { System.out.println(f.getMessage()); f.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); if (shell != null) { shell.close(); } } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; }
From source file:edu.byu.softwareDist.manager.impl.SendEmailImpl.java
private static File saveTemplateToDisk(final FileSet fileSet) { File f = null; PrintStream out = null;//from w ww.j av a 2 s .com try { f = File.createTempFile("software-distribution-email-content." + fileSet.getFileSetId() + "-", ".vm"); out = new PrintStream(new FileOutputStream(f)); out.print(fileSet.getEmailContent()); out.flush(); return f; } catch (IOException e) { LOG.error("Error writing template to temporary file.", e); return null; } finally { if (f != null) { f.deleteOnExit(); } if (out != null) { out.close(); } } }