Example usage for java.util.concurrent.atomic AtomicInteger get

List of usage examples for java.util.concurrent.atomic AtomicInteger get

Introduction

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

Prototype

public final int get() 

Source Link

Document

Returns the current value, with memory effects as specified by VarHandle#getVolatile .

Usage

From source file:com.couchbase.client.core.endpoint.query.QueryHandlerTest.java

@Test
public void shouldDecodeArrayAsSignature() throws Exception {
    String response = Resources.read("signature_array.json", this.getClass());
    HttpResponse responseHeader = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
            new HttpResponseStatus(200, "OK"));
    HttpContent responseChunk = new DefaultLastHttpContent(Unpooled.copiedBuffer(response, CharsetUtil.UTF_8));

    GenericQueryRequest requestMock = mock(GenericQueryRequest.class);
    queue.add(requestMock);//from   w w  w  . j  a va 2  s. c o  m
    channel.writeInbound(responseHeader, responseChunk);
    latch.await(1, TimeUnit.SECONDS);
    assertEquals(1, firedEvents.size());
    GenericQueryResponse inbound = (GenericQueryResponse) firedEvents.get(0);

    final AtomicInteger invokeCounter1 = new AtomicInteger();
    assertResponse(inbound, true, ResponseStatus.SUCCESS, FAKE_REQUESTID, FAKE_CLIENTID, "success",
            "[\"json\",\"array\",[\"sub\",true]]", new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    invokeCounter1.incrementAndGet();
                    String item = buf.toString(CharsetUtil.UTF_8);
                    buf.release();
                    fail("no result expected, got " + item);
                }
            }, new Action1<ByteBuf>() {
                @Override
                public void call(ByteBuf buf) {
                    buf.release();
                    fail("no error expected");
                }
            },
            //no metrics in this json sample
            expectedMetricsCounts(0, 1));
    assertEquals(0, invokeCounter1.get());
}

From source file:com.datasnap.android.integration.IntegrationManagerTest.java

@Test
public void testIntegrationSelection() {

    final String key = "Some Integration";

    // create a settings cache that will insert fake provider settings for this key
    SettingsCache settingsCache = new SettingsCache(context, layer, Defaults.SETTINGS_CACHE_EXPIRY) {
        @Override//w w w .j a  v  a 2s.  c  om
        public EasyJSONObject getSettings() {
            // get them directly from the server with blocking
            EasyJSONObject settings = requester.fetchSettings();
            if (settings != null)
                settings.putObject(key, new JSONObject());
            return settings;
        }
    };

    // make the sure the settings cache has nothing in it right now
    settingsCache.reset();

    IntegrationManager integrationManager = new IntegrationManager(settingsCache);

    // removes all the providers
    integrationManager.getIntegrations().clear();

    final AtomicInteger identifies = new AtomicInteger();
    final AtomicInteger tracks = new AtomicInteger();
    final AtomicInteger screens = new AtomicInteger();
    final AtomicInteger aliases = new AtomicInteger();

    Integration provider = new SimpleIntegration() {
        @Override
        public void onCreate(Context context) {
            ready();
        }

        @Override
        public String getKey() {
            return key;
        }

        @Override
        public void validate(EasyJSONObject settings) throws InvalidSettingsException {
        }

        @Override
        public void identify(Identify identify) {
            identifies.addAndGet(1);
        }

        @Override
        public void track(Track track) {
            tracks.addAndGet(1);
        }

        @Override
        public void screen(Screen screen) {
            screens.addAndGet(1);
        }

        @Override
        public void alias(Alias alias) {
            aliases.addAndGet(1);
        }
    };

    // add a simple adding provider
    integrationManager.addIntegration(provider);

    // get the settings from the server, which won't include this provider
    integrationManager.refresh();

    // call the method that enables it
    integrationManager.onCreate(context);

    //
    // Test the no specific context.providers added
    //

    integrationManager.identify(TestCases.identify());
    assertThat(identifies.get()).isEqualTo(1);

    integrationManager.track(TestCases.track());
    assertThat(tracks.get()).isEqualTo(1);

    integrationManager.screen(TestCases.screen());
    assertThat(screens.get()).isEqualTo(1);

    integrationManager.alias(TestCases.alias());
    assertThat(aliases.get()).isEqualTo(1);

    //
    // Assemble test values
    //

    Identify identify = TestCases.identify();

    String userId = identify.getUserId();
    Traits traits = identify.getTraits();
    Calendar timestamp = Calendar.getInstance();

    Track track = TestCases.track();

    String event = TestCases.track().getEvent();
    Props properties = track.getProperties();

    Alias alias = TestCases.alias();

    String from = alias.getPreviousId();
    String to = alias.getUserId();

    //
    // Test the integrations.all = false setting default to false
    //

    Options allFalseOptions = new Options().setTimestamp(timestamp).setIntegration("all", false);
    EasyJSONObject bundledIntegrations = new EasyJSONObject();

    integrationManager.identify(new Identify(userId, traits, bundledIntegrations, allFalseOptions));
    assertThat(identifies.get()).isEqualTo(1);

    integrationManager.track(new Track(userId, event, properties, bundledIntegrations, allFalseOptions));
    assertThat(tracks.get()).isEqualTo(1);

    integrationManager.alias(new Alias(from, to, bundledIntegrations, allFalseOptions));
    assertThat(aliases.get()).isEqualTo(1);

    //
    // Test the integrations[integration.key] = false turns it off
    //

    Options integrationFalseOptions = new Options().setTimestamp(timestamp).setIntegration(key, false);

    integrationManager.identify(new Identify(userId, traits, bundledIntegrations, integrationFalseOptions));
    assertThat(identifies.get()).isEqualTo(1);

    integrationManager
            .track(new Track(userId, event, properties, bundledIntegrations, integrationFalseOptions));
    assertThat(tracks.get()).isEqualTo(1);

    integrationManager.alias(new Alias(from, to, bundledIntegrations, integrationFalseOptions));
    assertThat(aliases.get()).isEqualTo(1);

    //
    // Test the integrations[integration.key] = true, All=false keeps it on
    //

    Options integrationTrueOptions = new Options().setTimestamp(timestamp).setIntegration("all", false)
            .setIntegration(key, true);

    integrationManager.identify(new Identify(userId, traits, bundledIntegrations, integrationTrueOptions));
    assertThat(identifies.get()).isEqualTo(2);

    integrationManager.track(new Track(userId, event, properties, bundledIntegrations, integrationTrueOptions));
    assertThat(tracks.get()).isEqualTo(2);

    integrationManager.alias(new Alias(from, to, bundledIntegrations, integrationTrueOptions));
    assertThat(aliases.get()).isEqualTo(2);
}

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

public PreferencesDialog(final DownloaderGUI owner, Properties config) {
    super(owner, "Preferences", true);

    HttpClientParams params = new HttpClientParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    params.setSoTimeout(30000);/*from   ww  w  .j  a  v  a  2 s .c  om*/
    client = new HttpClient(params);
    setProxy(ProxyCfg.parseConfig(config));

    sample = new Deviation();
    sample.setId(15972367L);
    sample.setTitle("Fella Promo");
    sample.setArtist("devart");
    sample.setImageDownloadUrl(DOWNLOAD_URL);
    sample.setImageFilename(Deviation.extractFilename(DOWNLOAD_URL));
    sample.setCollection(new Collection(1L, "MyCollect"));
    setLayout(new BorderLayout());
    panes = new JTabbedPane(JTabbedPane.TOP);

    JPanel genPanel = new JPanel();
    BoxLayout genLayout = new BoxLayout(genPanel, BoxLayout.Y_AXIS);
    genPanel.setLayout(genLayout);
    panes.add("General", genPanel);

    JLabel userLabel = new JLabel("Username");

    userLabel.setToolTipText("The username the account you want to download the favorites from.");

    userField = new JTextField(config.getProperty(Constants.USERNAME));

    userLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    userField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    userField.setMaximumSize(new Dimension(Integer.MAX_VALUE, userField.getFont().getSize() * 2));

    genPanel.add(userLabel);
    genPanel.add(userField);

    JPanel radioPanel = new JPanel();
    BoxLayout radioLayout = new BoxLayout(radioPanel, BoxLayout.X_AXIS);
    radioPanel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    radioPanel.setBorder(new EmptyBorder(0, 5, 0, 5));

    radioPanel.setLayout(radioLayout);

    JLabel searchLabel = new JLabel("Search for");
    searchLabel
            .setToolTipText("Select what you want to download from that user: it favorites or it galleries.");
    searchLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searchLabel.setBorder(new EmptyBorder(0, 5, 0, 5));

    selectedSearch = SEARCH.lookup(config.getProperty(Constants.SEARCH, SEARCH.getDefault().getId()));
    buttonGroup = new ButtonGroup();

    for (final SEARCH search : SEARCH.values()) {
        JRadioButton radio = new JRadioButton(search.getLabel());
        radio.setAlignmentX(JLabel.LEFT_ALIGNMENT);
        radio.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                selectedSearch = search;
            }
        });

        buttonGroup.add(radio);
        radioPanel.add(radio);
        if (search.equals(selectedSearch)) {
            radio.setSelected(true);
        }
    }

    genPanel.add(radioPanel);

    final JTextField sampleField = new JTextField("");
    sampleField.setEditable(false);

    JLabel locationLabel = new JLabel("Download location");
    locationLabel.setToolTipText("The folder pattern where you want the file to be downloaded in.");

    JLabel legendsLabel = new JLabel(
            "<html><body>Field names: %user%, %artist%, %title%, %id%, %filename%, %collection%, %ext%<br></br>Example:</body></html>");
    legendsLabel.setToolTipText("An example of where a file will be downloaded to.");

    locationString = new StringBuilder();
    locationField = new JTextField(config.getProperty(Constants.LOCATION));
    locationField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationString.setLength(0);
            locationString.append(dest.getAbsolutePath());
            sampleField.setText(locationString.toString());
            if (useSameForMatureBox.isSelected()) {
                locationMatureString.setLength(0);
                locationMatureString.append(sampleField.getText());
                locationMatureField.setText(locationField.getText());
            }
        }

        public void keyTyped(KeyEvent e) {
        }

    });
    locationField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });
    JLabel locationMatureLabel = new JLabel("Mature download location");
    locationMatureLabel.setToolTipText(
            "The folder pattern where you want the file marked as 'Mature' to be downloaded in.");

    locationMatureString = new StringBuilder();
    locationMatureField = new JTextField(config.getProperty(Constants.MATURE));
    locationMatureField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            // TODO Auto-generated method stub

        }

        public void keyReleased(KeyEvent e) {
            File dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
                    sample.getImageFilename());
            locationMatureString.setLength(0);
            locationMatureString.append(dest.getAbsolutePath());
            sampleField.setText(locationMatureString.toString());
        }

        public void keyTyped(KeyEvent e) {
        }

    });

    locationMatureField.addMouseListener(new MouseListener() {
        public void mouseReleased(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
            sampleField.setText(locationString.toString());
        }

        public void mouseEntered(MouseEvent e) {
            sampleField.setText(locationMatureString.toString());
        }

        public void mouseClicked(MouseEvent e) {
        }
    });

    useSameForMatureBox = new JCheckBox("Use same location for mature deviation?");
    useSameForMatureBox.setSelected(locationLabel.getText().equals(locationMatureField.getText()));
    useSameForMatureBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (useSameForMatureBox.isSelected()) {
                locationMatureField.setEditable(false);
                locationMatureField.setText(locationField.getText());
                locationMatureString.setLength(0);
                locationMatureString.append(locationString);
            } else {
                locationMatureField.setEditable(true);
            }

        }
    });

    File dest = LocationHelper.getFile(locationField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    sampleField.setText(dest.getAbsolutePath());
    locationString.append(sampleField.getText());

    dest = LocationHelper.getFile(locationMatureField.getText(), userField.getText(), sample,
            sample.getImageFilename());
    locationMatureString.append(dest.getAbsolutePath());

    locationLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationField.setMaximumSize(new Dimension(Integer.MAX_VALUE, locationField.getFont().getSize() * 2));
    locationMatureLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    locationMatureField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    locationMatureField
            .setMaximumSize(new Dimension(Integer.MAX_VALUE, locationMatureField.getFont().getSize() * 2));
    useSameForMatureBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    legendsLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    legendsLabel.setMaximumSize(new Dimension(Integer.MAX_VALUE, legendsLabel.getFont().getSize() * 2));
    sampleField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    sampleField.setMaximumSize(new Dimension(Integer.MAX_VALUE, sampleField.getFont().getSize() * 2));

    genPanel.add(locationLabel);
    genPanel.add(locationField);

    genPanel.add(locationMatureLabel);
    genPanel.add(locationMatureField);
    genPanel.add(useSameForMatureBox);

    genPanel.add(legendsLabel);
    genPanel.add(sampleField);
    genPanel.add(Box.createVerticalBox());

    final KeyListener prxChangeListener = new KeyListener() {

        public void keyTyped(KeyEvent e) {
            proxyChangeState = true;
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
        }
    };

    JPanel prxPanel = new JPanel();
    BoxLayout prxLayout = new BoxLayout(prxPanel, BoxLayout.Y_AXIS);
    prxPanel.setLayout(prxLayout);
    panes.add("Proxy", prxPanel);

    JLabel prxHostLabel = new JLabel("Proxy Host");
    prxHostLabel.setToolTipText("The hostname of the proxy server");
    prxHostField = new JTextField(config.getProperty(Constants.PROXY_HOST));
    prxHostLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxHostField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxHostField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxHostField.getFont().getSize() * 2));

    JLabel prxPortLabel = new JLabel("Proxy Port");
    prxPortLabel.setToolTipText("The port of the proxy server (Default 80).");

    prxPortSpinner = new JSpinner();
    prxPortSpinner.setModel(new SpinnerNumberModel(
            Integer.parseInt(config.getProperty(Constants.PROXY_PORT, "80")), 1, 65535, 1));

    prxPortLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPortSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPortSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPortSpinner.getFont().getSize() * 2));

    JLabel prxUserLabel = new JLabel("Proxy username");
    prxUserLabel.setToolTipText("The username used for authentication, if applicable.");
    prxUserField = new JTextField(config.getProperty(Constants.PROXY_USERNAME));
    prxUserLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxUserField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxUserField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxUserField.getFont().getSize() * 2));

    JLabel prxPassLabel = new JLabel("Proxy username");
    prxPassLabel.setToolTipText("The username used for authentication, if applicable.");
    prxPassField = new JPasswordField(config.getProperty(Constants.PROXY_PASSWORD));
    prxPassLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    prxPassField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    prxPassField.setMaximumSize(new Dimension(Integer.MAX_VALUE, prxPassField.getFont().getSize() * 2));

    prxUseBox = new JCheckBox("Use a proxy?");
    prxUseBox.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            prxChangeListener.keyTyped(null);

            if (prxUseBox.isSelected()) {
                prxHostField.setEditable(true);
                prxPortSpinner.setEnabled(true);
                prxUserField.setEditable(true);
                prxPassField.setEditable(true);

            } else {
                prxHostField.setEditable(false);
                prxPortSpinner.setEnabled(false);
                prxUserField.setEditable(false);
                prxPassField.setEditable(false);
            }
        }
    });

    prxUseBox.setSelected(!Boolean.parseBoolean(config.getProperty(Constants.PROXY_USE)));
    prxUseBox.doClick();
    proxyChangeState = false;

    prxHostField.addKeyListener(prxChangeListener);
    prxUserField.addKeyListener(prxChangeListener);
    prxPassField.addKeyListener(prxChangeListener);
    prxPortSpinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            proxyChangeState = true;
        }
    });
    prxPanel.add(prxUseBox);

    prxPanel.add(prxHostLabel);
    prxPanel.add(prxHostField);

    prxPanel.add(prxPortLabel);
    prxPanel.add(prxPortSpinner);

    prxPanel.add(prxUserLabel);
    prxPanel.add(prxUserField);

    prxPanel.add(prxPassLabel);
    prxPanel.add(prxPassField);
    prxPanel.add(Box.createVerticalBox());

    final JPanel advPanel = new JPanel();
    BoxLayout advLayout = new BoxLayout(advPanel, BoxLayout.Y_AXIS);
    advPanel.setLayout(advLayout);
    panes.add("Advanced", advPanel);
    panes.addChangeListener(new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            JTabbedPane pane = (JTabbedPane) e.getSource();

            if (proxyChangeState && pane.getSelectedComponent() == advPanel) {
                Properties properties = new Properties();
                properties.setProperty(Constants.PROXY_USERNAME, prxUserField.getText().trim());
                properties.setProperty(Constants.PROXY_PASSWORD, new String(prxPassField.getPassword()).trim());
                properties.setProperty(Constants.PROXY_HOST, prxHostField.getText().trim());
                properties.setProperty(Constants.PROXY_PORT, prxPortSpinner.getValue().toString());
                properties.setProperty(Constants.PROXY_USE, Boolean.toString(prxUseBox.isSelected()));
                ProxyCfg prx = ProxyCfg.parseConfig(properties);
                setProxy(prx);
                revalidateSearcher(null);
            }
        }
    });
    JLabel domainLabel = new JLabel("Deviant Art domain name");
    domainLabel.setToolTipText("The deviantART main domain, should it ever change.");

    domainField = new JTextField(config.getProperty(Constants.DOMAIN));
    domainLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    domainField.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    domainField.setMaximumSize(new Dimension(Integer.MAX_VALUE, domainField.getFont().getSize() * 2));

    advPanel.add(domainLabel);
    advPanel.add(domainField);

    JLabel throttleLabel = new JLabel("Throttle search delay");
    throttleLabel.setToolTipText(
            "Slow down search query by inserting a pause between them. This help prevent abuse when doing a massive download.");

    throttleSpinner = new JSpinner();
    throttleSpinner.setModel(
            new SpinnerNumberModel(Integer.parseInt(config.getProperty(Constants.THROTTLE, "0")), 5, 60, 1));

    throttleLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    throttleSpinner.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    throttleSpinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, throttleSpinner.getFont().getSize() * 2));

    advPanel.add(throttleLabel);
    advPanel.add(throttleSpinner);

    JLabel searcherLabel = new JLabel("Searcher");
    searcherLabel.setToolTipText("Select a searcher that will look for your favorites.");

    searcherBox = new JComboBox();
    searcherBox.setRenderer(new TogglingRenderer());

    final AtomicInteger index = new AtomicInteger(0);
    searcherBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComboBox combo = (JComboBox) e.getSource();
            Object selectedItem = combo.getSelectedItem();
            if (selectedItem instanceof SearchItem) {
                SearchItem item = (SearchItem) selectedItem;
                if (item.isValid) {
                    index.set(combo.getSelectedIndex());
                } else {
                    combo.setSelectedIndex(index.get());
                }
            }
        }
    });

    try {
        for (Class<Search> clazz : SearcherClassCache.getInstance().getClasses()) {

            Search searcher = clazz.newInstance();
            String name = searcher.getName();

            SearchItem item = new SearchItem(name, clazz.getName(), true);
            searcherBox.addItem(item);
        }
        String selectedClazz = config.getProperty(Constants.SEARCHER,
                com.dragoniade.deviantart.deviation.SearchRss.class.getName());
        revalidateSearcher(selectedClazz);
    } catch (Exception e1) {
        throw new RuntimeException(e1);
    }

    searcherLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherLabel.setBorder(new EmptyBorder(0, 5, 0, 5));
    searcherBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    searcherBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, searcherBox.getFont().getSize() * 2));

    advPanel.add(searcherLabel);
    advPanel.add(searcherBox);

    advPanel.add(Box.createVerticalBox());

    add(panes, BorderLayout.CENTER);

    JButton saveBut = new JButton("Save");

    userField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            if (field.getText().trim().length() == 0) {
                JOptionPane.showMessageDialog(input, "The user musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The location must contains at least a %filename% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    locationMatureField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String content = field.getText().trim();
            if (content.length() == 0) {
                JOptionPane.showMessageDialog(input, "The Mature location musn't be empty.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (!content.contains("%filename%") && !content.contains("%id%")) {
                JOptionPane.showMessageDialog(input,
                        "The Mature location must contains at least a %username% or an %id% field.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }
            return true;
        }
    });

    domainField.setInputVerifier(new InputVerifier() {
        @Override
        public boolean verify(JComponent input) {
            JTextField field = (JTextField) input;
            String domain = field.getText().trim();
            if (domain.length() == 0) {
                JOptionPane.showMessageDialog(input, "You must specify the deviantART main domain.", "Warning",
                        JOptionPane.WARNING_MESSAGE);
                return false;
            }

            if (domain.toLowerCase().startsWith("http://")) {
                JOptionPane.showMessageDialog(input,
                        "You must specify the deviantART main domain, not the full URL (aka www.deviantart.com).",
                        "Warning", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            return true;
        }
    });
    locationField.setVerifyInputWhenFocusTarget(true);

    final JDialog parent = this;
    saveBut.addActionListener(new ActionListener() {

        String errorMsg = "The location is invalid or cannot be written to.";

        public void actionPerformed(ActionEvent e) {

            String username = userField.getText().trim();
            String location = locationField.getText().trim();
            String locationMature = locationMatureField.getText().trim();
            String domain = domainField.getText().trim();
            String throttle = throttleSpinner.getValue().toString();
            String searcher = searcherBox.getSelectedItem().toString();

            String prxUse = Boolean.toString(prxUseBox.isSelected());
            String prxHost = prxHostField.getText().trim();
            String prxPort = prxPortSpinner.getValue().toString();
            String prxUsername = prxUserField.getText().trim();
            String prxPassword = new String(prxPassField.getPassword()).trim();

            if (!testPath(location, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (!testPath(locationMature, username)) {
                JOptionPane.showMessageDialog(parent, errorMsg, "Error", JOptionPane.ERROR_MESSAGE);
            }

            Properties p = new Properties();
            p.setProperty(Constants.USERNAME, username);
            p.setProperty(Constants.LOCATION, location);
            p.setProperty(Constants.MATURE, locationMature);
            p.setProperty(Constants.DOMAIN, domain);
            p.setProperty(Constants.THROTTLE, throttle);
            p.setProperty(Constants.SEARCHER, searcher);
            p.setProperty(Constants.SEARCH, selectedSearch.getId());

            p.setProperty(Constants.PROXY_USE, prxUse);
            p.setProperty(Constants.PROXY_HOST, prxHost);
            p.setProperty(Constants.PROXY_PORT, prxPort);
            p.setProperty(Constants.PROXY_USERNAME, prxUsername);
            p.setProperty(Constants.PROXY_PASSWORD, prxPassword);

            owner.savePreferences(p);
            parent.dispose();
        }
    });

    JButton cancelBut = new JButton("Cancel");
    cancelBut.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            parent.dispose();
        }
    });

    JPanel buttonPanel = new JPanel();
    BoxLayout butLayout = new BoxLayout(buttonPanel, BoxLayout.X_AXIS);
    buttonPanel.setLayout(butLayout);

    buttonPanel.add(saveBut);
    buttonPanel.add(cancelBut);
    add(buttonPanel, BorderLayout.SOUTH);

    pack();
    setResizable(false);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((d.width - getWidth()) / 2, (d.height - getHeight()) / 2);
    setVisible(true);
}

From source file:com.radiohitwave.ftpsync.API.java

public void DeleteNonExistingFiles(String localBasePath) {
    Log.info("Searching for non-existing Files");
    String[] remoteFiles = this.GetRemoteFileList();
    final String finalLocalPath = this.RemoveTrailingSlash(localBasePath);
    AtomicInteger logDeletedFiles = new AtomicInteger();

    try {/*  w ww .j av  a 2s .  c  o m*/
        Files.walk(Paths.get(localBasePath)).forEach(filePath -> {
            if (Files.isRegularFile(filePath)) {
                String file = filePath.toString().replace(finalLocalPath, "");
                file = file.substring(1);
                file = file.replace("\\", "/");
                if (Arrays.binarySearch(remoteFiles, file) < 0) {
                    try {
                        Log.info("Deleting <" + file + ">");
                        Files.delete(filePath);
                        logDeletedFiles.incrementAndGet();
                    } catch (IOException ex) {
                        Log.error("Cant delete File:" + ex.toString());
                        Log.remoteError(ex);
                    }
                }
            }
        });
        Files.walk(Paths.get(localBasePath)).forEach(filePath -> {
            if (Files.isDirectory(filePath)) {
                String file = filePath.toString().replace(finalLocalPath + "/", "");
                try {
                    Files.delete(filePath);
                    Log.info("Deleting empty Directory <" + file + ">");
                } catch (IOException e) {

                }
            }
        });
    } catch (IOException ex) {
        Log.error(ex.toString());
    }
    Log.info("Disk-Cleanup finished, deleted " + logDeletedFiles.get() + " Files");
    if (logDeletedFiles.get() > this.nonExistingFilesThreesholdBeforeAlert) {
        Log.remoteInfo("Deleted " + logDeletedFiles.get() + " non-existing Files");
    }

}

From source file:com.vmware.admiral.adapter.docker.service.DockerAdapterService.java

private void processStopContainerWithRetry(RequestContext context, int retriesCount, int maxRetryCount) {
    AtomicInteger retryCount = new AtomicInteger(retriesCount);
    CommandInput stopCommandInput = new CommandInput(context.commandInput)
            .withProperty(DOCKER_CONTAINER_ID_PROP_NAME, context.containerState.id);
    context.executor.stopContainer(stopCommandInput, (o, ex) -> {
        if (ex != null) {
            if (RETRIABLE_HTTP_STATUSES.contains(o.getStatusCode())
                    && retryCount.getAndIncrement() < maxRetryCount) {
                logWarning("Stopping container %s failed with %s. Retries left %d",
                        context.containerState.names.get(0), Utils.toString(ex),
                        maxRetryCount - retryCount.get());
                processStopContainerWithRetry(context, retryCount.get(), maxRetryCount);
            } else {
                fail(context.request, o, ex);
            }//www  .ja  v a2 s.  c  o  m
        } else {
            handleExceptions(context.request, context.operation, () -> {
                NetworkUtils.updateConnectedNetworks(getHost(), context.containerState, -1);
                inspectContainer(context);
            });
        }
    });
}

From source file:com.vmware.admiral.adapter.docker.service.DockerAdapterService.java

private void processStartContainerWithRetry(RequestContext context, int retriesCount, Integer maxRetryCount) {
    AtomicInteger retryCount = new AtomicInteger(retriesCount);
    CommandInput startCommandInput = new CommandInput(context.commandInput)
            .withProperty(DOCKER_CONTAINER_ID_PROP_NAME, context.containerState.id);
    context.executor.startContainer(startCommandInput, (o, ex) -> {
        if (ex != null) {
            if (RETRIABLE_HTTP_STATUSES.contains(o.getStatusCode())
                    && retryCount.getAndIncrement() < maxRetryCount) {
                logWarning("Starting container %s failed with %s. Retries left %d",
                        context.containerState.names.get(0), Utils.toString(ex),
                        maxRetryCount - retryCount.get());
                processStartContainerWithRetry(context, retryCount.get(), maxRetryCount);
            } else {
                fail(context.request, o, ex);
            }//  w w  w. j a  v a2 s . c  o  m
        } else {
            handleExceptions(context.request, context.operation, () -> {
                NetworkUtils.updateConnectedNetworks(getHost(), context.containerState, 1);
                inspectContainer(context);
            });
        }
    });
}

From source file:co.cask.cdap.gateway.router.NettyRouterTestBase.java

@Test
public void testRouterAsync() throws Exception {
    int numElements = 123;
    AsyncHttpClientConfig.Builder configBuilder = new AsyncHttpClientConfig.Builder();

    final AsyncHttpClient asyncHttpClient = new AsyncHttpClient(
            new NettyAsyncHttpProvider(configBuilder.build()), configBuilder.build());

    final CountDownLatch latch = new CountDownLatch(numElements);
    final AtomicInteger numSuccessfulRequests = new AtomicInteger(0);
    for (int i = 0; i < numElements; ++i) {
        final int elem = i;
        final Request request = new RequestBuilder("GET")
                .setUrl(resolveURI(DEFAULT_SERVICE, String.format("%s/%s-%d", "/v1/ping", "async", i))).build();
        asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Void>() {
            @Override/*  w  ww.j  a  va 2 s  . c om*/
            public Void onCompleted(Response response) throws Exception {
                latch.countDown();
                Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusCode());
                numSuccessfulRequests.incrementAndGet();
                return null;
            }

            @Override
            public void onThrowable(Throwable t) {
                LOG.error("Got exception while posting {}", elem, t);
                latch.countDown();
            }
        });

        // Sleep so as not to overrun the server.
        TimeUnit.MILLISECONDS.sleep(1);
    }
    latch.await();
    asyncHttpClient.close();

    Assert.assertEquals(numElements, numSuccessfulRequests.get());
    // we use sticky endpoint strategy so the sum of requests from the two gateways should be NUM_ELEMENTS
    Assert.assertTrue(numElements == (defaultServer1.getNumRequests() + defaultServer2.getNumRequests()));
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testBasic() throws Exception {
    final int CONCURRENCY = 8;
    final int ITERATIONS = 100;

    final Random random = new Random();
    final AtomicInteger concurrentCount = new AtomicInteger(0);
    final AtomicInteger maxConcurrentCount = new AtomicInteger(0);
    final AtomicInteger writeCount = new AtomicInteger(0);
    final AtomicInteger readCount = new AtomicInteger(0);

    List<Future<Void>> futures = Lists.newArrayList();
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0; i < CONCURRENCY; ++i) {
        Future<Void> future = service.submit(new Callable<Void>() {
            @Override//from   w ww  .j av  a 2  s  .c om
            public Void call() throws Exception {
                CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                        new RetryOneTime(1));
                client.start();
                try {
                    InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");
                    for (int i = 0; i < ITERATIONS; ++i) {
                        if (random.nextInt(100) < 10) {
                            doLocking(lock.writeLock(), concurrentCount, maxConcurrentCount, random, 1);
                            writeCount.incrementAndGet();
                        } else {
                            doLocking(lock.readLock(), concurrentCount, maxConcurrentCount, random,
                                    Integer.MAX_VALUE);
                            readCount.incrementAndGet();
                        }
                    }
                } finally {
                    IOUtils.closeQuietly(client);
                }
                return null;
            }
        });
        futures.add(future);
    }

    for (Future<Void> future : futures) {
        future.get();
    }

    System.out.println("Writes: " + writeCount.get() + " - Reads: " + readCount.get() + " - Max Reads: "
            + maxConcurrentCount.get());

    Assert.assertTrue(writeCount.get() > 0);
    Assert.assertTrue(readCount.get() > 0);
    Assert.assertTrue(maxConcurrentCount.get() > 1);
}

From source file:org.apache.hadoop.hbase.client.TestAdmin2.java

@Test(timeout = 300000)
public void testCreateBadTables() throws IOException {
    String msg = null;// ww  w .  j av  a  2s  . com
    try {
        this.admin.createTable(new HTableDescriptor(TableName.META_TABLE_NAME));
    } catch (TableExistsException e) {
        msg = e.toString();
    }
    assertTrue("Unexcepted exception message " + msg,
            msg != null && msg.startsWith(TableExistsException.class.getName())
                    && msg.contains(TableName.META_TABLE_NAME.getNameAsString()));

    // Now try and do concurrent creation with a bunch of threads.
    final HTableDescriptor threadDesc = new HTableDescriptor(TableName.valueOf("threaded_testCreateBadTables"));
    threadDesc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
    int count = 10;
    Thread[] threads = new Thread[count];
    final AtomicInteger successes = new AtomicInteger(0);
    final AtomicInteger failures = new AtomicInteger(0);
    final Admin localAdmin = this.admin;
    for (int i = 0; i < count; i++) {
        threads[i] = new Thread(Integer.toString(i)) {
            @Override
            public void run() {
                try {
                    localAdmin.createTable(threadDesc);
                    successes.incrementAndGet();
                } catch (TableExistsException e) {
                    failures.incrementAndGet();
                } catch (IOException e) {
                    throw new RuntimeException("Failed threaded create" + getName(), e);
                }
            }
        };
    }
    for (int i = 0; i < count; i++) {
        threads[i].start();
    }
    for (int i = 0; i < count; i++) {
        while (threads[i].isAlive()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // continue
            }
        }
    }
    // All threads are now dead.  Count up how many tables were created and
    // how many failed w/ appropriate exception.
    assertEquals(1, successes.get());
    assertEquals(count - 1, failures.get());
}

From source file:org.apache.bookkeeper.bookie.CreateNewLogTest.java

@Test
public void testConcurrentEntryLogCreations() throws Exception {
    ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();

    // Creating a new configuration with a number of ledger directories.
    conf.setLedgerDirNames(ledgerDirs);// www . j a  va  2s .  c  o  m
    // pre-allocation is enabled
    conf.setEntryLogFilePreAllocationEnabled(true);
    conf.setEntryLogPerLedgerEnabled(true);
    LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(),
            new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()));
    EntryLogger entryLogger = new EntryLogger(conf, ledgerDirsManager);
    EntryLogManagerForEntryLogPerLedger entrylogManager = (EntryLogManagerForEntryLogPerLedger) entryLogger
            .getEntryLogManager();

    int numOfLedgers = 10;
    int numOfThreadsForSameLedger = 10;
    AtomicInteger createdEntryLogs = new AtomicInteger(0);
    CountDownLatch startLatch = new CountDownLatch(1);
    CountDownLatch createdLatch = new CountDownLatch(numOfLedgers * numOfThreadsForSameLedger);

    for (long i = 0; i < numOfLedgers; i++) {
        for (int j = 0; j < numOfThreadsForSameLedger; j++) {
            long ledgerId = i;
            new Thread(() -> {
                try {
                    startLatch.await();
                    entrylogManager.createNewLog(ledgerId);
                    createdEntryLogs.incrementAndGet();
                } catch (InterruptedException | IOException e) {
                    LOG.error("Got exception while trying to createNewLog for Ledger: " + ledgerId, e);
                } finally {
                    createdLatch.countDown();
                }
            }).start();
        }
    }

    startLatch.countDown();
    createdLatch.await(5, TimeUnit.SECONDS);
    Assert.assertEquals("Created EntryLogs", numOfLedgers * numOfThreadsForSameLedger, createdEntryLogs.get());
    Assert.assertEquals("Active currentlogs size", numOfLedgers, entrylogManager.getCopyOfCurrentLogs().size());
    Assert.assertEquals("Rotated entrylogs size", (numOfThreadsForSameLedger - 1) * numOfLedgers,
            entrylogManager.getRotatedLogChannels().size());
    /*
     * EntryLogFilePreAllocation is Enabled so
     * getPreviousAllocatedEntryLogId would be (numOfLedgers *
     * numOfThreadsForSameLedger) instead of (numOfLedgers *
     * numOfThreadsForSameLedger - 1)
     */
    Assert.assertEquals("PreviousAllocatedEntryLogId", numOfLedgers * numOfThreadsForSameLedger,
            entryLogger.getPreviousAllocatedEntryLogId());
}