List of usage examples for java.lang.reflect Array getLength
@HotSpotIntrinsicCandidate public static native int getLength(Object array) throws IllegalArgumentException;
From source file:ArraysX.java
/** * Shrink the specified array. It is similar to duplicate, except * it returns the previous instance if je==length && jb==0. * * @param ary the array//from w w w .ja v a2s . c o m * @param jb the beginning index (included) * @param je the ending index (excluded) * @return ary or an array duplicated from ary * @exception IllegalArgumentException if ary is not any array * @exception IndexOutOfBoundsException if out of bounds */ public static final Object shrink(Object ary, int jb, int je) { if (jb == 0 && je == Array.getLength(ary)) return ary; //nothing changed return duplicate(ary, jb, je); }
From source file:com.ctriposs.rest4j.client.Request.java
/** * Returns a read only version of {@code value} * @param value the object we want to get a read only version of * @return a read only version of {@code value} *///from w ww. jav a2 s. c o m private Object getReadOnly(Object value) { if (value == null) { return null; } if (value instanceof Object[]) { // array of non-primitives Object[] arr = (Object[]) value; List<Object> list = new ArrayList<Object>(arr.length); for (Object o : arr) { list.add(getReadOnly(o)); } return Collections.unmodifiableList(list); } else if (value.getClass().isArray()) { // array of primitives int length = Array.getLength(value); List<Object> list = new ArrayList<Object>(); for (int i = 0; i < length; i++) { list.add(Array.get(value, i)); } return Collections.unmodifiableList(list); } else if (value instanceof ComplexResourceKey) { ((ComplexResourceKey) value).makeReadOnly(); return value; } else if (value instanceof CompoundKey) { ((CompoundKey) value).makeReadOnly(); return value; } else if (value instanceof DataTemplate) { Object data = ((DataTemplate) value).data(); if (data instanceof DataComplex) { ((DataComplex) data).makeReadOnly(); } // we don't try to make other types of data read only. return value; } else if (value instanceof Iterable) { List<Object> list = new ArrayList<Object>(); for (Object o : (Iterable) value) { list.add(getReadOnly(o)); } return Collections.unmodifiableList(list); } return value; }
From source file:org.apache.commons.httpclient.contrib.proxy.PluginProxyUtil.java
/** * Returns the proxy information for the specified sampleURL using JRE 1.4+ * specific plugin classes./*from w w w . j a v a2s.c o m*/ * * Notes: * Plugin 1.4+ Final added * com.sun.java.browser.net.* classes ProxyInfo & ProxyService... * Use those with JREs => 1.4+ * * @param sampleURL the URL to check proxy settings for * @return ProxyHost the host and port of the proxy that should be used */ private static HttpHost detectProxySettingsJDK14_JDK15_JDK16(URL sampleURL) { HttpHost result = null; try { // Look around for the 1.4+ plugin proxy detection class... // Without it, cannot autodetect... Class<?> ProxyServiceClass = Class.forName("com.sun.java.browser.net.ProxyService"); Method getProxyInfoMethod = ProxyServiceClass.getDeclaredMethod("getProxyInfo", new Class[] { URL.class }); Object proxyInfoArrayObj = getProxyInfoMethod.invoke(null, new Object[] { sampleURL }); if (proxyInfoArrayObj == null || Array.getLength(proxyInfoArrayObj) == 0) { if (LOG.isDebugEnabled()) { LOG.debug("1.4+ reported NULL proxy (no proxy assumed)"); } result = NO_PROXY_HOST; } else { Object proxyInfoObject = Array.get(proxyInfoArrayObj, 0); Class<?> proxyInfoClass = proxyInfoObject.getClass(); Method getHostMethod = proxyInfoClass.getDeclaredMethod("getHost", (Class[]) null); String proxyIP = (String) getHostMethod.invoke(proxyInfoObject, (Object[]) null); Method getPortMethod = proxyInfoClass.getDeclaredMethod("getPort", (Class[]) null); Integer portInteger = (Integer) getPortMethod.invoke(proxyInfoObject, (Object[]) null); int proxyPort = portInteger.intValue(); if (LOG.isDebugEnabled()) { LOG.debug("1.4+ Proxy info get Proxy:" + proxyIP + " get Port:" + proxyPort); } result = new HttpHost(proxyIP, proxyPort); } } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.debug("Sun Plugin 1.4+ proxy detection class not found, " + "will try failover detection" /*, e*/); } return result; }
From source file:org.apache.axis2.jaxws.utility.ConvertUtils.java
/** * Utility function to convert an Object to some desired Class. * <p/>/*from w w w.j ava 2 s . co m*/ * Normally this is used for T[] to List<T> processing. Other conversions are also done (i.e. * HashMap <->Hashtable, etc.) * <p/> * Use the isConvertable() method to determine if conversion is possible. Note that any changes * to convert() must also be accompanied by similar changes to isConvertable() * * @param arg the array to convert * @param destClass the actual class we want * @return object of destClass if conversion possible, otherwise returns arg */ public static Object convert(Object arg, Class destClass) throws WebServiceException { if (destClass == null) { return arg; } if (arg != null && destClass.isAssignableFrom(arg.getClass())) { return arg; } if (log.isDebugEnabled()) { String clsName = "null"; if (arg != null) clsName = arg.getClass().getName(); log.debug("Converting an object of type " + clsName + " to an object of type " + destClass.getName()); } // Convert between Calendar and Date if (arg instanceof Calendar && destClass == Date.class) { return ((Calendar) arg).getTime(); } // Convert between HashMap and Hashtable if (arg instanceof HashMap && destClass == Hashtable.class) { return new Hashtable((HashMap) arg); } if (arg instanceof InputStream && destClass == byte[].class) { try { InputStream is = (InputStream) arg; return getBytesFromStream(is); } catch (IOException e) { throw ExceptionFactory.makeWebServiceException(e); } } if (arg instanceof Source && destClass == byte[].class) { try { if (arg instanceof StreamSource) { InputStream is = ((StreamSource) arg).getInputStream(); if (is != null) { return getBytesFromStream(is); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform((Source) arg, result); byte[] bytes = out.toByteArray(); return bytes; } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } if (arg instanceof DataHandler) { try { InputStream is = ((DataHandler) arg).getInputStream(); if (destClass == Image.class) { return ImageIO.read(is); } else if (destClass == Source.class) { return new StreamSource(is); } byte[] bytes = getBytesFromStream(is); return convert(bytes, destClass); } catch (Exception e) { throw ExceptionFactory.makeWebServiceException(e); } } if (arg instanceof byte[] && destClass == String.class) { return new String((byte[]) arg); } // If the destination is an array and the source // is a suitable component, return an array with // the single item. /* REVIEW do we need to support atomic to array conversion ? if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class) && destClass.getComponentType().isAssignableFrom(arg.getClass())) { Object array = Array.newInstance(destClass.getComponentType(), 1); Array.set(array, 0, arg); return array; } */ // Return if no conversion is available if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))) { return arg; } if (arg == null) { return null; } // The arg may be an array or List Object destValue = null; int length = 0; if (arg.getClass().isArray()) { length = Array.getLength(arg); } else { length = ((Collection) arg).size(); } try { if (destClass.isArray()) { if (destClass.getComponentType().isPrimitive()) { Object array = Array.newInstance(destClass.getComponentType(), length); // Assign array elements if (arg.getClass().isArray()) { for (int i = 0; i < length; i++) { Array.set(array, i, Array.get(arg, i)); } } else { int idx = 0; for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) { Array.set(array, idx++, i.next()); } } destValue = array; } else { Object[] array; try { array = (Object[]) Array.newInstance(destClass.getComponentType(), length); } catch (Exception e) { return arg; } // Use convert to assign array elements. if (arg.getClass().isArray()) { for (int i = 0; i < length; i++) { array[i] = convert(Array.get(arg, i), destClass.getComponentType()); } } else { int idx = 0; for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) { array[idx++] = convert(i.next(), destClass.getComponentType()); } } destValue = array; } } else if (Collection.class.isAssignableFrom(destClass)) { Collection newList = null; try { // if we are trying to create an interface, build something // that implements the interface if (destClass == Collection.class || destClass == List.class) { newList = new ArrayList(); } else if (destClass == Set.class) { newList = new HashSet(); } else { newList = (Collection) destClass.newInstance(); } } catch (Exception e) { // No FFDC code needed // Couldn't build one for some reason... so forget it. return arg; } if (arg.getClass().isArray()) { for (int j = 0; j < length; j++) { newList.add(Array.get(arg, j)); } } else { for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) { newList.add(j.next()); } } destValue = newList; } else { destValue = arg; } } catch (Throwable t) { throw ExceptionFactory.makeWebServiceException( Messages.getMessage("convertUtils", arg.getClass().toString(), destClass.toString()), t); } return destValue; }
From source file:com.astamuse.asta4d.web.form.flow.base.AbstractFormFlowSnippet.java
/** * //w w w .j a va 2 s .com * Render the value of all the given form's fields.The rendering of cascade forms will be done here as well(recursively call the * {@link #renderForm(String, Object, int)}). * * @param renderTargetStep * @param form * @param cascadeFormArrayIndex * @return * @throws Exception */ private Renderer renderValueOfFields(String renderTargetStep, Object form, int cascadeFormArrayIndex) throws Exception { Renderer render = Renderer.create(); List<AnnotatedPropertyInfo> fieldList = AnnotatedPropertyUtil.retrieveProperties(form.getClass()); for (AnnotatedPropertyInfo field : fieldList) { Object v = field.retrieveValue(form); CascadeFormField cff = field.getAnnotation(CascadeFormField.class); if (cff != null) { String containerSelector = cff.containerSelector(); if (field.getType().isArray()) {// a cascade form for array int len = Array.getLength(v); List<Renderer> subRendererList = new ArrayList<>(len); int loopStart = 0; if (renderForEdit(renderTargetStep, form, cff.name())) { // for rendering a template DOM loopStart = -1; } Class<?> subFormType = field.getType().getComponentType(); Object subForm; for (int i = loopStart; i < len; i++) { // retrieve the form instance if (i >= 0) { subForm = Array.get(v, i); } else { // create a template instance subForm = createFormInstanceForCascadeFormArrayTemplate(subFormType); } Renderer subRenderer = Renderer.create(); // only rewrite the refs for normal instances if (i >= 0) { // subRenderer.add(setCascadeFormContainerArrayRef(i)); subRenderer.add(rewriteCascadeFormFieldArrayRef(renderTargetStep, subForm, i)); } subRenderer.add(renderForm(renderTargetStep, subForm, i)); // hide the template DOM if (i < 0) { subRenderer.add(":root", hideCascadeFormTemplateDOM(subFormType)); } subRendererList.add(subRenderer); } render.add(containerSelector, subRendererList); } else {// a simple cascade form if (StringUtils.isNotEmpty(containerSelector)) { render.add(containerSelector, renderForm(renderTargetStep, v, -1)); } else { render.add(renderForm(renderTargetStep, v, -1)); } } continue; } if (v == null) { @SuppressWarnings("rawtypes") ContextDataHolder valueHolder; if (field.getField() != null) { valueHolder = InjectTrace.getInstanceInjectionTraceInfo(form, field.getField()); } else { valueHolder = InjectTrace.getInstanceInjectionTraceInfo(form, field.getSetter()); } if (valueHolder != null) { v = convertRawInjectionTraceDataToRenderingData(field.getName(), field.getType(), valueHolder.getFoundOriginalData()); } } FieldRenderingInfo renderingInfo = getRenderingInfo(field, cascadeFormArrayIndex); // render.addDebugger("whole form before: " + field.getName()); if (renderForEdit(renderTargetStep, form, field.getName())) { render.add(renderingInfo.valueRenderer.renderForEdit(renderingInfo.editSelector, v)); } else { render.add(renderingInfo.valueRenderer.renderForDisplay(renderingInfo.editSelector, renderingInfo.displaySelector, v)); } } return render; }
From source file:ArraysX.java
/** * Resizes the specified array. Similar to {@link #shrink}, but * it can enlarge and it keeps elements from the first. *//*from w w w .j av a2 s . co m*/ public static final Object resize(Object ary, int size) { final int oldsz = Array.getLength(ary); if (oldsz == size) return ary; final Object dst = Array.newInstance(ary.getClass().getComponentType(), size); System.arraycopy(ary, 0, dst, 0, oldsz > size ? size : oldsz); return dst; }
From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java
private Object doConvertToArray(Map<String, Object> context, Object o, Member member, String s, Object value, Class toType) {/*from ww w . j a v a 2 s . com*/ Object result = null; Class componentType = toType.getComponentType(); if (componentType != null) { TypeConverter converter = getTypeConverter(context); if (value.getClass().isArray()) { int length = Array.getLength(value); result = Array.newInstance(componentType, length); for (int i = 0; i < length; i++) { Object valueItem = Array.get(value, i); Array.set(result, i, converter.convertValue(context, o, member, s, valueItem, componentType)); } } else { result = Array.newInstance(componentType, 1); Array.set(result, 0, converter.convertValue(context, o, member, s, value, componentType)); } } return result; }
From source file:com.espertech.esper.epl.annotation.AnnotationUtil.java
private static Object getFinalValue(Class annotationClass, AnnotationAttribute annotationAttribute, Object value, EngineImportService engineImportService) throws AnnotationException { if (value == null) { if (annotationAttribute.getDefaultValue() == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a value for attribute '" + annotationAttribute.getName() + "'"); }/*from w ww . j a va 2 s . com*/ return annotationAttribute.getDefaultValue(); } // handle non-array if (!annotationAttribute.getType().isArray()) { // handle primitive value if (!annotationAttribute.getType().isAnnotation()) { SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(value.getClass(), annotationAttribute.getType()); Object finalValue = caster.cast(value); if (finalValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } return finalValue; } else { // nested annotation if (!(value instanceof AnnotationDesc)) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } return createProxy((AnnotationDesc) value, engineImportService); } } if (!value.getClass().isArray()) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getSimpleName() + "-typed value for attribute '" + annotationAttribute.getName() + "' but received " + "a " + value.getClass().getSimpleName() + "-typed value"); } Object array = Array.newInstance(annotationAttribute.getType().getComponentType(), Array.getLength(value)); for (int i = 0; i < Array.getLength(value); i++) { Object arrayValue = Array.get(value, i); if (arrayValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + "non-null value for array elements for attribute '" + annotationAttribute.getName() + "'"); } SimpleTypeCaster caster = SimpleTypeCasterFactory.getCaster(arrayValue.getClass(), annotationAttribute.getType().getComponentType()); Object finalValue = caster.cast(arrayValue); if (finalValue == null) { throw new AnnotationException("Annotation '" + annotationClass.getSimpleName() + "' requires a " + annotationAttribute.getType().getComponentType().getSimpleName() + "-typed value for array elements for attribute '" + annotationAttribute.getName() + "' but received " + "a " + arrayValue.getClass().getSimpleName() + "-typed value"); } Array.set(array, i, finalValue); } return array; }
From source file:me.code4fun.roboq.Request.java
protected HttpUriRequest createHttpRequest(int method, String url, Options opts) { String url1 = makeUrl(url, opts); // Create HTTP request HttpUriRequest httpReq;/*w ww . j av a 2 s. com*/ if (GET == method) { httpReq = new HttpGet(url1); } else if (POST == method) { httpReq = new HttpPost(url1); } else if (PUT == method) { httpReq = new HttpPut(url1); } else if (DELETE == method) { httpReq = new HttpDelete(url1); } else if (TRACE == method) { httpReq = new HttpTrace(url1); } else if (HEAD == method) { httpReq = new HttpHead(url1); } else if (OPTIONS == method) { httpReq = new HttpOptions(url1); } else { throw new IllegalStateException("Illegal HTTP method " + method); } // Set headers Map<String, Object> headers = opts.getHeaders(); for (Map.Entry<String, Object> entry : headers.entrySet()) { String k = entry.getKey(); Object v = entry.getValue(); if (v != null && v.getClass().isArray()) { int len = Array.getLength(v); for (int i = 0; i < len; i++) { Object v0 = Array.get(v, i); httpReq.addHeader(k, o2s(v0, "")); } } else if (v instanceof List) { for (Object v0 : (List) v) httpReq.addHeader(k, o2s(v0, "")); } else { httpReq.addHeader(k, o2s(v, "")); } } // set body if (httpReq instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) httpReq).setEntity(createRequestBody(method, url, opts)); } return httpReq; }
From source file:gool.generator.common.CommonCodeGenerator.java
/** * Produces code for a constant.// ww w .j a v a2 s. c o m * * @param constant * a constant value. * @return the formatted constant value. */ @Override public String getCode(Constant constant) { if (constant.getType() instanceof TypeArray) { StringBuffer sb = new StringBuffer(); int size = Array.getLength(constant.getValue()); boolean escape = ((TypeArray) constant.getType()).getElementType() instanceof TypeString; sb.append("{"); for (int i = 0; i < size; i++) { if (escape) { return "\"" + StringEscapeUtils.escapeJava(Array.get(constant.getValue(), i).toString()) + "\""; } else { sb.append(Array.get(constant.getValue(), i)); } sb.append(","); } sb.append("}"); return sb.toString(); } else if (constant.getType() == TypeString.INSTANCE) { return "\"" + StringEscapeUtils.escapeJava(constant.getValue().toString()) + "\""; } else if (constant.getType() == TypeChar.INSTANCE) { return "'" + StringEscapeUtils.escapeJava(constant.getValue().toString()) + "'"; } return constant.getValue().toString(); }