List of usage examples for java.util.concurrent.atomic AtomicInteger set
public final void set(int newValue)
From source file:org.apache.storm.daemon.supervisor.SyncSupervisorEvent.java
protected Map<Integer, LocalAssignment> readAssignments(Map<String, Map<String, Object>> assignmentsSnapshot, Map<Integer, LocalAssignment> existingAssignment, String assignmentId, AtomicInteger retries) { try {//from ww w .jav a2s .c om Map<Integer, LocalAssignment> portLA = new HashMap<Integer, LocalAssignment>(); for (Map.Entry<String, Map<String, Object>> assignEntry : assignmentsSnapshot.entrySet()) { String stormId = assignEntry.getKey(); Assignment assignment = (Assignment) assignEntry.getValue().get(IStateStorage.DATA); Map<Integer, LocalAssignment> portTasks = readMyExecutors(stormId, assignmentId, assignment); for (Map.Entry<Integer, LocalAssignment> entry : portTasks.entrySet()) { Integer port = entry.getKey(); LocalAssignment la = entry.getValue(); if (!portLA.containsKey(port)) { portLA.put(port, la); } else { throw new RuntimeException("Should not have multiple topologys assigned to one port"); } } } retries.set(0); return portLA; } catch (RuntimeException e) { if (retries.get() > 2) { throw e; } else { retries.addAndGet(1); } LOG.warn("{} : retrying {} of 3", e.getMessage(), retries.get()); return existingAssignment; } }
From source file:org.eclipse.jubula.client.core.ClientTest.java
/** {@inheritDoc} */ public void startTestJob(ITestJobPO testJob, Locale locale, boolean autoScreenshot) { TestExecution.getInstance().setStartedTestJob(testJob); m_testjobStartTime = new Date(); try {/* w ww .j a va2 s . c o m*/ final AtomicBoolean isTestExecutionFailed = new AtomicBoolean(false); final AtomicInteger testExecutionMessageId = new AtomicInteger(0); final AtomicInteger testExecutionState = new AtomicInteger(0); final AtomicBoolean isTestExecutionFinished = new AtomicBoolean(false); ITestExecutionEventListener executionListener = new ITestExecutionEventListener() { /** {@inheritDoc} */ public void stateChanged(TestExecutionEvent event) { testExecutionState.set(event.getState().ordinal()); if (event.getState() == State.TEST_EXEC_FAILED) { if (event.getException() instanceof JBException) { JBException e = (JBException) event.getException(); testExecutionMessageId.set(e.getErrorId()); } isTestExecutionFailed.set(true); testExecutionFinished(); } } /** {@inheritDoc} */ public void endTestExecution() { testExecutionFinished(); } private void testExecutionFinished() { isTestExecutionFinished.set(true); removeTestExecutionEventListener(this); } }; List<INodePO> refTestSuiteList = testJob.getUnmodifiableNodeList(); for (INodePO node : refTestSuiteList) { IRefTestSuitePO refTestSuite = (IRefTestSuitePO) node; isTestExecutionFailed.set(false); isTestExecutionFinished.set(false); addTestExecutionEventListener(executionListener); AutIdentifier autId = new AutIdentifier(refTestSuite.getTestSuiteAutID()); startTestSuite(refTestSuite.getTestSuite(), locale, autId, autoScreenshot, null); while (!isTestExecutionFinished.get()) { TimeUtil.delay(500); } if (!continueTestJobExecution(testExecutionState, testExecutionMessageId)) { break; } } } finally { TestExecution.getInstance().setStartedTestJob(null); } }
From source file:org.apache.hadoop.hbase.client.TestHCM.java
private void testConnectionClose(boolean allowsInterrupt) throws Exception { String tableName = "HCM-testConnectionClose" + allowsInterrupt; TEST_UTIL.createTable(tableName.getBytes(), FAM_NAM).close(); boolean previousBalance = TEST_UTIL.getHBaseAdmin().setBalancerRunning(false, true); Configuration c2 = new Configuration(TEST_UTIL.getConfiguration()); // We want to work on a separate connection. c2.set(HConstants.HBASE_CLIENT_INSTANCE_ID, String.valueOf(-1)); c2.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 100); // retry a lot c2.setInt(HConstants.HBASE_CLIENT_PAUSE, 0); // don't wait between retries. c2.setInt(RpcClient.FAILED_SERVER_EXPIRY_KEY, 0); // Server do not really expire c2.setBoolean(RpcClient.ALLOWS_INTERRUPTS, allowsInterrupt); final HTable table = new HTable(c2, tableName.getBytes()); Put put = new Put(ROW); put.add(FAM_NAM, ROW, ROW);//from www. j a v a 2 s .c om table.put(put); // 4 steps: ready=0; doGets=1; mustStop=2; stopped=3 final AtomicInteger step = new AtomicInteger(0); final AtomicReference<Throwable> failed = new AtomicReference<Throwable>(null); Thread t = new Thread("testConnectionCloseThread") { public void run() { int done = 0; try { step.set(1); while (step.get() == 1) { Get get = new Get(ROW); table.get(get); done++; if (done % 100 == 0) LOG.info("done=" + done); } } catch (Throwable t) { failed.set(t); LOG.error(t); } step.set(3); } }; t.start(); TEST_UTIL.waitFor(20000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { return step.get() == 1; } }); ServerName sn = table.getRegionLocation(ROW).getServerName(); ConnectionManager.HConnectionImplementation conn = (ConnectionManager.HConnectionImplementation) table .getConnection(); RpcClient rpcClient = conn.getRpcClient(); LOG.info("Going to cancel connections. connection=" + conn.toString() + ", sn=" + sn); for (int i = 0; i < 5000; i++) { rpcClient.cancelConnections(sn.getHostname(), sn.getPort()); Thread.sleep(5); } step.compareAndSet(1, 2); // The test may fail here if the thread doing the gets is stuck. The way to find // out what's happening is to look for the thread named 'testConnectionCloseThread' TEST_UTIL.waitFor(40000, new Waiter.Predicate<Exception>() { @Override public boolean evaluate() throws Exception { return step.get() == 3; } }); table.close(); Assert.assertTrue("Unexpected exception is " + failed.get(), failed.get() == null); TEST_UTIL.getHBaseAdmin().setBalancerRunning(previousBalance, true); }
From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessSemaphore.java
@Test public void testRelease1AtATime() throws Exception { final int CLIENT_QTY = 10; final int MAX = CLIENT_QTY / 2; final AtomicInteger maxLeases = new AtomicInteger(0); final AtomicInteger activeQty = new AtomicInteger(0); final AtomicInteger uses = new AtomicInteger(0); List<Future<Object>> futures = Lists.newArrayList(); ExecutorService service = Executors.newFixedThreadPool(CLIENT_QTY); for (int i = 0; i < CLIENT_QTY; ++i) { Future<Object> f = service.submit(new Callable<Object>() { @Override/*from ww w . ja v a2 s . c om*/ public Object call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1)); client.start(); try { InterProcessSemaphoreV2 semaphore = new InterProcessSemaphoreV2(client, "/test", MAX); Lease lease = semaphore.acquire(10, TimeUnit.SECONDS); Assert.assertNotNull(lease); uses.incrementAndGet(); try { synchronized (maxLeases) { int qty = activeQty.incrementAndGet(); if (qty > maxLeases.get()) { maxLeases.set(qty); } } Thread.sleep(500); } finally { activeQty.decrementAndGet(); lease.close(); } } finally { client.close(); } return null; } }); futures.add(f); } for (Future<Object> f : futures) { f.get(); } Assert.assertEquals(uses.get(), CLIENT_QTY); Assert.assertEquals(maxLeases.get(), MAX); }
From source file:com.netflix.curator.framework.recipes.queue.TestDistributedQueue.java
@Test public void testErrorMode() throws Exception { Timing timing = new Timing(); CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start();//from w ww . ja v a 2 s . c om try { final AtomicReference<CountDownLatch> latch = new AtomicReference<CountDownLatch>( new CountDownLatch(1)); final AtomicInteger count = new AtomicInteger(0); QueueConsumer<TestQueueItem> consumer = new QueueConsumer<TestQueueItem>() { @Override public void consumeMessage(TestQueueItem message) throws Exception { if (count.incrementAndGet() < 2) { throw new Exception(); } latch.get().countDown(); } @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { } }; DistributedQueue<TestQueueItem> queue = QueueBuilder.builder(client, consumer, serializer, QUEUE_PATH) .lockPath("/locks").buildQueue(); try { queue.start(); TestQueueItem item = new TestQueueItem("1"); queue.put(item); Assert.assertTrue(timing.awaitLatch(latch.get())); Assert.assertEquals(count.get(), 2); queue.setErrorMode(ErrorMode.DELETE); count.set(0); latch.set(new CountDownLatch(1)); item = new TestQueueItem("1"); queue.put(item); Assert.assertFalse(latch.get().await(5, TimeUnit.SECONDS)); // consumer should get called only once Assert.assertEquals(count.get(), 1); } finally { queue.close(); } } finally { client.close(); } }
From source file:org.springframework.integration.mail.ImapMailReceiverTests.java
@SuppressWarnings("resource") @Test/*www. j a v a2 s .c o m*/ public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); adapter.setOutputChannel(channel); ImapMailReceiver receiver = new ImapMailReceiver("imap:foo"); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); final IMAPFolder folder = mock(IMAPFolder.class); given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER)); given(folder.isOpen()).willReturn(false).willReturn(true); given(folder.exists()).willReturn(true); DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); adapterAccessor.setPropertyValue("mailReceiver", receiver); Field storeField = AbstractMailReceiver.class.getDeclaredField("store"); storeField.setAccessible(true); Store store = mock(Store.class); given(store.isConnected()).willReturn(true); given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder); storeField.set(receiver, store); willAnswer(invocation -> folder).given(receiver).getFolder(); MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); given(mailMessage.getFlags()).willReturn(flags); final Message[] messages = new Message[] { mailMessage }; final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2); willAnswer(invocation -> { /* * Return the message from first invocation of waitForMessages() * and in receive(); then return false in the next call to * waitForMessages() so we enter idle(); counter will be reset * to 1 in the mocked idle(). */ if (shouldFindMessagesCounter.decrementAndGet() >= 0) { return messages; } else { return new Message[0]; } }).given(receiver).searchForNewMessages(); willAnswer(invocation -> null).given(receiver).fetchMessages(messages); willAnswer(invocation -> { Thread.sleep(5000); shouldFindMessagesCounter.set(1); return null; }).given(folder).idle(); adapter.start(); /* * Idle takes 5 seconds; if all is well, we should receive the first message * before then. */ assertNotNull(channel.receive(3000)); // We should not receive any more until the next idle elapses assertNull(channel.receive(3000)); assertNotNull(channel.receive(6000)); adapter.stop(); context.close(); }
From source file:com.twitter.distributedlog.BKLogHandler.java
/** * Get a list of all segments in the journal. */// ww w .ja va2 s. c om protected List<LogSegmentMetadata> forceGetLedgerList(final Comparator<LogSegmentMetadata> comparator, final LogSegmentFilter segmentFilter, boolean throwOnEmpty) throws IOException { final List<LogSegmentMetadata> ledgers = new ArrayList<LogSegmentMetadata>(); final AtomicInteger result = new AtomicInteger(-1); final CountDownLatch latch = new CountDownLatch(1); Stopwatch stopwatch = Stopwatch.createStarted(); asyncGetLedgerListInternal(comparator, segmentFilter, null, new GenericCallback<List<LogSegmentMetadata>>() { @Override public void operationComplete(int rc, List<LogSegmentMetadata> logSegmentMetadatas) { result.set(rc); if (KeeperException.Code.OK.intValue() == rc) { ledgers.addAll(logSegmentMetadatas); } else { LOG.error("Failed to get ledger list for {} : with error {}", getFullyQualifiedName(), rc); } latch.countDown(); } }, new AtomicInteger(conf.getZKNumRetries()), new AtomicLong(conf.getZKRetryBackoffStartMillis())); try { latch.await(); } catch (InterruptedException e) { forceGetListStat.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS)); throw new DLInterruptedException( "Interrupted on reading ledger list from zkfor " + getFullyQualifiedName(), e); } long elapsedMicros = stopwatch.stop().elapsed(TimeUnit.MICROSECONDS); KeeperException.Code rc = KeeperException.Code.get(result.get()); if (rc == KeeperException.Code.OK) { forceGetListStat.registerSuccessfulEvent(elapsedMicros); } else { forceGetListStat.registerFailedEvent(elapsedMicros); if (KeeperException.Code.NONODE == rc) { throw new LogNotFoundException("Log " + getFullyQualifiedName() + " is not found"); } else { throw new IOException("ZK Exception " + rc + " reading ledger list for " + getFullyQualifiedName()); } } if (throwOnEmpty && ledgers.isEmpty()) { throw new LogEmptyException("Log " + getFullyQualifiedName() + " is empty"); } return ledgers; }
From source file:com.android.sdklib.internal.repository.DownloadCache.java
/** * Download, cache and return as an in-memory byte stream. * The download is only done if the server returns 200/OK. * On success, store an info file next to the download with * a few headers./*w w w . j av a2 s . c om*/ * <p/> * This method deletes the cached file and the info file ONLY if it * attempted a download and it failed to complete. It doesn't erase * anything if there's no download because the server returned a 404 * or 304 or similar. * * @return An in-memory byte buffer input stream for the downloaded * and locally cached file, or null if nothing was downloaded * (including if it was a 304 Not-Modified status code.) */ @Nullable private InputStream downloadAndCache(@NonNull String urlString, @NonNull ITaskMonitor monitor, @NonNull File cached, @NonNull File info, @Nullable Header[] headers, @Nullable AtomicInteger outStatusCode) throws FileNotFoundException, IOException, CanceledByUserException { InputStream is = null; OutputStream os = null; int inc = 65536; int curr = 0; byte[] result = new byte[inc]; try { Pair<InputStream, HttpResponse> r = openUrl(urlString, true /*needsMarkResetSupport*/, monitor, headers); is = r.getFirst(); HttpResponse response = r.getSecond(); if (DEBUG) { System.out.println(String.format("%s : fetch: %s => %s", //$NON-NLS-1$ urlString, headers == null ? "" : Arrays.toString(headers), //$NON-NLS-1$ response.getStatusLine())); } int code = response.getStatusLine().getStatusCode(); if (outStatusCode != null) { outStatusCode.set(code); } if (code != HttpStatus.SC_OK) { // Only a 200 response code makes sense here. // Even the other 20x codes should not apply, e.g. no content or partial // content are not statuses we want to handle and should never happen. // (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6.1.1 for list) return null; } os = mFileOp.newFileOutputStream(cached); int n; while ((n = is.read(result, curr, result.length - curr)) != -1) { if (os != null && n > 0) { os.write(result, curr, n); } curr += n; if (os != null && curr > MAX_SMALL_FILE_SIZE) { // If the file size exceeds our "small file size" threshold, // stop caching. We don't want to fill the disk. try { os.close(); } catch (IOException ignore) { } try { cached.delete(); info.delete(); } catch (SecurityException ignore) { } os = null; } if (curr == result.length) { byte[] temp = new byte[curr + inc]; System.arraycopy(result, 0, temp, 0, curr); result = temp; } } // Close the output stream, signaling it was stored properly. if (os != null) { try { os.close(); os = null; saveInfo(urlString, response, info); } catch (IOException ignore) { } } return new ByteArrayInputStream(result, 0, curr); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (os != null) { try { os.close(); } catch (IOException ignore) { } // If we get here with the output stream not null, it means there // was an issue and we don't want to keep that file. We'll try to // delete it. try { mFileOp.delete(cached); mFileOp.delete(info); } catch (SecurityException ignore) { } } } }
From source file:org.apache.nifi.cluster.coordination.http.replication.ThreadPoolRequestReplicator.java
/** * When all nodes have completed a request and provided a response (or have timed out), this method will be invoked * to handle calling the Callback that was provided for the request, if any, and handle any cleanup or post-processing * related to the request//from w w w . j a v a2s. co m * * @param requestId the ID of the request that has completed */ private void onCompletedResponse(final String requestId) { final AsyncClusterResponse response = responseMap.get(requestId); if (response != null && callback != null) { try { callback.afterRequest(response.getURIPath(), response.getMethod(), response.getCompletedNodeResponses()); } catch (final Exception e) { logger.warn( "Completed request {} {} but failed to properly handle the Request Completion Callback due to {}", response.getMethod(), response.getURIPath(), e.toString()); logger.warn("", e); } } if (response != null && logger.isDebugEnabled()) { logTimingInfo(response); } // If we have any nodes that are slow to respond, keep track of this. If the same node is slow 3 times in // a row, log a warning to indicate that the node is responding slowly. final Set<NodeIdentifier> slowResponseNodes = ResponseUtils.findLongResponseTimes(response, 1.5D); for (final NodeIdentifier nodeId : response.getNodesInvolved()) { final AtomicInteger counter = sequentialLongRequestCounts.computeIfAbsent(nodeId, id -> new AtomicInteger(0)); if (slowResponseNodes.contains(nodeId)) { final int sequentialLongRequests = counter.incrementAndGet(); if (sequentialLongRequests >= 3) { final String message = "Response time from " + nodeId + " was slow for each of the last 3 requests made. " + "To see more information about timing, enable DEBUG logging for " + logger.getName(); logger.warn(message); if (eventReporter != null) { eventReporter.reportEvent(Severity.WARNING, "Node Response Time", message); } counter.set(0); } } else { counter.set(0); } } }
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 w w w. jav a 2 s . c o m*/ 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); }