List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:com.twosigma.beaker.sql.QueryExecutor.java
public synchronized Object executeQuery(String script, NamespaceClient namespaceClient, ConnectionStringHolder defaultConnectionString, Map<String, ConnectionStringHolder> namedConnectionString) throws SQLException, IOException, ReadVariableException { BeakerParser beakerParser = new BeakerParser(script, namespaceClient, defaultConnectionString, namedConnectionString, jdbcClient); BasicDataSource ds = jdbcClient.getDataSource(beakerParser.getDbURI().getActualConnectionString()); Properties info = null;/*from w ww . ja v a2 s . c om*/ if (beakerParser.getDbURI().getUser() != null && !beakerParser.getDbURI().getUser().isEmpty()) { if (info == null) { info = new Properties(); } info.put("user", beakerParser.getDbURI().getUser()); } if (beakerParser.getDbURI().getPassword() != null && !beakerParser.getDbURI().getPassword().isEmpty()) { if (info == null) { info = new Properties(); } info.put("password", beakerParser.getDbURI().getPassword()); } boolean isConnectionExeption = true; // Workaround for "h2database" : do not work correctly with empty or null "Properties" try (Connection connection = info != null ? ds.getDriver().connect(beakerParser.getDbURI().getActualConnectionString(), info) : ds.getConnection()) { this.connection = connection; connection.setAutoCommit(false); List<Object> resultsForOutputCell = new ArrayList<>(); Map<String, List<Object>> resultsForNamspace = new HashMap<>(); for (BeakerParseResult queryLine : beakerParser.getResults()) { BeakerInputVar basicIterationArray = null; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.isAll()) { basicIterationArray = parameter; if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); //ToDo make recursively iteration over several arrays break; } } try { if (basicIterationArray != null) { int l; Object obj; try { obj = namespaceClient.get(basicIterationArray.objectName); } catch (Exception e) { throw new ReadVariableException(basicIterationArray.objectName, e); } if (obj instanceof List) { l = ((List) obj).size(); } else if (obj.getClass().isArray()) { l = Array.getLength(obj); } else break; for (int i = 0; i < l; i++) { QueryResult queryResult = executeQuery(i, queryLine, connection, namespaceClient); adoptResult(queryLine, queryResult, resultsForOutputCell, resultsForNamspace); } } else { QueryResult queryResult = executeQuery(-1, queryLine, connection, namespaceClient); adoptResult(queryLine, queryResult, resultsForOutputCell, resultsForNamspace); } } catch (Exception e) { isConnectionExeption = false; throw e; } } connection.commit(); for (String output : resultsForNamspace.keySet()) { if (resultsForNamspace.get(output).size() > 1) { OutputContainer outputContainer = new OutputContainer(resultsForNamspace.get(output)); namespaceClient.set(output, outputContainer); } else if (!resultsForNamspace.get(output).isEmpty()) { namespaceClient.set(output, resultsForNamspace.get(output).get(0)); } else { namespaceClient.set(output, null); } } if (resultsForOutputCell.size() > 1) { OutputContainer outputContainer = new OutputContainer(resultsForOutputCell); return outputContainer; } else if (!resultsForOutputCell.isEmpty()) { return resultsForOutputCell.get(0); } else { return null; } } catch (Exception e) { if (beakerParser.getDbURI() != null && isConnectionExeption) { beakerParser.getDbURI().setShowDialog(true); } throw e; } finally { statement = null; } }
From source file:com.twosigma.beakerx.sql.QueryExecutor.java
public synchronized Object executeQuery(String script, BeakerXClient namespaceClient, ConnectionStringHolder defaultConnectionString, Map<String, ConnectionStringHolder> namedConnectionString) throws SQLException, IOException, ReadVariableException { BeakerParser beakerParser = new BeakerParser(script, namespaceClient, defaultConnectionString, namedConnectionString, jdbcClient); BasicDataSource ds = jdbcClient.getDataSource(beakerParser.getDbURI().getActualConnectionString()); Properties info = null;//from w w w . jav a2 s . co m if (beakerParser.getDbURI().getUser() != null && !beakerParser.getDbURI().getUser().isEmpty()) { if (info == null) { info = new Properties(); } info.put("user", beakerParser.getDbURI().getUser()); } if (beakerParser.getDbURI().getPassword() != null && !beakerParser.getDbURI().getPassword().isEmpty()) { if (info == null) { info = new Properties(); } info.put("password", beakerParser.getDbURI().getPassword()); } boolean isConnectionExeption = true; // Workaround for "h2database" : do not work correctly with empty or null "Properties" try (Connection connection = info != null ? ds.getDriver().connect(beakerParser.getDbURI().getActualConnectionString(), info) : ds.getConnection()) { this.connection = connection; connection.setAutoCommit(false); List<Object> resultsForOutputCell = new ArrayList<>(); Map<String, List<Object>> resultsForNamspace = new HashMap<>(); for (BeakerParseResult queryLine : beakerParser.getResults()) { BeakerInputVar basicIterationArray = null; for (BeakerInputVar parameter : queryLine.getInputVars()) { if (parameter.isAll()) { basicIterationArray = parameter; if (parameter.getErrorMessage() != null) throw new ReadVariableException(parameter.getErrorMessage()); //ToDo make recursively iteration over several arrays break; } } try { if (basicIterationArray != null) { int l; Object obj; try { obj = namespaceClient.get(basicIterationArray.objectName); } catch (Exception e) { throw new ReadVariableException(basicIterationArray.objectName, e); } if (obj instanceof List) { l = ((List) obj).size(); } else if (obj.getClass().isArray()) { l = Array.getLength(obj); } else break; for (int i = 0; i < l; i++) { QueryResult queryResult = executeQuery(i, queryLine, connection, namespaceClient); adoptResult(queryLine, queryResult, resultsForOutputCell, resultsForNamspace); } } else { QueryResult queryResult = executeQuery(-1, queryLine, connection, namespaceClient); adoptResult(queryLine, queryResult, resultsForOutputCell, resultsForNamspace); } } catch (Exception e) { isConnectionExeption = false; throw e; } } connection.commit(); for (String output : resultsForNamspace.keySet()) { if (resultsForNamspace.get(output).size() > 1) { OutputContainer outputContainer = new OutputContainer(resultsForNamspace.get(output)); namespaceClient.set(output, outputContainer); } else if (!resultsForNamspace.get(output).isEmpty()) { namespaceClient.set(output, resultsForNamspace.get(output).get(0)); } else { namespaceClient.set(output, null); } } if (resultsForOutputCell.size() > 1) { OutputContainer outputContainer = new OutputContainer(resultsForOutputCell); return outputContainer; } else if (!resultsForOutputCell.isEmpty()) { return resultsForOutputCell.get(0); } else { return OutputCell.HIDDEN; } } catch (Exception e) { if (beakerParser.getDbURI() != null && isConnectionExeption) { beakerParser.getDbURI().setShowDialog(true); } throw e; } finally { statement = null; } }
From source file:com.frostwire.android.gui.StoragePicker.java
private static String getVolumePath(StorageManager mStorageManager, final String volumeId) { try {/*from w w w . j a v a 2 s . c om*/ Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume"); Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList"); Method getUuid = storageVolumeClazz.getMethod("getUuid"); Method getPath = storageVolumeClazz.getMethod("getPath"); Method isPrimary = storageVolumeClazz.getMethod("isPrimary"); Object result = getVolumeList.invoke(mStorageManager); final int length = Array.getLength(result); for (int i = 0; i < length; i++) { Object storageVolumeElement = Array.get(result, i); String uuid = (String) getUuid.invoke(storageVolumeElement); Boolean primary = (Boolean) isPrimary.invoke(storageVolumeElement); // primary volume? if (primary && PRIMARY_VOLUME_NAME.equals(volumeId)) { return (String) getPath.invoke(storageVolumeElement); } // other volumes? if (uuid != null) { if (uuid.equals(volumeId)) { return (String) getPath.invoke(storageVolumeElement); } } } // not found. return null; } catch (Exception ex) { return null; } }
From source file:de.pribluda.android.jsonmarshaller.JSONMarshaller.java
/** * recursively marshall [multidimensional? - of course!!! ] array * * @param array/*from w w w .ja va2s . co m*/ * @return */ public static JSONArray marshallArray(Object array) throws InvocationTargetException, NoSuchMethodException, JSONException, IllegalAccessException { if (array != null && array.getClass().isArray()) { Class<?> componentType = array.getClass().getComponentType(); JSONArray retval = new JSONArray(); final int arrayLength = Array.getLength(array); // stirngs and primitives must be marshalled directly if (componentType.isPrimitive() || String.class.equals(componentType)) { for (int i = 0; i < arrayLength; i++) { retval.put(Array.get(array, i)); } } else if (componentType.isArray()) { // that's cool, nested array recurse for (int i = 0; i < arrayLength; i++) { retval.put(marshallArray(Array.get(array, i))); } } else { // treat component as a bean if it got default constructor try { if (componentType.getConstructor() != null) { for (int i = 0; i < arrayLength; i++) { retval.put(marshall(Array.get(array, i))); } } } catch (NoSuchMethodException ex) { // just ignore it here, it means no such constructor was found } } return retval; } return null; }
From source file:com.espertech.esper.event.util.JSONRendererImpl.java
private static void recursiveRender(EventBean theEvent, StringBuilder buf, int level, RendererMeta meta, RendererMetaOptions rendererOptions) { String delimiter = ""; // simple properties GetterPair[] simpleProps = meta.getSimpleProperties(); if (rendererOptions.getRenderer() == null) { for (GetterPair simpleProp : simpleProps) { Object value = simpleProp.getGetter().get(theEvent); writeDelimitedIndentedProp(buf, delimiter, level, simpleProp.getName()); simpleProp.getOutput().render(value, buf); delimiter = COMMA_DELIMITER_NEWLINE; }//from w ww . j a v a2s. co m } else { EventPropertyRendererContext context = rendererOptions.getRendererContext(); context.setStringBuilderAndReset(buf); for (GetterPair simpleProp : simpleProps) { Object value = simpleProp.getGetter().get(theEvent); writeDelimitedIndentedProp(buf, delimiter, level, simpleProp.getName()); context.setDefaultRenderer(simpleProp.getOutput()); context.setPropertyName(simpleProp.getName()); context.setPropertyValue(value); rendererOptions.getRenderer().render(context); delimiter = COMMA_DELIMITER_NEWLINE; } } GetterPair[] indexProps = meta.getIndexProperties(); for (GetterPair indexProp : indexProps) { Object value = indexProp.getGetter().get(theEvent); writeDelimitedIndentedProp(buf, delimiter, level, indexProp.getName()); if (value == null) { buf.append("null"); } else { if (!value.getClass().isArray()) { buf.append("[]"); } else { buf.append('['); String arrayDelimiter = ""; if (rendererOptions.getRenderer() == null) { for (int i = 0; i < Array.getLength(value); i++) { Object arrayItem = Array.get(value, i); buf.append(arrayDelimiter); indexProp.getOutput().render(arrayItem, buf); arrayDelimiter = ", "; } } else { EventPropertyRendererContext context = rendererOptions.getRendererContext(); context.setStringBuilderAndReset(buf); for (int i = 0; i < Array.getLength(value); i++) { Object arrayItem = Array.get(value, i); buf.append(arrayDelimiter); context.setPropertyName(indexProp.getName()); context.setPropertyValue(arrayItem); context.setIndexedPropertyIndex(i); context.setDefaultRenderer(indexProp.getOutput()); rendererOptions.getRenderer().render(context); arrayDelimiter = ", "; } } buf.append(']'); } } delimiter = COMMA_DELIMITER_NEWLINE; } GetterPair[] mappedProps = meta.getMappedProperties(); for (GetterPair mappedProp : mappedProps) { Object value = mappedProp.getGetter().get(theEvent); if ((value != null) && (!(value instanceof Map))) { log.warn("Property '" + mappedProp.getName() + "' expected to return Map and returned " + value.getClass() + " instead"); continue; } writeDelimitedIndentedProp(buf, delimiter, level, mappedProp.getName()); if (value == null) { buf.append("null"); buf.append(NEWLINE); } else { Map<String, Object> map = (Map<String, Object>) value; if (map.isEmpty()) { buf.append("{}"); buf.append(NEWLINE); } else { buf.append('{'); buf.append(NEWLINE); String localDelimiter = ""; Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); for (; it.hasNext();) { Map.Entry<String, Object> entry = it.next(); if (entry.getKey() == null) { continue; } buf.append(localDelimiter); ident(buf, level + 1); buf.append('\"'); buf.append(entry.getKey()); buf.append("\": "); if (entry.getValue() == null) { buf.append("null"); } else { OutputValueRenderer outRenderer = OutputValueRendererFactory .getOutputValueRenderer(entry.getValue().getClass(), rendererOptions); if (rendererOptions.getRenderer() == null) { outRenderer.render(entry.getValue(), buf); } else { EventPropertyRendererContext context = rendererOptions.getRendererContext(); context.setStringBuilderAndReset(buf); context.setPropertyName(mappedProp.getName()); context.setPropertyValue(entry.getValue()); context.setMappedPropertyKey(entry.getKey()); context.setDefaultRenderer(outRenderer); rendererOptions.getRenderer().render(context); } } localDelimiter = COMMA_DELIMITER_NEWLINE; } buf.append(NEWLINE); ident(buf, level); buf.append('}'); } } delimiter = COMMA_DELIMITER_NEWLINE; } NestedGetterPair[] nestedProps = meta.getNestedProperties(); for (NestedGetterPair nestedProp : nestedProps) { Object value = nestedProp.getGetter().getFragment(theEvent); writeDelimitedIndentedProp(buf, delimiter, level, nestedProp.getName()); if (value == null) { buf.append("null"); } else if (!nestedProp.isArray()) { if (!(value instanceof EventBean)) { log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean and returned " + value.getClass() + " instead"); buf.append("null"); continue; } EventBean nestedEventBean = (EventBean) value; buf.append('{'); buf.append(NEWLINE); recursiveRender(nestedEventBean, buf, level + 1, nestedProp.getMetadata(), rendererOptions); ident(buf, level); buf.append('}'); } else { if (!(value instanceof EventBean[])) { log.warn("Property '" + nestedProp.getName() + "' expected to return EventBean[] and returned " + value.getClass() + " instead"); buf.append("null"); continue; } StringBuilder arrayDelimiterBuf = new StringBuilder(); arrayDelimiterBuf.append(','); arrayDelimiterBuf.append(NEWLINE); ident(arrayDelimiterBuf, level + 1); EventBean[] nestedEventArray = (EventBean[]) value; String arrayDelimiter = ""; buf.append('['); for (int i = 0; i < nestedEventArray.length; i++) { EventBean arrayItem = nestedEventArray[i]; buf.append(arrayDelimiter); arrayDelimiter = arrayDelimiterBuf.toString(); buf.append('{'); buf.append(NEWLINE); recursiveRender(arrayItem, buf, level + 2, nestedProp.getMetadata(), rendererOptions); ident(buf, level + 1); buf.append('}'); } buf.append(']'); } delimiter = COMMA_DELIMITER_NEWLINE; } buf.append(NEWLINE); }
From source file:ArrayMap.java
private static void put(Object array, Object element, int index) { try {//from w ww.jav a 2 s . c o m if (array instanceof Object[]) { try { ((Object[]) array)[index] = element; } catch (ArrayStoreException e) { throw new IllegalArgumentException( e.getMessage() + ": " + (element == null ? "null" : element.getClass().getName()) + " into " + array.getClass().getName()); } } else { try { Array.set(array, index, element); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( e.getMessage() + ": " + (element == null ? "null" : element.getClass().getName()) + " into " + array.getClass().getName(), e); } } } catch (ArrayIndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException(index + " into " + Array.getLength(array)); } }
From source file:net.sourceforge.jaulp.lang.ObjectUtils.java
/** * Try to clone the given object.//from w w w .j a v a 2s . c o m * * @param object * The object to clone. * @return The cloned object or null if the clone process failed. * @throws NoSuchMethodException * the no such method exception * @throws SecurityException * Thrown if the security manager indicates a security violation. * @throws IllegalAccessException * the illegal access exception * @throws IllegalArgumentException * the illegal argument exception * @throws InvocationTargetException * the invocation target exception * @throws ClassNotFoundException * the class not found exception * @throws InstantiationException * the instantiation exception * @throws IOException * Signals that an I/O exception has occurred. */ public static Object cloneObject(final Object object) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException, IOException { Object clone = null; // Try to clone the object if it implements Serializable. if (object instanceof Serializable) { clone = SerializedObjectUtils.copySerializedObject((Serializable) object); if (clone != null) { return clone; } } // Try to clone the object if it is Cloneble. if (clone == null && object instanceof Cloneable) { if (object.getClass().isArray()) { final Class<?> componentType = object.getClass().getComponentType(); if (componentType.isPrimitive()) { int length = Array.getLength(object); clone = Array.newInstance(componentType, length); while (length-- > 0) { Array.set(clone, length, Array.get(object, length)); } } else { clone = ((Object[]) object).clone(); } if (clone != null) { return clone; } } Class<?> clazz = object.getClass(); Method cloneMethod = clazz.getMethod("clone", (Class[]) null); clone = cloneMethod.invoke(object, (Object[]) null); if (clone != null) { return clone; } } // Try to clone the object by copying all his properties with // the BeanUtils.copyProperties() method. if (clone == null) { clone = ReflectionUtils.getNewInstance(object); BeanUtils.copyProperties(clone, object); } return clone; }
From source file:edu.sdsc.scigraph.neo4j.GraphUtil.java
static <T> Set<T> getPropertiesAsSet(Object value, Class<T> type) { Set<T> set = new HashSet<>(); if (value.getClass().isArray()) { List<Object> objects = new ArrayList<>(); for (int i = 0; i < Array.getLength(value); i++) { objects.add(Array.get(value, i)); }/*from www . j av a 2s .co m*/ for (Object o : objects) { set.add(type.cast(o)); } } else { set.add(type.cast(value)); } return set; }
From source file:ArrayUtils.java
/** * @param anArray//from w ww. j a va2 s . c om * The array to extend * @param anElement * The element to add into <code>anArray</code> * @return A new array of length <code>anArray.length+1</code> whose * contents are those of <code>anArray</code> followed by * <code>anElement</code> */ public static Object addP(Object anArray, Object anElement) { int len = anArray == null ? 0 : Array.getLength(anArray); return addP(anArray, anElement, len); }
From source file:org.apache.hawq.pxf.plugins.hdfs.WritableResolver.java
int setArrayField(List<OneField> record, int dataType, Field reflectedField) throws IllegalAccessException { Object array = reflectedField.get(userObject); int length = Array.getLength(array); for (int j = 0; j < length; j++) { record.add(new OneField(dataType, Array.get(array, j))); }//from w ww .j a v a2 s . com return length; }