Example usage for java.lang ThreadLocal set

List of usage examples for java.lang ThreadLocal set

Introduction

In this page you can find the example usage for java.lang ThreadLocal set.

Prototype

public void set(T value) 

Source Link

Document

Sets the current thread's copy of this thread-local variable to the specified value.

Usage

From source file:org.codice.alliance.transformer.nitf.image.NitfPreStoragePlugin.java

private BufferedImage renderImage(ContentItem contentItem)
        throws IOException, ParseException, NitfFormatException {

    final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>();

    if (contentItem != null && contentItem.getInputStream() != null) {
        NitfRenderer renderer = new NitfRenderer();

        new NitfParserInputFlow().inputStream(contentItem.getInputStream()).allData()
                .forEachImageSegment(segment -> {
                    if (bufferedImage.get() == null) {
                        try {
                            bufferedImage.set(renderer.render(segment));
                        } catch (IOException e) {
                            LOGGER.error(e.getMessage(), e);
                        }/*ww  w . ja  va2s . co m*/
                    }
                }).end();
    }

    return bufferedImage.get();
}

From source file:org.codice.alliance.transformer.nitf.NitfPreStoragePlugin.java

private BufferedImage renderImage(ContentItem contentItem)
        throws IOException, ParseException, NitfFormatException {

    final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>();

    if (contentItem != null && contentItem.getInputStream() != null) {
        NitfRenderer renderer = new NitfRenderer();

        new NitfParserInputFlow().inputStream(contentItem.getInputStream()).allData()
                .forEachImageSegment(segment -> {
                    if (bufferedImage.get() == null) {
                        try {
                            bufferedImage.set(renderer.render(segment));
                        } catch (IOException e) {
                            LOGGER.error(e.getMessage(), e);
                        }//  www  .j ava 2s .  com
                    }
                });
    }

    return bufferedImage.get();
}

From source file:net.netheos.pcsapi.oauth.PasswordSessionManager.java

private synchronized HttpContext getHttpContext(HttpHost host) {
    ThreadLocal<HttpContext> tlContext = cache.get(host);
    if (tlContext == null) {
        tlContext = new ThreadLocal<HttpContext>();
        cache.put(host, tlContext);/*w  w w  . j a v  a2  s .  c  om*/
    }
    HttpContext context = tlContext.get();
    if (context == null) {
        AuthScope scope = new AuthScope(host.getHostName(), host.getPort());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(scope, usernamePasswordCredentials);

        context = new BasicHttpContext();
        context.setAttribute(ClientContext.CREDS_PROVIDER, credentialsProvider);
        tlContext.set(context);
    }
    return context;
}

From source file:com.blackducksoftware.integration.hub.jenkins.gradle.GradleBuildWrapper.java

@Override
public Environment setUp(final AbstractBuild build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    // no failure to report yet
    final HubJenkinsLogger buildLogger = new HubJenkinsLogger(listener);
    buildLogger.setLogLevel(LogLevel.TRACE);
    Gradle gradleBuilder = null;//from w  w  w .j  ava  2  s.c  om
    if (build.getProject() instanceof FreeStyleProject) {
        // Project should always be a FreeStyleProject, thats why we have the isApplicable() method
        final List<Builder> builders = ((FreeStyleProject) build.getProject()).getBuilders();

        if (builders == null || builders.isEmpty()) {
            // User didn't configure the job with a Builder
            buildLogger.error("No Builder found for this job.");
            buildLogger.error("Will not run the Hub Gradle Build wrapper.");
            build.setResult(Result.UNSTABLE);
            return new Environment() {
            }; // Continue with the rest of the Build
        }

        for (final Builder builder : builders) {
            if (builder instanceof Gradle) {
                gradleBuilder = (Gradle) builder;
            }
        }
        if (gradleBuilder == null) {
            // User didn't configure the job with a Gradle Builder
            buildLogger.error("This Wrapper should be run with a Gradle Builder");
            buildLogger.error("Will not run the Hub Gradle Build wrapper.");
            build.setResult(Result.UNSTABLE);
            return new Environment() {
            }; // Continue with the rest of the Build
        }
    } else {
        buildLogger.error("Cannot run the Hub Gradle Build Wrapper for this type of Project.");
        build.setResult(Result.UNSTABLE);
        return new Environment() {
        }; // Continue with the rest of the Build
    }
    if (validateConfiguration(buildLogger)) {
        buildLogger.info("Build Recorder enabled");
        buildLogger.info("Hub Jenkins Plugin version : " + getDescriptor().getPluginVersion());

    } else {
        build.setResult(Result.UNSTABLE);
        return new Environment() {
        }; // Continue with the rest of the Build
    }

    final ThreadLocal<String> originalSwitches = new ThreadLocal<String>();
    final ThreadLocal<String> originalTasks = new ThreadLocal<String>();

    if (gradleBuilder != null) {

        originalSwitches.set(gradleBuilder.getSwitches() + "");
        originalTasks.set(gradleBuilder.getTasks() + "");

        final BDGradleInitScriptWriter writer = new BDGradleInitScriptWriter(build, buildLogger);
        final FilePath workspace = build.getWorkspace();
        FilePath initScript;
        String initScriptPath;
        try {
            if (workspace == null) {
                buildLogger.error("Workspace: null");
            } else {
                initScript = workspace.createTextTempFile("init-blackduck", "gradle",
                        writer.generateInitScript(), false);
                if (initScript != null) {
                    initScriptPath = initScript.getRemote();
                    initScriptPath = initScriptPath.replace('\\', '/');

                    String newSwitches = originalSwitches.get();
                    String newTasks = originalTasks.get();

                    if (!originalSwitches.get().contains("--init-script ")
                            && !originalSwitches.get().contains("init-blackduck")) {
                        newSwitches = newSwitches + " --init-script " + initScriptPath;
                    }
                    if (!originalSwitches.get().contains(" -D" + BDGradleUtil.BUILD_ID_PROPERTY)) {
                        newSwitches = newSwitches + " -D" + BDGradleUtil.BUILD_ID_PROPERTY + "="
                                + build.getId();
                    }
                    if (!originalSwitches.get()
                            .contains(" -D" + BDGradleUtil.INCLUDED_CONFIGURATIONS_PROPERTY)) {
                        String configurations = getUserScopesToInclude();
                        configurations = configurations.replaceAll(" ", "");

                        newSwitches = newSwitches + " -D" + BDGradleUtil.INCLUDED_CONFIGURATIONS_PROPERTY + "="
                                + configurations;
                    }
                    // // Following used to generate the dependency tree
                    // // written to a file
                    // if (!originalSwitches.get().contains(" -D" +
                    // BDGradleUtil.DEPENDENCY_REPORT_OUTPUT)) {
                    // FilePath dependencyTreeFile = new FilePath(workspace, "dependencyTree.txt");
                    // newSwitches = newSwitches + " -D" +
                    // BDGradleUtil.DEPENDENCY_REPORT_OUTPUT + "='" +
                    // dependencyTreeFile.getRemote() + "'";
                    // }

                    if (!originalTasks.get().contains("bdCustomTask")) {
                        newTasks = newTasks + " bdCustomTask";
                    }

                    if (!originalTasks.get().contains("bdDependencyTree")) {
                        newTasks = newTasks + " bdDependencyTree";
                    }
                    setField(gradleBuilder, "switches", newSwitches);
                    setField(gradleBuilder, "tasks", newTasks);
                }
            }
        } catch (final Exception e) {
            listener.getLogger().println("Error occurred while writing Gradle Init Script: " + e.getMessage());
            build.setResult(Result.FAILURE);
        }

    }

    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    boolean changed = false;
    try {
        if (GradleBuildWrapper.class.getClassLoader() != originalClassLoader) {
            changed = true;
            Thread.currentThread().setContextClassLoader(GradleBuildWrapper.class.getClassLoader());
        }
        return new Environment() {
            @Override
            public boolean tearDown(final AbstractBuild build, final BuildListener listener)
                    throws IOException, InterruptedException {
                final HubJenkinsLogger buildLogger = new HubJenkinsLogger(listener);
                Gradle gradleBuilder = null;
                try {
                    if (build.getProject() instanceof FreeStyleProject) {
                        // Project should always be a FreeStyleProject, thats why we have the isApplicable() method
                        final List<Builder> builders = ((FreeStyleProject) build.getProject()).getBuilders();

                        for (final Builder builder : builders) {
                            if (builder instanceof Gradle) {
                                gradleBuilder = (Gradle) builder;
                            }
                        }
                    }
                    if (gradleBuilder != null) {
                        String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();

                        if (StringUtils.startsWithIgnoreCase(rootBuildScriptDir, "${WORKSPACE}")
                                || StringUtils.startsWithIgnoreCase(rootBuildScriptDir, "$WORKSPACE")) {
                            final EnvVars variables = build.getEnvironment(listener);
                            rootBuildScriptDir = BuildHelper.handleVariableReplacement(variables,
                                    rootBuildScriptDir);
                        }

                        String fileSeparator = null;
                        try {
                            final VirtualChannel channel = build.getBuiltOn().getChannel();
                            if (channel == null) {
                                buildLogger.error("Channel build on: null");
                            } else {
                                fileSeparator = channel.call(new GetSeparator());
                            }
                        } catch (final IOException e) {
                            buildLogger.error(e.toString(), e);
                        } catch (final InterruptedException e) {
                            buildLogger.error(e.toString(), e);
                        }
                        if (StringUtils.isEmpty(fileSeparator)) {
                            fileSeparator = File.separator;
                        }

                        File workspaceFile = null;
                        if (build.getWorkspace() == null) {
                            // might be using custom workspace
                            workspaceFile = new File(build.getProject().getCustomWorkspace());
                        } else {
                            workspaceFile = new File(build.getWorkspace().getRemote());
                        }

                        String workingDirectory = "";
                        try {
                            workingDirectory = build.getBuiltOn().getChannel()
                                    .call(new GetCanonicalPath(workspaceFile));
                        } catch (final IOException e) {
                            buildLogger.error("Problem getting the working directory on this node. Error : "
                                    + e.getMessage(), e);
                        }

                        if (!StringUtils.startsWithIgnoreCase(rootBuildScriptDir, workingDirectory)) {
                            if (workingDirectory.endsWith(fileSeparator)) {
                                rootBuildScriptDir = workingDirectory + rootBuildScriptDir;
                            } else {
                                rootBuildScriptDir = workingDirectory + fileSeparator + rootBuildScriptDir;
                            }
                        }

                        FilePath buildInfo = null;
                        final Node buildOn = build.getBuiltOn();
                        if (buildOn == null) {
                            buildLogger.error("Node build on: null");
                        } else {
                            final VirtualChannel channel = buildOn.getChannel();
                            if (channel == null) {
                                buildLogger.error("Channel build on: null");
                            } else {
                                // buildInfoFile = new FilePath(channel, workspacePath);
                                buildInfo = new FilePath(channel, rootBuildScriptDir);
                                buildInfo = new FilePath(buildInfo, "build");
                                buildInfo = new FilePath(buildInfo, "BlackDuck");
                                buildInfo = new FilePath(buildInfo, BuildInfo.OUTPUT_FILE_NAME);

                            }
                        }

                        if (buildInfo != null) {

                            if (buildInfo.exists()) {
                                return universalTearDown(build, buildLogger, buildInfo, getDescriptor(),
                                        BuilderType.GRADLE);
                            } else {
                                buildLogger.error(
                                        "The " + BuildInfo.OUTPUT_FILE_NAME + " file does not exist at : "
                                                + buildInfo.getRemote() + ", on machine : "
                                                + (buildOn == null ? "null" : buildOn.getDisplayName()));
                                build.setResult(Result.UNSTABLE);
                                return true;
                            }
                        }
                        // }
                    } else {
                        buildLogger.error("[WARNING] no gradle build step found");
                        build.setResult(Result.UNSTABLE);
                        return true;
                    }
                } catch (final BDJenkinsHubPluginException e) {
                    buildLogger.error(e.getMessage(), e);
                    build.setResult(Result.UNSTABLE);
                    return true;
                } catch (final Exception e) {
                    buildLogger.error(e.getMessage(), e);
                    build.setResult(Result.UNSTABLE);
                    return true;
                } finally {
                    if (gradleBuilder != null) {
                        synchronized (this) {
                            try {
                                // restore the original configuration
                                setField(gradleBuilder, "switches", originalSwitches.get());
                                setField(gradleBuilder, "tasks", originalTasks.get());
                            } catch (final Exception e) {
                                buildLogger.error(e.getMessage(), e);
                                build.setResult(Result.UNSTABLE);
                                return true;
                            }
                        }
                    }
                }
                return true;
            }
        };
    } finally {
        if (changed) {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
    }
}

From source file:org.geowebcache.layer.TileLayer.java

protected ByteArrayResource getImageBuffer(ThreadLocal<ByteArrayResource> tl) {
    ByteArrayResource buffer = tl.get();
    if (buffer == null) {
        buffer = new ByteArrayResource(16 * 1024);
        tl.set(buffer);
    }//from   w  w  w  .java  2  s.co m
    buffer.truncate();
    return buffer;
}

From source file:org.codice.alliance.plugin.nitf.NitfPostIngestPlugin.java

private BufferedImage render(InputStream inputStream,
        Function<Pair<ImageSegment, NitfRenderer>, BufferedImage> imageSegmentFunction)
        throws NitfFormatException {

    final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>();

    if (inputStream != null) {
        NitfRenderer renderer = getNitfRenderer();
        nitfParserService.parseNitf(inputStream, true).forEachImageSegment(segment -> {
            if (bufferedImage.get() == null) {
                BufferedImage bi = imageSegmentFunction.apply(new ImmutablePair<>(segment, renderer));
                if (bi != null) {
                    bufferedImage.set(bi);
                }/*from   w ww .  ja  v a  2s .  co  m*/
            }
        }).end();
    }

    return bufferedImage.get();
}

From source file:ch.cyberduck.core.sftp.SFTPQuotaFeature.java

@Override
public Space get() throws BackgroundException {
    final ThreadLocal<Space> quota = new ThreadLocal<Space>() {
        @Override/*from  w  ww.j  a va 2  s  . c  o m*/
        protected Space initialValue() {
            return new Space(0L, Long.MAX_VALUE);
        }
    };
    final Path home = new SFTPHomeDirectoryService(session).find();
    new SFTPCommandFeature(session).send(String.format("df -Pk %s | awk '{print $3, $4}'", home.getAbsolute()),
            new DisabledProgressListener(), new TranscriptListener() {
                @Override
                public void log(final Type request, final String output) {
                    switch (request) {
                    case response:
                        final String[] numbers = StringUtils.split(output, ' ');
                        if (numbers.length == 2) {
                            try {
                                quota.set(new Space(Long.valueOf(numbers[0]) * 1000L,
                                        Long.valueOf(numbers[1]) * 1000L));
                            } catch (NumberFormatException e) {
                                log.warn(String.format("Ignore line %s", output));
                            }
                        } else {
                            log.warn(String.format("Ignore line %s", output));
                        }
                    }
                }
            });
    return quota.get();
}

From source file:org.codice.alliance.plugin.nitf.NitfPostProcessPlugin.java

private BufferedImage render(InputStream inputStream,
        Function<Pair<ImageSegment, NitfRenderer>, BufferedImage> imageSegmentFunction)
        throws InterruptedException, NitfFormatException {

    final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>();

    if (inputStream != null) {
        try {//www  . ja v  a2  s .c  o m
            available.acquire();
            NitfRenderer renderer = nitfRendererSupplier.get();
            NitfParserInputFlow parserInputFlow = nitfParserSupplier.get();

            parserInputFlow.inputStream(inputStream).allData().forEachImageSegment(segment -> {
                if (bufferedImage.get() == null) {
                    BufferedImage bi = imageSegmentFunction.apply(new ImmutablePair<>(segment, renderer));
                    if (bi != null) {
                        bufferedImage.set(bi);
                    }
                }
            }).end();
        } finally {
            IOUtils.closeQuietly(inputStream);
            available.release();
        }
    }

    BufferedImage image = bufferedImage.get();
    bufferedImage.remove();
    return image;
}

From source file:org.codice.alliance.plugin.nitf.NitfPreStoragePlugin.java

private BufferedImage render(ContentItem contentItem,
        Function<Pair<ImageSegment, NitfRenderer>, BufferedImage> imageSegmentFunction)
        throws IOException, ParseException, NitfFormatException {

    final ThreadLocal<BufferedImage> bufferedImage = new ThreadLocal<>();

    if (contentItem != null) {
        InputStream inputStream = contentItem.getInputStream();

        if (inputStream != null) {
            try {
                NitfRenderer renderer = getNitfRenderer();

                new NitfParserInputFlowImpl().inputStream(inputStream).allData()
                        .forEachImageSegment(segment -> {
                            if (bufferedImage.get() == null) {
                                BufferedImage bi = imageSegmentFunction
                                        .apply(new ImmutablePair<>(segment, renderer));
                                if (bi != null) {
                                    bufferedImage.set(bi);
                                }/*w w  w.  j av a 2 s .com*/
                            }
                        }).end();
            } finally {
                IOUtils.closeQuietly(inputStream);
            }
        }
    }

    return bufferedImage.get();
}

From source file:org.kaaproject.kaa.server.appenders.cassandra.appender.CassandraLogEventDao.java

private String formatTs(String tsValue, ColumnMappingElement element) {
    if (tsValue == null) {
        long ts = System.currentTimeMillis();
        final String pattern = element.getValue();
        if (pattern == null || pattern.isEmpty()) {
            tsValue = ts + "";
        } else {/*w  ww .  jav a 2s .  c  o m*/
            ThreadLocal<SimpleDateFormat> formatterTL = dateFormatMap.get(pattern);
            if (formatterTL == null) {
                formatterTL = new ThreadLocal<SimpleDateFormat>() {
                    @Override
                    protected SimpleDateFormat initialValue() {
                        return new SimpleDateFormat(pattern);
                    }
                };
                dateFormatMap.putIfAbsent(pattern, formatterTL);
            }
            SimpleDateFormat formatter = formatterTL.get();
            if (formatter == null) {
                formatter = new SimpleDateFormat(pattern);
                formatterTL.set(formatter);
            }
            tsValue = formatter.format(new Date(ts));
        }
    }
    return tsValue;
}