/** * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually * should go to struct. * * @param from * @param to * @param excludes * @return * @throws Exception */ public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception { Arrays.sort(excludes); for (Field f : from.fields()) { if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue; Object o = f.get(from); if (o == null) continue; Field tof = to.getField(f.getName()); if (tof != null) try { tof.set(to, Converter.cnv(tof.getGenericType(), o)); } catch (Exception e) { System.out.println( "Failed to convert " + f.getName() + " from " + from.getClass() + " to " + to.getClass() + " value " + o + " exception " + e); } } return to; }
/** * Method to convert a List of beans to a List of Array of Strings. * * @param beans the List of Beans. * @param addNewHeader the new String Array for the Header row. * @param <T> generic value. * @return the List of Array of String content of the csv. */ @SuppressWarnings("unchecked") public static <T> List<String[]> toStringArray(List<T> beans, String[] addNewHeader) { List<String[]> records = new ArrayList<>(); // add header record // records.add(new String[]{"ID","Name","Role","Salary"}); if (addNewHeader != null) records.add(addNewHeader); for (T bean : beans) { // beans.stream().map((bean) -> { List<String> record = new ArrayList<>(); // invoke getter method and convert to String Class<T> clazz = (Class<T>) bean.getClass(); // T t = ReflectionUtilities.invokeConstructor(clazz); List<Method> getter = (List<Method>) ReflectionUtilities.findGetters(clazz, true); for (Method method : getter) { record.add(String.valueOf(ReflectionUtilities.invokeGetter(bean, method))); } // getter.stream().forEach((method) -> // record.add(String.valueOf(ReflectionUtilities.invokeGetter(bean,method)))); // return record; // }).forEach((record) -> records.add(ListUtilities.toArray(record))); records.add(ListUtilities.toArray(record)); } return records; }
public T call() throws Exception { final T result1 = step1.call(); if (result1.isSuccess() && !Thread.currentThread().isInterrupted()) { return step2.call(); } else { return result1; } }
public static <T> String fmtList(final List<T> list) { String result = ""; for (T item : list) { result += item.toString() + "\n"; } return result; }
@Override public Tag copy() { ListTag<T> res = new ListTag<T>(getName()); res.type = type; for (T t : list) { @SuppressWarnings("unchecked") T copy = (T) t.copy(); res.list.add(copy); } return res; }
public <T> void logMany(final PrintStream stream, final Collection<T> list) { final String[] a = new String[list.size()]; int i = 0; for (T e : list) { a[i++] = e.toString(); } Arrays.sort(a); for (String o : a) { stream.println(o); } }
/** * @throws OSStatusException * @since Available in iOS 2.0 and later. */ public <T extends Struct<T>> T getProperty(Struct<?> specifier, Class<T> type) throws OSStatusException { T data = Struct.allocate(type); IntPtr dataSize = new IntPtr(Struct.sizeOf(data)); OSStatus status = getProperty0( this, specifier == null ? 0 : Struct.sizeOf(specifier), specifier == null ? null : specifier.as(VoidPtr.class), dataSize, data.as(VoidPtr.class)); OSStatusException.throwIfNecessary(status); return data; }
// insertion sort (n^2) ///bien public int InsertionSort(T a[]) { int comparaciones = 0; for (int i = 1; i < a.length; i++) { T aux = a[i]; int j = i - 1; comparaciones++; while (j >= 0 && aux.compareTo(a[j]) < 0) { a[j + 1] = a[j]; // haces el hueco para insercion j--; } a[j + 1] = aux; // insertas elemento } return comparaciones; }
public String[] datosAleatorios(T[] a, int tamaño) { ArrayList<String> aux = new ArrayList(); String[] b = new String[tamaño]; Random rnd = new Random(); int i = 0; T elem = a[rnd.nextInt(a.length)]; while (i < tamaño) { if (!aux.contains(elem.toString())) { aux.add(elem.toString()); i++; } elem = a[rnd.nextInt(a.length)]; } return aux.toArray(b); }
public <T> String post(String resource, T object) throws JAXBException, CloudException, InternalException { StringWriter stringWriter = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(object.getClass()); Marshaller m = jc.createMarshaller(); m.marshal(object, stringWriter); return post(provider.getContext().getAccountNumber(), resource, stringWriter.toString()); }
/** * This function returns a map whose entries hold the coordinates of the sequence as keys and the * coordinates of the target sequences as values.</br> If a coordinate in sequence corresponds to * a gap in another sequence, then -1 is assigned to that position.</br> For example suppose we * have the sequences:</br> seq1: AAT-GCT-TCG</br> seq2: G--C-CTCT-C</br> seq3: A-T--GT-AG-</br> * Then, if we wish to find the mapping of seq1's coordinates to seq2's coordinates, this will * give us: 0 -> 0, 1 -> -1, 2 -> -1, 3 -> -1, 4 -> 2, 5 -> 3, 6 -> 5, 7 -> -1, 8 -> 6.</br> Also, * if we wish to find the mapping of seq1's coordinates to seq2's and seq3's coordinates, this * will give us: 0 -> {0, 0}, 1 -> {-1, -1}, 2 -> {-1, 1}, 3 -> {-1, -1}, 4 -> {2, 2}, 5 -> {3, * 3}, 6 -> {5, 4}, 7 -> {-1, 5}, 8 -> {6, -1}. * * @param <T> This could be either the serial number of the sequence (valid range: [0, * sequences.length-1]) or the sequence names * @param <E> * @param seqID The sequence ID (either serial number or name) which we wish to map</br> Note that * the valid range of serial numbers is [0, sequences.length-1] * @param targetSeqIDs The (target) sequences IDs (either serial numbers or names) * @return A map whose keys are the sequence coordinates and values the corresponding coordinates * of the target sequences * @throws IllegalArgumentException * @see GappedAlignmentString */ public <T extends Object> Map mapSeqCoords2SeqsCoords( T generic_seqID, Vector<T> generic_targetSeqIDs) throws IllegalArgumentException, IndexOutOfBoundsException { GappedAlignmentString gas_seq; GappedAlignmentString[] gas_targetSeqs; String[] speciesNames = species(); // Check if generic_seqID is mistakenly included in the generic_targetSeqIDs set if (generic_targetSeqIDs.contains(generic_seqID)) generic_targetSeqIDs.remove(generic_seqID); if (generic_targetSeqIDs.size() + 1 > speciesNames.length) throw new IndexOutOfBoundsException("You entered more sequences than are in the file."); Map map = new HashMap(); // Check whether sequence IDs are inputed as serial numbers or as names String seqsClassName = generic_seqID.getClass().getSimpleName(); // if( generic_seqID.getClass() instanceof java.lang.Integer ) // System.out.println("XAXA"); if (seqsClassName.equals("Integer")) { Integer seqID = (Integer) generic_seqID; Integer[] seqIDs = generic_targetSeqIDs.toArray(new Integer[generic_targetSeqIDs.size()]); if ((StatUtil.findMax(seqIDs).getFirst() > speciesNames.length - 1) || (StatUtil.findMin(seqIDs).getFirst() < 0)) throw new IndexOutOfBoundsException( "The sequence IDs (aka, serial numbers have to lie inside" + " the range 0 to speciesNames.length -1"); gas_seq = getGappedAlignment(speciesNames[seqID]); gas_targetSeqs = new GappedAlignmentString[seqIDs.length]; for (int i = 0; i < seqIDs.length; i++) gas_targetSeqs[i] = getGappedAlignment(speciesNames[seqIDs[i]]); } else if (seqsClassName.equals("String")) { String seqID = (String) generic_seqID; String[] seqIDs = generic_targetSeqIDs.toArray(new String[generic_targetSeqIDs.size()]); gas_seq = getGappedAlignment(seqID); gas_targetSeqs = new GappedAlignmentString[seqIDs.length]; for (int i = 0; i < seqIDs.length; i++) gas_targetSeqs[i] = getGappedAlignment(seqIDs[i]); } else { throw new IllegalArgumentException("Sequence IDs should be either of type Integer or String"); } // Pairwise Alignment if (gas_targetSeqs.length == 1) { map = doMapSeq2Seq(gas_seq, gas_targetSeqs); } // Multiple Alignment else { map = doMapSeq2Seqs(gas_seq, gas_targetSeqs); } return map; } // end of mapSeqCoords2SeqsCoords method
/** * Make a copy of a writable object using serialization to a buffer. * * @param orig The object to copy * @return The copied object */ public static <T extends Writable> T clone(T orig, Configuration conf) { try { @SuppressWarnings("unchecked") // Unchecked cast from Class to Class<T> T newInst = ReflectionUtils.newInstance((Class<T>) orig.getClass(), conf); ReflectionUtils.copy(conf, orig, newInst); return newInst; } catch (IOException e) { throw new RuntimeException("Error writing/reading clone buffer", e); } }
/** * Construct a client-side proxy that implements the named protocol, talking to a server at the * named address. * * @param protocol protocol * @param clientVersion client's version * @param addr server address * @param ticket security ticket * @param conf configuration * @param factory socket factory * @param rpcTimeout max time for each rpc; 0 means no timeout * @return the proxy * @throws IOException if any error occurs */ @SuppressWarnings("unchecked") public static <T extends VersionedProtocol> ProtocolProxy<T> getProtocolProxy( Class<T> protocol, long clientVersion, InetSocketAddress addr, UserGroupInformation ticket, Configuration conf, SocketFactory factory, int rpcTimeout) throws IOException { T proxy = (T) Proxy.newProxyInstance( protocol.getClassLoader(), new Class[] {protocol}, new Invoker(addr, ticket, conf, factory, rpcTimeout, protocol)); String protocolName = protocol.getName(); try { ProtocolSignature serverInfo = proxy.getProtocolSignature( protocolName, clientVersion, ProtocolSignature.getFingerprint(protocol.getMethods())); return new ProtocolProxy<T>(protocol, proxy, serverInfo.getMethods()); } catch (RemoteException re) { IOException ioe = re.unwrapRemoteException(IOException.class); if (ioe.getMessage() .startsWith(IOException.class.getName() + ": " + NoSuchMethodException.class.getName())) { // Method getProtocolSignature not supported long serverVersion = proxy.getProtocolVersion(protocol.getName(), clientVersion); if (serverVersion == clientVersion) { return new ProtocolProxy<T>(protocol, proxy, null); } throw new VersionMismatch(protocolName, clientVersion, serverVersion, proxy); } throw re; } }
/** * Method use OpenCsv Library for * * @param clazz the Class of the Bean. * @param fileInputCsv the File CSV to parse. * @param separator the char separator. * @param <T> the generic variable. * @return the List of Bean parsed from the CSV file. */ public static <T> List<T> parseCSVFileAsList(Class<T> clazz, File fileInputCsv, char separator) { try { List<T> beans; try ( // create CSVReader object CSVReader reader = new CSVReader(new FileReader(fileInputCsv), separator)) { beans = new ArrayList<>(); // read line by line String[] record; // skip header row String[] headers = reader.readNext(); // read content while ((record = reader.readNext()) != null) { T t = ReflectionUtilities.invokeConstructor(clazz); for (int i = 0; i < record.length; i++) { String nameMethod = "set" + org.apache.commons.lang3.StringUtils.capitalize(headers[i]); // invoke setter method if (ReflectionUtilities.checkMethod(clazz, nameMethod)) { ReflectionUtilities.invokeSetter(t, nameMethod, record[i]); } else { logger.warn( "Not exists the Method with name:" + nameMethod + " on the Bean:" + t.getClass().getName()); } } beans.add(t); } } return beans; } catch (IOException e) { logger.error( "Can't parse the CSV file:" + fileInputCsv.getAbsolutePath() + " -> " + e.getMessage(), e); return new ArrayList<>(); } }
/** Return the value of an enum of the given type. Prefix allows a shortened form of the enum */ @SuppressWarnings("unchecked") public <T extends Enum<T>> T getEnum(String prop, String prefix, T dflt) { Enum<?> v = dflt; String s = getProperty(prop); if (s == null || s.length() == 0) return dflt; if (prefix != null && !s.startsWith(prefix)) s = prefix + s; Object[] vals = dflt.getClass().getEnumConstants(); if (vals == null) return dflt; for (int i = 0; i < vals.length; ++i) { Enum<?> e = (Enum<?>) vals[i]; if (e.name().equalsIgnoreCase(s)) { v = e; break; } } return (T) v; }
@SuppressWarnings("unchecked") public static <T extends JsonElement> T deepCopy(T from) { if (from == null) { throw new IllegalArgumentException("from must not be null"); } if (from instanceof JsonObject) { return (T) deepCopyObj((JsonObject) from); } if (from instanceof JsonArray) { return (T) deepCopyArr((JsonArray) from); } if (from instanceof JsonNull) { return (T) JsonNull.INSTANCE; } if (from instanceof JsonPrimitive) { // Nulls and primitives are immutable return from; } throw new AssertionError("Unknown element type " + from.getClass().getName()); }
public void add(T tag) { type = tag.getId(); list.add(tag); }
@UsedFromByteCode public static <T> int hashCode(T elementType) { return elementType == null ? Integer.MIN_VALUE : elementType.hashCode(); }
@UsedFromByteCode public static <T> boolean notEquals(T t1, T t2) { return t1 == null ? t2 != null : !t1.equals(t2); }
public static <T> boolean areObjectsEqual(T a, T b) { if (a == null) { return b == null; } return a.equals(b); }
public <T> T map(Object source, T target, Object mappingCase) { if (source != null && target != null) map(source, target, target.getClass(), mappingCase); return target; }
public <T> T get(String path, Class<T> c) { Log.d(TAG, "get " + path); // NON-NLS File f = new File(getFullCachePath(path)); if (!f.exists()) { Log.w(TAG, "file: " + f.toString() + " not exists"); // NON-NLS return null; } T object; try { StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader(new FileReader(f)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); String json = fileData.toString(); Log.d(TAG, "cache: " + json); // NON-NLS object = getGson().fromJson(json, c); } catch (FileNotFoundException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (StreamCorruptedException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IOException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (JsonSyntaxException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (IllegalArgumentException e) { Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (RuntimeException e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } catch (Exception e) { // не позволим кэшу убить нашу программу Log.w(TAG, e.getMessage()); e.printStackTrace(); absoluteDelete(path); return null; } if (object.getClass().toString().equals(c.toString())) return object; else return null; }
public void applyInputsToObject(Object obj) { T config = this.getConfig(); if (config == null) { return; } Field[] toObjectFields = obj.getClass().getSuperclass().getDeclaredFields(); Field[] fromObjectFields = config.getClass().getDeclaredFields(); for (int to = 0; to < toObjectFields.length; to++) { String inputToName = toObjectFields[to].getName(); // Only input starting fields are used in configuration file if (inputToName.startsWith("input")) { for (int from = 0; from < fromObjectFields.length; from++) { String inputFromName = fromObjectFields[from].getName(); if (toObjectFields[to].getType() == fromObjectFields[from].getType() && inputFromName.compareTo(inputToName) == 0) { try { if (toObjectFields[to].getType() == Calendar.class && inputToName.compareTo("inputEndingDate") == 0) { Calendar currentDate = Calendar.getInstance(); toObjectFields[to].set(obj, currentDate); continue; } toObjectFields[to].set(obj, fromObjectFields[from].get(config)); } catch (IllegalArgumentException ex) { Logger.getLogger(ConfigLoader.class.getName()).log(Level.SEVERE, null, ex); return; } catch (IllegalAccessException ex) { Logger.getLogger(ConfigLoader.class.getName()).log(Level.SEVERE, null, ex); return; } } } } } toObjectFields = obj.getClass().getDeclaredFields(); fromObjectFields = config.getClass().getDeclaredFields(); for (int to = 0; to < toObjectFields.length; to++) { String inputToName = toObjectFields[to].getName(); // Only input starting fields are used in configuration file if (inputToName.startsWith("input")) { for (int from = 0; from < fromObjectFields.length; from++) { String inputFromName = fromObjectFields[from].getName(); if (toObjectFields[to].getType() == fromObjectFields[from].getType() && inputFromName.compareTo(inputToName) == 0) { try { if (toObjectFields[to].getType() == Calendar.class && inputToName.compareTo("inputEndingDate") == 0) { Calendar currentDate = Calendar.getInstance(); toObjectFields[to].set(obj, currentDate); continue; } toObjectFields[to].set(obj, fromObjectFields[from].get(config)); } catch (IllegalArgumentException ex) { Logger.getLogger(ConfigLoader.class.getName()).log(Level.SEVERE, null, ex); return; } catch (IllegalAccessException ex) { Logger.getLogger(ConfigLoader.class.getName()).log(Level.SEVERE, null, ex); return; } } } } } }
/** * Read an Enum value from DataInput, Enums are read and written using String values. * * @param <T> Enum type * @param in DataInput to read from * @param enumType Class type of Enum * @return Enum represented by String read from DataInput * @throws IOException */ public static <T extends Enum<T>> T readEnum(DataInput in, Class<T> enumType) throws IOException { return T.valueOf(enumType, Text.readString(in)); }