List of usage examples for java.lang InterruptedException InterruptedException
public InterruptedException()
InterruptedException
with no detail message. From source file:net.wimpi.telnetd.util.Mutex.java
public boolean attempt(long msecs) throws InterruptedException { //log.debug("attempt()::" + Thread.currentThread().toString()); if (Thread.interrupted()) throw new InterruptedException(); synchronized (this) { if (!inuse_) { inuse_ = true;// ww w . j a va 2s . c o m return true; } else if (msecs <= 0) return false; else { long waitTime = msecs; long start = System.currentTimeMillis(); try { for (;;) { wait(waitTime); if (!inuse_) { inuse_ = true; return true; } else { waitTime = msecs - (System.currentTimeMillis() - start); if (waitTime <= 0) return false; } } } catch (InterruptedException ex) { notify(); throw ex; } } } }
From source file:com.kabootar.GlassMemeGenerator.ImageOverlay.java
/** * Draws the given string centered, as big as possible, on either the top or * bottom 20% of the image given./*ww w . j a va 2 s . co m*/ */ private static void drawStringCentered(Canvas g, String text, Bitmap image, boolean top, Context baseContext) throws InterruptedException { if (text == null) text = ""; int height = 0; int fontSize = MAX_FONT_SIZE; int maxCaptionHeight = image.getHeight() / 5; int maxLineWidth = image.getWidth() - SIDE_MARGIN * 2; String formattedString = ""; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); Paint stkPaint = new Paint(Paint.ANTI_ALIAS_FLAG); stkPaint.setStyle(STROKE); stkPaint.setStrokeWidth(8); stkPaint.setColor(Color.BLACK); //Typeface tf = Typeface.create("Arial", Typeface.BOLD); Typeface tf = Typeface.createFromAsset(baseContext.getAssets(), "fonts/impact.ttf"); paint.setTypeface(tf); stkPaint.setTypeface(tf); do { paint.setTextSize(fontSize); // first inject newlines into the text to wrap properly StringBuilder sb = new StringBuilder(); int left = 0; int right = text.length() - 1; while (left < right) { String substring = text.substring(left, right + 1); Rect stringBounds = new Rect(); paint.getTextBounds(substring, 0, substring.length(), stringBounds); while (stringBounds.width() > maxLineWidth) { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException(); } // look for a space to break the line boolean spaceFound = false; for (int i = right; i > left; i--) { if (text.charAt(i) == ' ') { right = i - 1; spaceFound = true; break; } } substring = text.substring(left, right + 1); paint.getTextBounds(substring, 0, substring.length(), stringBounds); // If we're down to a single word and we are still too wide, // the font is just too big. if (!spaceFound && stringBounds.width() > maxLineWidth) { break; } } sb.append(substring).append("\n"); left = right + 2; right = text.length() - 1; } formattedString = sb.toString(); // now determine if this font size is too big for the allowed height height = 0; for (String line : formattedString.split("\n")) { Rect stringBounds = new Rect(); paint.getTextBounds(line, 0, line.length(), stringBounds); height += stringBounds.height(); } fontSize--; } while (height > maxCaptionHeight); // draw the string one line at a time int y = 0; if (top) { y = TOP_MARGIN; } else { y = image.getHeight() - height - BOTTOM_MARGIN; } for (String line : formattedString.split("\n")) { // Draw each string twice for a shadow effect Rect stringBounds = new Rect(); paint.getTextBounds(line, 0, line.length(), stringBounds); //paint.setColor(Color.BLACK); //g.drawText(line, (image.getWidth() - (int) stringBounds.width()) / 2 + 2, y + stringBounds.height() + 2, paint); paint.setColor(Color.WHITE); g.drawText(line, (image.getWidth() - (int) stringBounds.width()) / 2, y + stringBounds.height(), paint); //stroke Rect strokeBounds = new Rect(); stkPaint.setTextSize(fontSize); stkPaint.getTextBounds(line, 0, line.length(), strokeBounds); g.drawText(line, (image.getWidth() - (int) strokeBounds.width()) / 2, y + strokeBounds.height(), stkPaint); y += stringBounds.height(); } }
From source file:eu.stratosphere.nephele.io.channels.bytebuffered.AbstractByteBufferedOutputChannel.java
/** * Requests a new write buffer from the framework. This method blocks until the requested buffer is available. * // w w w . j a v a 2 s. c o m * @throws InterruptedException * thrown if the thread is interrupted while waiting for the buffer * @throws IOException * thrown if an I/O error occurs while waiting for the buffer */ private void requestWriteBufferFromBroker() throws InterruptedException, IOException { if (Thread.interrupted()) { throw new InterruptedException(); } this.dataBuffer = this.outputChannelBroker.requestEmptyWriteBuffer(); }
From source file:org.ut.biolab.medsavant.client.util.ExportVCF.java
public static File exportVCF(File destFile, MedSavantWorker worker, Condition[][] conditions) throws Exception { int fileID = MedSavantClient.VariantManager.exportVariants(LoginController.getSessionID(), ProjectController.getInstance().getCurrentProjectID(), ReferenceController.getInstance().getCurrentReferenceID(), conditions, true, false); if (worker != null) { if (worker.isCancelled()) { throw new InterruptedException(); }/*from w w w .ja va 2 s. c o m*/ worker.showProgress(0.5); } LOG.info("Copying file " + fileID + " from sever to " + destFile.getAbsolutePath()); ClientNetworkUtils.moveFileFromServer(fileID, destFile); LOG.info("Done copying file to " + destFile); // maintain lists of chrs, dnaids, ... Map<String, BufferedWriter> out = new HashMap<String, BufferedWriter>(); Map<String, File> files = new HashMap<String, File>(); List<String> chrs = new ArrayList<String>(); Set<String> dnaIds = new HashSet<String>(); // info fields TableSchema table = ProjectController.getInstance().getCurrentVariantTableSchema(); String[] customColumnNames = new String[table.getNumFields() - INDEX_OF_CUSTOM_INFO - 1]; List<DbColumn> allColumns = table.getColumns(); for (int i = INDEX_OF_CUSTOM_INFO + 1; i < table.getNumFields(); i++) { customColumnNames[i - 1 - INDEX_OF_CUSTOM_INFO] = allColumns.get(i).getColumnNameSQL().toUpperCase(); } int infoMin = INDEX_OF_CUSTOM_INFO + 1; int infoMax = table.getNumFields(); BufferedReader in = new BufferedReader(new FileReader(destFile)); double numSteps = ReferenceController.getInstance().getChromosomes().length * 6; String line; while ((line = in.readLine()) != null) { // parse row //String[] record = line.split(","); String[] record = line.split("\t"); String row = ""; // dna id String dnaId = cleanField(record[BasicVariantColumns.INDEX_OF_DNA_ID]); row += dnaId + "\t"; dnaIds.add(dnaId); // genotype row += cleanField(record[BasicVariantColumns.INDEX_OF_GT]) + "\t"; // default fields row += cleanField(record[BasicVariantColumns.INDEX_OF_CHROM]) + "\t" + cleanField(record[BasicVariantColumns.INDEX_OF_START_POSITION]) + "\t" + parseMandatoryField(cleanField(record[BasicVariantColumns.INDEX_OF_DBSNP_ID])) + "\t" + parseMandatoryField(cleanField(record[BasicVariantColumns.INDEX_OF_REF])) + "\t" + parseMandatoryField(cleanField(record[BasicVariantColumns.INDEX_OF_ALT])) + "\t" + parseMandatoryField(cleanField(record[BasicVariantColumns.INDEX_OF_QUAL])) + "\t" + parseMandatoryField(cleanField(record[BasicVariantColumns.INDEX_OF_FILTER])) + "\t"; // extra fields for (int j = infoMin; j < infoMax; j++) { if (j < record.length) { row += cleanField(record[j]); } if (j != infoMax - 1) { row += "\t"; } } // get writer for chrom, or create BufferedWriter writer = out.get(cleanField(record[BasicVariantColumns.INDEX_OF_CHROM])); if (writer == null) { String chrom = cleanField(record[BasicVariantColumns.INDEX_OF_CHROM]); File f = new File( DirectorySettings.getTmpDirectory() + File.separator + destFile.getName() + chrom); writer = new BufferedWriter(new FileWriter(f, false)); out.put(chrom, writer); chrs.add(chrom); files.put(chrom, f); if (worker != null) { worker.showProgress(files.size() / numSteps + 0.5); } } // write record writer.write(row + "\n"); if (worker != null) { if (worker.isCancelled()) { throw new InterruptedException(); } } } // close writers for (String key : out.keySet()) { out.get(key).close(); } // concatenate separate chrom files in proper order Collections.sort(chrs, new ChromosomeComparator()); File temp1 = new File( DirectorySettings.getTmpDirectory() + File.separator + destFile.getName() + "_complete"); for (int i = 0; i < files.size(); i++) { copyFile(files.get(chrs.get(i)), temp1, i != 0); if (worker != null) { if (worker.isCancelled()) { throw new InterruptedException(); } worker.showProgress((i + files.size()) / numSteps + 0.5); } } // merge vcf to remove duplicates mergeVCF(temp1, destFile, dnaIds, customColumnNames); if (worker != null) { worker.showProgress(1.0); } return destFile; }
From source file:com.google.zxing.client.android.result.supplement.SupplementalInfoRetriever.java
final void append(String itemID, String source, String[] newTexts, String linkURL) throws InterruptedException { final TextView textView = textViewRef.get(); if (textView == null) { throw new InterruptedException(); }//from ww w .jav a 2 s . co m StringBuilder newTextCombined = new StringBuilder(); if (source != null) { newTextCombined.append(source).append(" : "); } int linkStart = newTextCombined.length(); boolean first = true; for (String newText : newTexts) { if (first) { newTextCombined.append(newText); first = false; } else { newTextCombined.append(" ["); newTextCombined.append(newText); newTextCombined.append(']'); } } int linkEnd = newTextCombined.length(); String newText = newTextCombined.toString(); final Spannable content = new SpannableString(newText + "\n\n"); if (linkURL != null) { content.setSpan(new URLSpan(linkURL), linkStart, linkEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } handler.post(new Runnable() { public void run() { textView.append(content); textView.setMovementMethod(LinkMovementMethod.getInstance()); } }); // Add the text to the history. historyManager.addHistoryItemDetails(itemID, newText); }
From source file:org.geowebcache.seed.GWCTask.java
protected void checkInterrupted() throws InterruptedException { if (Thread.interrupted()) { this.state = STATE.DEAD; throw new InterruptedException(); }/*from w w w . ja v a2s.com*/ }
From source file:net.technicpack.launchercore.mirror.MirrorStore.java
public Download downloadFile(String url, String name, String output, File cache, IFileVerifier verifier, DownloadListener listener) throws IOException, InterruptedException { int tries = DOWNLOAD_RETRIES; File outputFile = null;//w ww . j a v a 2 s .c o m Download download = null; while (tries > 0) { Utils.getLogger().info("Starting download of " + url + ", with " + tries + " tries remaining"); tries--; download = new Download(getFullUrl(url), name, output); download.setListener(listener); download.run(); if (download.getResult() != Download.Result.SUCCESS) { if (download.getOutFile() != null) { download.getOutFile().delete(); } if (Thread.interrupted()) throw new InterruptedException(); System.err.println("Download of " + url + " Failed!"); if (listener != null) { listener.stateChanged("Download failed, retries remaining: " + tries, 0F); } } else { if (download.getOutFile().exists() && (verifier == null || verifier.isFileValid(download.getOutFile()))) { outputFile = download.getOutFile(); break; } } } if (outputFile == null) { throw new DownloadException("Failed to download " + url, download != null ? download.getException() : null); } if (cache != null) { FileUtils.copyFile(outputFile, cache); } return download; }
From source file:com.joyepay.qrcode.result.supplement.SupplementalInfoRetriever.java
final void append(String itemID, String source, String[] newTexts, String linkURL) throws InterruptedException { final TextView textView = textViewRef.get(); if (textView == null) { throw new InterruptedException(); }/* w w w . j a v a 2 s . co m*/ StringBuilder newTextCombined = new StringBuilder(); if (source != null) { newTextCombined.append(source).append(" : "); } int linkStart = newTextCombined.length(); boolean first = true; for (String newText : newTexts) { if (first) { newTextCombined.append(newText); first = false; } else { newTextCombined.append(" ["); newTextCombined.append(newText); newTextCombined.append(']'); } } int linkEnd = newTextCombined.length(); String newText = newTextCombined.toString(); final Spannable content = new SpannableString(newText + "\n\n"); if (linkURL != null) { content.setSpan(new URLSpan(linkURL), linkStart, linkEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } handler.post(new Runnable() { public void run() { textView.append(content); textView.setMovementMethod(LinkMovementMethod.getInstance()); } }); // Add the text to the history. // historyManager.addHistoryItemDetails(itemID, newText); }
From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java
@Override public Collection<Playground> getAll(Context context) { // synchronized (Swingset.initPlaygroundLock) { playgrounds = new ArrayList<Playground>(); String result = swingset.getResources().getString(R.string.error); HttpURLConnection httpConnection = null; Log.d(TAG, "getPlaygrounds()"); try {//from www . ja v a 2s. c o m // Check if task has been interrupted if (Thread.interrupted()) { throw new InterruptedException(); } // Build query URL url = new URL("http://swingsetweb.appspot.com/playground"); httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(15000); httpConnection.setReadTimeout(15000); StringBuilder response = new StringBuilder(); if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { // Read results from the query BufferedReader input = new BufferedReader( new InputStreamReader(httpConnection.getInputStream(), "UTF-8")); String strLine = null; while ((strLine = input.readLine()) != null) { response.append(strLine); } input.close(); } // Parse to get translated text JSONArray jsonPlaygrounds = new JSONArray(response.toString()); int numOfPlaygrounds = jsonPlaygrounds.length(); JSONObject jsonPlayground = null; for (int i = 0; i < numOfPlaygrounds; i++) { jsonPlayground = jsonPlaygrounds.getJSONObject(i); playgrounds.add(toPlayground(jsonPlayground)); } } catch (Exception e) { Log.e(TAG, "Exception", e); Intent errorIntent = new Intent(context, Playgrounds.class); errorIntent.putExtra("Exception", e.getLocalizedMessage()); errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(errorIntent); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } // all done Log.d(TAG, " -> returned " + result); return playgrounds; // } }
From source file:savant.data.sources.TDFDataSource.java
@Override public List<GenericContinuousRecord> getRecords(String ref, RangeAdapter r, Resolution res, RecordFilterAdapter filt) throws IOException, InterruptedException { List<GenericContinuousRecord> result = new ArrayList<GenericContinuousRecord>(); TDFDataset ds = getTDFDataset(ref, (Range) r); if (ds != null) { int nextPos = r.getFrom(); int rangeEnd = r.getTo() + 1; int usefulStep = Math.max(1, r.getLength() / NOTIONAL_SCREEN_WIDTH); // No need for more points than we have pixels. List<TDFTile> tiles = ds.getTiles(r.getFrom(), rangeEnd); for (TDFTile t : tiles) { for (int i = 0; i < t.getSize() && nextPos <= rangeEnd; i++) { int datumEnd = t.getEndPosition(i); if (nextPos < datumEnd) { int datumStart = t.getStartPosition(i); // If there's a gap before the data starts, fill it with NaNs. if (datumStart == nextPos + 1 && usefulStep > 2) { // Special case. TDF formatter occasionally leaves a gap of one base between tiles. This isn't a real NaN. LOG.debug("Skipping NaN hole at " + nextPos); } else { while (nextPos < datumStart && nextPos <= rangeEnd) { result.add(GenericContinuousRecord.valueOf(ref, nextPos, Float.NaN)); nextPos += usefulStep; }/* ww w . j ava 2 s .c om*/ } float datum = t.getValue(0, i); LOG.debug("Tile " + i + " from " + datumStart + " to " + datumEnd + "=" + datum); while (nextPos < datumEnd && nextPos <= rangeEnd) { result.add(GenericContinuousRecord.valueOf(ref, nextPos, datum)); nextPos += usefulStep; } } } if (Thread.interrupted()) { throw new InterruptedException(); } } } return result; }