List of usage examples for java.util.concurrent.atomic AtomicReference set
public final void set(V newValue)
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;//w w w . j a v 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:org.apache.flink.streaming.connectors.kinesis.manualtests.ManualExactlyOnceWithStreamReshardingTest.java
public static void main(String[] args) throws Exception { final ParameterTool pt = ParameterTool.fromArgs(args); LOG.info("Starting exactly once with stream resharding test"); final String streamName = "flink-test-" + UUID.randomUUID().toString(); final String accessKey = pt.getRequired("accessKey"); final String secretKey = pt.getRequired("secretKey"); final String region = pt.getRequired("region"); final Properties configProps = new Properties(); configProps.setProperty(ConsumerConfigConstants.AWS_ACCESS_KEY_ID, accessKey); configProps.setProperty(ConsumerConfigConstants.AWS_SECRET_ACCESS_KEY, secretKey); configProps.setProperty(ConsumerConfigConstants.AWS_REGION, region); configProps.setProperty(ConsumerConfigConstants.SHARD_DISCOVERY_INTERVAL_MILLIS, "0"); final AmazonKinesisClient client = AWSUtil.createKinesisClient(configProps); // the stream is first created with 1 shard client.createStream(streamName, 1);//from w w w.ja v a 2 s. c o m // wait until stream has been created DescribeStreamResult status = client.describeStream(streamName); LOG.info("status {}", status); while (!status.getStreamDescription().getStreamStatus().equals("ACTIVE")) { status = client.describeStream(streamName); LOG.info("Status of stream {}", status); Thread.sleep(1000); } final Configuration flinkConfig = new Configuration(); flinkConfig.setInteger(ConfigConstants.LOCAL_NUMBER_TASK_MANAGER, 1); flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_NUM_TASK_SLOTS, 8); flinkConfig.setInteger(ConfigConstants.TASK_MANAGER_MEMORY_SIZE_KEY, 16); flinkConfig.setString(ConfigConstants.RESTART_STRATEGY_FIXED_DELAY_DELAY, "0 s"); LocalFlinkMiniCluster flink = new LocalFlinkMiniCluster(flinkConfig, false); flink.start(); final int flinkPort = flink.getLeaderRPCPort(); try { // we have to use a manual generator here instead of the FlinkKinesisProducer // because the FlinkKinesisProducer currently has a problem where records will be resent to a shard // when resharding happens; this affects the consumer exactly-once validation test and will never pass final AtomicReference<Throwable> producerError = new AtomicReference<>(); Runnable manualGenerate = new Runnable() { @Override public void run() { AmazonKinesisClient client = AWSUtil.createKinesisClient(configProps); int count = 0; final int batchSize = 30; while (true) { try { Thread.sleep(10); Set<PutRecordsRequestEntry> batch = new HashSet<>(); for (int i = count; i < count + batchSize; i++) { if (i >= TOTAL_EVENT_COUNT) { break; } batch.add(new PutRecordsRequestEntry() .withData( ByteBuffer.wrap(((i) + "-" + RandomStringUtils.randomAlphabetic(12)) .getBytes(ConfigConstants.DEFAULT_CHARSET))) .withPartitionKey(UUID.randomUUID().toString())); } count += batchSize; PutRecordsResult result = client.putRecords( new PutRecordsRequest().withStreamName(streamName).withRecords(batch)); // the putRecords() operation may have failing records; to keep this test simple // instead of retrying on failed records, we simply pass on a runtime exception // and let this test fail if (result.getFailedRecordCount() > 0) { producerError.set(new RuntimeException( "The producer has failed records in one of the put batch attempts.")); break; } if (count >= TOTAL_EVENT_COUNT) { break; } } catch (Exception e) { producerError.set(e); } } } }; Thread producerThread = new Thread(manualGenerate); producerThread.start(); final AtomicReference<Throwable> consumerError = new AtomicReference<>(); Thread consumerThread = ExactlyOnceValidatingConsumerThread.create(TOTAL_EVENT_COUNT, 10000, 2, 500, 500, accessKey, secretKey, region, streamName, consumerError, flinkPort, flinkConfig); consumerThread.start(); // reshard the Kinesis stream while the producer / and consumers are running Runnable splitShard = new Runnable() { @Override public void run() { try { // first, split shard in the middle of the hash range Thread.sleep(5000); LOG.info("Splitting shard ..."); client.splitShard(streamName, KinesisShardIdGenerator.generateFromShardOrder(0), "170141183460469231731687303715884105727"); // wait until the split shard operation finishes updating ... DescribeStreamResult status; Random rand = new Random(); do { status = null; while (status == null) { // retry until we get status try { status = client.describeStream(streamName); } catch (LimitExceededException lee) { LOG.warn("LimitExceededException while describing stream ... retrying ..."); Thread.sleep(rand.nextInt(1200)); } } } while (!status.getStreamDescription().getStreamStatus().equals("ACTIVE")); // then merge again Thread.sleep(7000); LOG.info("Merging shards ..."); client.mergeShards(streamName, KinesisShardIdGenerator.generateFromShardOrder(1), KinesisShardIdGenerator.generateFromShardOrder(2)); } catch (InterruptedException iex) { // } } }; Thread splitShardThread = new Thread(splitShard); splitShardThread.start(); boolean deadlinePassed = false; long deadline = System.currentTimeMillis() + (1000 * 5 * 60); // wait at most for five minutes // wait until both producer and consumer finishes, or an unexpected error is thrown while ((consumerThread.isAlive() || producerThread.isAlive()) && (producerError.get() == null && consumerError.get() == null)) { Thread.sleep(1000); if (System.currentTimeMillis() >= deadline) { LOG.warn("Deadline passed"); deadlinePassed = true; break; // enough waiting } } if (producerThread.isAlive()) { producerThread.interrupt(); } if (consumerThread.isAlive()) { consumerThread.interrupt(); } if (producerError.get() != null) { LOG.info("+++ TEST failed! +++"); throw new RuntimeException("Producer failed", producerError.get()); } if (consumerError.get() != null) { LOG.info("+++ TEST failed! +++"); throw new RuntimeException("Consumer failed", consumerError.get()); } if (!deadlinePassed) { LOG.info("+++ TEST passed! +++"); } else { LOG.info("+++ TEST failed! +++"); } } finally { client.deleteStream(streamName); client.shutdown(); // stopping flink flink.stop(); } }
From source file:com.github.horrorho.inflatabledonkey.cloud.clients.AssetsClient.java
static Assets assets(CloudKit.Record record, ProtectionZone zone, AtomicReference<ProtectionZone> previous) { return zone.newProtectionZone(record.getProtectionInfo()).map(z -> { previous.set(z); return AssetsFactory.from(record, z::decrypt); }).orElse(AssetsFactory.from(record, previous.get()::decrypt)); }
From source file:Main.java
/** * Runs arbitrary code in the Event Dispatch Thread. * <p>/*from ww w . j a v a 2 s . com*/ * The first operation performed by this method is fetching the {@code Object} to return. If {@code supplier} is not {@code null}, its {@code get()} method will be called to fetch the {@code Object}. But if {@code supplier} is {@code null}, or it * produces a {@code null} "value" from its {@code get()} method, then {@code defaultObject}, which may also be {@code null}, will be used instead. * <p> * The second operation performed by this method is handling the {@code Object} to return. So if neither {@code consumer} nor the fetched {@code Object} are {@code null}, the fetched {@code Object} will be handed to {@code consumer}. * <p> * Returns the fetched {@code Object}, which may be {@code null}. * * @param <T> the type of the returned result * @param supplier the {@code Supplier}, which may be {@code null} * @param consumer the {@code Consumer}, which may be {@code null} * @param defaultObject the default {@code Object}, which may be {@code null} * @return the fetched {@code Object}, which may be {@code null} */ public static <T> T runInEDT(final Supplier<T> supplier, final Consumer<T> consumer, final T defaultObject) { final AtomicReference<T> atomicReference = new AtomicReference<>(); if (supplier != null) { runInEDT(() -> atomicReference.set(supplier.get())); } if (defaultObject != null) { atomicReference.compareAndSet(null, defaultObject); } if (atomicReference.get() != null && consumer != null) { runInEDT(() -> consumer.accept(atomicReference.get())); } return atomicReference.get(); }
From source file:com.netflix.suro.SuroServer.java
public static void create(AtomicReference<Injector> injector, final Properties properties, Module... modules) throws Exception { // Create the injector injector.set(LifecycleInjector.builder().withBootstrapModule(new BootstrapModule() { @Override/*from w w w . jav a2 s .c o m*/ public void configure(BootstrapBinder binder) { binder.bindConfigurationProvider().toInstance(new PropertiesConfigurationProvider(properties)); } }).withModules(new RoutingPlugin(), new ServerSinkPlugin(), new SuroInputPlugin(), new SuroDynamicPropertyModule(), new SuroModule(), StatusServer.createJerseyServletModule()) .withAdditionalModules(modules).build().createInjector()); }
From source file:com.raphfrk.craftproxyclient.gui.GUIManager.java
public static JSONObject getNewLoginDetails() { final AtomicReference<LoginDialog> login = new AtomicReference<LoginDialog>(); Runnable r = (new Runnable() { public void run() { login.set(new LoginDialog(CraftProxyClient.getGUI())); login.get().setVisible(true); login.get().dispose();/*from w ww . j av a2s . c o m*/ } }); if (SwingUtilities.isEventDispatchThread()) { r.run(); } else { try { SwingUtilities.invokeAndWait(r); } catch (InvocationTargetException | InterruptedException e) { return null; } } return AuthManager.authAccessToken(login.get().getEmail(), login.get().getPassword()); }
From source file:Main.java
public static void runInThread(final Runnable runnable) throws Throwable { final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Runnable exceptionGuard = new Runnable() { public void run() { try { runnable.run();// ww w . j a va2 s. c o m } catch (Throwable throwable) { exception.set(throwable); } } }; Thread thread = new Thread(exceptionGuard); thread.setDaemon(true); thread.start(); thread.join(); if (exception.get() != null) { throw exception.get(); } }
From source file:com.dgtlrepublic.anitomyj.AnitomyJ.java
/** * Removes the extension from the {@code filename}. * * @param filename the ref that will be updated with the new filename * @param extension the ref that will be updated with the file extension * @return true if then extension was separated from the filename *///from w w w . j a va 2 s .co m private static boolean removeExtensionFromFilename(AtomicReference<String> filename, AtomicReference<String> extension) { int position; if (StringUtils.isEmpty(filename.get()) || (position = filename.get().lastIndexOf('.')) == -1) return false; /** remove file extension */ extension.set(filename.get().substring(position + 1)); if (extension.get().length() > 4) return false; if (!StringHelper.isAlphanumericString(extension.get())) return false; /** check if valid anime extension */ String keyword = KeywordManager.normalzie(extension.get()); if (!KeywordManager.getInstance().contains(kElementFileExtension, keyword)) return false; filename.set(filename.get().substring(0, position)); return true; }
From source file:org.elasticsearch.client.HeapBufferedAsyncResponseConsumerTests.java
private static void bufferLimitTest(HeapBufferedAsyncResponseConsumer consumer, int bufferLimit) throws Exception { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); StatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "OK"); consumer.onResponseReceived(new BasicHttpResponse(statusLine)); final AtomicReference<Long> contentLength = new AtomicReference<>(); HttpEntity entity = new StringEntity("", ContentType.APPLICATION_JSON) { @Override/*w w w.j ava2 s. co m*/ public long getContentLength() { return contentLength.get(); } }; contentLength.set(randomLong(bufferLimit)); consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); contentLength.set(randomLongBetween(bufferLimit + 1, MAX_TEST_BUFFER_SIZE)); try { consumer.onEntityEnclosed(entity, ContentType.APPLICATION_JSON); } catch (ContentTooLongException e) { assertEquals("entity content is too long [" + entity.getContentLength() + "] for the configured buffer limit [" + bufferLimit + "]", e.getMessage()); } }
From source file:jp.realglobe.sugo.actor.android.call.MainActivity.java
/** * ??/*from w w w.j a v a 2s.c om*/ * * @param interval ?????? * @param context * @param listener ???? * @param errorCallback ?? * @return ?? */ private static GoogleApiClient setupLocationClient(long interval, Context context, LocationListener listener, StringCallback errorCallback) { final AtomicReference<GoogleApiClient> client = new AtomicReference<>(); client.set((new GoogleApiClient.Builder(context)).addApi(LocationServices.API) .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { @Override public void onConnected(@Nullable Bundle bundle) { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } LocationServices.FusedLocationApi.requestLocationUpdates(client.get(), LocationRequest .create().setInterval(interval).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY), location -> { Log.d(LOG_TAG, "Location changed to " + location); if (listener != null) { listener.onLocationChanged(location); } }); Log.d(LOG_TAG, "Location monitor started"); } @Override public void onConnectionSuspended(int i) { Log.d(LOG_TAG, "Location monitor suspended"); } }).addOnConnectionFailedListener(connectionResult -> { final String warning = "Location detector error: " + connectionResult; Log.w(LOG_TAG, warning); if (errorCallback != null) { errorCallback.call(connectionResult.getErrorMessage()); } }).build()); return client.get(); }