List of usage examples for java.lang String subSequence
public CharSequence subSequence(int beginIndex, int endIndex)
From source file:info.guardianproject.otr.app.im.app.ChatView.java
private static String prettyPrintFingerprint(String fingerprint) { StringBuffer spacedFingerprint = new StringBuffer(); for (int i = 0; i + 8 <= fingerprint.length(); i += 8) { spacedFingerprint.append(fingerprint.subSequence(i, i + 8)); spacedFingerprint.append(' '); }//from w ww.jav a 2 s. c om return spacedFingerprint.toString(); }
From source file:jef.tools.StringUtils.java
/** * ?$[key}properties/*from www . ja v a 2 s. c o m*/ * * @param s * @param prop * @return */ public static String convertProperty(String s, Properties prop) { int i = s.indexOf("${"); if (i > -1) { StringBuilder sb = new StringBuilder(); int j = -1; while (i > -1) { sb.append(s.subSequence(j + 1, i)); j = s.indexOf('}', i + 1); String key = ""; if (j > 0) {// Invalid block key = s.substring(i + 2, j); } else { j = s.indexOf("${", i + 2) - 1;// if (j < 0) { j = s.length() - 1; } } if (StringUtils.isEmpty(key)) { sb.append(s.subSequence(i, j + 1));// J } else { String value = prop.getProperty(key); if (value != null) sb.append(value); } i = s.indexOf("${", j); } sb.append(s.substring(j + 1)); return sb.toString(); } return s; }
From source file:org.apache.nutch.parse.ext.WaxExtParser.java
public Parse getParse(Content content) { String contentType = content.getContentType(); String[] params = (String[]) TYPE_PARAMS_MAP.get(contentType); if (params == null) { return new ParseStatus(ParseStatus.FAILED, "No external command defined for contentType: " + contentType).getEmptyParse(getConf()); }//from ww w. ja v a2s . c o m String command = params[0]; int timeout = Integer.parseInt(params[1]); if (LOG.isDebugEnabled()) { LOG.debug("Use " + command + " with timeout=" + timeout + "secs"); } String text = null; String title = null; try { byte[] raw = content.getContent(); String contentLength = content.getMetadata().get("contentLength"); if (contentLength != null && raw.length != Integer.parseInt(contentLength)) { return new ParseStatus(ParseStatus.FAILED, ParseStatus.FAILED_TRUNCATED, "Content truncated at " + raw.length + " bytes (Original was " + contentLength + ". Parser can't handle incomplete " + contentType + " file.") .getEmptyParse(getConf()); } ByteArrayOutputStream os = new ByteArrayOutputStream(BUFFER_SIZE); ByteArrayOutputStream es = new ByteArrayOutputStream(BUFFER_SIZE / 4); CommandRunner cr = new CommandRunner(); cr.setCommand(command + " " + System.getProperty("java.io.tmpdir") + " " + contentType); cr.setInputStream(new ByteArrayInputStream(raw)); cr.setStdOutputStream(os); cr.setStdErrorStream(es); cr.setTimeout(timeout); cr.evaluate(); if (cr.getExitValue() != 0) { return new ParseStatus(ParseStatus.FAILED, "External command " + command + " failed with error: " + es.toString() + ", contentLength " + contentLength + ", raw length " + Integer.toString(raw.length)) .getEmptyParse(getConf()); } text = os.toString(); CharSequence cs = text.subSequence(0, Math.min(512, text.length())); Matcher m = TITLE.matcher(cs); if (m.find()) { if (m.group(1) != null) { title = m.group(1).trim(); } } else { if (LOG.isDebugEnabled()) { LOG.debug("PDFInfo: " + cs.toString()); } } } catch (Exception e) // run time exception { return new ParseStatus(e).getEmptyParse(getConf()); } if (title == null) { title = ""; } if (text == null) { text = ""; } // collect outlink Outlink[] outlinks = OutlinkExtractor.getOutlinks(text, getConf()); ParseData parseData = new ParseData(ParseStatus.STATUS_SUCCESS, title, outlinks, content.getMetadata()); parseData.setConf(this.conf); return new ParseImpl(text, parseData); }
From source file:org.amplafi.json.JSONObject.java
private void writePathInitialization(Writer writer, String root) throws IOException { JSONObject empty = new JSONObject(); if (root != null) { int dotPos = -1; do {/*w w w . j a va2s. c o m*/ dotPos++; if (root.charAt(dotPos) == '.') { throw new JSONException( "double '.', or leading '.' in position " + dotPos + " in string " + root); } dotPos = root.indexOf('.', dotPos); if (dotPos < 0) { writeConditional(writer, true, root, empty); } else if (dotPos == root.length() - 1) { throw new JSONException("trailing '.' in position " + dotPos + " in string " + root); } else { writeConditional(writer, true, root.subSequence(0, dotPos).toString(), empty); } } while (dotPos > 0); } }
From source file:info.staticfree.android.units.Units.java
public void go() { String haveStr = haveEditText.getText().toString().trim(); String wantStr = wantEditText.getText().toString().trim(); try {/*from w ww . j av a 2s. co m*/ Value have = null; try { if (haveStr.length() == 0) { haveEditText.requestFocus(); haveEditText.setError(getText(R.string.err_have_empty)); return; } haveStr = ValueGui.closeParens(haveStr); have = ValueGui.fromUnicodeString(haveStr); } catch (final EvalError e) { haveEditText.requestFocus(); haveEditText.setError(e.getLocalizedMessage()); return; } Value want = null; Function func = null; try { func = DefinedFunction.table.get(wantStr); if (func == null && wantStr.endsWith("(")) { func = DefinedFunction.table.get(wantStr.subSequence(0, wantStr.length() - 1)); } if (func == null) { wantStr = ValueGui.closeParens(wantStr); want = ValueGui.fromUnicodeString(wantStr); } } catch (final EvalError e) { wantEditText.requestFocus(); wantEditText.setError(e.getLocalizedMessage()); return; } Double resultVal; boolean reciprocal = false; try { wantEditText.setError(null); // if no want value is specified, provide a definition. if (wantStr.length() > 0) { if (func != null) { // functions are a special case and don't have a reciprocal, so the result // is just stored in the wantStr. resultVal = null; wantStr = ValueGui.convertNonInteractive(ValueGui.fromUnicodeString(haveStr), func); } else { resultVal = ValueGui.convertNonInteractive(have, want); } } else { resultVal = have.factor; final StringBuffer haveDef = new StringBuffer(); haveDef.append(have.numerator.asString()); if (have.denominator.size() > 0) { haveDef.append(" ").append(have.denominator.asString()); } wantStr = haveDef.toString(); } } catch (final ReciprocalException re) { reciprocal = true; resultVal = ValueGui.convertNonInteractive(re.reciprocal, want); } allClear(); addToHistory(haveStr, wantStr, resultVal, reciprocal); } catch (final ConversionException e) { resultView.setText(null); wantEditText.requestFocus(); wantEditText.setError(getText(R.string.err_no_conform)); return; } }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.structure.devices.impl.DeviceImpl.java
@SuppressWarnings("null") @Override//from ww w . ja va2 s .co m public void saveConfigSceneSpecificationIntoDevice(Map<String, String> propertries) { if (propertries != null) { String sceneSave; for (String key : propertries.keySet()) { if (key.startsWith(DigitalSTROMBindingConstants.DEVICE_SCENE)) { try { short sceneID = Short.parseShort((String) key .subSequence(DigitalSTROMBindingConstants.DEVICE_SCENE.length(), key.length())); sceneSave = propertries.get(key); if (StringUtils.isNotBlank(sceneSave)) { logger.debug("Find saved scene configuration for device with dSID {} and sceneID {}", dsid, key); String[] sceneParm = sceneSave.replace(" ", "").split(","); JSONDeviceSceneSpecImpl sceneSpecNew = null; int sceneValue = -1; int sceneAngle = -1; for (int j = 0; j < sceneParm.length; j++) { String[] sceneParmSplit = sceneParm[j].split(":"); switch (sceneParmSplit[0]) { case "Scene": sceneSpecNew = new JSONDeviceSceneSpecImpl(sceneParmSplit[1]); break; case "dontcare": sceneSpecNew.setDontcare(Boolean.parseBoolean(sceneParmSplit[1])); break; case "localPrio": sceneSpecNew.setLocalPrio(Boolean.parseBoolean(sceneParmSplit[1])); break; case "specialMode": sceneSpecNew.setSpecialMode(Boolean.parseBoolean(sceneParmSplit[1])); break; case "sceneValue": sceneValue = Integer.parseInt(sceneParmSplit[1]); break; case "sceneAngle": sceneAngle = Integer.parseInt(sceneParmSplit[1]); break; } } if (sceneValue > -1) { logger.debug( "Saved sceneValue {}, sceneAngle {} for scene id {} into device with dsid {}", sceneValue, sceneAngle, sceneID, getDSID().getValue()); internalSetSceneOutputValue(sceneID, sceneValue, sceneAngle); deviceStateUpdates .add(new DeviceStateUpdateImpl(DeviceStateUpdate.UPDATE_SCENE_OUTPUT, new Short[] { sceneID, (short) -1 })); } if (sceneSpecNew != null) { logger.debug("Saved sceneConfig: [{}] for scene id {} into device with dsid {}", sceneSpecNew.toString(), sceneID, getDSID().getValue()); synchronized (sceneConfigMap) { sceneConfigMap.put(sceneID, sceneSpecNew); } deviceStateUpdates .add(new DeviceStateUpdateImpl(DeviceStateUpdate.UPDATE_SCENE_CONFIG, new Short[] { sceneID, (short) -1 })); } } } catch (NumberFormatException e) { // ignore } } } } }
From source file:com.sastra.app.timetable.TimetableActivity.java
public boolean onContextItemSelected(android.view.MenuItem item) { data.open();//from www . j a va 2s. co m int day = currentDay = mPager.getCurrentItem(); System.out.println(day); results = data.selectAllFromDay(day); data.close(); AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); String course = results.get(info.position).get("SName").toString(); String type = results.get(info.position).get("HType").toString(); String classroom = results.get(info.position).get("HClass").toString(); String startH = results.get(info.position).get("HStart").toString(); String endH = results.get(info.position).get("HEnd").toString(); switch (item.getItemId()) { case 1: action = "edit"; data.open(); ArrayList<HashMap<String, Object>> arrayS = data.selectSubjects(); data.close(); arraySubjects = new String[arrayS.size()]; colo = new String[arrayS.size()]; Iterator<HashMap<String, Object>> it = arrayS.iterator(); int i = 0; while (it.hasNext()) { HashMap<String, Object> hm = it.next(); arraySubjects[i] = hm.get("SName").toString(); colo[i] = hm.get("SColor").toString(); i++; } newSpinnerAdapter maa = new newSpinnerAdapter(this, R.id.text1, arraySubjects); SName.setAdapter(maa); // Sarrayadapter = new ArrayAdapter<String>(this,R.layout.timetable_spinner_layout,arraySubjects); // Sarrayadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // SName.setAdapter(Sarrayadapter); SName.setSelection(maa.getPosition(course)); String dayS = IDay2SDay(day); HDay.setSelection(arrayadapter.getPosition(dayS)); CharSequence fhour = startH.subSequence(0, 2); CharSequence fminutes = startH.subSequence(3, 5); CharSequence thour = endH.subSequence(0, 2); CharSequence tminutes = endH.subSequence(3, 5); int fhourInt; int fminutesInt; try { fhourInt = Integer.parseInt((String) fhour); fminutesInt = Integer.parseInt((String) fminutes); } catch (Exception e) { fhourInt = 12; fminutesInt = 0; } int thourInt; int tminutesInt; try { thourInt = Integer.parseInt((String) thour); tminutesInt = Integer.parseInt((String) tminutes); } catch (Exception e) { thourInt = 12; tminutesInt = 0; } fromDialog.updateTime(fhourInt, fminutesInt); toDialog.updateTime(thourInt, tminutesInt); start.setText(startH); end.setText(endH); HType.setText(type); HClass.setText(classroom); addDialog.setTitle("Edit Class"); OLDSName = course; OLDHType = type; OLDHClass = classroom; OLDHDay = day; OLDHStart = startH; OLDHEnd = endH; addDialog.show(); break; case 2: OLDSName = course; OLDHType = type; OLDHClass = classroom; OLDHDay = day; OLDHStart = startH; OLDHEnd = endH; alert2.show(); break; } mAdapter.notifyDataSetChanged(); mAdapter.finishUpdate(mPager); //update(); return true; }
From source file:com.halseyburgund.rwframework.core.RWService.java
/** * Updates the text in the RWService notification placed in the Android * notification bar on the screen of the device. * /*w w w. j a va 2 s .c o m*/ * @param message to be displayed */ public void setNotificationText(String message) { if ((mRwNotification != null) && (mNotificationPendingIntent != null)) { NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (nm != null) { if (message != null) { boolean debugMsg = message.startsWith("."); String msg = debugMsg ? message.subSequence(1, message.length()).toString() : message; boolean defaultMsg = message.equalsIgnoreCase(mNotificationDefaultText); if ((!debugMsg) || (mShowDetailedMessages)) { mRwNotification.setLatestEventInfo(this, mNotificationTitle, msg, mNotificationPendingIntent); if (!defaultMsg) { mRwNotification.tickerText = msg; } else { mRwNotification.tickerText = ""; } } } mRwNotification.when = System.currentTimeMillis(); mRwNotification.number = RWActionQueue.instance().count(); nm.notify(NOTIFICATION_ID, mRwNotification); } } }
From source file:edu.jhu.cvrg.ceptools.main.PubMedSearch.java
public Publication convertStore(String fileinfo, Publication currlist) { int fname, fsize, ffigure, fpanel, fdescription = -1; String sname, ssize, sfigure, spanel, sdescription; sname = ssize = sfigure = spanel = sdescription = ""; fsize = fileinfo.indexOf("filesize:"); fdescription = fileinfo.indexOf(",filedescription:"); ffigure = fileinfo.indexOf(",filefigure:"); fpanel = fileinfo.indexOf(",filepanel:"); fname = fileinfo.indexOf(",filename:"); if (fsize != -1 && fdescription != -1) { ssize = (String) fileinfo.subSequence(fsize, fdescription); }/* w ww . j ava2 s.c o m*/ if (ffigure != -1 && fdescription != -1) { sdescription = (String) fileinfo.subSequence(fdescription, ffigure); } if (ffigure != -1 && fpanel != -1) { sfigure = (String) fileinfo.subSequence(ffigure, fpanel); } if (fname != -1 && fpanel != -1) { spanel = (String) fileinfo.subSequence(fpanel, fname); } if (fname != -1) { sname = (String) fileinfo.subSequence(fname, fileinfo.length()); } ssize = ssize.replace("filesize:", ""); sname = sname.replace(",filename:", ""); sdescription = sdescription.replace(",filedescription:", ""); sfigure = sfigure.replace(",filefigure:", ""); spanel = spanel.replace(",filepanel:", ""); String fileloc = PropsUtil.get("data_store2") + currlist.getPmid() + "/"; FileStorer currfile = new FileStorer(); currfile.setDescription(sdescription); currfile.setFigure(sfigure); currfile.setFilesize(Long.valueOf(ssize)); currfile.setFilename(sname); currfile.setPanel(spanel); currfile.setIndex(solrindex); currfile.setFilelocation(fileloc); currfile.setLocalfilestore(fileloc); currlist.getFstorefiles().add(currfile); solrindex++; return currlist; }
From source file:tds.itemscoringengine.ItemScoreResponse.java
private void writeXmlInternal(Object out) throws XMLStreamException { try {//from ww w .ja v a 2s . co m Marshaller jaxbMarshaller = JAXBContext.newInstance(ItemScoreResponse.class).createMarshaller(); // Shiva: We do not want to escape CDATA. JaxB does not internally // support // it. // Here is an alternate way to achieve the same thing: // http://odedpeer.blogspot.com/2010/07/jaxb-sun-and-how-to-marshal-cdata.html // However this is a sun internal class and we probably should not // be // using. TODO. There may be "access restriction" issues: // http://stackoverflow.com/questions/860187/access-restriction-on-class-due-to-restriction-on-required-library-rt-jar // http://stackoverflow.com/questions/16653519/jaxb-marshal-setproperty-com-sun-xml-bind-characterescapehandler jaxbMarshaller.setProperty("com.sun.xml.bind.characterEscapeHandler", new CharacterEscapeHandler() { @Override public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException { if (ac != null && i < ac.length && (i + j) <= ac.length) { StringBuilder incomingStringBuilder = new StringBuilder(); for (int counter1 = i; counter1 < i + j; ++counter1) { incomingStringBuilder.append(ac[counter1]); } String incomingString = incomingStringBuilder.toString(); final String BEGIN_CDATA = "<![CDATA["; final String END_CDATA = "]]>"; StringBuilder outgoingString = new StringBuilder(); // there may be multiple CDATA sections. first lets find the index // of "<![CDATA[". // Shiva: Assumptions 1) the CDATA section is whole i.e. we will not // see something like "abc <!CDATA[ x y z". instead we will see // "abc <!CDATA[ x y z ]]> m n o p" // 2) CDATA may be anywhere. 3) there may be multiple CDATA segments // but each will be whole. int currentIndex = 0; while (currentIndex < incomingString.length()) { int indexOfBeginCdata = incomingString.indexOf(BEGIN_CDATA, currentIndex); if (indexOfBeginCdata >= 0) { if (indexOfBeginCdata != currentIndex) { // we will copy everything upto the begining of CDATA and // escape it. String substr = incomingString.substring(currentIndex, indexOfBeginCdata); outgoingString.append(StringEscapeUtils.escapeXml(substr)); } // lets move the current index to at least after the match. currentIndex = indexOfBeginCdata + BEGIN_CDATA.length(); // do we have a end cdata int indexOfEndCData = incomingString.indexOf(END_CDATA, currentIndex); // because of our assumptions above we are not going to check if // this is < 0. outgoingString.append(incomingString.subSequence(indexOfBeginCdata, indexOfEndCData + END_CDATA.length())); // move currentIndex again. currentIndex = indexOfEndCData + END_CDATA.length(); } else { // no more CDATA sections left. outgoingString.append(StringEscapeUtils.escapeXml( incomingString.substring(currentIndex, incomingString.length()))); break; } } writer.write(outgoingString.toString()); // do not escape } else { // TODO Shiva: if they are not within the range then I do not know // what to do. i will just let it go. writer.write(ac, i, j); } } }); if (out instanceof OutputStream) jaxbMarshaller.marshal(this, (OutputStream) out); else if (out instanceof XMLStreamWriter) jaxbMarshaller.marshal(this, (XMLStreamWriter) out); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); _logger.error("Exception writing ItemScoreResponse", e); throw new XMLStreamException(e); } }