예제 #1
0
  /**
   * 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;
  }
예제 #2
0
  /**
   * 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;
  }
예제 #3
0
  /**
   * 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
  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());
  }
예제 #5
0
 /**
  * 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);
   }
 }
  /** 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;
  }
예제 #7
0
 @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());
 }
예제 #8
0
 /**
  * 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<>();
   }
 }
예제 #9
0
 public <T> T map(Object source, T target, Object mappingCase) {
   if (source != null && target != null) map(source, target, target.getClass(), mappingCase);
   return target;
 }
예제 #10
0
  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;
            }
          }
        }
      }
    }
  }
예제 #11
0
파일: Cache.java 프로젝트: Calc86/ipartner
  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;
  }