List of usage examples for org.apache.commons.lang ArrayUtils add
public static double[] add(double[] array, int index, double element)
Inserts the specified element at the specified position in the array.
From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java
protected Object set(NeoEMFEObject object, EAttribute eAttribute, int index, Object value) { Object oldValue = isSet((InternalEObject) object, eAttribute) ? get(object, eAttribute, index) : null; try {// ww w . j av a 2 s . co m if (!eAttribute.isMany()) { Put put = new Put(Bytes.toBytes(object.neoemfId())); put.add(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), Bytes.toBytes(serializeValue(eAttribute, value))); table.put(put); } else { try { String[] array; boolean passed = false; int attemp = 0; do { array = (String[]) getFromTable(object, eAttribute); //array = (String[]) ArrayUtils.add(array, index, serializeValue(eAttribute, value)); Put put = new Put(Bytes.toBytes(object.neoemfId())).add(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), NeoEMFUtil.EncoderUtil.toBytes((String[]) ArrayUtils.add(array, index, serializeValue(eAttribute, value)))); passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()), array == null ? null : NeoEMFUtil.EncoderUtil.toBytes(array), put); if (!passed) { if (attemp > ATTEMP_TIMES_DEFAULT) throw new TimeoutException(); Thread.sleep((++attemp) * SLEEP_DEFAULT); } } while (!passed); } catch (IOException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format("Unable to set ''{0}'' to ''{1}'' for element ''{2}''", value, eAttribute.getName(), object)); } catch (TimeoutException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format( "Unable to set ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", value, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT)); e.printStackTrace(); } catch (InterruptedException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format( "InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage())); e.printStackTrace(); } } } catch (IOException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format("Unable to set information for element ''{0}''", object)); } return oldValue; }
From source file:fr.inria.atlanmod.neoemf.map.datastore.estores.impl.DirectWriteMapResourceEStoreImpl.java
protected void add(PersistentEObject object, EReference eReference, int index, PersistentEObject referencedObject) { updateContainment(object, eReference, referencedObject); updateInstanceOf(referencedObject);/* w w w . j a v a 2s . co m*/ Object[] array = (Object[]) getFromMap(object, eReference); if (array == null) { array = new Object[] {}; } array = ArrayUtils.add(array, index, referencedObject.id()); map.put(Fun.t2(object.id(), eReference.getName()), array); loadedEObjects.put(referencedObject.id(), (InternalPersistentEObject) referencedObject); }
From source file:com.opengamma.analytics.financial.model.volatility.smile.fitting.sabr.StandardSmileSurfaceDataBundleTest.java
@Test public void testObject() { assertArrayEquals(FORWARDS, DATA.getForwards(), EPS); assertArrayEquals(EXPIRIES, DATA.getExpiries(), 0); for (int i = 0; i < STRIKES.length; i++) { assertArrayEquals(STRIKES[i], DATA.getStrikes()[i], 0); assertArrayEquals(VOLS[i], DATA.getVolatilities()[i], 0); }//w ww . jav a 2 s.c o m assertEquals(FORWARD_CURVE, DATA.getForwardCurve()); // assertEquals(IS_CALL_DATA, DATA.isCallData()); StandardSmileSurfaceDataBundle other = new StandardSmileSurfaceDataBundle(FORWARD_CURVE, EXPIRIES, STRIKES, VOLS); assertEquals(DATA, other); assertEquals(DATA.hashCode(), other.hashCode()); other = new StandardSmileSurfaceDataBundle(SPOT, FORWARDS, EXPIRIES, STRIKES, VOLS, INTERPOLATOR); assertArrayEquals(DATA.getExpiries(), other.getExpiries(), 0); for (int i = 0; i < STRIKES.length; i++) { assertArrayEquals(DATA.getStrikes()[i], other.getStrikes()[i], 0); assertArrayEquals(DATA.getVolatilities()[i], other.getVolatilities()[i], 0); } assertArrayEquals(ArrayUtils.toPrimitive(DATA.getForwardCurve().getForwardCurve().getXData()), ArrayUtils.toPrimitive(other.getForwardCurve().getForwardCurve().getXData()), 0); assertArrayEquals(ArrayUtils.toPrimitive(DATA.getForwardCurve().getForwardCurve().getYData()), ArrayUtils.toPrimitive(other.getForwardCurve().getForwardCurve().getYData()), 0); assertEquals(((InterpolatedDoublesCurve) DATA.getForwardCurve().getForwardCurve()).getInterpolator(), ((InterpolatedDoublesCurve) other.getForwardCurve().getForwardCurve()).getInterpolator()); final ForwardCurve otherCurve = new ForwardCurve(InterpolatedDoublesCurve .from(ArrayUtils.add(EXPIRIES, 0, 0), ArrayUtils.add(EXPIRIES, 0, SPOT), INTERPOLATOR)); other = new StandardSmileSurfaceDataBundle(otherCurve, EXPIRIES, STRIKES, VOLS); assertFalse(DATA.equals(other)); other = new StandardSmileSurfaceDataBundle(FORWARD_CURVE, new double[] { 0, 0.01, 0.02 }, STRIKES, VOLS); assertFalse(DATA.equals(other)); other = new StandardSmileSurfaceDataBundle(FORWARD_CURVE, EXPIRIES, VOLS, VOLS); assertFalse(DATA.equals(other)); other = new StandardSmileSurfaceDataBundle(FORWARD_CURVE, EXPIRIES, STRIKES, STRIKES); assertFalse(DATA.equals(other)); // other = new StandardSmileSurfaceDataBundle(FORWARD_CURVE, EXPIRIES, STRIKES, VOLS, !IS_CALL_DATA); // assertFalse(DATA.equals(other)); }
From source file:au.org.ala.biocache.service.SpeciesLookupRestService.java
@Override public String[] getHeaderDetails(String field, boolean includeCounts, boolean includeSynonyms) { if (baseHeader == null) { //initialise all the headers initHeaders();//from w w w.j a v a2 s .c o m } String[] startArray = baseHeader; if (includeCounts) { if (includeSynonyms) { startArray = countSynonymHeader; } else { startArray = countBaseHeader; } } else if (includeSynonyms) { startArray = synonymHeader; } return (String[]) ArrayUtils.add(startArray, 0, messageSource.getMessage("facet." + field, null, field, null)); }
From source file:gda.device.detector.countertimer.TfgScaler.java
public double[][] readoutFrames(int startFrame, int finalFrame) throws DeviceException { // read the lot int numFrames = finalFrame - startFrame + 1; int width = scaler.getDimension()[0]; double rawData[] = scaler.read(0, 0, startFrame, width, 1, numFrames); double[][] rawDataAsFrames = unpackRawDataToFrames(rawData, numFrames, width); // if no change required to the raw data if ((firstDataChannel == null || firstDataChannel == 0) && !timeChannelRequired && !isTFGv2 && (numChannelsToRead == null || numChannelsToRead == width)) { return rawDataAsFrames; }//w ww .ja va 2 s .co m // convert to frame objects ScalerFrame[] frames = convertToFrames(rawDataAsFrames); // remove unwanted channels based on firstDataChannel and numChannelsToRead frames = reduceFrames(frames); // output basic 2D array double[][] output = new double[numFrames][]; for (int i = 0; i < numFrames; i++) { if (timeChannelRequired) { output[i] = ArrayUtils.add(frames[i].data, 0, frames[i].time); } else { output[i] = frames[i].data; } } return output; }
From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java
protected void add(NeoEMFEObject object, EReference eReference, int index, NeoEMFInternalEObject referencedObject) { try {//from w ww . j a v a 2 s . co m // as long as the element is not attached to the resource, the containment and type information // are not stored. updateLoadedEObjects(referencedObject); updateContainment(object, eReference, referencedObject); updateInstanceOf(referencedObject); if (index == NO_INDEX) { addAsAppend(object, eReference, index == NO_INDEX, referencedObject); } else { String[] array; boolean passed = false; int attemp = 0; do { array = (String[]) getFromTable(object, eReference); //array = (String[]) ArrayUtils.add(array, index, referencedObject.neoemfId()); Put put = new Put(Bytes.toBytes(object.neoemfId())).add(PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), NeoEMFUtil.EncoderUtil.toBytesReferences( (String[]) ArrayUtils.add(array, index, referencedObject.neoemfId()))); passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY, Bytes.toBytes(eReference.getName()), array == null ? null : NeoEMFUtil.EncoderUtil.toBytesReferences(array), put); if (!passed) { if (attemp > ATTEMP_TIMES_DEFAULT) throw new TimeoutException(); Thread.sleep((++attemp) * SLEEP_DEFAULT); } } while (!passed); } } catch (IOException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format("Unable to add ''{0}'' to ''{1}'' for element ''{2}''", referencedObject, eReference.getName(), object)); } catch (TimeoutException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format("Unable to add ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times", referencedObject, eReference.getName(), object, ATTEMP_TIMES_DEFAULT)); e.printStackTrace(); } catch (InterruptedException e) { Logger.log(Logger.SEVERITY_ERROR, MessageFormat .format("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage())); e.printStackTrace(); } }
From source file:com.michelin.cio.hudson.plugins.clearcaseucmbaseline.ClearCaseUcmBaselineParameterValue.java
/** * Returns the {@link BuildWrapper} (defined as an inner class) which does * the "checkout" from the ClearCase UCM baseline selected by the user. * * <p>If a {@link ClearCaseUcmBaselineParameterDefinition} is added for the * build but the SCM is not {@link ClearCaseUcmBaselineSCM}, then the * {@link BuildWrapper} which is returned will make the build fail.</p> *///from www .j a va 2 s .c o m @Override public BuildWrapper createBuildWrapper(AbstractBuild<?, ?> build) { // let's ensure that a baseline has been really provided if (baseline == null || baseline.length() == 0) { fatalErrorMessage.append("The value '" + baseline + "' is not a valid ClearCase UCM baseline."); } // HUDSON-5877: let's ensure the job has no publishers/notifiers coming // from the ClearCase plugin DescribableList<Publisher, Descriptor<Publisher>> publishersList = build.getProject().getPublishersList(); for (Publisher publisher : publishersList) { if (publisher instanceof UcmMakeBaseline || publisher instanceof UcmMakeBaselineComposite) { if (fatalErrorMessage.length() > 0) { fatalErrorMessage.append('\n'); } fatalErrorMessage.append("This job is set up to use a '") .append(publisher.getDescriptor().getDisplayName()) .append("' publisher which is not compatible with the ClearCase UCM baseline SCM mode. Please remove this publisher."); } } if (fatalErrorMessage.length() > 0) { return new BuildWrapper() { /** * This method just makes the build fail for various reasons. */ @Override public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { listener.fatalError(fatalErrorMessage.toString()); return null; } }; } if (build.getProject().getScm() instanceof ClearCaseUcmBaselineSCM) { // the job is apparently set-up in a clean way, the build can take place return new BuildWrapper() { private ClearToolLauncher createClearToolLauncher(TaskListener listener, FilePath workspace, Launcher launcher) { return new HudsonClearToolLauncher(PluginImpl.getDescriptor().getCleartoolExe(), Hudson.getInstance().getDescriptor(ClearCaseUcmBaselineSCM.class).getDisplayName(), listener, workspace, launcher); } /** * This method is a copy of {@link AbstractClearCaseScm#generateNormalizedViewName} * which is unfortunately not static. * * @see AbstractClearCaseScm#generateNormalizedViewName */ private String generateNormalizedViewName(VariableResolver variableResolver, String viewName) { String normalizedViewName = Util.replaceMacro(viewName, variableResolver); normalizedViewName = normalizedViewName.replaceAll("[\\s\\\\\\/:\\?\\*\\|]+", "_"); return normalizedViewName; } /** * This method is the one which actually does the ClearCase stuff * (creating the view, setting the config spec, downloading the * view, etc.). * * <p>This method is invoked when the user clicks on the 'Build' * button appearing on the parameters page.</p> */ @Override public Environment setUp(AbstractBuild build, final Launcher launcher, BuildListener listener) throws IOException, InterruptedException { // we use our own variable resolver to have the support for // the CLEARCASE_BASELINE env variable (cf. HUDSON-6410) VariableResolver variableResolver = new BuildVariableResolver(build, launcher, listener, baseline); ClearToolLauncher clearToolLauncher = createClearToolLauncher(listener, build.getProject().getWorkspace(), launcher); ClearToolUcmBaseline cleartool = new ClearToolUcmBaseline(variableResolver, clearToolLauncher); viewName = generateNormalizedViewName(variableResolver, viewName); FilePath workspace = build.getProject().getWorkspace(); FilePath viewPath = workspace.child(viewName); StringBuilder configSpec = new StringBuilder(); // --- 0. Has the same baseline been retrieved during last execution? --- boolean lastBuildUsedSameBaseline = false; if (forceRmview == false) { // we care only if we don't want to remove the existing view ClearCaseUcmBaselineParameterValue lastCcParamValue = null; // tons of loops and ifs to find the ClearCaseUcmBaselineParameterValue of the last build, if any List<Run> builds = build.getProject().getBuilds(); if (builds.size() > 1) { Run latestBuild = builds.get(1); // builds.get(0) is the currently running build List<ParametersAction> actions = latestBuild.getActions(ParametersAction.class); if (actions != null) { for (ParametersAction action : actions) { List<ParameterValue> parameters = action.getParameters(); if (parameters != null) { for (ParameterValue parameter : parameters) { if (parameter instanceof ClearCaseUcmBaselineParameterValue) { lastCcParamValue = (ClearCaseUcmBaselineParameterValue) parameter; // there can be only one time this kind of parameter, so let's break break; } } } if (lastCcParamValue != null) { // there can be only one time this kind of parameter, so let's break here too break; } } } } if (lastCcParamValue != null) { if (pvob.equals(lastCcParamValue.pvob) && component.equals(lastCcParamValue.component) && baseline.equals(lastCcParamValue.baseline)) { // the baseline used in the latest build is the same as the newly requested one lastBuildUsedSameBaseline = true; } } } final String newlineForOS = launcher.isUnix() ? "\n" : "\r\n"; // we assume that the slave OS file separator is the same as the server // since we have no way of determining the OS of the Clearcase server final String fileSepForOS = PathUtil.fileSepForOS(launcher.isUnix()); if (forceRmview || !lastBuildUsedSameBaseline || !viewPath.exists()) { // --- 1. We remove the view if it already exists --- if (viewPath.exists()) { if (!useUpdate || forceRmview) { cleartool.rmview(viewName); // --- 2. We create the view to be loaded --- cleartool.mkview(viewName, mkviewOptionalParam, snapshotView, null); } } else { cleartool.mkview(viewName, mkviewOptionalParam, snapshotView, null); } // --- 3. We create the configspec --- if (!excludeElementCheckedout) { configSpec.append("element * CHECKEDOUT").append(newlineForOS); } Set<String> loadRules = new HashSet<String>(); // we use a Set to avoid duplicate load rules (cf. HUDSON-6398) // cleartool lsbl -fmt "%[depends_on_closure]p" <baseline>@<pvob> String[] dependentBaselines = cleartool.getDependentBaselines(pvob, baseline); // we add the selected baseline at the beginning of the dependentBaselines // array so that the "element" and "load" sections of the config spec are // generated for this baseline dependentBaselines = (String[]) ArrayUtils.add(dependentBaselines, 0, baseline + '@' + pvob); for (String dependentBaselineSelector : dependentBaselines) { int indexOfSeparator = dependentBaselineSelector.indexOf('@'); if (indexOfSeparator == -1) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Ignoring dependent baseline '" + dependentBaselineSelector + '\''); } continue; } String dependentBaseline = dependentBaselineSelector.substring(0, indexOfSeparator); String component = cleartool.getComponentFromBaseline(pvob, dependentBaseline); String componentRootDir = cleartool.getComponentRootDir(pvob, component); // some components may be rootless: they must simply be skipped (cf. HUDSON-6398) if (StringUtils.isBlank(componentRootDir)) { continue; } // example of generated config spec "element": // element /xxx/spd_comp/... spd_comp_v1.x_20100402100000 -nocheckout configSpec.append("element \"").append(componentRootDir).append(fileSepForOS) .append("...\" ").append(dependentBaseline).append(" -nocheckout") .append(newlineForOS); // is any download restriction defined? if (restrictions != null && restrictions.size() > 0) { for (String restriction : restrictions) { // the comparison must not take into account path separators, // so let's unify them to / for that purpose String restrictionForComparison = restriction.replace('\\', '/'); String componentRootDirForComparison = componentRootDir.replace('\\', '/'); if (restrictionForComparison.startsWith(componentRootDirForComparison)) { // example of generated config spec "load": // load /xxx/spd_comp/src loadRules.add("load " + restriction); } } } else { loadRules.add("load " + componentRootDir); } } configSpec.append("element * /main/0 -ucm -nocheckout").append(newlineForOS); for (String loadRule : loadRules) { configSpec.append(loadRule).append(newlineForOS); } listener.getLogger() .println("The view will be created based on the following config spec:"); listener.getLogger().println("--- config spec start ---"); listener.getLogger().print(configSpec.toString()); listener.getLogger().println("--- config spec end ---"); // --- 4. We actually load the view based on the configspec --- // cleartool setcs <configspec> cleartool.setcs(viewName, configSpec.toString()); } else { listener.getLogger().println( "The requested ClearCase UCM baseline is the same as previous build: Reusing previously loaded view"); } // --- 5. Create the environment variables --- return new Environment() { @Override public void buildEnvVars(Map<String, String> env) { env.put(ClearCaseUcmBaselineSCM.CLEARCASE_BASELINE_ENVSTR, baseline); env.put(AbstractClearCaseScm.CLEARCASE_VIEWNAME_ENVSTR, viewName); env.put(AbstractClearCaseScm.CLEARCASE_VIEWPATH_ENVSTR, env.get("WORKSPACE") + fileSepForOS + viewName); } }; } }; } else { return new BuildWrapper() { /** * This method makes the build fail when a {@link ClearCaseUcmBaselineParameterDefinition} * parameter is defined for the job, but the SCM is not an instance * of {@link ClearCaseUcmBaselineSCM}. */ @Override public Environment setUp(AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { String ccUcmBaselineSCMDisplayName = Hudson.getInstance() .getDescriptor(ClearCaseUcmBaselineSCM.class).getDisplayName(); listener.fatalError("This job is not set up to use a '" + ccUcmBaselineSCMDisplayName + "' SCM while it has a '" + Hudson.getInstance().getDescriptor(ClearCaseUcmBaselineParameterDefinition.class) .getDisplayName() + "' parameter: Either remove the parameter or set the SCM to be '" + ccUcmBaselineSCMDisplayName + "'; In the meantime: Aborting!"); return null; } }; } }
From source file:com.jfinal.plugin.activerecord.Model.java
public void addColumn(String colName) { String[] newColumns = (String[]) ArrayUtils.add(columns, columns.length, colName); this.columns = newColumns; }
From source file:org.codehaus.groovy.grails.commons.metaclass.BaseApiProvider.java
@SuppressWarnings("unchecked") public void addApi(final Object apiInstance) { if (apiInstance == null) { return;//from w w w . j av a 2s . c o m } Class<?> currentClass = apiInstance.getClass(); while (currentClass != Object.class) { final Method[] declaredMethods = currentClass.getDeclaredMethods(); for (final Method javaMethod : declaredMethods) { final int modifiers = javaMethod.getModifiers(); if (!isNotExcluded(javaMethod, modifiers)) { continue; } if (Modifier.isStatic(modifiers)) { if (isConstructorCallMethod(javaMethod)) { constructors.add(javaMethod); } else { staticMethods.add(javaMethod); } } else { instanceMethods.add(new ReflectionMetaMethod(new CachedMethod(javaMethod)) { @Override public String getName() { String methodName = super.getName(); if (isConstructorCallMethod(javaMethod)) { return CTOR_GROOVY_METHOD; } return methodName; } @Override public Object invoke(Object object, Object[] arguments) { if (arguments.length == 0) { return super.invoke(apiInstance, new Object[] { object }); } return super.invoke(apiInstance, ArrayUtils.add(checkForGStrings(arguments), 0, object)); } private Object[] checkForGStrings(Object[] arguments) { for (int i = 0; i < arguments.length; i++) { if (arguments[i] instanceof GString) { arguments[i] = arguments[i].toString(); } } return arguments; } @Override public CachedClass[] getParameterTypes() { final CachedClass[] paramTypes = method.getParameterTypes(); if (paramTypes.length > 0) { return (CachedClass[]) ArrayUtils.subarray(paramTypes, 1, paramTypes.length); } return paramTypes; } }); } } currentClass = currentClass.getSuperclass(); } }
From source file:org.eclipse.wb.android.internal.model.layouts.table.TableLayoutSupport.java
/** * Adds information about new row. Note: it doesn't update visual information. *//*from ww w .ja v a2s .co m*/ public void insertRow(int rowIndex) throws Exception { CellInfo newRowCells[] = new CellInfo[m_columns]; for (int column = 0; column < m_columns; ++column) { newRowCells[column] = new CellInfo(rowIndex, column); } m_cells = (CellInfo[][]) ArrayUtils.add(m_cells, rowIndex, newRowCells); // update cells row for (int row = rowIndex + 1; row < m_rows + 1; ++row) { for (int column = 0; column < m_columns; ++column) { m_cells[row][column].row++; } } m_rows++; }