code
stringlengths
10
174k
nl
stringlengths
3
129k
public static void save(final String path,final byte[] data){ if (!TextUtils.isEmpty(path) && data != null && data.length > 0) { FileOutputStream out=null; try { File destFile=createFile(path); out=new FileOutputStream(destFile); out.write(data); } catch ( FileNotFoundException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.flush(); out.close(); } } catch ( IOException e) { e.printStackTrace(); } } } }
save data to a file
public String resolveTemplate(ITemplateType templateType,Map<String,String> replacements) throws IOException { Path path=getTemplatePath(templateType); String template=new String(Files.readAllBytes(path),StandardCharsets.UTF_8); return insertProperties(template,replacements); }
Resolves a template for the given template type and set of placeholder to replace.
public static int uninstallSilent(Context context,String packageName,boolean isKeepData){ if (packageName == null || packageName.length() == 0) { return DELETE_FAILED_INVALID_PACKAGE; } StringBuilder command=new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall").append(isKeepData ? " -k " : " ").append(packageName.replace(" ","\\ ")); ShellUtils.CommandResult commandResult=ShellUtils.execCommand(command.toString(),!isSystemApplication(context),true); if (commandResult.successMsg != null && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) { return DELETE_SUCCEEDED; } Log.e(TAG,new StringBuilder().append("uninstallSilent successMsg:").append(commandResult.successMsg).append(", ErrorMsg:").append(commandResult.errorMsg).toString()); if (commandResult.errorMsg == null) { return DELETE_FAILED_INTERNAL_ERROR; } if (commandResult.errorMsg.contains("Permission denied")) { return DELETE_FAILED_PERMISSION_DENIED; } return DELETE_FAILED_INTERNAL_ERROR; }
uninstall package silent by root <ul> <strong>Attentions:</strong> <li>Don't call this on the ui thread, it may costs some times.</li> <li>You should add <strong>android.permission.DELETE_PACKAGES</strong> in manifest, so no need to request root permission, if you are system app.</li> </ul>
public ArrestWarrantList(final StendhalRPZone zone){ super(zone,ArrestWarrant.class); }
Creates a new ArrestWarrantList.
public static String byteCountToDisplaySize(BigInteger size){ String displaySize; if (size.divide(ONE_EB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize=String.valueOf(size.divide(ONE_EB_BI)) + " EB"; } else if (size.divide(ONE_PB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize=String.valueOf(size.divide(ONE_PB_BI)) + " PB"; } else if (size.divide(ONE_TB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize=String.valueOf(size.divide(ONE_TB_BI)) + " TB"; } else if (size.divide(ONE_GB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize=String.valueOf(size.divide(ONE_GB_BI)) + " GB"; } else if (size.divide(ONE_MB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize=String.valueOf(size.divide(ONE_MB_BI)) + " MB"; } else if (size.divide(ONE_KB_BI).compareTo(BigInteger.ZERO) > 0) { displaySize=String.valueOf(size.divide(ONE_KB_BI)) + " KB"; } else { displaySize=String.valueOf(size) + " bytes"; } return displaySize; }
Returns a human-readable version of the file size, where the input represents a specific number of bytes. <p> If the size is over 1GB, the size is returned as the number of whole GB, i.e. the size is rounded down to the nearest GB boundary. </p> <p> Similarly for the 1MB and 1KB boundaries. </p>
protected static LocaleData lookupLocaleData(String code){ LocaleData localeData=locales.get(code); if (localeData == null) { String[] data=decodeLocaleCode(code); localeData=new LocaleData(new Locale(data[0],data[1],data[2])); locales.put(code,localeData); } return localeData; }
Lookups for locale data and creates new if it doesn't exist.
public Period toPeriodFrom(ReadableInstant startInstant,PeriodType type){ return new Period(startInstant,this,type); }
Converts this duration to a Period instance by adding the duration to a start instant to obtain an interval. <p> This conversion will determine the fields of a period accurately. The results are based on the instant millis, the chronology of the instant, the period type and the length of this duration.
public boolean bound(){ return bound; }
Returns true if the shader is bound, false otherwise.
public JSONObject(Map<String,Object> map){ this.map=new HashMap<String,Object>(); if (map != null) { Iterator<Entry<String,Object>> i=map.entrySet().iterator(); while (i.hasNext()) { Entry<String,Object> entry=i.next(); Object value=entry.getValue(); if (value != null) { this.map.put(entry.getKey(),wrap(value)); } } } }
Construct a JSONObject from a Map.
private void populateDatabase(String username){ Group defaultPublicGroup=Group.getDefaultGroup(); DatabaseFactory.getGroupDatabase(this).insertGroup(defaultPublicGroup); Contact marlinski=new Contact(RUMBLE_AUTHOR_NAME,"/Marlinski/=",false); DatabaseFactory.getContactDatabase(this).insertOrUpdateContact(marlinski); long contactDBID=DatabaseFactory.getContactDatabase(this).getContactDBID(marlinski.getUid()); long groupDBID=DatabaseFactory.getGroupDatabase(this).getGroupDBID(defaultPublicGroup.getGid()); DatabaseFactory.getContactJoinGroupDatabase(this).insertContactGroup(contactDBID,groupDBID); long time=System.currentTimeMillis(); PushStatus message4=new PushStatus(marlinski,defaultPublicGroup,getResources().getString(R.string.swipe_down),time,marlinski.getUid()); message4.setTimeOfExpiration(0); DatabaseFactory.getPushStatusDatabase(this).insertStatus(message4); time=System.currentTimeMillis(); PushStatus message3=new PushStatus(marlinski,defaultPublicGroup,getResources().getString(R.string.swipe_right),time,marlinski.getUid()); message3.setTimeOfExpiration(0); DatabaseFactory.getPushStatusDatabase(this).insertStatus(message3); time=System.currentTimeMillis(); PushStatus message2=new PushStatus(marlinski,defaultPublicGroup,getResources().getString(R.string.swipe_left),time,marlinski.getUid()); message2.setTimeOfExpiration(0); DatabaseFactory.getPushStatusDatabase(this).insertStatus(message2); time=System.currentTimeMillis(); PushStatus message1=new PushStatus(marlinski,defaultPublicGroup,getResources().getString(R.string.welcome_notice),time,marlinski.getUid()); message1.setTimeOfExpiration(0); DatabaseFactory.getPushStatusDatabase(this).insertStatus(message1); time=System.currentTimeMillis(); ChatMessage message5=new ChatMessage(marlinski,getResources().getString(R.string.chat_message_tuto),time,time,RumbleProtocol.protocolID); DatabaseFactory.getChatMessageDatabase(this).insertMessage(message5); Contact localContact=Contact.createLocalContact(username); DatabaseFactory.getContactDatabase(this).insertOrUpdateContact(localContact); contactDBID=DatabaseFactory.getContactDatabase(this).getContactDBID(localContact.getUid()); groupDBID=DatabaseFactory.getGroupDatabase(this).getGroupDBID(defaultPublicGroup.getGid()); DatabaseFactory.getContactJoinGroupDatabase(this).insertContactGroup(contactDBID,groupDBID); }
Insert a few explaining messages and the Marlinski user into the database
public synchronized void accept() throws IOException { if (_acceptable) { _acceptable=false; int[] ip=_bot.longToIp(_address); String ipStr=ip[0] + "." + ip[1]+ "."+ ip[2]+ "."+ ip[3]; _socket=new Socket(ipStr,_port); _reader=new BufferedReader(new InputStreamReader(_socket.getInputStream())); _writer=new BufferedWriter(new OutputStreamWriter(_socket.getOutputStream())); } }
Accept this DccChat connection.
public boolean isDescending(){ return isDescending; }
Returns true for ascending, false for descending.
public Query limit(int limit,int offset){ return limit(limit < 0 ? NO_LIMIT : Field.<Integer>field(Integer.toString(limit)),offset < 1 ? NO_OFFSET : Field.<Integer>field(Integer.toString(offset))); }
Set the limit and offset of this statement. Use a negative value for limit to remove the limit. Use a value less than one for offset to remove the offset.
private Follower createFollowerItem(String stream,String name,String display_name,long time){ if (name == null) { return null; } if (display_name == null || display_name.trim().isEmpty()) { display_name=name; } stream=StringUtil.toLowerCase(stream); if (!alreadyFollowed.containsKey(stream)) { alreadyFollowed.put(stream,new HashMap<String,Follower>()); } Map<String,Follower> entries=alreadyFollowed.get(stream); Follower existingEntry=entries.get(name); boolean refollow=false; boolean newFollow=true; if (existingEntry != null) { newFollow=false; if (existingEntry.time != time) { refollow=true; } } if (!requested.contains(stream)) { newFollow=false; } Follower newEntry=new Follower(type,name,display_name,time,refollow,newFollow); if (existingEntry == null) { alreadyFollowed.get(stream).put(name,newEntry); } return newEntry; }
Creates a new Follower item with the given values, also adding information about whether it is a refollow/new follower in this request.
private void removeStaleSpans(){ Iterator<Entry<String,TreeSet<CacheSpan>>> iterator=cachedSpans.entrySet().iterator(); while (iterator.hasNext()) { Entry<String,TreeSet<CacheSpan>> next=iterator.next(); Iterator<CacheSpan> spanIterator=next.getValue().iterator(); boolean isEmpty=true; while (spanIterator.hasNext()) { CacheSpan span=spanIterator.next(); if (!span.file.exists()) { spanIterator.remove(); if (span.isCached) { totalSpace-=span.length; } notifySpanRemoved(span); } else { isEmpty=false; } } if (isEmpty) { iterator.remove(); } } }
Scans all of the cached spans in the in-memory representation, removing any for which files no longer exist.
@Override public int read(){ return -1; }
Returns -1 to indicate that the stream is closed.
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:11.205 -0500",hash_original_method="2785BD3BA93222E8AB5B460FDCCCF9E9",hash_generated_method="3A258E0C2116CB2D762D495F6C5139B6") private static SslError verifyServerDomainAndCertificates(X509Certificate[] chain,String domain,String authType) throws IOException { X509Certificate currCertificate=chain[0]; if (currCertificate == null) { throw new IllegalArgumentException("certificate for this site is null"); } if (!DomainNameValidator.match(currCertificate,domain)) { if (HttpLog.LOGV) { HttpLog.v("certificate not for this host: " + domain); } return new SslError(SslError.SSL_IDMISMATCH,currCertificate); } try { SSLParametersImpl.getDefaultTrustManager().checkServerTrusted(chain,authType); return null; } catch ( CertificateException e) { if (HttpLog.LOGV) { HttpLog.v("failed to validate the certificate chain, error: " + e.getMessage()); } return new SslError(SslError.SSL_UNTRUSTED,currCertificate); } }
Common code of doHandshakeAndValidateServerCertificates and verifyServerCertificates. Calls DomainNamevalidator to verify the domain, and TrustManager to verify the certs.
public Finds(){ super("text_information.finds"); }
Creates a function which checks whether any substring of a nominal Value matches a regular expression
public SuggestWord[][] suggestWordBreaks(Term term,int maxSuggestions,IndexReader ir,SuggestMode suggestMode,BreakSuggestionSortMethod sortMethod) throws IOException { if (maxSuggestions < 1) { return new SuggestWord[0][0]; } if (suggestMode == null) { suggestMode=SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX; } if (sortMethod == null) { sortMethod=BreakSuggestionSortMethod.NUM_CHANGES_THEN_MAX_FREQUENCY; } int queueInitialCapacity=maxSuggestions > 10 ? 10 : maxSuggestions; Comparator<SuggestWordArrayWrapper> queueComparator=sortMethod == BreakSuggestionSortMethod.NUM_CHANGES_THEN_MAX_FREQUENCY ? new LengthThenMaxFreqComparator() : new LengthThenSumFreqComparator(); Queue<SuggestWordArrayWrapper> suggestions=new PriorityQueue<>(queueInitialCapacity,queueComparator); int origFreq=ir.docFreq(term); if (origFreq > 0 && suggestMode == SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX) { return new SuggestWord[0][]; } int useMinSuggestionFrequency=minSuggestionFrequency; if (suggestMode == SuggestMode.SUGGEST_MORE_POPULAR) { useMinSuggestionFrequency=(origFreq == 0 ? 1 : origFreq); } generateBreakUpSuggestions(term,ir,1,maxSuggestions,useMinSuggestionFrequency,new SuggestWord[0],suggestions,0,sortMethod); SuggestWord[][] suggestionArray=new SuggestWord[suggestions.size()][]; for (int i=suggestions.size() - 1; i >= 0; i--) { suggestionArray[i]=suggestions.remove().suggestWords; } return suggestionArray; }
<p> Generate suggestions by breaking the passed-in term into multiple words. The scores returned are equal to the number of word breaks needed so a lower score is generally preferred over a higher score. </p>
private void parseWidths(PDFObject fontObj) throws IOException { PDFObject defaultWidthObj=fontObj.getDictRef("DW"); if (defaultWidthObj != null) { defaultWidth=defaultWidthObj.getIntValue(); } int entryIdx=0; int first=0; int last=0; PDFObject[] widthArray; PDFObject widthObj=fontObj.getDictRef("W"); if (widthObj != null) { widths=new HashMap<Character,Float>(); widthArray=widthObj.getArray(); for (int i=0; i < widthArray.length; i++) { if (entryIdx == 0) { first=widthArray[i].getIntValue(); } else if (entryIdx == 1) { if (widthArray[i].getType() == PDFObject.ARRAY) { PDFObject[] entries=widthArray[i].getArray(); for (int c=0; c < entries.length; c++) { Character key=new Character((char)(c + first)); float value=entries[c].getIntValue(); widths.put(key,new Float(value)); } entryIdx=-1; } else { last=widthArray[i].getIntValue(); } } else { int value=widthArray[i].getIntValue(); for (int c=first; c <= last; c++) { widths.put(new Character((char)c),new Float(value)); } entryIdx=-1; } entryIdx++; } } defaultWidthObj=fontObj.getDictRef("DW2"); if (defaultWidthObj != null) { defaultWidthVertical=defaultWidthObj.getIntValue(); } widthObj=fontObj.getDictRef("W2"); if (widthObj != null) { widthsVertical=new HashMap<Character,Float>(); widthArray=widthObj.getArray(); entryIdx=0; first=0; last=0; for (int i=0; i < widthArray.length; i++) { if (entryIdx == 0) { first=widthArray[i].getIntValue(); } else if (entryIdx == 1) { if (widthArray[i].getType() == PDFObject.ARRAY) { PDFObject[] entries=widthArray[i].getArray(); for (int c=0; c < entries.length; c++) { Character key=new Character((char)(c + first)); float value=entries[c].getIntValue(); widthsVertical.put(key,new Float(value)); } entryIdx=-1; } else { last=widthArray[i].getIntValue(); } } else { int value=widthArray[i].getIntValue(); for (int c=first; c <= last; c++) { widthsVertical.put(new Character((char)c),new Float(value)); } entryIdx=-1; } entryIdx++; } } }
Parse the Widths array and DW object
@Nullable private File[] listFiles0(IgfsPath path){ File f=fileForPath(path); if (!f.exists()) throw new IgfsPathNotFoundException("Failed to list files (path not found): " + path); else return f.listFiles(); }
Returns an array of File object. Under the specific path.
protected void updateElements(MWebProject project,MCStage stage,String trxName){ org.compiere.cm.CacheHandler thisHandler=new org.compiere.cm.CacheHandler(org.compiere.cm.CacheHandler.convertJNPURLToCacheURL(getCtx().getProperty("java.naming.provider.url")),log,getCtx(),get_TrxName()); int[] tableKeys=X_CM_CStage_Element.getAllIDs("CM_CStage_Element","CM_CStage_ID=" + stage.get_ID(),trxName); if (tableKeys != null && tableKeys.length > 0) { for (int i=0; i < tableKeys.length; i++) { X_CM_CStage_Element thisStageElement=new X_CM_CStage_Element(project.getCtx(),tableKeys[i],trxName); int[] thisContainerElementKeys=X_CM_Container_Element.getAllIDs("CM_Container_Element","CM_Container_ID=" + stage.get_ID() + " AND Name LIKE '"+ thisStageElement.getName()+ "'",trxName); X_CM_Container_Element thisContainerElement; if (thisContainerElementKeys != null && thisContainerElementKeys.length > 0) { thisContainerElement=new X_CM_Container_Element(project.getCtx(),thisContainerElementKeys[0],trxName); } else { thisContainerElement=new X_CM_Container_Element(project.getCtx(),0,trxName); } thisContainerElement.setCM_Container_ID(stage.get_ID()); X_CM_CStage_Element stageElement=new X_CM_CStage_Element(project.getCtx(),tableKeys[i],trxName); thisContainerElement.setName(stageElement.getName()); thisContainerElement.setDescription(stageElement.getDescription()); thisContainerElement.setHelp(stageElement.getHelp()); thisContainerElement.setIsActive(stageElement.isActive()); thisContainerElement.setIsValid(stageElement.isValid()); String contentHTML=thisStageElement.getContentHTML(); thisContainerElement.setContentHTML(contentHTML); thisContainerElement.save(trxName); thisHandler.cleanContainerElement(thisContainerElement.get_ID()); } } tableKeys=X_CM_Container_Element.getAllIDs("CM_Container_Element","CM_Container_ID=" + stage.get_ID(),trxName); if (tableKeys != null && tableKeys.length > 0) { for (int i=0; i < tableKeys.length; i++) { X_CM_Container_Element thisContainerElement=new X_CM_Container_Element(project.getCtx(),tableKeys[i],trxName); int[] thisCStageElementKeys=X_CM_CStage_Element.getAllIDs("CM_CStage_Element","CM_CStage_ID=" + stage.get_ID() + " AND Name LIKE '"+ thisContainerElement.getName()+ "'",trxName); if (thisCStageElementKeys == null || thisCStageElementKeys.length < 1) { thisHandler.cleanContainerElement(thisContainerElement.get_ID()); thisContainerElement.delete(true); } } } }
Update Elements in Container from Stage
public void testVocabulary() throws IOException { assertVocabulary(analyzer,getDataPath("rulighttestdata.zip"),"rulight.txt"); }
Test against a vocabulary from the reference impl
public void openMsrpSession(long timeout) throws NetworkException, PayloadException { mMsrpSession.getConnection().open(timeout); }
Open the connection with SO_TIMEOUT on the socket
public DisqueReactiveCommandsImpl(DisqueConnection<K,V> connection,RedisCodec<K,V> codec){ this.connection=connection; this.codec=codec; commandBuilder=new DisqueCommandBuilder<K,V>(codec); }
Initialize a new instance.
public boolean isActive(){ return isActive; }
Checks if is active.
public V remove(Object key){ int h=hash(key.hashCode()); return segFor(h).remove(key,h,null); }
Removes the key (and its corresponding value) from this map. This method does nothing if the key is not in the map.
public boolean isWriteable(MailboxSession session) throws MailboxException { return aclResolver.isReadWrite(myRights(session),getSharedPermanentFlags(session)); }
This mailbox is writable
public void addLayer(Layer layer){ if (allLayers == null) { addLayer(layer,0); return; } if (!allLayers.contains(layer)) { allLayers.add(layer); } }
Add a layer to the bottom of the layer stack. If the layer is already part of the layer stack, nothing is done.
private void showFeedback(String message){ if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } }
Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface.
public DateAttributeInfo(String dateFormat){ if (dateFormat != null) { m_DateFormat=new SimpleDateFormat(dateFormat); } else { m_DateFormat=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); } m_DateFormat.setLenient(false); }
Constructs info based on argument.
public String readString() throws IOException { int len=readVarInt(); return readString(len); }
Read a string from the stream.
public NameService createNameService() throws Exception { return new SimpleNameService(); }
Create a new instance of the corresponding name service.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public StringConstant(ConstantPool pool,int index,int stringIndex){ super(pool,index); _stringIndex=stringIndex; }
Creates a new string constant.
public boolean isSetHello(){ return this.hello != null; }
Returns true if field hello is set (has been assigned a value) and false otherwise
@Override public void onSend(byte[] msg,int offset,int count,long timestamp) throws IOException { MidiEvent event=createScheduledEvent(msg,offset,count,timestamp); if (event != null) { add(event); } }
Store these bytes in the EventScheduler to be delivered at the specified time.
public boolean hasIdenticalTaxa(List<AbstractPartitionData> partitionDataList){ TaxonList taxa=null; for ( AbstractPartitionData partition : partitionDataList) { if (taxa == null) { taxa=partition.getTaxonList(); } else { final TaxonList taxa1=partition.getTaxonList(); if (taxa1 != null) { if (taxa1.getTaxonCount() != taxa.getTaxonCount()) { return false; } for (int k=0; k < taxa1.getTaxonCount(); ++k) { if (taxa.getTaxonIndex(taxa1.getTaxonId(k)) == -1) { return false; } } } } } return true; }
check if all taxa are same across partitions.
public HandleException(String message,Throwable cause){ super(message,cause); }
Constructs a new HandleException with the specified detail message and cause.
public long run(String[] args) throws Exception { int size=Integer.parseInt(args[0]); int nbatches=Integer.parseInt(args[1]); int ncycles=Integer.parseInt(args[2]); short[][] arrays=new short[ncycles][size]; StreamBuffer sbuf=new StreamBuffer(); ObjectOutputStream oout=new ObjectOutputStream(sbuf.getOutputStream()); ObjectInputStream oin=new ObjectInputStream(sbuf.getInputStream()); doReps(oout,oin,sbuf,arrays,1); long start=System.currentTimeMillis(); doReps(oout,oin,sbuf,arrays,nbatches); return System.currentTimeMillis() - start; }
Write and read short arrays to/from a stream. The benchmark is run in batches, with each batch consisting of a fixed number of read/write cycles. The ObjectOutputStream is reset after each batch of cycles has completed. Arguments: <array size> <# batches> <# cycles per batch>
public boolean isStatic(){ return isStatic(opcode); }
Returns true if the field is static.
public StatusChecker createStatusChecker(Service service,NodeType nodeType){ Preconditions.checkNotNull(service); switch (nodeType) { case KubernetesMaster: case KubernetesSlave: return new KubernetesStatusChecker(HostUtils.getKubernetesClient(service)); case MesosZookeeper: return new ZookeeperStatusChecker(); case MesosMaster: case MesosSlave: return new MesosStatusChecker(HostUtils.getMesosClient(service)); case MesosMarathon: return new MarathonStatusChecker(HostUtils.getMesosClient(service)); case KubernetesEtcd: case SwarmEtcd: return new EtcdStatusChecker(HostUtils.getEtcdClient(service)); case SwarmMaster: case SwarmSlave: return new SwarmStatusChecker(HostUtils.getSwarmClient(service)); default : throw new RuntimeException("Unsupported nodeType: " + nodeType.toString()); } }
Factory method used to create an instance of a StatusChecker corresponding to the passed NodeType.
@Override protected final void onCreate(final Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_signin); if (!Constants.SIGN_IN_REQUIRED) { startMainActivity(); return; } if (!checkPlayServices()) { return; } if (isSignedIn()) { startMainActivity(); } else { startActivityForResult(credential.newChooseAccountIntent(),REQUEST_ACCOUNT_PICKER); } }
Initializes the activity content and then navigates to the MainActivity if the user is already signed in or if the app is configured to not require the sign in. Otherwise it initiates starting the UI for the account selection and a check for Google Play Services being up to date.
public boolean isMissingDataNotificationEnabled(){ return missingDataNotificationEnabled; }
Indicates if an alert should trigger if no data is available to evaluate.
protected Object findFilterId(SerializationConfig config,BasicBeanDescription beanDesc){ return config.getAnnotationIntrospector().findFilterId(beanDesc.getClassInfo()); }
Method called to find filter that is configured to be used with bean serializer being built, if any.
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); initializeDownloadUI(); if (!expansionFilesDelivered()) { try { Intent launchIntent=SampleDownloaderActivity.this.getIntent(); Intent intentToLaunchThisActivityFromNotification=new Intent(SampleDownloaderActivity.this,SampleDownloaderActivity.this.getClass()); intentToLaunchThisActivityFromNotification.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); intentToLaunchThisActivityFromNotification.setAction(launchIntent.getAction()); if (launchIntent.getCategories() != null) { for ( String category : launchIntent.getCategories()) { intentToLaunchThisActivityFromNotification.addCategory(category); } } PendingIntent pendingIntent=PendingIntent.getActivity(SampleDownloaderActivity.this,0,intentToLaunchThisActivityFromNotification,PendingIntent.FLAG_UPDATE_CURRENT); int startResult=DownloaderClientMarshaller.startDownloadServiceIfRequired(this,pendingIntent,SampleDownloaderService.class); if (startResult != DownloaderClientMarshaller.NO_DOWNLOAD_REQUIRED) { initializeDownloadUI(); return; } } catch ( NameNotFoundException e) { Log.e(LOG_TAG,"Cannot find own package! MAYDAY!"); e.printStackTrace(); } } else { validateXAPKZipFiles(); } }
Called when the activity is first create; we wouldn't create a layout in the case where we have the file and are moving to another activity without downloading.
public static void updateVisible(VisualItem item,boolean val){ item.setStartVisible(item.isVisible()); item.setVisible(val); item.setEndVisible(val); }
Update the visibility of an item. The current visibility will become the new starting visibility, while the given visibility value will become the new current and ending visibility.
protected int numAutoMoves(){ return autoMoves.size(); }
Determine the number of automoves made.
public void runResultHandlers(ResultHierarchy hier,Database db){ for ( ResultHandler resulthandler : resulthandlers) { Thread.currentThread().setName(resulthandler.toString()); resulthandler.processNewResult(hier,db); } }
Run the result handlers.
public AnnotationVisitor visitAnnotation(String desc,boolean visible){ if (cv != null) { return cv.visitAnnotation(desc,visible); } return null; }
Visits an annotation of the class.
private static Expression createNarrowCastIfNessecary(Expression expression,ITypeBinding expressionType,AST ast,ITypeBinding variableType,boolean is50OrHigher){ PrimitiveType castTo=null; if (variableType.isEqualTo(expressionType)) return expression; if (is50OrHigher) { if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(variableType)) castTo=ast.newPrimitiveType(PrimitiveType.CHAR); if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(variableType)) castTo=ast.newPrimitiveType(PrimitiveType.BYTE); if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(variableType)) castTo=ast.newPrimitiveType(PrimitiveType.SHORT); } if (ast.resolveWellKnownType("char").isEqualTo(variableType)) castTo=ast.newPrimitiveType(PrimitiveType.CHAR); if (ast.resolveWellKnownType("byte").isEqualTo(variableType)) castTo=ast.newPrimitiveType(PrimitiveType.BYTE); if (ast.resolveWellKnownType("short").isEqualTo(variableType)) castTo=ast.newPrimitiveType(PrimitiveType.SHORT); if (castTo != null) { CastExpression cast=ast.newCastExpression(); if (NecessaryParenthesesChecker.needsParentheses(expression,cast,CastExpression.EXPRESSION_PROPERTY)) { ParenthesizedExpression parenthesized=ast.newParenthesizedExpression(); parenthesized.setExpression(expression); cast.setExpression(parenthesized); } else cast.setExpression(expression); cast.setType(castTo); return cast; } return expression; }
Checks if the assignment needs a downcast and inserts it if necessary
public AbstractEvaluatorTest(String name){ super(name); }
Constructs the <code>AbstractEvaluatorTest</code>. Called by subclasses.
void recycleTask(AttachmentTask downloadTask){ downloadTask.recycle(); mPhotoTaskWorkQueue.offer(downloadTask); }
Recycles tasks by calling their internal recycle() method and then putting them back into the task queue.
public void waitForCycle(){ lock.lock(); while (contextsParked < contexts.length) { lock.await(); } lock.unlock(); }
Wait until the group is idle.
protected CoreContainer(Object testConstructor){ solrHome=null; loader=null; coresLocator=null; cfg=null; }
This method allows subclasses to construct a CoreContainer without any default init behavior.
public static void logArticleProcessed(final Logger logger,final Task<Revision> article,long time){ logger.logMessage(Level.INFO,"Generated Diff\t" + Time.toClock(time) + "\t"+ article.toString()); }
Logs the processing of a revision task.
public static GreeterBlockingStub newBlockingStub(io.grpc.Channel channel){ return new GreeterBlockingStub(channel); }
Creates a new blocking-style stub that supports unary and streaming output calls on the service
Socket checkConnector(AsyncConnector connector) throws IOException { Exception e=connector.getException(); if (e != null) { e.fillInStackTrace(); if (e instanceof IOException) { throw (IOException)e; } else if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new Error("internal error: " + "unexpected checked exception: " + e.toString()); } } return connector.getSocket(); }
Check if an AsyncConnector succeeded. If not, return socket given to fall back to.
public void skipMessage() throws IOException { while (true) { final int tag=readTag(); if (tag == 0 || !skipField(tag)) { return; } } }
Reads and discards an entire message. This will read either until EOF or until an endgroup tag, whichever comes first.
@Override public void add(CharSequence key,CharSequence cmd){ if (cmd.length() == 0) { return; } CharSequence p[]=decompose(cmd); int levels=p.length; while (levels >= tries.size()) { tries.add(new Trie(forward)); } CharSequence lastkey=key; for (int i=0; i < levels; i++) { if (key.length() > 0) { tries.get(i).add(key,p[i]); lastkey=key; } else { tries.get(i).add(lastkey,p[i]); } if (p[i].length() > 0 && p[i].charAt(0) == '-') { if (i > 0) { key=skip(key,lengthPP(p[i - 1])); } key=skip(key,lengthPP(p[i])); } } if (key.length() > 0) { tries.get(levels).add(key,EOM_NODE); } else { tries.get(levels).add(lastkey,EOM_NODE); } }
Add an element to this structure consisting of the given key and patch command. <p> This method will return without executing if the <tt>cmd</tt> parameter's length is 0.
public ExceptionOccurredSynchronizer(final IDebugger debugger,final ListenerProvider<IDebugEventListener> listeners){ super(debugger,listeners); }
Creates a new Exception Occurred synchronizer.
public Builder serializer(final ISerializer serializer){ mClient.setSerializer(serializer); return this; }
Sets the serializer
public int openFile(int pageCount,final int insetW,final int insetH,final PdfPageData pageData,final PdfObjectReader currentPdfFile,final PdfObject acroObj){ this.pageCount=pageCount; this.currentPdfFile=currentPdfFile; this.pageData=pageData; compData.flushFormData(); sigObject=null; sigKeys=null; compData.setPageData(pageData,insetW,insetH); if (acroObj == null) { FfieldCount=0; fieldList=null; } else { final PdfObject XFAasStream; PdfArrayIterator XFAasArray=null; XFAasStream=acroObj.getDictionary(PdfDictionary.XFA); if (XFAasStream == null) { XFAasArray=acroObj.getMixedArray(PdfDictionary.XFA); if (XFAasArray != null && XFAasArray.getTokenCount() == 0) { XFAasArray=null; } } hasXFA=XFAasStream != null || XFAasArray != null; isContainXFAStream=hasXFA; fieldList=acroObj.getMixedArray(PdfDictionary.Fields); CO=acroObj.getObjectArray(PdfDictionary.CO); if (fieldList != null) { FfieldCount=fieldList.getTokenCount(); AcroRes=acroObj.getDictionary(PdfDictionary.DR); if (AcroRes != null) { currentPdfFile.checkResolved(AcroRes); } } else { FfieldCount=0; AcroRes=null; } if (hasXFA && useXFA) { processXFAFields(acroObj,currentPdfFile,pageData); } if (!hasXFA) { resolveIndirectFieldList(false); } } resetContainers(true); return pageCount; }
initialise holders and variables, data structures and get a handle on data object
public MonitoringParameters clone(){ MonitoringParameters result=new MonitoringParameters(); result.ClientHandle=ClientHandle; result.SamplingInterval=SamplingInterval; result.Filter=Filter; result.QueueSize=QueueSize; result.DiscardOldest=DiscardOldest; return result; }
Deep clone
@Override public void visit(NodeVisitor v){ v.visit(this); }
Visits this label. There are no children to visit.
void waitForDictionaryLoading(){ while (mUpdatingDictionary) { try { Thread.sleep(100); } catch ( InterruptedException e) { } } }
Used only for testing purposes This function will wait for loading from database to be done
protected void loadValue(String sValue){ value=decode(sValue); }
Load value from property string value
public static String toString(boolean[] self){ return InvokerHelper.toString(self); }
Returns the string representation of the given array.
private void updateView(){ if (rebuildItems()) { calculateLayoutWidth(getWidth(),MeasureSpec.EXACTLY); layout(getWidth(),getHeight()); } }
Updates view. Rebuilds items and label if necessary, recalculate items sizes.
public void addErrorAndContinue(Message message){ if (this.errors == null) { this.errors=new LinkedList(); } this.errors.add(message); }
Adds an error to the message set, but does not cause a failure. The message is not required to have a source line and column specified, but it is best practice to try and include that information.
public static void removeNotifications(final Collection<Notification> notifications,final Collection<Long> ids){ notifications.removeIf(null); ids.clear(); }
Remove the given notification IDs from the list of notifications.
private void addTag(String key,String value,boolean mandatory,List<String> values,int position,boolean updatable,TagItem.Type type){ String valueFormatted=ParserManager.getValue(value,type); type=type == null ? TagItem.Type.TEXT : type; type=key.equals("collection_times") ? TagItem.Type.TIME : type; type=key.equals("opening_hours") ? TagItem.Type.OPENING_HOURS : type; TagItem tagItem=new TagItem(key,value,mandatory,values,updatable ? type : TagItem.Type.CONSTANT,valueFormatted != null || type == TagItem.Type.NUMBER); if (!tagItemList.contains(tagItem)) { tagItemList.add(position,tagItem); } keyTagItem.put(key,tagItem); notifyItemInserted(position); }
Add tag into global list of tag
public Status(String code,String level,String description){ this.code=code; this.level=level; this.description=description; }
Creates status object with given level, description and status code
public HttpEngine recover(RouteException e){ if (!streamAllocation.recover(e)) { return null; } if (!client.getRetryOnConnectionFailure()) { return null; } StreamAllocation streamAllocation=close(); return new HttpEngine(client,userRequest,bufferRequestBody,callerWritesRequestBody,forWebSocket,streamAllocation,(RetryableSink)requestBodyOut,priorResponse); }
Attempt to recover from failure to connect via a route. Returns a new HTTP engine that should be used for the retry if there are other routes to try, or null if there are no more routes to try.
public static String encodeFromFile(String filename) throws java.io.IOException { String encodedData=null; Base64.InputStream bis=null; try { java.io.File file=new java.io.File(filename); byte[] buffer=new byte[Math.max((int)(file.length() * 1.4 + 1),40)]; int length=0; int numBytes=0; bis=new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)),Base64.ENCODE); while ((numBytes=bis.read(buffer,length,4096)) >= 0) { length+=numBytes; } encodedData=new String(buffer,0,length,Base64.PREFERRED_ENCODING); } catch ( java.io.IOException e) { throw e; } finally { try { bis.close(); } catch ( Exception e) { } } return encodedData; }
Convenience method for reading a binary file and base64-encoding it. <p>As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it.</p>
public Object runSafely(Catbert.FastStack stack) throws Exception { return sage.plugin.CorePluginManager.getInstance().isRestartNeeded() ? Boolean.TRUE : Boolean.FALSE; }
Returns true if the server instance of SageTV needs to be restarted due to a plugin install/uninstall
@Override protected void initialize(){ super.initialize(); m_LastNonIncrementalClassifier=new meka.classifiers.multilabel.BR(); m_LastIncrementalClassifier=new meka.classifiers.multilabel.incremental.BRUpdateable(); m_GenericObjectEditor=new GenericObjectEditor(true); m_GenericObjectEditor.setClassType(MultiLabelClassifier.class); m_GenericObjectEditor.setValue(m_LastNonIncrementalClassifier); m_Seed=1; m_SplitPercentage=66.0; m_Folds=10; m_Samples=10; m_Randomize=true; m_TOP="PCut1"; m_VOP="3"; m_TestInstances=null; m_ClassifyTabOptions=null; m_AdditionalMenuItems=new HashMap<>(); }
Initializes the members.
public static Object evaluate(String language,String script,Class<?> scriptClass,Map<String,Object> context) throws Exception { Assert.notNull("context",context); if (scriptClass != null) { return InvokerHelper.createScript(scriptClass,GroovyUtil.getBinding(context)).run(); } try { CompiledScript compiledScript=compileScriptString(language,script); if (compiledScript != null) { return executeScript(compiledScript,null,createScriptContext(context),null); } ScriptEngineManager manager=new ScriptEngineManager(); ScriptEngine engine=manager.getEngineByName(language); if (engine == null) { throw new IllegalArgumentException("The script type is not supported for language: " + language); } if (Debug.verboseOn()) { Debug.logVerbose("Begin processing script [" + script + "] using engine "+ engine.getClass().getName(),module); } ScriptContext scriptContext=createScriptContext(context); return engine.eval(script,scriptContext); } catch ( Exception e) { String errMsg="Error running " + language + " script ["+ script+ "]: "+ e.toString(); Debug.logWarning(e,errMsg,module); throw new IllegalArgumentException(errMsg); } }
Executes a script <code>String</code> and returns the result.
public ConfigurableCaret(int style){ seg=new Segment(); setStyle(style); selectionPainter=new ChangeableHighlightPainter(); }
Constructs a new <code>ConfigurableCaret</code>.
protected void releaseBeanContextResources(){ }
This method may be overridden by subclasses to provide their own release behaviors. When invoked any resources held by this instance obtained from its current BeanContext property should be released since the object is no longer nested within that BeanContext.
public void harvest(final List<Component> components,TrickleCallback trickleCallback){ synchronized (elements) { harvest(elements.iterator(),components,threadPool,trickleCallback); } }
Gathers candidate addresses for a specific <tt>Component</tt>. <tt>CandidateHarvesterSet</tt> delegates to the <tt>CandidateHarvester</tt>s which are its <tt>Set</tt> elements.
@Override protected void register(ContainerCapabilityFactory containerCapabilityFactory){ containerCapabilityFactory.registerContainerCapability("jboss3x",JBossContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss4x",JBoss4xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss42x",JBoss4xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss5x",JBoss5xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss51x",JBoss5xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss6x",JBoss5xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss61x",JBoss5xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss7x",JBoss7xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss71x",JBoss7xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss72x",JBoss7xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss73x",JBoss7xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss74x",JBoss7xContainerCapability.class); containerCapabilityFactory.registerContainerCapability("jboss75x",JBoss7xContainerCapability.class); }
Register container capabilities.
private void moveHistory(final IProject oldProject,final IProject newProject,final IProgressMonitor monitor){ try { monitor.beginTask(RefactoringCoreMessages.RefactoringHistoryService_updating_history,60); final IFileStore historyStore=EFS.getLocalFileSystem().getStore(RefactoringCorePlugin.getDefault().getStateLocation()).getChild(NAME_HISTORY_FOLDER); final String oldName=oldProject.getName(); final String newName=newProject.getName(); final IFileStore oldStore=historyStore.getChild(oldName); if (oldStore.fetchInfo(EFS.NONE,new SubProgressMonitor(monitor,10,SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists()) { final IFileStore newStore=historyStore.getChild(newName); if (newStore.fetchInfo(EFS.NONE,new SubProgressMonitor(monitor,10,SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)).exists()) newStore.delete(EFS.NONE,new SubProgressMonitor(monitor,20,SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); oldStore.move(newStore,EFS.OVERWRITE,new SubProgressMonitor(monitor,20,SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)); } } catch ( CoreException exception) { RefactoringCorePlugin.log(exception); } finally { monitor.done(); } }
Moves the project history from the old project to the new one.
@Override protected Template copyValue(Template t){ return Template.create(t.toString()); }
Copies a template
public static Test suite(){ return (new TestSuite(MethodRefITCase.class)); }
Return the tests included in this test suite.
protected int dp2px(int dpVal){ return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dpVal,getResources().getDisplayMetrics()); }
dp 2 px
public BasicHttpResponse(final ProtocolVersion ver,final int code,final String reason){ this(new BasicStatusLine(ver,code,reason),null,null); }
Creates a response from elements of a status line. The response will not have a reason phrase catalog and use the system default locale.
public static void main(final String[] args){ DOMTestCase.doMain(nodeentitynodevalue.class,args); }
Runs this test from the command line.
public void requestShowToolTip(InfoDisplayEvent event){ if (map != null) { if (ttmanager == null) { initToolTip(); } map.setToolTipText(event.getInformation()); } }
If a tooltip is required over a spot on the map then a <code>MouseMapListener</code> should pass a MouseEvent to this method. The Swing ToolTipManager is used to achieve this. A call to this method should always be followed by a call to <code>hideToolTip</code>
public String toString(){ String eol=System.getProperty("line.separator"); StringBuffer sb=new StringBuffer("XNode:["); sb.append("Node Name:" + getNode().getNodeName()); sb.append(eol); sb.append("Node Value:" + getNode().getNodeValue()); sb.append(eol); sb.append("Node Type:" + getNode().getNodeType()); sb.append(eol); sb.append("Node XPath:" + getXPath()); sb.append(eol); sb.append("]"); return sb.toString(); }
Gets String representation of the XNode.
public static int numOfParameters(String desc){ int n=0; int i=1; for (; ; ) { char c=desc.charAt(i); if (c == ')') break; while (c == '[') c=desc.charAt(++i); if (c == 'L') { i=desc.indexOf(';',i) + 1; if (i <= 0) throw new IndexOutOfBoundsException("bad descriptor"); } else ++i; ++n; } return n; }
Returns the number of the prameters included in the given descriptor.
public int search(final char[] array){ return search(array,0,array.length); }
Returns the index of the first occurrence of this pattern in the given character array.
public void enableProtection(RecoverPointVolumeProtectionInfo volumeInfo) throws RecoverPointException { try { ConsistencyGroupUID cgUID=new ConsistencyGroupUID(); cgUID.setId(volumeInfo.getRpVolumeGroupID()); ConsistencyGroupCopyUID cgCopyUID=null; cgCopyUID=RecoverPointUtils.mapRPVolumeProtectionInfoToCGCopyUID(volumeInfo); String cgCopyName=functionalAPI.getGroupCopyName(cgCopyUID); String cgName=functionalAPI.getGroupName(cgUID); if (volumeInfo.getRpVolumeCurrentProtectionStatus() == RecoverPointVolumeProtectionInfo.volumeProtectionStatus.PROTECTED_SOURCE) { logger.info("Enabling consistency group " + cgName); functionalAPI.enableConsistencyGroup(cgUID,true); RecoverPointImageManagementUtils imageManager=new RecoverPointImageManagementUtils(); imageManager.waitForCGLinkState(functionalAPI,cgUID,RecoverPointImageManagementUtils.getPipeActiveState(functionalAPI,cgUID)); logger.info("Protection enabled on CG " + cgName); } else { logger.info("Enabling CG copy " + cgCopyName + " on CG "+ cgName); functionalAPI.enableConsistencyGroupCopy(cgCopyUID,true); RecoverPointImageManagementUtils imageManager=new RecoverPointImageManagementUtils(); imageManager.waitForCGCopyLinkState(functionalAPI,cgCopyUID,PipeState.ACTIVE); logger.info("Protection enabled on CG copy " + cgCopyName + " on CG "+ cgName); } } catch ( FunctionalAPIActionFailedException_Exception e) { throw RecoverPointException.exceptions.failedToEnableProtection(volumeInfo.getRpVolumeGroupID(),e); } catch ( FunctionalAPIInternalError_Exception e) { throw RecoverPointException.exceptions.failedToEnableProtection(volumeInfo.getRpVolumeGroupID(),e); } }
Enable (start) the consistency group protection specified by the input volume info Requires a full sweep.
public NeighborHighlightControl(){ this(null); }
Creates a new highlight control.
public static final <T>Event<T> of(Selector selector){ return of(selector,null); }
Create a event with given selector without any data
public void init(FilterConfig filterConfig) throws ServletException { }
Performs initialisation.
public static String toString(boolean[] a){ if (a == null) return "null"; int iMax=a.length - 1; if (iMax == -1) return "[]"; StringBuilder b=new StringBuilder(); b.append('['); for (int i=0; ; i++) { b.append(a[i]); if (i == iMax) return b.append(']').toString(); b.append(", "); } }
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets (<tt>"[]"</tt>). Adjacent elements are separated by the characters <tt>", "</tt> (a comma followed by a space). Elements are converted to strings as by <tt>String.valueOf(boolean)</tt>. Returns <tt>"null"</tt> if <tt>a</tt> is <tt>null</tt>.
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
public CreateQueueResult createQueue(CreateQueueRequest createQueueRequest) throws AmazonServiceException, AmazonClientException { return amazonSqsToBeExtended.createQueue(createQueueRequest); }
<p> Creates a new queue, or returns the URL of an existing one. When you request <code>CreateQueue</code> , you provide a name for the queue. To successfully create a new queue, you must provide a name that is unique within the scope of your own queues. </p> <p> <b>NOTE:</b> If you delete a queue, you must wait at least 60 seconds before creating a queue with the same name. </p> <p> You may pass one or more attributes in the request. If you do not provide a value for any attribute, the queue will have the default value for that attribute. Permitted attributes are the same that can be set using SetQueueAttributes. </p> <p> <b>NOTE:</b> Use GetQueueUrl to get a queue's URL. GetQueueUrl requires only the QueueName parameter. </p> <p> If you provide the name of an existing queue, along with the exact names and values of all the queue's attributes, <code>CreateQueue</code> returns the queue URL for the existing queue. If the queue name, attribute names, or attribute values do not match an existing queue, <code>CreateQueue</code> returns an error. </p> <p> <b>NOTE:</b>Some API actions take lists of parameters. These lists are specified using the param.n notation. Values of n are integers starting from 1. For example, a parameter list with two elements looks like this: </p> <p> <code>&Attribute.1=this</code> </p> <p> <code>&Attribute.2=that</code> </p>
public static String[] readFileLines(File file) throws IOException { List<String> lines=new LinkedList<>(); Files.lines(file.toPath()).forEach(null); while (StringUtils.strip(lines.get(0)).isEmpty()) { lines.remove(0); } while (StringUtils.strip(lines.get(lines.size() - 1)).isEmpty()) { lines.remove(lines.size() - 1); } return lines.toArray(new String[lines.size()]); }
Read the file and return all the lines, with any leading or trailing 'empty' lines omitted. Lines that consist solely of whitespace are assumed to be empty. Lines are trimmed of any leading or trailing whitespace as they are read. Implemented as per BufferedReader.