code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
public int getSubIfdCount() { int c = 0; if (metadata != null && metadata.contains("SubIFDs")) c = getMetadataList("SubIFDs").size(); return c; }
Gets the Subifd count. @return the Subifd count
public List<TiffObject> getIfds() { List<TiffObject> l = new ArrayList<TiffObject>(); if (metadata != null && metadata.contains("IFD")) l = getMetadataList("IFD"); return l; }
Returns a list of ifds including exifds. @return the ifds list
public List<TiffObject> getImageIfds() { List<TiffObject> l = new ArrayList<TiffObject>(); IFD oifd = this.firstIFD; while (oifd != null) { if (oifd.isImage()) { if (oifd.hasSubIFD()) { try { long length = oifd.getMetadata().get("ImageLength").getFirstNumericValue(); long width = oifd.getMetadata().get("ImageWidth").getFirstNumericValue(); long sublength = oifd.getsubIFD().getMetadata().get("ImageLength").getFirstNumericValue(); long subwidth = oifd.getsubIFD().getMetadata().get("ImageWidth").getFirstNumericValue(); if (sublength > length && subwidth > width) { l.add(oifd.getsubIFD()); } else { l.add(oifd); } } catch (Exception ex) { l.add(oifd); } } else { l.add(oifd); } } oifd = oifd.getNextIFD(); } return l; }
Returns a list of ifds representing Images. @return the ifds list
public List<TiffObject> getIfdsAndSubIfds() { List<TiffObject> all = new ArrayList<TiffObject>(); all.addAll(getMetadataList("IFD")); all.addAll(getMetadataList("SubIFDs")); return all; }
Returns a list of subifds. @return the subifds list
public String getMetadataSingleString(String name) { String s = ""; if (metadata == null) createMetadataDictionary(); if (metadata.contains(name)) s = metadata.get(name).toString(); return s; }
Gets an string with the value of the first tag matching the given tag name.<br> @param name the tag name @return the metadata single string
public List<TiffObject> getMetadataList(String name) { List<TiffObject> l = new ArrayList<TiffObject>(); if (metadata == null) createMetadataDictionary(); if (metadata.contains(name)) l = metadata.getList(name); return l; }
Gets the metadata ok a given class name. @param name the class name @return the list of metadata that matches with the class name
private void addMetadataFromIFD(IFD ifd, String key, boolean exif) { metadata.add(key, ifd); for (TagValue tag : ifd.getMetadata().getTags()) { if (tag.getCardinality() == 1) { abstractTiffType t = tag.getValue().get(0); if (t.isIFD()) { addMetadataFromIFD((IFD) t, key, true); } else if (t.containsMetadata()) { try { Metadata meta = t.createMetadata(); metadata.addMetadata(meta); } catch (Exception ex) { // TODO: What? } } else { if (exif) t.setContainer("EXIF"); metadata.add(tag.getName(), t); } } else { if (exif) tag.setContainer("EXIF"); metadata.add(tag.getName(), tag); } } if (ifd.hasNextIFD()) { addMetadataFromIFD(ifd.getNextIFD(), key, false); } }
Adds the metadata from ifd. @param ifd the ifd @param key the key @param exif the exif @the tiff tags io exception
public void printMetadata() { if (metadata == null) createMetadataDictionary(); System.out.println("METADATA"); // if (metadata.getCreator() != null) System.out.println("Creator:" + metadata.getCreator()); for (String name : metadata.keySet()) { String mult = ""; if (getMetadataList(name).size() > 1) mult = "(x" + getMetadataList(name).size() + ")"; if (metadata.getMetadataObject(name).isDublinCore()) System.out.println("[DC]"); System.out.println(name + mult + ": " + getMetadataSingleString(name)); } }
Prints the metadata.
public boolean removeTag(String tagName) { boolean result = false; IFD ifd = firstIFD; while (ifd != null) { if (ifd.containsTagId(TiffTags.getTagId(tagName))) { ifd.removeTag(tagName); } ifd = ifd.getNextIFD(); } createMetadataDictionary(); return result; }
Removes the tag. @param tagName the tag name @return true, if successful
public boolean addTag(String tagName, String tagValue) { boolean result = false; if (firstIFD != null) { if (firstIFD.containsTagId(TiffTags.getTagId(tagName))) { firstIFD.removeTag(tagName); } firstIFD.addTag(tagName, tagValue); createMetadataDictionary(); } return result; }
Adds the tag. @param tagName the tag name @param tagValue the tag value @return true, if successful
@Override protected void searchStep() { // get random move Move<? super SolutionType> move = getNeighbourhood().getRandomMove(getCurrentSolution(), getRandom()); // got move? if(move != null){ // valid move? if(validate(move).passed()){ // valid move: improvement? if(isImprovement(move)){ // improvement: always accept accept(move); } else { // no improvement: accept with probability based on temperature and delta double delta = computeDelta(evaluate(move), getCurrentSolutionEvaluation()); double r = getRandom().nextDouble(); if(Math.exp(delta/temperature) > r){ // accept inferior move accept(move); } else { // reject inferior move reject(move); } } } else { // invalid move: reject reject(move); } } else { // no move/neighbour found stop(); } }
Creates a random neighbour of the current solution and accepts it as the new current solution if it is valid and either improves the current solution or \[ e^{\frac{\Delta E}{T}} &gt; R(0,1) \] where \(\Delta E\) is the difference between the evaluation of the neighbour and that of the current solution, \(T\) is the temperature, and \(R(0,1)\) is a random number in the interval \([0,1]\) sampled using the search's dedicated random generator. @throws JamesRuntimeException if depending on malfunctioning components (problem, neighbourhood, ...)
public static int updateVirtualDns(Properties properties) { Iterator<Entry<Object, Object>> iterator = properties.entrySet().iterator(); int count = 0; while (iterator.hasNext()) { Entry<Object, Object> entry = iterator.next(); if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String)) { continue; } String host = ((String) entry.getKey()).trim(); String ip = ((String) entry.getValue()).trim(); if (!isLocalHost(host)) { count += updateVirtualDnsByStrings(host, ip); } } return count; }
更新虚拟DNS域名指向. @param properties key为域名,value为IP地址 @return 更新虚拟DNS记录的条数
public static void printAllVirtualDns() { List<Host> list = dns.list(); for (Host host : list) { System.out.println(host); } }
打印所有虚拟DNS记录.
public static String queryIp(String host) { InetAddress[] addresses; try { addresses = InetAddress.getAllByName(host); } catch (UnknownHostException e) { return null; } // System.out.println("len:" + addresses.length); if (addresses.length == 1) { return addresses[0].getHostAddress(); } else { // 多IP时,随机返回一个 int random = new Random().nextInt(addresses.length); return addresses[random].getHostAddress(); } }
根据域名查询IP,多IP时随机返回1个(查询范围:包括hosts文件、DNS服务器、虚拟DNS). @param host 域名 @return IP
public static String getIp(String host) { InetAddress address; try { address = InetAddress.getByName(host); } catch (UnknownHostException e) { return null; } return address.getHostAddress(); }
根据域名查询IP,多IP时只返回第一个(查询范围:包括hosts文件、DNS服务器、虚拟DNS). @param host 域名 @return IP
public static void showToast(String message, int duration) { showToast(message, duration, null, null, null); }
Show the {@link Toast} on the current Thread. @param message The text to show. Can be formatted text. @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} {@link Toast#LENGTH_LONG}
public static void showToast(String message, int duration, Integer gravity, Integer xOffset, Integer yOffset) { AbstractApplication androidApplication = AbstractApplication.get(); if (!androidApplication.isInBackground()) { cancelCurrentToast(); Toast toast = Toast.makeText(androidApplication, message, duration); if ((gravity != null) && (xOffset != null) && (yOffset != null)) { toast.setGravity(gravity, xOffset, yOffset); } toast.setDuration(duration); toast.show(); currentToast = new WeakReference<>(toast); } }
Show the {@link Toast} on the current Thread. @param message The text to show. Can be formatted text. @param duration How long to display the message. Either {@link Toast#LENGTH_SHORT} {@link Toast#LENGTH_LONG} @param gravity The location at which the notification should appear on the screen. @param xOffset The X offset in pixels to apply to the gravity's location. @param yOffset The Y offset in pixels to apply to the gravity's location.
public void setNeighbourhood(Neighbourhood<? super SolutionType> neighbourhood){ // synchronize with status updates synchronized(getStatusLock()){ // assert idle assertIdle("Cannot set neighbourhood."); // check not null if(neighbourhood == null){ throw new NullPointerException("Cannot set neighbourhood: received null."); } // go ahead this.neighbourhood = neighbourhood; } }
Sets the neighbourhood used to modify the current solution. Note that <code>neighbourhood</code> can not be <code>null</code> and that this method may only be called when the search is idle. @throws NullPointerException if <code>neighbourhood</code> is <code>null</code> @throws SearchException if the search is currently not idle @param neighbourhood neighbourhood used to modify the current solution
@Override public Result<MZMLIndexElement> buildIndex(final Info info) throws Exception { Result<MZMLIndexElement> result = new IndexBuilder.Result<>(info); vars.reset(); XMLStreamReaderImpl reader = (pool == null) ? new XMLStreamReaderImpl() : pool.borrowObject(); try { reader.setInput(info.is, StandardCharsets.UTF_8.name()); LogHelper.setJavolutionLogLevelFatal(); int eventType; do { // Read the next XML element try { eventType = reader.next(); } catch (XMLStreamException e) { if (e instanceof XMLUnexpectedEndTagException) { // it's ok to have unexpected closing tags eventType = reader.getEventType(); } else if (e instanceof XMLUnexpectedEndOfDocumentException) { // as we're reading arbitrary chunks of file, we will almost always finish parsing by hitting this condition break; } else { throw new FileParsingException(e); } } // process the read event switch (eventType) { case XMLStreamConstants.START_ELEMENT: CharArray localName = reader.getLocalName(); Attributes attrs = reader.getAttributes(); if (localName.contentEquals(MZMLMultiSpectraParser.TAG.SPECTRUM.name)) { if (vars.offsetLo != null) { throw new FileParsingException("Nested spectrum tags not allowed in mzml."); } // these are required attributes, if they're not there, just throw an exception try { vars.spectrumIndex = attrs.getValue(MZMLMultiSpectraParser.ATTR.SPECTRUM_INDEX.name) .toInt(); vars.spectrumId = attrs.getValue(MZMLMultiSpectraParser.ATTR.SPECTRUM_ID.name) .toString(); vars.offsetLo = reader.getLocation().getLastStartTagPos(); addAndFlush(result, info.offsetInFile); } catch (NumberFormatException e) { throw new FileParsingException("Malformed scan number while building index", e); } } break; case XMLStreamConstants.CHARACTERS: break; case XMLStreamConstants.END_ELEMENT: localName = reader.getLocalName(); if (localName.contentEquals(MZMLMultiSpectraParser.TAG.SPECTRUM.name)) { vars.offsetHi = reader.getLocation().getTotalCharsRead(); addAndFlush(result, info.offsetInFile); } break; } } while (eventType != XMLStreamConstants.END_DOCUMENT); } finally { addAndFlush(result, info.offsetInFile); // we need to return the reaer to the pool, if we borrowed it from there if (pool != null && reader != null) { pool.returnObject(reader); } } return result; }
For use with Executors, consider using instead of calling this method directly. @param info info about offsets in file and in currently read buffer
@Override public boolean isTabu(Move<? super SolutionType> move, SolutionType currentSolution) { // apply move move.apply(currentSolution); // check: contained in tabu memory? boolean tabu = memory.contains(currentSolution); // undo move move.undo(currentSolution); // return result return tabu; }
Verifies whether the given move is tabu by applying it to the current solution and checking if the obtained neighbour is currently contained in the tabu memory. If not, the move is allowed. Before returning, the move is undone to restore the original state of the current solution. @param move move to be applied to the current solution @param currentSolution current solution @return <code>true</code> if the neighbour obtained by applying the given move to the current solution is currently already contained in the tabu memory
@Override public void registerVisitedSolution(SolutionType visitedSolution, Move<? super SolutionType> appliedMove) { // store deep copy of newly visited solution memory.add(Solution.checkedCopy(visitedSolution)); }
A newly visited solution is registered by storing a deep copy of this solution in the full tabu memory. @param visitedSolution newly visited solution (copied to memory) @param appliedMove applied move (not used here, allowed to be <code>null</code>)
@Override public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) { // check size limit if(maxSizeReached(solution)){ // size limit would be exceeded return null; } // get set of candidate IDs for addition (possibly fixed IDs are discarded) Set<Integer> addCandidates = getAddCandidates(solution); // check if addition is possible if(addCandidates.isEmpty()){ return null; } // select random ID to add to selection int add = SetUtilities.getRandomElement(addCandidates, rnd); // create and return addition move return new AdditionMove(add); }
Generates a random addition move for the given subset solution that adds a single ID to the selection. Possible fixed IDs are not considered to be added and the maximum subset size is taken into account. If no addition move can be generated, <code>null</code> is returned. @param solution solution for which a random addition move is generated @param rnd source of randomness used to generate random move @return random addition move, <code>null</code> if no move can be generated
@Override public List<SubsetMove> getAllMoves(SubsetSolution solution) { // check size limit if(maxSizeReached(solution)){ return Collections.emptyList(); } // get set of candidate IDs for addition (possibly fixed IDs are discarded) Set<Integer> addCandidates = getAddCandidates(solution); // check if there are any candidates to be added if(addCandidates.isEmpty()){ return Collections.emptyList(); } // create addition move for all add candidates return addCandidates.stream() .map(add -> new AdditionMove(add)) .collect(Collectors.toList()); }
Generates a list of all possible addition moves that add a single ID to the selection of a given subset solution. Possible fixed IDs are not considered to be added and the maximum subset size is taken into account. May return an empty list if no addition moves can be generated. @param solution solution for which all possible addition moves are generated @return list of all addition moves, may be empty
@Override protected void searchStep() { // cyclically reset s to zero if no more shaking neighbourhoods are available if(s >= getNeighbourhoods().size()){ s = 0; } // create copy of current solution to shake and modify by applying local search procedure SolutionType shakedSolution = Solution.checkedCopy(getCurrentSolution()); // 1) SHAKING // get random move from current shaking neighbourhood Move<? super SolutionType> shakeMove = getNeighbourhoods().get(s).getRandomMove(shakedSolution, getRandom()); // shake (only if a move was obtained) Evaluation shakedEval = getCurrentSolutionEvaluation(); Validation shakedVal = getCurrentSolutionValidation(); if(shakeMove != null){ shakedEval = evaluate(shakeMove); shakedVal = validate(shakeMove); shakeMove.apply(shakedSolution); } // 2) LOCAL SEARCH // create instance of local search algorithm LocalSearch<SolutionType> localSearch = localSearchFactory.create(getProblem()); // set initial solution to be modified localSearch.setCurrentSolution(shakedSolution, shakedEval, shakedVal); // interrupt local search algorithm when main VNS search wants to terminate localSearch.addStopCriterion(_search -> getStatus() == SearchStatus.TERMINATING); // run local search localSearch.start(); // dispose local search when completed localSearch.dispose(); // 3) ACCEPTANCE SolutionType lsBestSolution = localSearch.getBestSolution(); Evaluation lsBestSolutionEvaluation = localSearch.getBestSolutionEvaluation(); Validation lsBestSolutionValidation = localSearch.getBestSolutionValidation(); // check improvement if(lsBestSolution != null && lsBestSolutionValidation.passed() // should always be true but it doesn't hurt to check && computeDelta(lsBestSolutionEvaluation, getCurrentSolutionEvaluation()) > 0){ // improvement: increase number of accepted moves incNumAcceptedMoves(1); // update current and best solution updateCurrentAndBestSolution(lsBestSolution, lsBestSolutionEvaluation, lsBestSolutionValidation); // reset shaking neighbourhood s = 0; } else { // no improvement: stick with current solution, adopt next shaking neighbourhood incNumRejectedMoves(1); s++; } }
Performs a step of VNS. One step consists of: <ol> <li>Shaking using the current shaking neighbourhood</li> <li>Modification using a new instance of the local search algorithm</li> <li> Acceptance of modified solution if it is a global improvement. In such case, the search continues with the first shaking neighbourhood; else, the next shaking neighbourhood will be used (cyclically). </li> </ol> @throws JamesRuntimeException if depending on malfunctioning components (problem, neighbourhood, ...)
@Override public boolean searchShouldStop(Search<?> search) { return search.getMinDelta() != JamesConstants.INVALID_DELTA && search.getMinDelta() < minDelta; }
Checks whether the minimum delta observed during the current run of the given search is still above the required minimum. @param search search for which the minimum delta has to be checked @return <code>true</code> in case of a minimum delta below the required minimum
public void setBah(ByteArrayHolder bah, ObjectPool<ByteArrayHolder> pool) { this.bah = bah; this.pool = pool; }
Sets the byte[] and indicates which pool this array is from.
public Class<?> getType(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base == null || property == null){ return null; } BeanProperty bp = getBeanProperty(context, base, property); context.setPropertyResolved(true); return bp.getPropertyType(); }
If the base object is not <code>null</code>, returns the most general acceptable type that can be set on this bean property. <p>If the base is not <code>null</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller should ignore the return value.</p> <p>The provided property will first be coerced to a <code>String</code>. If there is a <code>BeanInfoProperty</code> for this property and there were no errors retrieving it, the <code>propertyType</code> of the <code>propertyDescriptor</code> is returned. Otherwise, a <code>PropertyNotFoundException</code> is thrown.</p> @param context The context of this evaluation. @param base The bean to analyze. @param property The name of the property to analyze. Will be coerced to a <code>String</code>. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then the most general acceptable type; otherwise undefined. @throws NullPointerException if context is <code>null</code> @throws PropertyNotFoundException if <code>base</code> is not <code>null</code> and the specified property does not exist or is not readable. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
public Object getValue(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base == null || property == null){ return null; } BeanProperty bp = getBeanProperty(context, base, property); Method method = bp.getReadMethod(); if (method == null) { throw new PropertyNotFoundException( ELUtil.getExceptionMessageString(context, "propertyNotReadable", new Object[] { base.getClass().getName(), property.toString()})); } Object value; try { value = method.invoke(base, new Object[0]); context.setPropertyResolved(base, property); } catch (ELException ex) { throw ex; } catch (InvocationTargetException ite) { throw new ELException(ite.getCause()); } catch (Exception ex) { throw new ELException(ex); } return value; }
If the base object is not <code>null</code>, returns the current value of the given property on this bean. <p>If the base is not <code>null</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller should ignore the return value.</p> <p>The provided property name will first be coerced to a <code>String</code>. If the property is a readable property of the base object, as per the JavaBeans specification, then return the result of the getter call. If the getter throws an exception, it is propagated to the caller. If the property is not found or is not readable, a <code>PropertyNotFoundException</code> is thrown.</p> @param context The context of this evaluation. @param base The bean on which to get the property. @param property The name of the property to get. Will be coerced to a <code>String</code>. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then the value of the given property. Otherwise, undefined. @throws NullPointerException if context is <code>null</code>. @throws PropertyNotFoundException if <code>base</code> is not <code>null</code> and the specified property does not exist or is not readable. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
public void setValue(ELContext context, Object base, Object property, Object val) { if (context == null) { throw new NullPointerException(); } if (base == null || property == null){ return; } if (isReadOnly) { throw new PropertyNotWritableException( ELUtil.getExceptionMessageString(context, "resolverNotwritable", new Object[] { base.getClass().getName() })); } BeanProperty bp = getBeanProperty(context, base, property); Method method = bp.getWriteMethod(); if (method == null) { throw new PropertyNotWritableException( ELUtil.getExceptionMessageString(context, "propertyNotWritable", new Object[] { base.getClass().getName(), property.toString()})); } try { method.invoke(base, new Object[] {val}); context.setPropertyResolved(base, property); } catch (ELException ex) { throw ex; } catch (InvocationTargetException ite) { throw new ELException(ite.getCause()); } catch (Exception ex) { if (null == val) { val = "null"; } String message = ELUtil.getExceptionMessageString(context, "setPropertyFailed", new Object[] { property.toString(), base.getClass().getName(), val }); throw new ELException(message, ex); } }
If the base object is not <code>null</code>, attempts to set the value of the given property on this bean. <p>If the base is not <code>null</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller can safely assume no value was set.</p> <p>If this resolver was constructed in read-only mode, this method will always throw <code>PropertyNotWritableException</code>.</p> <p>The provided property name will first be coerced to a <code>String</code>. If property is a writable property of <code>base</code> (as per the JavaBeans Specification), the setter method is called (passing <code>value</code>). If the property exists but does not have a setter, then a <code>PropertyNotFoundException</code> is thrown. If the property does not exist, a <code>PropertyNotFoundException</code> is thrown.</p> @param context The context of this evaluation. @param base The bean on which to set the property. @param property The name of the property to set. Will be coerced to a <code>String</code>. @param val The value to be associated with the specified key. @throws NullPointerException if context is <code>null</code>. @throws PropertyNotFoundException if <code>base</code> is not <code>null</code> and the specified property does not exist. @throws PropertyNotWritableException if this resolver was constructed in read-only mode, or if there is no setter for the property. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (base == null || method == null) { return null; } Method m = ELUtil.findMethod(base.getClass(), method.toString(), paramTypes,params, false); m = BeanPropertiesCache.getMethod(base.getClass(), m); for (Object p: params) { // If the parameters is a LambdaExpression, set the ELContext // for its evaluation if (p instanceof javax.el.LambdaExpression) { ((javax.el.LambdaExpression) p).setELContext(context); } } Object ret = ELUtil.invokeMethod(context, m, base, params); context.setPropertyResolved(base, method); return ret; }
If the base object is not <code>null</code>, invoke the method, with the given parameters on this bean. The return value from the method is returned. <p>If the base is not <code>null</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller should ignore the return value.</p> <p>The provided method object will first be coerced to a <code>String</code>. The methods in the bean is then examined and an attempt will be made to select one for invocation. If no suitable can be found, a <code>MethodNotFoundException</code> is thrown. If the given paramTypes is not <code>null</code>, select the method with the given name and parameter types. Else select the method with the given name that has the same number of parameters. If there are more than one such method, the method selection process is undefined. Else select the method with the given name that takes a variable number of arguments. Note the resolution for overloaded methods will likely be clarified in a future version of the spec. The provide parameters are coerced to the corresponding parameter types of the method, and the method is then invoked. @param context The context of this evaluation. @param base The bean on which to invoke the method @param method The simple name of the method to invoke. Will be coerced to a <code>String</code>. If method is "&lt;init&gt;"or "&lt;clinit&gt;" a MethodNotFoundException is thrown. @param paramTypes An array of Class objects identifying the method's formal parameter types, in declared order. Use an empty array if the method has no parameters. Can be <code>null</code>, in which case the method's formal parameter types are assumed to be unknown. @param params The parameters to pass to the method, or <code>null</code> if no parameters. @return The result of the method invocation (<code>null</code> if the method has a <code>void</code> return type). @throws MethodNotFoundException if no suitable method can be found. @throws ELException if an exception was thrown while performing (base, method) resolution. The thrown exception must be included as the cause property of this exception, if available. If the exception thrown is an <code>InvocationTargetException</code>, extract its <code>cause</code> and pass it to the <code>ELException</code> constructor. @since EL 2.2
public boolean isReadOnly(ELContext context, Object base, Object property) { if (context == null) { throw new NullPointerException(); } if (base == null || property == null){ return false; } context.setPropertyResolved(true); if (isReadOnly) { return true; } BeanProperty bp = getBeanProperty(context, base, property); return bp.isReadOnly(); }
If the base object is not <code>null</code>, returns whether a call to {@link #setValue} will always fail. <p>If the base is not <code>null</code>, the <code>propertyResolved</code> property of the <code>ELContext</code> object must be set to <code>true</code> by this resolver, before returning. If this property is not <code>true</code> after this method is called, the caller can safely assume no value was set.</p> <p>If this resolver was constructed in read-only mode, this method will always return <code>true</code>.</p> <p>The provided property name will first be coerced to a <code>String</code>. If property is a writable property of <code>base</code>, <code>false</code> is returned. If the property is found but is not writable, <code>true</code> is returned. If the property is not found, a <code>PropertyNotFoundException</code> is thrown.</p> @param context The context of this evaluation. @param base The bean to analyze. @param property The name of the property to analyzed. Will be coerced to a <code>String</code>. @return If the <code>propertyResolved</code> property of <code>ELContext</code> was set to <code>true</code>, then <code>true</code> if calling the <code>setValue</code> method will always fail or <code>false</code> if it is possible that such a call may succeed; otherwise undefined. @throws NullPointerException if context is <code>null</code> @throws PropertyNotFoundException if <code>base</code> is not <code>null</code> and the specified property does not exist. @throws ELException if an exception was thrown while performing the property or variable resolution. The thrown exception must be included as the cause property of this exception, if available.
public Iterator<FeatureDescriptor> getFeatureDescriptors( ELContext context, Object base) { if (base == null){ return null; } BeanInfo info = null; try { info = Introspector.getBeanInfo(base.getClass()); } catch (Exception ex) { } if (info == null) { return null; } ArrayList<FeatureDescriptor> list = new ArrayList<FeatureDescriptor>( info.getPropertyDescriptors().length); for (PropertyDescriptor pd: info.getPropertyDescriptors()) { pd.setValue("type", pd.getPropertyType()); pd.setValue("resolvableAtDesignTime", Boolean.TRUE); list.add(pd); } return list.iterator(); }
If the base object is not <code>null</code>, returns an <code>Iterator</code> containing the set of JavaBeans properties available on the given object. Otherwise, returns <code>null</code>. <p>The <code>Iterator</code> returned must contain zero or more instances of {@link java.beans.FeatureDescriptor}. Each info object contains information about a property in the bean, as obtained by calling the <code>BeanInfo.getPropertyDescriptors</code> method. The <code>FeatureDescriptor</code> is initialized using the same fields as are present in the <code>PropertyDescriptor</code>, with the additional required named attributes "<code>type</code>" and "<code>resolvableAtDesignTime</code>" set as follows: <dl> <li>{@link ELResolver#TYPE} - The runtime type of the property, from <code>PropertyDescriptor.getPropertyType()</code>.</li> <li>{@link ELResolver#RESOLVABLE_AT_DESIGN_TIME} - <code>true</code>.</li> </dl> </p> @param context The context of this evaluation. @param base The bean to analyze. @return An <code>Iterator</code> containing zero or more <code>FeatureDescriptor</code> objects, each representing a property on this bean, or <code>null</code> if the <code>base</code> object is <code>null</code>.
private static Tag readTagFromBuffer(BufferedReader br, boolean close) { int id = 0; String name = "", forceDescription = null; ArrayList<String> types = new ArrayList<>(); String cardinality = ""; String defaultValue = ""; String typedef = null; String description = null; String[] valueCodes = null; String[] valueDescriptions = null; try { String sCurrentLine; boolean readingTypes = false; while ((sCurrentLine = br.readLine()) != null) { if (sCurrentLine.contains("\"id\"")) { String sid = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace(",", "").trim(); id = Integer.parseInt(sid); } else if (sCurrentLine.contains("\"name\"")) { String sval = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace("\"", "").replace(",", "").trim(); name = sval; } else if (sCurrentLine.contains("\"forceDescription\"")) { String sval = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace("\"", "").replace(",", "").trim(); forceDescription = sval; } else if (sCurrentLine.contains("\"cardinality\"")) { String sval = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace("\"", "").replace(",", "").trim(); cardinality = sval; } else if (sCurrentLine.contains("\"defaultValue\"")) { String sval = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace("\"", "").replace(",", "").trim(); defaultValue = sval; } else if (sCurrentLine.contains("\"valueCodes\"")) { sCurrentLine = br.readLine(); valueCodes = sCurrentLine.split(","); } else if (sCurrentLine.contains("\"description\"")) { description = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace("\"", "").replace(",", "").trim(); } else if (sCurrentLine.contains("\"valueDescriptions\"")) { sCurrentLine = br.readLine(); valueDescriptions = sCurrentLine.split(","); } else if (sCurrentLine.contains("\"typedef\"")) { String sval = sCurrentLine.substring(sCurrentLine.indexOf(":") + 1).replace("\"", "").replace(",", "").trim(); typedef = sval; } else if (sCurrentLine.contains("\"type\"")) { readingTypes = true; } else if (sCurrentLine.contains("],")) { readingTypes = false; } else if (readingTypes) { String sval = sCurrentLine.replace("\"", "").replace(",", "").trim(); types.add(sval); } } } catch (IOException e) { e.printStackTrace(); } finally { try { //br.reset(); if (br != null && close) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } Tag tag = new Tag(id, name, types, cardinality, defaultValue, typedef, forceDescription); tag.setDescription(description); tag.createValuesDictionary(); if (valueCodes != null && valueDescriptions != null && valueCodes.length == valueDescriptions.length) { HashMap<String, String> values = new HashMap<String, String>(); for (int i=0;i<valueCodes.length;i++) { values.put(valueCodes[i].trim(), valueDescriptions[i].trim().replace("\"", "")); } tag.setValues(values); } tagMap.put(tag.getId(), tag); tagNames.put(tag.getName(), tag); return tag; }
Read tag from buffer. @param br the br @return the tag
protected void generateTagRules() throws ReadTagsIOException { try { PrintWriter writer = new PrintWriter("typecheck.xml", "UTF-8"); for (int tagId : tagMap.keySet()) { Tag tag = tagMap.get(tagId); writer.println(" <rule context=\"tag[id=" + tag.getId() + "]\">"); String typeRule = ""; for (String tagType : tag.getType()) { if (typeRule.length() > 0) typeRule += " || "; typeRule += "{type=='" + tagType + "'}"; } writer.println(" <assert test=\"" + typeRule + "\">Tag type does not match</assert>"); writer.println(" </rule>"); } writer.close(); writer = new PrintWriter("cardinalitycheck.xml", "UTF-8"); for (int tagId : tagMap.keySet()) { Tag tag = tagMap.get(tagId); if (tag.getCardinality().length() > 0 && !tag.getCardinality().equals("N")) { try { int card = Integer.parseInt(tag.getCardinality()); writer.println(" <rule context=\"tag[id=" + tag.getId() + "]\">"); String typeRule = "{cardinality==" + card + "}"; writer.println(" <assert test=\"" + typeRule + "\">Tag cardinality does not match</assert>"); writer.println(" </rule>"); } catch (Exception ex) { // TODO: Deal with formulas System.err.println("Formula in tag " + tag.getName() + ": " + tag.getCardinality()); } } } writer.close(); } catch (Exception ex) { throw new ReadTagsIOException(); } }
Generate tag rules. @throws ReadTagsIOException the read tags io exception
public static Tag getTag(int identifier) { Tag t = null; try { if (instance == null) getTiffTags(); } catch (ReadTagsIOException e) { /*Nothing to be shown*/ } if (tagMap.containsKey(identifier)) t = tagMap.get(identifier); return t; }
Gets tag information. @param identifier Tag id @return the tag or null if the identifier does not exist
public static int getTagId(String name) { int id = -1; try { if (instance == null) getTiffTags(); } catch (ReadTagsIOException e) { /*Nothing to be shown*/ } if (tagNames.containsKey(name)) id = tagNames.get(name).getId(); return id; }
Gets the tag id. @param name the name @return the tag id
public void add(String name, TiffObject value, String path, String schema) { if (!metadata.containsKey(name)) { metadata.put(name, new MetadataObject()); } metadata.get(name).getObjectList().add(value); metadata.get(name).setPath(path); metadata.get(name).setSchema(schema); }
Adds a metadata value to the dictionary. @param name the name @param value the value
public void add(String name, TiffObject value) { if (!metadata.containsKey(name)) { metadata.put(name, new MetadataObject()); } metadata.get(name).getObjectList().add(value); }
Adds a metadata value to the dictionary. @param name the name @param value the value
public void add(String name, TiffObject value, boolean isDC, String path) { if (!metadata.containsKey(name)) { metadata.put(name, new MetadataObject()); metadata.get(name).setIsDublinCore(isDC); metadata.get(name).setPath(path); } metadata.get(name).getObjectList().add(value); }
Adds a metadata value to the dictionary. @param name the name @param value the value @param isDC the is dublin core
public TiffObject get(String name) { TiffObject result = null; String container = null; ArrayList<TiffObject> found = new ArrayList<>(); if (contains(name)) { // Find objects with this exact name if (metadata.get(name).getObjectList().size() == 1) { found.add(getFirst(name)); } else { for (TiffObject to : metadata.get(name).getObjectList()) { found.add(to); } } } else { // Find objects with similar or equivalent name for (String key : metadata.keySet()) { boolean similar = key.toLowerCase().equals(name.toLowerCase()); if (!similar) similar = name.toLowerCase().equals("date") && key.toLowerCase().equals("datetime"); if (!similar) similar = name.toLowerCase().equals("date") && key.toLowerCase().equals("creatordate"); if (!similar) similar = name.toLowerCase().equals("description") && key.toLowerCase().equals("imagedescription"); if (!similar) similar = name.toLowerCase().equals("creator") && key.toLowerCase().equals("artist"); if (!similar) similar = name.toLowerCase().equals("creator") && key.toLowerCase().equals("creatortool"); if (similar) { for (TiffObject to : metadata.get(key).getObjectList()) { found.add(to); } } } } // Return the most prioritary result if (found.size()==1) { result = found.get(0); } else { for (TiffObject to : found) { if (result == null) { result = to; container = to.getContainer(); } else if (to.getContainer() != null) { // Preferences in (descending) order: EXIF, XMP, IPTC, Tiff tag if (container == null || to.getContainer().equals("EXIF") || (to.getContainer().equals("XMP") && container.equals("IPTC"))) { result = to; container = to.getContainer(); } } } } return result; }
Gets a metadata value, returning the appropriate value when multiple are found. @param name the name of the metadata. @return the tiff object with the value of the metadata.
public void addMetadata(Metadata meta) { for (String k : meta.keySet()) { for (TiffObject to : meta.getList(k)) { add(k, to, meta.getMetadataObject(k).isDublinCore(), meta.getMetadataObject(k).getPath()); } } }
Adds a complete dictionary to the current one. @param meta the metadata dictionary to add
public ValidationResult getTiffEPValidation() { TiffEPProfile bpep = new TiffEPProfile(tiffModel); bpep.validate(); return bpep.getValidation(); }
Gets the result of the validation. @return the validation result
public ValidationResult getTiffITValidation(int profile) { TiffITProfile bpit = new TiffITProfile(tiffModel, profile); bpit.validate(); return bpit.getValidation(); }
Gets the result of the validation. @param profile the TiffIT profile (0: default, 1: P1, 2: P2) @return the validation result
public int readFile(String filename, boolean validate) { int result = 0; try { if (Files.exists(Paths.get(filename))) { data = new TiffInputStream(new File(filename)); tiffModel = new TiffDocument(); validation = new ValidationResult(validate); tiffModel.setSize(data.size()); boolean correctHeader = readHeader(); if (correctHeader) { if (tiffModel.getMagicNumber() < 42) { validation .addError("Incorrect tiff magic number", "Header", tiffModel.getMagicNumber()); } else if (tiffModel.getMagicNumber() == 43) { validation.addErrorLoc("Big tiff file not yet supported", "Header"); } else if (validation.isCorrect()) { readIFDs(); if (validate) { BaselineProfile bp = new BaselineProfile(tiffModel); bp.validate(); getBaselineValidation().add(bp.getValidation()); } } } if (getBaselineValidation().getFatalError()) { tiffModel.setFatalError(true, getBaselineValidation().getFatalErrorMessage()); } data.close(); } else { // File not found result = -1; tiffModel.setFatalError(true, "File not found"); } } catch (Exception ex) { // IO exception result = -2; tiffModel.setFatalError(true, "IO Exception"); } return result; }
Parses a Tiff File and create an internal model representation. @param filename the Tiff filename @return Error code (0: successful, -1: file not found, -2: IO exception)
private boolean readHeader() { boolean correct = true; ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN; int c1 = 0; int c2 = 0; try { c1 = data.readByte().toInt(); c2 = data.readByte().toInt(); } catch (Exception ex) { validation.addErrorLoc("Header IO Exception", "Header"); } // read the first two bytes, in order to know the byte ordering if (c1 == 'I' && c2 == 'I') { byteOrder = ByteOrder.LITTLE_ENDIAN; } else if (c1 == 'M' && c2 == 'M') { byteOrder = ByteOrder.BIG_ENDIAN; } else if (byteOrderErrorTolerance > 0 && c1 == 'i' && c2 == 'i') { validation.addWarning("Byte Order in lower case", "" + c1 + c2, "Header"); byteOrder = ByteOrder.LITTLE_ENDIAN; } else if (byteOrderErrorTolerance > 0 && c1 == 'm' && c2 == 'm') { validation.addWarning("Byte Order in lower case", "" + c1 + c2, "Header"); byteOrder = ByteOrder.BIG_ENDIAN; } else if (byteOrderErrorTolerance > 1) { validation.addWarning("Non-sense Byte Order. Trying Little Endian.", "" + c1 + c2, "Header"); byteOrder = ByteOrder.LITTLE_ENDIAN; } else { validation.addErrorLoc("Invalid Byte Order " + c1 + c2, "Header"); correct = false; } if (correct) { tiffModel.setByteOrder(byteOrder); data.setByteOrder(byteOrder); try { // read magic number int magic = data.readShort().toInt(); tiffModel.setMagicNumber(magic); } catch (Exception ex) { validation.addErrorLoc("Magic number parsing error", "Header"); correct = false; } } return correct; }
Reads the Tiff header. @return true, if successful
private void readIFDs() { int offset0 = 0; try { // The pointer to the first IFD is located in bytes 4-7 offset0 = data.readLong(4).toInt(); tiffModel.setFirstIFDOffset(offset0); if (offset0 == 0) validation.addErrorLoc("There is no first IFD", "Header"); else if (offset0 > data.size()) validation.addErrorLoc("Incorrect offset", "Header"); } catch (Exception ex) { validation.addErrorLoc("IO exception", "Header"); } if (validation.isCorrect()) { int nifd = 1; try { IfdReader ifd0 = readIFD(offset0, true, 0); HashSet<Integer> usedOffsets = new HashSet<Integer>(); usedOffsets.add(offset0); if (ifd0.getIfd() == null) { validation.addErrorLoc("Parsing error in first IFD", "IFD" + 0); } else { IFD iifd = ifd0.getIfd(); iifd.setNextOffset(ifd0.getNextIfdOffset()); tiffModel.addIfd0(iifd); IfdReader current_ifd = ifd0; // Read next IFDs boolean stop = false; while (current_ifd.getNextIfdOffset() > 0 && !stop) { if (usedOffsets.contains(current_ifd.getNextIfdOffset())) { // Circular reference validation.addErrorLoc("IFD offset already used", "IFD" + nifd); stop = true; } else if (current_ifd.getNextIfdOffset() > data.size()) { validation.addErrorLoc("Incorrect offset", "IFD" + nifd); stop = true; } else { usedOffsets.add(current_ifd.getNextIfdOffset()); IfdReader next_ifd = readIFD(current_ifd.getNextIfdOffset(), true, nifd); if (next_ifd == null) { validation.addErrorLoc("Parsing error in IFD " + nifd, "IFD" + nifd); stop = true; } else { iifd = next_ifd.getIfd(); iifd.setNextOffset(next_ifd.getNextIfdOffset()); current_ifd.getIfd().setNextIFD(iifd); current_ifd = next_ifd; } nifd++; } } } } catch (Exception ex) { validation.addErrorLoc("IFD parsing error", "IFD" + nifd); } try { tiffModel.createMetadataDictionary(); } catch (Exception ex) { } } }
Read the IFDs contained in the Tiff file.
private IfdReader readIFD(int offset, boolean isImage, int n) { IFD ifd = new IFD(isImage); ifd.setOffset(offset); IfdReader ir = new IfdReader(); ir.setIfd(ifd); int nextIfdOffset = 0; try { if (offset % 2 != 0) { validation.addErrorLoc("Bad word alignment in the offset of the IFD", "IFD" + n); } int index = offset; int directoryEntries = data.readShort(offset).toInt(); if (directoryEntries < 1) { validation.addError("Incorrect number of IFD entries", "IFD" + n, directoryEntries); validation.setFatalError(true, "Incorrect number of IFD entries"); } else if (directoryEntries > 500) { if (n < 0) { validation.addError("Incorrect number of IFD entries", "SubIFD" + (-n), directoryEntries); validation.setFatalError(true, "Incorrect number of IFD entries"); } else { validation.addError("Incorrect number of IFD entries", "IFD" + n, directoryEntries); validation.setFatalError(true, "Incorrect number of IFD entries"); } } else { index += 2; // Reads the tags for (int i = 0; i < directoryEntries; i++) { int tagid = 0; int tagType = -1; int tagN = -1; try { tagid = data.readShort(index).toInt(); tagType = data.readShort(index + 2).toInt(); tagN = data.readLong(index + 4).toInt(); boolean ok = checkType(tagid, tagType, n); if (!ok && tagN > 1000) tagN = 1000; TagValue tv = getValue(tagType, tagN, tagid, index + 8, ifd, n); if (ifd.containsTagId(tagid)) { if (duplicateTagTolerance > 0) validation.addWarning("Duplicate tag", "" + tagid, "IFD" + n); else validation.addError("Duplicate tag", "IFD" + n, tagid); } ifd.addTag(tv); } catch (Exception ex) { validation.addErrorLoc("Parse error in tag #" + i + " (" + tagid + ")", "IFD" + n); TagValue tv = new TagValue(tagid, tagType); tv.setReadOffset(index + 8); tv.setReadLength(tagN); ifd.addTag(tv); } index += 12; } // Reads the position of the next IFD nextIfdOffset = 0; try { nextIfdOffset = data.readLong(index).toInt(); } catch (Exception ex) { nextIfdOffset = 0; if (nextIFDTolerance > 0) validation.addWarning("Unreadable next IFD offset", "", "IFD" + n); else validation.addErrorLoc("Unreadable next IFD offset", "IFD" + n); } if (nextIfdOffset > 0 && nextIfdOffset < 7) { validation.addError("Invalid next IFD offset", "IFD" + n, nextIfdOffset); nextIfdOffset = 0; } ir.setNextIfdOffset(nextIfdOffset); ir.readImage(); if (isImage && !ifd.hasStrips() && !ifd.hasTiles()) { validation.setFatalError(true, "Incorrect image"); } } } catch (Exception ex) { validation.addErrorLoc("IO Exception", "IFD" + n); return null; } return ir; }
Parses the image file descriptor data. @param offset the file offset (in bytes) pointing to the IFD @param isImage the is image @param n the IFD number @return the ifd reading result
private boolean checkType(int tagid, int tagType, int n) { if (TiffTags.hasTag(tagid) && !TiffTags.getTag(tagid).getName().equals("IPTC")) { boolean found = false; String stagType = TiffTags.getTagTypeName(tagType); if (stagType != null) { if (stagType.equals("SUBIFD")) stagType = "IFD"; if (stagType.equals("UNDEFINED")) stagType = "BYTE"; for (String vType : TiffTags.getTag(tagid).getType()) { String vType2 = vType; if (vType2.equals("UNDEFINED")) vType2 = "BYTE"; if (vType2.equals(stagType)) { found = true; } } } if (!found) { validation.addError("Incorrect type for tag " + TiffTags.getTag(tagid).getName(), "IFD" + n, stagType); return false; } return true; } return false; }
Check tag type. @param tagid the tagid @param tagType the tag type @param n the n
protected TagValue getValue(int tagtype, int n, int id, int beginOffset, IFD parentIFD, int nifd) { int type = tagtype; if (id == 330 && type != 13) type = 13; // Create TagValue object TagValue tv = new TagValue(id, type); tv.setTagOffset(beginOffset - 8); // Defined tags int offset = beginOffset; // Get type Size int typeSize = TiffTags.getTypeSize(type); boolean ok = true; // Check if the tag value fits in the directory entry value field, and get offset if not if (typeSize * n > tagValueSize) { try { offset = data.readLong(offset).toInt(); if (offset % 2 != 0) { validation.addErrorLoc("Bad word alignment in the offset of tag " + id, "IFD" + n); } } catch (Exception ex) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + n); ok = false; } } tv.setReadOffset(offset); tv.setReadLength(n); if (ok) { try { for (int i = 0; i < n; i++) { // Get N tag values switch (type) { case 1: tv.add(data.readByte(offset)); break; case 2: tv.add(data.readAscii(offset)); break; case 6: tv.add(data.readSByte(offset)); break; case 7: tv.add(data.readUndefined(offset)); break; case 3: tv.add(data.readShort(offset)); break; case 8: tv.add(data.readSShort(offset)); break; case 4: tv.add(data.readLong(offset)); break; case 9: tv.add(data.readSLong(offset)); break; case 5: tv.add(data.readRational(offset)); break; case 10: tv.add(data.readSRational(offset)); break; case 11: tv.add(data.readFloat(offset)); break; case 12: tv.add(data.readDouble(offset)); break; case 13: int ifdOffset = data.readLong(offset).toInt(); if (ifdOffset % 2 != 0) { validation .addErrorLoc("Bad word alignment in the offset of the sub IFD", "IFD" + n); } IfdReader ifd = readIFD(ifdOffset, true, -nifd); IFD subIfd = ifd.getIfd(); subIfd.setParent(parentIFD); parentIFD.setsubIFD(subIfd); tv.add(subIfd); break; } offset += typeSize; } } catch (Exception ex) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); ok = false; } } if (type == 2) { tv.readString(); } if (ok && TiffTags.hasTag(id)) { Tag t = TiffTags.getTag(id); if (t.hasTypedef() && !t.getTypedef().equals("SubIFD")) { String tagclass = t.getTypedef(); try { abstractTiffType instanceOfMyClass = (abstractTiffType) Class.forName("com.easyinnova.tiff.model.types." + tagclass) .getConstructor().newInstance(); if (instanceOfMyClass.isIFD()) { long ifdOffset = tv.getFirstNumericValue(); try { if (ifdOffset % 2 != 0) { validation.addErrorLoc("Bad word alignment in the offset of Exif", "IFD" + n); } IfdReader ifd = readIFD((int) ifdOffset, false, -1); IFD exifIfd = ifd.getIfd(); exifIfd.setIsIFD(true); tv.clear(); tv.add(exifIfd); } catch (Exception ex) { validation.addErrorLoc("Parse error in Exif", "IFD" + nifd); } } else { if (tv.getId() == 33723) instanceOfMyClass.read(tv, data.getFilePath()); else instanceOfMyClass.read(tv); } } catch (ClassNotFoundException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (NoSuchMethodException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (SecurityException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (InstantiationException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (IllegalAccessException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (IllegalArgumentException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (InvocationTargetException e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } catch (Exception e) { validation.addErrorLoc("Parse error getting tag " + id + " value", "IFD" + nifd); } } } if (ok) tv.setReadValue(); return tv; }
Gets the value of the given tag field. @param tagtype the tag type @param n the cardinality @param id the tag id @param beginOffset the offset position of the tag value @param parentIFD the parent ifd @param nifd the ifd number @return the tag value object
public void addTag(TagValue tag) { //int pos = 0; //while (pos < tags.size() && tags.get(pos).getId() < tag.getId()) pos++; //tags.add(pos, tag); tags.add(tag); if (!hashTagsId.containsKey(tag.getId())) { hashTagsId.put(tag.getId(), tag); } Tag t = TiffTags.getTag(tag.getId()); if (t != null) { if (hashTagsName.containsKey(t.getName())) { hashTagsName.put(t.getName(), tag); } } }
Adds a tag to the set. @param tag the tag to add
public void addTag(String tagName, int[] tagValue) { int id = TiffTags.getTagId(tagName); TagValue tag = new TagValue(id, 3); for (int i = 0; i < tagValue.length; i++) { com.easyinnova.tiff.model.types.Short val = new com.easyinnova.tiff.model.types.Short(tagValue[i]); tag.add(val); } addTag(tag); }
Adds the tag. @param tagName the tag name @param tagValue the tag value
public void addTag(String tagName, String tagValue) { int id = TiffTags.getTagId(tagName); TagValue tag = new TagValue(id, 2); for (int i = 0; i < tagValue.length(); i++) { int val = tagValue.charAt(i); if (val > 127) val = 0; Ascii cha = new Ascii(val); tag.add(cha); } Ascii chaf = new Ascii(0); tag.add(chaf); addTag(tag); }
Adds the tag. @param tagName the tag name @param tagValue the tag value
public void removeTag(String tagName) { for (int i = 0; i < tags.size(); i++) { if (tags.get(i).getName().equals(tagName)) { tags.remove(i); if (hashTagsName.containsKey(tagName)) hashTagsName.remove(tagName); if (hashTagsId.containsKey(TiffTags.getTagId(tagName))) hashTagsId.remove(TiffTags.getTagId(tagName)); i--; } } }
Removes the tag. @param tagName the tag name
public void startChecking() { // synchronize with other attempts to update the running task synchronized(runningTaskLock){ // check if not already active if(runningTask == null) { // only activate if at least one stop criterion has been set if(!stopCriteria.isEmpty()){ // schedule periodical check runningTask = new StopCriterionCheckTask(); runningTaskFuture = SCHEDULER.scheduleWithFixedDelay(runningTask, period, period, periodTimeUnit); // log LOGGER.debug("Stop criterion checker for search {} activated", search); } } else { // issue a warning LOGGER.warn("Attempted to activate already active stop criterion checker for search {}", search); } } }
Start checking the stop criteria, in a separate background thread. If the stop criterion checker is already active, or if no stop criteria have been added, calling this method does not have any effect.
public void stopChecking() { // synchronize with other attempts to update the running task synchronized(runningTaskLock){ if(runningTask != null) { // cancel task (let it complete its current run if running) runningTaskFuture.cancel(false); // log LOGGER.debug("Stop criterion checker for search {} deactivated", search); // discard task runningTask = null; runningTaskFuture = null; } } }
Instructs the stop criterion checker to stop checking. In case the checker is not active, calling this method does not have any effect.
public boolean stopCriterionSatisfied(){ int i = 0; while (i < stopCriteria.size() && !stopCriteria.get(i).searchShouldStop(search)) { i++; } return i < stopCriteria.size(); }
Check whether at least one stop criterion is satisfied. @return <code>true</code> if a stop condition is satisfied
public static DecodedData decode(byte[] bytesIn, int lengthIn, Integer precision, int numPoints, EnumSet<PeaksCompression> compressions) throws DataFormatException, IOException, FileParsingException { // for some reason there sometimes might be zero length <peaks> tags (ms2 usually) // in this case we jsut return an empty result if (bytesIn.length == 0 || lengthIn == 0) { return DecodedData.createEmpty(); } if (compressions == null) { compressions = EnumSet.noneOf(PeaksCompression.class); } ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ////// ////// ////// ////// ////// CRITICAL SPOT ////// ////// ////// ////// We might not have enough memory ////// ////// for the data array ////// ////// ////// ///////////////////////////////////////////////////////// ///////////////////////////////////////////////////////// ByteArrayHolder bytes = null; boolean isBytesFromPool = false; try { // try/catch to return the byte array, possibly borrowed from a pool double[] data = new double[numPoints]; // first check for zlib compression, inflation must be done before NumPress if (compressions.contains(PeaksCompression.ZLIB)) { bytes = ZlibInflater.zlibUncompressBuffer(bytesIn, lengthIn, null); isBytesFromPool = true; } else { bytes = new ByteArrayHolder(bytesIn); bytes.setPosition(lengthIn); } // now can check for NumPress if (compressions.contains(PeaksCompression.NUMPRESS_LINPRED)) { int numDecodedDoubles = MSNumpress .decodeLinear(bytes.getUnderlyingBytes(), bytes.getPosition(), data); if (numDecodedDoubles < 0) { throw new FileParsingException("MSNumpress linear decoder failed"); } return toDecodedData(data); } else if (compressions.contains(PeaksCompression.NUMPRESS_POSINT)) { int numDecodedDoubles = MSNumpress .decodePic(bytes.getUnderlyingBytes(), bytes.getPosition(), data); if (numDecodedDoubles < 0) { throw new FileParsingException("MSNumpress positive integer decoder failed"); } return toDecodedData(data); } else if (compressions.contains(PeaksCompression.NUMPRESS_SHLOGF)) { int numDecodedDoubles = MSNumpress .decodeSlof(bytes.getUnderlyingBytes(), bytes.getPosition(), data); if (numDecodedDoubles < 0) { throw new FileParsingException("MSNumpress short logged float decoder failed"); } return toDecodedData(data); } if (precision == null) { throw new IllegalArgumentException( "Precision MUST be specified, if MS-NUMPRESS compression was not used"); } int decodedLen = bytes.getPosition(); // in bytes byte[] decoded = bytes.getUnderlyingBytes(); int chunkSize = precision / 8; // in bytes int offset; double valMax = Double.NEGATIVE_INFINITY; int valMaxPos = 0; double valMin = Double.POSITIVE_INFINITY; int valMinPos = 0; double valMinNonZero = Double.POSITIVE_INFINITY; int valMinNonZeroPos = 0; double sum = 0d; switch (precision) { case (32): { int asInt; float asFloat; for (int i = 0; i < numPoints; i++) { offset = i * chunkSize; // hopefully this way is faster asInt = ((decoded[offset] & 0xFF)) // zero shift | ((decoded[offset + 1] & 0xFF) << 8) | ((decoded[offset + 2] & 0xFF) << 16) | ((decoded[offset + 3] & 0xFF) << 24); asFloat = Float.intBitsToFloat(asInt); if (asFloat > valMax) { valMax = asFloat; valMaxPos = i; } if (asFloat < valMinNonZero) { if (asFloat > 0) { valMinNonZero = asFloat; valMinNonZeroPos = i; } if (asFloat < valMin) { valMin = asFloat; valMinPos = i; } } sum = sum + asFloat; data[i] = asFloat; } break; } case (64): { long asLong; double asDouble; for (int i = 0; i < numPoints; i++) { offset = i * chunkSize; asLong = ((long) (decoded[offset] & 0xFF)) // zero shift | ((long) (decoded[offset + 1] & 0xFF) << 8) | ((long) (decoded[offset + 2] & 0xFF) << 16) | ((long) (decoded[offset + 3] & 0xFF) << 24) | ((long) (decoded[offset + 4] & 0xFF) << 32) | ((long) (decoded[offset + 5] & 0xFF) << 40) | ((long) (decoded[offset + 6] & 0xFF) << 48) | ((long) (decoded[offset + 7] & 0xFF) << 56); asDouble = Double.longBitsToDouble(asLong); if (asDouble > valMax) { valMax = asDouble; valMaxPos = i; } if (asDouble < valMinNonZero) { if (asDouble > 0) { valMinNonZero = asDouble; valMinNonZeroPos = i; } if (asDouble < valMin) { valMin = asDouble; valMinPos = i; } } sum = sum + asDouble; data[i] = asDouble; } break; } default: { throw new IllegalArgumentException( "Precision can only be 32/64 bits, other values are not valid."); } } return new DecodedData(data, valMax, valMaxPos, valMin, valMinPos, valMinNonZero, valMinNonZeroPos, sum); } catch (OutOfMemoryError oom) { throw new FileParsingException("Could not allocate arrays during spectra decoding step", oom); } finally { // return ByteArrayHolder to the pool if (isBytesFromPool && bytes != null) { try { ZlibInflater.getPool().returnObject(bytes); } catch (Exception e) { throw new FileParsingException("Could not return ByteArrayHolder to the pool.", e); } } } }
Converts a base64 encoded mz or intensity string used in mzML files to an array of doubles. If the original precision was 32 bit, you still get doubles as output, would be too complicated to provide another method to parseIndexEntries them as floats. Hopefully some day everything will be in 64 bits anyway. @param bytesIn Byte array, decoded from a base64 encoded string E.g. like: eNoNxltIkwEYBuAOREZFhrCudGFbbraTU+Zmue... @param lengthIn length of data to be treated as values, i.e. the input array can be longer, the values to be interpreted must start at offset 0, and this will indicate the length @param precision allowed values: 32 and 64, can be null only if MS-NUMPRESS compression was applied and is specified in the @{code compressions} enum set. @param compressions null or {@link PeaksCompression#NONE} have the same effect. Otherwise the binary data will be inflated according to the compression rules.
public static void doMapToolbarWorkaround(Bundle savedInstanceState) { // FIXME This is just a workaround to the following error: ClassNotFoundException when unmarshalling android.support.v7.widget.Toolbar$SavedState // It seems to be a problem with the SupportMapFragment implementation // https://code.google.com/p/android/issues/detail?id=175140 if (savedInstanceState != null) { SparseArray sparseArray = (SparseArray)savedInstanceState.get("android:view_state"); if (sparseArray != null) { Integer keyToRemove = null; for (int i = 0; i < sparseArray.size(); i++) { int key = sparseArray.keyAt(i); // get the object by the key. Object each = sparseArray.get(key); if (each.toString().startsWith("android.support.v7.widget.Toolbar$SavedState")) { keyToRemove = key; } } if (keyToRemove != null) { sparseArray.remove(keyToRemove); } } } }
Calling this before super.oncreate() when you try to use a toolbar and the view contains a map https://code.google.com/p/android/issues/detail?id=175140
@Override public void setNumThreadsForParsing(Integer numThreadsForParsing) { if (numThreadsForParsing == null) { this.numThreadsForParsing = Runtime.getRuntime().availableProcessors(); return; } if (numThreadsForParsing < 1) { throw new IllegalArgumentException("The number of threads can not be less than 1."); } this.numThreadsForParsing = numThreadsForParsing; }
How many batches of scans will be processed in parallel. Disk I/O is done once per batch. @param numThreadsForParsing must be greater than zero, if null, defaults to the number of available processor cores
private void flushBuffer() throws IOException { if (this.dirty_) { if (this.diskPos_ != this.lo_) { super.seek(this.lo_); } int len = (int) (this.curr_ - this.lo_); super.write(this.buff_, 0, len); this.diskPos_ = this.curr_; this.dirty_ = false; } }
/* Flush any dirty bytes in the buffer to disk.
private int fillBuffer() throws IOException { int cnt = 0; int rem = this.buff_.length; while (rem > 0) { int n = super.read(this.buff_, cnt, rem); if (n < 0) { break; } cnt += n; rem -= n; } if ((cnt < 0) && (this.hitEOF_ = (cnt < this.buff_.length))) { // make sure buffer that wasn't read is initialized with -1 Arrays.fill(this.buff_, cnt, this.buff_.length, (byte) 0xff); } this.diskPos_ += cnt; return cnt; }
/* Read at most "this.buff.length" bytes into "this.buff", returning the number of bytes read. If the return result is less than "this.buff.length", then EOF was read.
public void seek(long pos) throws IOException { if (pos >= this.hi_ || pos < this.lo_) { // seeking outside of current buffer -- flush and read this.flushBuffer(); this.lo_ = pos & BuffMask_; // start at BuffSz boundary this.maxHi_ = this.lo_ + (long) this.buff_.length; if (this.diskPos_ != this.lo_) { super.seek(this.lo_); this.diskPos_ = this.lo_; } int n = this.fillBuffer(); this.hi_ = this.lo_ + (long) n; } else { // seeking inside current buffer -- no read required if (pos < this.curr_) { // if seeking backwards, we must flush to maintain V4 this.flushBuffer(); } } this.curr_ = pos; }
/* This method positions <code>this.curr</code> at position <code>pos</code>. If <code>pos</code> does not fall in the current buffer, it flushes the current buffer and loads the correct one.<p> On exit from this routine <code>this.curr == this.hi</code> iff <code>pos</code> is at or past the end-of-file, which can only happen if the file was opened in read-only mode.
private int writeAtMost(byte[] b, int off, int len) throws IOException { if (this.curr_ >= this.hi_) { if (this.hitEOF_ && this.hi_ < this.maxHi_) { // at EOF -- bump "hi" this.hi_ = this.maxHi_; } else { // slow path -- write current buffer; read next one this.seek(this.curr_); if (this.curr_ == this.hi_) { // appending to EOF -- bump "hi" this.hi_ = this.maxHi_; } } } len = Math.min(len, (int) (this.hi_ - this.curr_)); int buffOff = (int) (this.curr_ - this.lo_); System.arraycopy(b, off, this.buff_, buffOff, len); this.curr_ += len; return len; }
/* Write at most "len" bytes to "b" starting at position "off", and return the number of bytes written.
public static String encode(String string, String enc) throws UnsupportedEncodingException { return new String(encode(string.getBytes(enc)), enc); }
Encode a String in Base64. No line breaks or other white space are inserted into the encoded data. @param string The data to encode. @param enc Character encoding to use when converting to and from bytes. @return An encoded String. @throws UnsupportedEncodingException if the character encoding specified is not supported. @since ostermillerutils 1.00.00
public static String encodeToString(byte[] bytes, boolean lineBreaks) { try { return new String(encode(bytes, lineBreaks), "ASCII"); } catch (UnsupportedEncodingException iex) { // ASCII should be supported throw new RuntimeException(iex); } }
Encode bytes in Base64. @param bytes The data to encode. @param lineBreaks Whether to insert line breaks every 76 characters in the output. @return String with Base64 encoded data. @since ostermillerutils 1.04.00
public static byte[] encode(byte[] bytes, boolean lineBreaks) { ByteArrayInputStream in = new ByteArrayInputStream(bytes); // calculate the length of the resulting output. // in general it will be 4/3 the size of the input // but the input length must be divisible by three. // If it isn't the next largest size that is divisible // by three is used. int mod; int length = bytes.length; if ((mod = length % 3) != 0) { length += 3 - mod; } length = length * 4 / 3; ByteArrayOutputStream out = new ByteArrayOutputStream(length); try { encode(in, out, lineBreaks); } catch (IOException x) { // This can't happen. // The input and output streams were constructed // on memory structures that don't actually use IO. throw new RuntimeException(x); } return out.toByteArray(); }
Encode bytes in Base64. @param bytes The data to encode. @param lineBreaks Whether to insert line breaks every 76 characters in the output. @return Encoded bytes. @since ostermillerutils 1.04.00
public static void encode(InputStream in, OutputStream out) throws IOException { encode(in, out, true); }
Encode data from the InputStream to the OutputStream in Base64. Line breaks are inserted every 76 characters in the output. @param in Stream from which to read data that needs to be encoded. @param out Stream to which to write encoded data. @throws IOException if there is a problem reading or writing. @since ostermillerutils 1.00.00
public static void encode(InputStream in, OutputStream out, boolean lineBreaks) throws IOException { // Base64 encoding converts three bytes of input to // four bytes of output int[] inBuffer = new int[3]; int lineCount = 0; boolean done = false; while (!done && (inBuffer[0] = in.read()) != END_OF_INPUT) { // Fill the buffer inBuffer[1] = in.read(); inBuffer[2] = in.read(); // Calculate the out Buffer // The first byte of our in buffer will always be valid // but we must check to make sure the other two bytes // are not END_OF_INPUT before using them. // The basic idea is that the three bytes get split into // four bytes along these lines: // [AAAAAABB] [BBBBCCCC] [CCDDDDDD] // [xxAAAAAA] [xxBBBBBB] [xxCCCCCC] [xxDDDDDD] // bytes are considered to be zero when absent. // the four bytes are then mapped to common ASCII symbols // A's: first six bits of first byte out.write(base64Chars[inBuffer[0] >> 2]); if (inBuffer[1] != END_OF_INPUT) { // B's: last two bits of first byte, first four bits of second byte out.write(base64Chars[((inBuffer[0] << 4) & 0x30) | (inBuffer[1] >> 4)]); if (inBuffer[2] != END_OF_INPUT) { // C's: last four bits of second byte, first two bits of third byte out.write(base64Chars[((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6)]); // D's: last six bits of third byte out.write(base64Chars[inBuffer[2] & 0x3F]); } else { // C's: last four bits of second byte out.write(base64Chars[((inBuffer[1] << 2) & 0x3c)]); // an equals sign for a character that is not a Base64 character out.write('='); done = true; } } else { // B's: last two bits of first byte out.write(base64Chars[((inBuffer[0] << 4) & 0x30)]); // an equal signs for characters that is not a Base64 characters out.write('='); out.write('='); done = true; } lineCount += 4; if (lineBreaks && lineCount >= 76) { out.write('\n'); lineCount = 0; } } if (lineBreaks && lineCount >= 1) { out.write('\n'); lineCount = 0; } out.flush(); }
Encode data from the InputStream to the OutputStream in Base64. @param in Stream from which to read data that needs to be encoded. @param out Stream to which to write encoded data. @param lineBreaks Whether to insert line breaks every 76 characters in the output. @throws IOException if there is a problem reading or writing. @since ostermillerutils 1.00.00
public static String decode(String string, String enc) throws UnsupportedEncodingException { return new String(decode(string.getBytes(enc)), enc); }
Decode a Base64 encoded String. Characters that are not part of the Base64 alphabet are ignored in the input. @param string The data to decode. @param enc Character encoding to use when converting to and from bytes. @return A decoded String. @throws UnsupportedEncodingException if the character encoding specified is not supported. @since ostermillerutils 1.00.00
public static String decode(String string, String encIn, String encOut) throws UnsupportedEncodingException { return new String(decode(string.getBytes(encIn)), encOut); }
Decode a Base64 encoded String. Characters that are not part of the Base64 alphabet are ignored in the input. @param string The data to decode. @param encIn Character encoding to use when converting input to bytes (should not matter because Base64 data is designed to survive most character encodings) @param encOut Character encoding to use when converting decoded bytes to output. @return A decoded String. @throws UnsupportedEncodingException if the character encoding specified is not supported. @since ostermillerutils 1.00.00
public static byte[] decodeToBytes(String string, String enc) throws UnsupportedEncodingException { return decode(string.getBytes(enc)); }
Decode a Base64 encoded String. Characters that are not part of the Base64 alphabet are ignored in the input. @param string The data to decode. @param enc Character encoding to use when converting from bytes. @return decoded data. @throws UnsupportedEncodingException if the character encoding specified is not supported. @since ostermillerutils 1.02.16
public static String decodeToString(byte[] bytes, String enc) throws UnsupportedEncodingException { return new String(decode(bytes), enc); }
Decode Base64 encoded bytes. Characters that are not part of the Base64 alphabet are ignored in the input. @param bytes The data to decode. @param enc Character encoding to use when converting to and from bytes. @return A decoded String. @throws UnsupportedEncodingException if the character encoding specified is not supported. @since ostermillerutils 1.02.16
public static byte[] decode(byte[] bytes) { ByteArrayInputStream in = new ByteArrayInputStream(bytes); // calculate the length of the resulting output. // in general it will be at most 3/4 the size of the input // but the input length must be divisible by four. // If it isn't the next largest size that is divisible // by four is used. int mod; int length = bytes.length; if ((mod = length % 4) != 0) { length += 4 - mod; } length = length * 3 / 4; ByteArrayOutputStream out = new ByteArrayOutputStream(length); try { decode(in, out, false); } catch (IOException x) { // This can't happen. // The input and output streams were constructed // on memory structures that don't actually use IO. throw new RuntimeException(x); } return out.toByteArray(); }
Decode Base64 encoded bytes. Characters that are not part of the Base64 alphabet are ignored in the input. @param bytes The data to decode. @return Decoded bytes. @since ostermillerutils 1.00.00
public static void decode(byte[] bytes, OutputStream out) throws IOException { ByteArrayInputStream in = new ByteArrayInputStream(bytes); decode(in, out, false); }
Decode Base64 encoded bytes to the an OutputStream. Characters that are not part of the Base64 alphabet are ignored in the input. @param bytes The data to decode. @param out Stream to which to write decoded data. @throws IOException if an IO error occurs. @since ostermillerutils 1.00.00
private static final int readBase64(InputStream in, boolean throwExceptions) throws IOException { int read; int numPadding = 0; do { read = in.read(); if (read == END_OF_INPUT) { return END_OF_INPUT; } read = reverseBase64Chars[(byte) read]; if (throwExceptions && (read == NON_BASE_64 || (numPadding > 0 && read > NON_BASE_64))) { throw new Base64DecodingException( MessageFormat.format( "Unexpected char", (Object[]) new String[]{ "'" + (char) read + "' (0x" + Integer.toHexString(read) + ")" } ), (char) read ); } if (read == NON_BASE_64_PADDING) { numPadding++; } } while (read <= NON_BASE_64); return read; }
Reads the next (decoded) Base64 character from the input stream. Non Base64 characters are skipped. @param in Stream from which bytes are read. @param throwExceptions Throw an exception if an unexpected character is encountered. @return the next Base64 character from the stream or -1 if there are no more Base64 characters on the stream. @throws IOException if an IO Error occurs. @throws Base64DecodingException if unexpected data is encountered when throwExceptions is specified. @since ostermillerutils 1.00.00
public static byte[] decodeToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); decode(in, out, false); return out.toByteArray(); }
Decode Base64 encoded data from the InputStream to a byte array. Characters that are not part of the Base64 alphabet are ignored in the input. @param in Stream from which to read data that needs to be decoded. @return decoded data. @throws IOException if an IO error occurs. @since ostermillerutils 1.00.00
public static String decodeToString(InputStream in, String enc) throws IOException { return new String(decodeToBytes(in), enc); }
Decode Base64 encoded data from the InputStream to a String. Characters that are not part of the Base64 alphabet are ignored in the input. @param in Stream from which to read data that needs to be decoded. @param enc Character encoding to use when converting bytes to characters. @return decoded data. @throws IOException if an IO error occurs.Throws: @throws UnsupportedEncodingException if the character encoding specified is not supported. @since ostermillerutils 1.02.16
public static void decode(InputStream in, OutputStream out) throws IOException { decode(in, out, true); }
Decode Base64 encoded data from the InputStream to the OutputStream. Characters in the Base64 alphabet, white space and equals sign are expected to be in url encoded data. The presence of other characters could be a sign that the data is corrupted. @param in Stream from which to read data that needs to be decoded. @param out Stream to which to write decoded data. @throws IOException if an IO error occurs. @throws Base64DecodingException if unexpected data is encountered. @since ostermillerutils 1.00.00
public static void decode(InputStream in, OutputStream out, boolean throwExceptions) throws IOException { // Base64 decoding converts four bytes of input to three bytes of output int[] inBuffer = new int[4]; // read bytes un-mapping them from their ASCII encoding in the process // we must read at least two bytes to be able to output anything boolean done = false; while (!done && (inBuffer[0] = readBase64(in, throwExceptions)) != END_OF_INPUT && (inBuffer[1] = readBase64(in, throwExceptions)) != END_OF_INPUT) { // Fill the buffer inBuffer[2] = readBase64(in, throwExceptions); inBuffer[3] = readBase64(in, throwExceptions); // Calculate the output // The first two bytes of our in buffer will always be valid // but we must check to make sure the other two bytes // are not END_OF_INPUT before using them. // The basic idea is that the four bytes will get reconstituted // into three bytes along these lines: // [xxAAAAAA] [xxBBBBBB] [xxCCCCCC] [xxDDDDDD] // [AAAAAABB] [BBBBCCCC] [CCDDDDDD] // bytes are considered to be zero when absent. // six A and two B out.write(inBuffer[0] << 2 | inBuffer[1] >> 4); if (inBuffer[2] != END_OF_INPUT) { // four B and four C out.write(inBuffer[1] << 4 | inBuffer[2] >> 2); if (inBuffer[3] != END_OF_INPUT) { // two C and six D out.write(inBuffer[2] << 6 | inBuffer[3]); } else { done = true; } } else { done = true; } } out.flush(); }
Decode Base64 encoded data from the InputStream to the OutputStream. Characters in the Base64 alphabet, white space and equals sign are expected to be in url encoded data. The presence of other characters could be a sign that the data is corrupted. @param in Stream from which to read data that needs to be decoded. @param out Stream to which to write decoded data. @param throwExceptions Whether to throw exceptions when unexpected data is encountered. @throws IOException if an IO error occurs. @throws Base64DecodingException if unexpected data is encountered when throwExceptions is specified. @since ostermillerutils 1.00.00
public static boolean isBase64(String string, String enc) throws UnsupportedEncodingException { return isBase64(string.getBytes(enc)); }
Determines if the String is in base64 format. <p> Data will be considered to be in base64 format if it contains only base64 characters and white space with equals sign padding on the end so that the number of base64 characters is divisible by four. <p> It is possible for data to be in base64 format but for it to not meet these stringent requirements. It is also possible for data to meet these requirements even though decoding it would not make any sense. This method should be used as a guide but it is not authoritative because of the possibility of these false positives and false negatives. <p> Additionally, extra data such as headers or footers may throw this method off the scent and cause it to return false. @param string String that may be in base64 format. @param enc Character encoding to use when converting to bytes. @return Best guess as to whether the data is in base64 format. @throws UnsupportedEncodingException if the character encoding specified is not supported.
public static boolean isBase64(InputStream in) throws IOException { long numBase64Chars = 0; int numPadding = 0; int read; while ((read = in.read()) != -1) { read = reverseBase64Chars[read]; if (read == NON_BASE_64) { return false; } else if (read == NON_BASE_64_WHITESPACE) { // ignore white space } else if (read == NON_BASE_64_PADDING) { numPadding++; numBase64Chars++; } else if (numPadding > 0) { return false; } else { numBase64Chars++; } } if (numBase64Chars == 0) { return false; } if (numBase64Chars % 4 != 0) { return false; } return true; }
Reads data from the stream and determines if it is in base64 format. <p> Data will be considered to be in base64 format if it contains only base64 characters and white space with equals sign padding on the end so that the number of base64 characters is divisible by four. <p> It is possible for data to be in base64 format but for it to not meet these stringent requirements. It is also possible for data to meet these requirements even though decoding it would not make any sense. This method should be used as a guide but it is not authoritative because of the possibility of these false positives and false negatives. <p> Additionally, extra data such as headers or footers may throw this method off the scent and cause it to return false. @param in Stream from which to read data to be tested. @return Best guess as to whether the data is in base64 format. @throws IOException if an IO error occurs. @since ostermillerutils 1.00.00
public static void starthHomeActivity(@Nullable Activity activity) { if (activity != null) { if (activity.getClass() != AbstractApplication.get().getHomeActivityClass()) { Intent intent = new Intent(activity, AbstractApplication.get().getHomeActivityClass()); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); activity.startActivity(intent); } } else { LOGGER.warn("Null activity. Ignoring launch of " + AbstractApplication.get().getHomeActivityClass().getSimpleName()); } }
Launches the {@link AbstractApplication#getHomeActivityClass()}
public static void startActivity(@Nullable Activity activity, Class<? extends Activity> targetActivityClass) { if (activity != null) { if (activity.getClass() != targetActivityClass) { Intent intent = new Intent(activity, targetActivityClass); activity.startActivity(intent); } } else { LOGGER.warn("Null activity. Ignoring launch of " + targetActivityClass.getSimpleName()); } }
Launches a new {@link Activity} @param targetActivityClass The target {@link Activity} class to launch
public static void main(final String[] args) throws IOException { ArrayList<String> files = new ArrayList<String>(); String output_file = null; // Reads the parameters int i = 0; boolean args_error = args.length == 0; while (i < args.length && !args_error) { String arg = args[i]; if (arg == "-o") { if (i + 1 < args.length) output_file = args[++i]; else { args_error = true; } } else if (arg == "-help") { displayHelp(); break; } else if (arg.startsWith("-")) { // unknown option args_error = true; } else { // File or directory to process File f = new File(arg); if (f.isFile()) files.add(arg); else if (f.isDirectory()) { File[] listOfFiles = f.listFiles(); for (int j = 0; j < listOfFiles.length; j++) { if (listOfFiles[j].isFile()) { files.add(listOfFiles[j].getPath()); } } } } i++; } if (args_error) { // Shows the program usage displayHelp(); } else { // Process files for (final String filename : files) { try { TiffReader tr = new TiffReader(); int result = tr.readFile(filename, true); // tr.getModel().getMetadata().get("Creator"); reportResults(tr, result, filename, output_file); TiffInputStream inputdata = new TiffInputStream(new File(filename)); TiffWriter tw = new TiffWriter(inputdata); TiffDocument tm = tr.getModel(); int[] val = new int[2]; val[0] = 2; val[1] = 1; //tm.getFirstIFD().addTag("PageNumber", val); tw.SetModel(tm); String filenameout = "out.tif"; try { tw.write(filenameout); System.out.println("File '" + filenameout + "' written successfully"); } catch (Exception ex) { // System.out.println("Error writting file '" + filenameout + "'"); } } catch (ReadTagsIOException e) { System.out.println("Error loading TIFF dependencies"); } catch (ReadIccConfigIOException e) { System.out.println("Error loading ICC Profile dependencies"); } } System.out.println("Finished"); } }
The main method. @param args the arguments @throws IOException Signals that an I/O exception has occurred.
private static void reportResults(TiffReader tiffReader, int result, String filename, String output_file) { TiffDocument to = tiffReader.getModel(); if (output_file != null) { // TODO: Create xml file with report } else { // Display results human readable switch (result) { case -1: System.out.println("File '" + filename + "' does not exist"); break; case -2: System.out.println("IO Exception in file '" + filename + "'"); break; case 0: if (tiffReader.getBaselineValidation().correct) { // The file is correct System.out.println("Everything ok in file '" + filename + "'"); System.out.println("IFDs: " + to.getIfdCount()); System.out.println("SubIFDs: " + to.getSubIfdCount()); to.printMetadata(); TiffEPProfile bpep = new TiffEPProfile(to); bpep.validate(); bpep.getValidation().printErrors(); TiffITProfile bpit = new TiffITProfile(to, 0); bpit.validate(); bpit.getValidation().printErrors(); int nifd = 1; for (TiffObject o : to.getImageIfds()) { IFD ifd = (IFD) o; if (ifd != null) { System.out.println("IFD " + nifd++ + " TAGS:"); ifd.printTags(); } } } else { // The file is not correct System.out.println("Errors in file '" + filename + "'"); if (to != null) { System.out.println("IFDs: " + to.getIfdCount()); System.out.println("SubIFDs: " + to.getSubIfdCount()); // int index = 0; to.printMetadata(); } tiffReader.getBaselineValidation().printErrors(); } tiffReader.getBaselineValidation().printWarnings(); break; default: System.out.println("Unknown result (" + result + ") in file '" + filename + "'"); break; } } }
Report the results of the reading process to the console. @param tiffReader the tiff reader @param result the result @param filename the filename @param output_file the output_file
public synchronized boolean isLoaded(LCMSDataSubset subset) { for (Map.Entry<Object, Set<LCMSDataSubset>> entry : cache.asMap().entrySet()) { Object user = entry.getKey(); if (user == null) { // it has already been reclaimed, move on // this condition should not be triggered though, because we // have eviction listener, which should run cleanup whenever // any key in the cache becomes null continue; } Set<LCMSDataSubset> subsets = entry.getValue(); for (LCMSDataSubset subsetInUse : subsets) { if (subsetInUse.contains(subset)) { return true; } } } return false; }
Checks among the loaded by all users if this particular subset has already been loaded by someone else. <b>Note</b> that if for scan collection you've set a {@link StorageStrategy} other than {@link StorageStrategy#STRONG}, this check won't guarantee anything other than the scan meta info was loaded. Spectra might have been garbage collected. You can remedy this by setting {@link IScanCollection#isAutoloadSpectra(boolean) } true, in which case spectra will be automatically loaded, whenever spectrum references are null.
public synchronized void load(LCMSDataSubset subset, Object user) throws FileParsingException { if (user == null) { throw new IllegalArgumentException("User can't be null"); } // load data, if it's not there yet if (!isLoaded(subset)) { scans.loadData(subset, null); } // add the subset Set<LCMSDataSubset> userSubsets = cache.getIfPresent(user); if (userSubsets == null) { addNewUser(user); userSubsets = new HashSet<>(2); userSubsets.add(subset); cache.put(user, userSubsets); } else { userSubsets.add(subset); } }
Will load scan meta-info and spectra for the specified subset. Will also keep track of loaded subsets. If a subset is loaded, then it is considered to be in use by some component until it doesn't explicitly call {@link #unload(umich.ms.datatypes.LCMSDataSubset) }. @param user identify yourself somehow, other components might be using this LCMSData as well, so if you don't provide that identifier, there is no way to tell, for example, when unloading a subset if it's in use by you or someone else. So some other component, might call unload() and without the identifier your spectra will be lost.
public synchronized void unload(LCMSDataSubset subset, Object user, Set<LCMSDataSubset> exclude) { //System.err.println("=========== UNLOAD (user) CALLED ***********************"); if (!isLoaded(subset)) { throw new IllegalStateException("LCMSData load/unload methods only" + " work for subsets loaded/unloaded using LCMSData API. The" + " subset you requested to unload wasn't loaded. If you've" + " loaded data into ScanCollection manually, then use" + " IScanCollection's API for unloading data manually as" + " well."); } Set<LCMSDataSubset> userSubsets = cache.getIfPresent(user); if (userSubsets == null) { throw new IllegalStateException("The user was not present in cache," + " which means it either has never been there, or has already" + " been reclaimed by GC."); } if (!userSubsets.contains(subset)) { throw new IllegalArgumentException("This user has not loaded the subset" + " in the first place. The user must load the subset using" + " LCMSData API first. Unloading a subset that a user has not" + " loaded itself is illegal."); } // removing the subset from the user's currently loaded subsets userSubsets.remove(subset); // getting subsets loaded by all other users of this LCMSData ConcurrentMap<Object, Set<LCMSDataSubset>> otherUserMaps = cache.asMap(); HashSet<LCMSDataSubset> otherUsersSubsetsCombined = new HashSet<>(); for (Map.Entry<Object, Set<LCMSDataSubset>> entry : otherUserMaps.entrySet()) { Object otherUser = entry.getKey(); if (otherUser != user) { // we need to exclude the user requesting the unloading operation from the // list of other loaded subsets Set<LCMSDataSubset> otherUserSubsets = entry.getValue(); otherUsersSubsetsCombined.addAll(otherUserSubsets); } } if (exclude != null) { otherUsersSubsetsCombined.addAll(exclude); } if (otherUsersSubsetsCombined.isEmpty()) { scans.unloadData(subset); } else { scans.unloadData(subset, otherUsersSubsetsCombined); } }
Unloads spectra matched by this subset. @param subset to be unloaded @param user the user, that has had this subset loaded. If other users have parts of this subset loaded, those parts won't be unloaded. @param exclude can be null. If specified, data from these subsets won't be excluded.
private void unsafeUnload(LCMSDataSubset subset) { //System.err.println("=========== UNLOAD (unsafe) CALLED ***********************"); // getting subsets loaded by all other users of this LCMSData ConcurrentMap<Object, Set<LCMSDataSubset>> otherUserMaps = cache.asMap(); HashSet<LCMSDataSubset> otherUsersSubsetsCombined = new HashSet<>(); for (Map.Entry<Object, Set<LCMSDataSubset>> entry : otherUserMaps.entrySet()) { Set<LCMSDataSubset> otherUserSubsets = entry.getValue(); otherUsersSubsetsCombined.addAll(otherUserSubsets); // for (LCMSDataSubset otherSubset : otherUserSubsets) { // if (otherSubset != subset) { // otherUsersSubsetsCombined.add(otherSubset); // } // } } if (otherUsersSubsetsCombined.isEmpty()) { scans.unloadData(subset); } else { scans.unloadData(subset, otherUsersSubsetsCombined); } }
Unloads the subset without checking the user. It's required by our user-tracking automatic cleanup, if a user was GCed and it hasn't unloaded its subsets, we detect the GC automatically, and unload all the subsets, used by this killed user. It will still check for other users using scans from this subset.
public synchronized void releaseMemory() { isReleasingMemory = true; userPhantomRefs.clear(); cache.invalidateAll(); scans.reset(); source.releaseMemory(); //loadedSubsets.clear(); isReleasingMemory = false; }
Releases all memory by calling {@link LCMSDataSource#releaseMemory() } and {@link IScanCollection#reset() }. Effectively, you get this object to the same state as it was after calling the constructor, however any ScanCollection configurations are preserved (e.g. spectra auto-loading) setting. <b>IMPORTANT: will clear the registry of loaded subsets without warning!</b> It's up to you to make sure you don't call this method while some component is still using the data.
public static boolean isWithinPpm(double mz1, double mz2, double ppm) { return Math.abs(amu2ppm(mz1, mz1 - mz2)) <= ppm; }
Check if the 2nd m/z value is within some PPM distance from the 1st one. PPM will be calculated based on the 1st m/z value. @param mz1 PPM tolerance will be calculated relative to this value @param mz2 the value to check for being within some PPM range
public Object invoke(ELContext elContext, Object... args) throws ELException { int i = 0; Map<String, Object> lambdaArgs = new HashMap<String, Object>(); // First get arguments injected from the outter lambda, if any lambdaArgs.putAll(envirArgs); for (String fParam: formalParameters) { if (i >= args.length) { throw new ELException("Expected Argument " + fParam + " missing in Lambda Expression"); } lambdaArgs.put(fParam, args[i++]); } elContext.enterLambdaScope(lambdaArgs); try { Object ret = expression.getValue(elContext); // If the result of evaluating the body is another LambdaExpression, // whose body has not been evaluated yet. (A LambdaExpression is // evaluated iff when its invoke method is called.) The current lambda // arguments may be needed in that body when it is evaluated later, // after the current lambda exits. To make these arguments available // then, they are injected into it. if (ret instanceof LambdaExpression) { ((LambdaExpression) ret).envirArgs.putAll(lambdaArgs); } return ret; } finally { elContext.exitLambdaScope(); } }
Invoke the encapsulated Lambda expression. <p> The supplied arguments are matched, in the same order, to the formal parameters. If there are more arguments than the formal parameters, the extra arguments are ignored. If there are less arguments than the formal parameters, an <code>ELException</code> is thrown.</p> <p>The actual Lambda arguments are added to the ELContext and are available during the evaluation of the Lambda expression. They are removed after the evaluation.</p> @param elContext The ELContext used for the evaluation of the expression The ELContext set by {@link #setELContext} is ignored. @param args The arguments to invoke the Lambda expression. For calls with no arguments, an empty array must be provided. A Lambda argument can be <code>null</code>. @return The result of invoking the Lambda expression @throws ELException if not enough arguments are provided @throws NullPointerException is elContext is null
@Override public SubsetMove getRandomMove(SubsetSolution solution, Random rnd) { // get set of candidate IDs for deletion and addition (fixed IDs are discarded) Set<Integer> removeCandidates = getRemoveCandidates(solution); Set<Integer> addCandidates = getAddCandidates(solution); // compute maximum number of swaps int curMaxSwaps = maxSwaps(addCandidates, removeCandidates); // return null if no swaps are possible if(curMaxSwaps == 0){ // impossible to perform a swap return null; } // pick number of swaps (in [1, curMaxSwaps]) int numSwaps = rnd.nextInt(curMaxSwaps) + 1; // pick random IDs to remove from selection Set<Integer> del = SetUtilities.getRandomSubset(removeCandidates, numSwaps, rnd); // pick random IDs to add to selection Set<Integer> add = SetUtilities.getRandomSubset(addCandidates, numSwaps, rnd); // create and return move return new GeneralSubsetMove(add, del); }
<p> Generates a move for the given subset solution that removes a random subset of IDs from the current selection and replaces them with an equally large random subset of the currently unselected IDs. Possible fixed IDs are not considered to be swapped. The maximum number of swaps \(k\) specified at construction is respected. If \(m &lt; k\) IDs are currently selected or unselected (excluding any fixed IDs), generated moves will perform up to \(m\) swaps only, as it is impossible to perform more than this amount of swaps. If no swaps can be performed, <code>null</code> is returned. </p> <p> Note that first, a random number of swaps is picked (uniformly distributed) from the valid range and then, a random subset of this size is sampled from the currently selected and unselected IDs, to be swapped (again, all possible subsets are uniformly distributed, within the fixed size). Because the amount of possible moves increases with the number of performed swaps, the probability of generating each specific move thus decreases with the number of swaps. In other words, randomly generated moves are <b>not</b> uniformly distributed across different numbers of performed swaps, but each specific move performing fewer swaps is more likely to be selected than each specific move performing more swaps. </p> @param solution solution for which a random multi swap move is generated @param rnd source of randomness used to generate random move @return random multi swap move, <code>null</code> if no swaps can be performed
private int maxSwaps(Set<Integer> addCandidates, Set<Integer> deleteCandidates){ return Math.min(maxSwaps, Math.min(addCandidates.size(), deleteCandidates.size())); }
Computes the maximum number of swaps that can be performed, given the set of candidate IDs for addition and deletion. Takes into account the desired maximum number of swaps \(k\) specified at construction (if set). The maximum number of swaps is equal to the minimum of \(k\) and the size of both candidate sets. Thus, if any of the given candidate sets is empty, zero is returned. @param addCandidates candidate IDs to be added to the selection @param deleteCandidates candidate IDs to be removed from the selection @return maximum number of swaps to be performed
@Override public SubsetSolution next() { // get next subset Set<Integer> subset = subsetIterator.next(); // wrap in subset solution return new SubsetSolution(IDs, subset); }
Generate the next subset solution. The returned subset will either have the same size as the previously generated solution, if any, or it will be a larger subset. @return next subset solution within the size bounds @throws NoSuchElementException if there is no next solution to be generated
public void printError() { System.out.print(description); if (value != null) System.out.print(" (" + value + ")"); System.out.println(); }
Prints the error in the console.
public void printWarning() { System.out.print("Warning: "); System.out.print(description); if (value != null) System.out.print(" (" + value + ")"); System.out.println(); }
Prints the warning in the console.
@Override public List<SubsetMove> getAllMoves(SubsetSolution solution) { // create empty list to store generated moves List<SubsetMove> moves = new ArrayList<>(); // get set of candidate IDs for deletion and addition Set<Integer> removeCandidates = getRemoveCandidates(solution); Set<Integer> addCandidates = getAddCandidates(solution); // possible to perform desired number of swaps? int curNumSwaps = numSwaps(addCandidates, removeCandidates); if(curNumSwaps == 0){ // impossible: return empty set return moves; } // create all moves performing numSwaps swaps SubsetIterator<Integer> itDel, itAdd; Set<Integer> del, add; itDel = new SubsetIterator<>(removeCandidates, curNumSwaps); while(itDel.hasNext()){ del = itDel.next(); itAdd = new SubsetIterator<>(addCandidates, curNumSwaps); while(itAdd.hasNext()){ add = itAdd.next(); // create and add move moves.add(new GeneralSubsetMove(add, del)); } } // return all moves return moves; }
<p> Generates the list of all possible moves that perform exactly \(k\) swaps, where \(k\) is the desired number of swaps specified at construction. Possible fixed IDs are not considered to be swapped. If \(m &lt; k\) IDs are currently selected or unselected (excluding any fixed IDs), no swaps can be performed and the returned list will be empty. @param solution solution for which all possible multi swap moves are generated @return list of all multi swap moves, may be empty
private int numSwaps(Set<Integer> addCandidates, Set<Integer> deleteCandidates){ return Math.min(addCandidates.size(), Math.min(deleteCandidates.size(), numSwaps)); }
Infer the number of swaps that will be performed, taking into account the fixed number of desired swaps as specified at construction and the maximum number of possible swaps for the given subset solution. @param addCandidates candidate IDs to be added to the selection @param deleteCandidates candidate IDs to be removed from the selection @return number of swaps to be performed: desired fixed number if possible, or less (as many as possible)
public DoubleRange getMzRange() { if (isolationWindowMzLo != null && isolationWindowMzHi != null) { return new DoubleRange(isolationWindowMzLo, isolationWindowMzHi); } return null; }
TODO: might be better to treat null values as infinity and always return non-null DoubleRange. Convenience method to get the precursor isolation window ange. @return null, if at least one range end is null (not set). Otherwise a new instance of {@link umich.ms.util.DoubleRange}