Example usage for java.util.concurrent.atomic AtomicReference AtomicReference

List of usage examples for java.util.concurrent.atomic AtomicReference AtomicReference

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference AtomicReference.

Prototype

public AtomicReference(V initialValue) 

Source Link

Document

Creates a new AtomicReference with the given initial value.

Usage

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;//from w  ww.  j  av  a 2s.co  m
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:com.dgtlrepublic.anitomyj.AnitomyJ.java

/**
 * Parses an anime {@code filename} into its constituent elements.
 *
 * @param filename the anime file name//  w  w w .  ja va  2  s . co  m
 * @return the list of parsed elements
 */
public static List<Element> parse(String filename) {
    Options options = new Options();
    List<Element> elements = new ArrayList<>(32);
    List<Token> tokens = new ArrayList<>();

    /** remove/parse extension */
    AtomicReference<String> fname = new AtomicReference<>(filename);
    if (options.parseFileExtension) {
        AtomicReference<String> extension = new AtomicReference<>();
        if (removeExtensionFromFilename(fname, extension)) {
            elements.add(new Element(kElementFileExtension, extension.get()));
        }
    }

    /** set filename */
    if (fname.get() == null || fname.get().length() == 0)
        return elements;
    elements.add(new Element(kElementFileName, fname.get()));

    /** tokenize */
    boolean isTokenized = new Tokenizer(fname.get(), elements, options, tokens).tokenize();
    if (!isTokenized)
        return elements;
    new Parser(elements, options, tokens).parse();
    return elements;
}

From source file:com.cloudera.livy.rsc.driver.Statement.java

public Statement(Integer id, StatementState state, String output) {
    this.id = id;
    this.state = new AtomicReference<>(state);
    this.output = output;
    this.progress = 0.0;
}

From source file:com.mattjtodd.coherence.CoherenceCacheManager.java

/**
 * Uses the supplied function for cached creation.
 *
 * @param cacheFactory the function to use for creating caches
 *//*from   w  w  w . jav a  2s .  c  o m*/
public CoherenceCacheManager(Function<String, CoherenceCache> cacheFactory) {
    this.cacheFactory = checkNotNull(cacheFactory);
    caches = new AtomicReference<>(ImmutableMap.of());
}

From source file:ch.algotrader.adapter.bb.BBSessionStateHolder.java

public BBSessionStateHolder(final String name, final EventDispatcher eventDispatcher) {
    Validate.notEmpty(name, "Session name is null");
    Validate.notNull(eventDispatcher, "PlatformEventDispatcher is null");

    this.name = name;
    this.eventDispatcher = eventDispatcher;
    this.connState = new AtomicReference<>(ConnectionState.DISCONNECTED);
}

From source file:ch.algotrader.adapter.fix.DefaultFixSessionStateHolder.java

public DefaultFixSessionStateHolder(final String name, final EventDispatcher eventDispatcher) {
    Validate.notEmpty(name, "Session name is null");
    Validate.notNull(eventDispatcher, "PlatformEventDispatcher is null");

    this.name = name;
    this.eventDispatcher = eventDispatcher;
    this.connState = new AtomicReference<>(ConnectionState.DISCONNECTED);
}

From source file:io.watchcat.node.metrics.DiskUsage.java

public DiskUsage() {
    command = new ShellCommand("/bin/df --block-size=1M|awk '{print $1\",\"$2\",\"$3\",\"$4\",\"$5\",\"$6}'");
    disks = new AtomicReference<>(new LinkedList<Disk>());
}

From source file:io.watchcat.node.metrics.Processes.java

public Processes() {
    command = new ShellCommand(
            "/bin/ps aux | /usr/bin/awk 'NR>1{print $1\",\"$2\",\"$3\",\"$4\",\"$5\",\"$6\",\"$7\",\"$8\",\"$9\",\"$10\",\"$11}'");

    processes = new AtomicReference<LinkedList<Process>>(new LinkedList<Process>());
}

From source file:com.github.horrorho.inflatabledonkey.cloud.clients.AssetsClient.java

public static List<Assets> assets(HttpClient httpClient, CloudKitty kitty, ProtectionZone zone,
        Collection<Manifest> manifests) throws IOException {

    if (manifests.isEmpty()) {
        return new ArrayList<>();
    }/*  w  w w . ja v  a  2  s .co  m*/

    List<String> manifestIDs = manifests.stream().map(AssetsClient::manifestIDs).flatMap(Collection::stream)
            .collect(Collectors.toList());

    List<CloudKit.RecordRetrieveResponse> responses = kitty.recordRetrieveRequest(httpClient, "_defaultZone",
            manifestIDs);
    logger.info("-- assets() - responses: {}", responses.size());

    // Manifests with multiple counts only return protection info for the first block, as we are passing blocks in
    // order we can reference the previous protection zone.
    // TODO tighten up.
    AtomicReference<ProtectionZone> previous = new AtomicReference<>(zone);

    return responses.stream().filter(CloudKit.RecordRetrieveResponse::hasRecord)
            .map(CloudKit.RecordRetrieveResponse::getRecord).map(r -> assets(r, zone, previous))
            .collect(Collectors.toList());
}

From source file:ch.algotrader.adapter.ib.DefaultIBSessionStateHolder.java

public DefaultIBSessionStateHolder(final String name, final EventDispatcher eventDispatcher) {

    Validate.notEmpty(name, "Session name is null");
    Validate.notNull(eventDispatcher, "PlatformEventDispatcher is null");

    this.name = name;
    this.eventDispatcher = eventDispatcher;
    this.connState = new AtomicReference<>(ConnectionState.DISCONNECTED);
}