Example usage for java.util List toArray

List of usage examples for java.util List toArray

Introduction

In this page you can find the example usage for java.util List toArray.

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

From source file:com.infullmobile.jenkins.plugin.restrictedregister.security.hudson.form.RequiredFieldsChecker.java

public static void checkRequiredFields(JSONObject payload, IFormField... requiredFields)
        throws RegistrationException {
    final List<IFormField> emptyFields = new ArrayList<>();
    for (IFormField field : requiredFields) {
        if (!payload.has(field.getFieldName())
                || StringUtils.isEmpty(payload.getString(field.getFieldName()))) {
            emptyFields.add(field);//ww  w  .java  2s .  com
        }
    }
    if (!emptyFields.isEmpty()) {
        throw new RegistrationException("One or more field is empty.",
                emptyFields.toArray(new IFormField[emptyFields.size()]));
    }
}

From source file:ArrayUtil.java

/**
 * Concatenates all the passed parameters.
 * @param <T>//from  w w  w.j av a  2 s. co m
 * @param objs
 * @return
 */
public static <T> T[] concat(T[]... objs) {
    List<T> out = new ArrayList<T>();

    int i = 0;
    T[] pass = null;
    for (T[] o : objs) {
        for (int j = 0; j < o.length; j++) {
            out.add(o[j]);
            i++;
        }
        pass = o;
    }

    return out.toArray(pass);
}

From source file:at.ac.tuwien.dsg.comot.m.common.Utils.java

@SuppressWarnings("unchecked")
public static <T> T asObjectFromJson(String str, Class<T> clazz, Class<?>... otherClazz) throws JAXBException {

    List<Object> list = new ArrayList<Object>(Arrays.asList(otherClazz));
    list.add(clazz);//from   ww  w  .  j av  a 2s. c  om

    Map<String, Object> props = new HashMap<String, Object>();
    props.put(JAXBContextProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);

    JAXBContext context = JAXBContextFactory.createContext(list.toArray(new Class[list.size()]), props);
    Unmarshaller unm = context.createUnmarshaller();

    return (T) unm.unmarshal(new StringReader(str));
}

From source file:com.google.dart.tools.ui.internal.refactoring.ServiceUtils_NEW.java

public static TextEdit[] toLTK(List<SourceEdit> edits) {
    List<TextEdit> ltkEdits = Lists.newArrayList();
    for (SourceEdit edit : edits) {
        TextEdit ltkEdit = toLTK(edit);//from w  w  w. j  a va 2  s.co m
        ltkEdits.add(ltkEdit);
    }
    return ltkEdits.toArray(new TextEdit[ltkEdits.size()]);
}

From source file:hudson.Main.java

/**
 * Run command and send result to {@code ExternalJob} in the {@code external-monitor-job} plugin.
 * Obsoleted by {@code SetExternalBuildResultCommand} but kept here for compatibility.
 *///from  w w w  .j  a v  a2 s.  com
public static int remotePost(String[] args) throws Exception {
    String projectName = args[0];

    String home = getHudsonHome();
    if (!home.endsWith("/"))
        home = home + '/'; // make sure it ends with '/'

    // check for authentication info
    String auth = new URL(home).getUserInfo();
    if (auth != null)
        auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));

    {// check if the home is set correctly
        HttpURLConnection con = open(new URL(home));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200 || con.getHeaderField("X-Hudson") == null) {
            System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
            return -1;
        }
    }

    URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

    {// check if the job name is correct
        HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200) {
            System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " "
                    + con.getResponseMessage() + ")");
            return -1;
        }
    }

    // get a crumb to pass the csrf check
    String crumbField = null, crumbValue = null;
    try {
        HttpURLConnection con = open(
                new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
        String[] components = line.split(":");
        if (components.length == 2) {
            crumbField = components[0];
            crumbValue = components[1];
        }
    } catch (IOException e) {
        // presumably this Hudson doesn't use CSRF protection
    }

    // write the output to a temporary file first.
    File tmpFile = File.createTempFile("jenkins", "log");
    try {
        int ret;
        try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
                Writer w = new OutputStreamWriter(os, "UTF-8")) {
            w.write("<?xml version='1.1' encoding='UTF-8'?>");
            w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name()
                    + "'>");
            w.flush();

            // run the command
            long start = System.currentTimeMillis();

            List<String> cmd = new ArrayList<String>();
            for (int i = 1; i < args.length; i++)
                cmd.add(args[i]);
            Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
                    new DualOutputStream(System.out, new EncodingStream(os)));

            ret = proc.join();

            w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start)
                    + "</duration></run>");
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }

        URL location = new URL(jobURL, "postBuildResult");
        while (true) {
            try {
                // start a remote connection
                HttpURLConnection con = open(location);
                if (auth != null)
                    con.setRequestProperty("Authorization", auth);
                if (crumbField != null && crumbValue != null) {
                    con.setRequestProperty(crumbField, crumbValue);
                }
                con.setDoOutput(true);
                // this tells HttpURLConnection not to buffer the whole thing
                con.setFixedLengthStreamingMode((int) tmpFile.length());
                con.connect();
                // send the data
                try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
                    org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }

                if (con.getResponseCode() != 200) {
                    org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
                }

                return ret;
            } catch (HttpRetryException e) {
                if (e.getLocation() != null) {
                    // retry with the new location
                    location = new URL(e.getLocation());
                    continue;
                }
                // otherwise failed for reasons beyond us.
                throw e;
            }
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:com.curl.orb.generator.ClassPropertyLoader.java

/**
 * Get all class properties in ApplicationContext.
 * /*from w  w  w.j  a  va2  s.c  o  m*/
 * @return class properties
 * @throws ApplicationContextException
 * @throws GeneratorException
 */
public static ClassProperty[] getAllClassPropertiesInApplicationContext()
        throws ApplicationContextException, GeneratorException {
    AbstractApplicationContext context = ApplicationContextFactory.getInstance(null).getApplicationContext();
    String[] names = context.getObjectNames();
    java.util.Arrays.sort(names);
    List<ClassProperty> classProperties = new ArrayList<ClassProperty>();
    for (int i = 0; i < names.length; i++) {
        String name = names[i];
        ClassProperty classProperty = new ClassProperty(context.getObjectType(name).getName(), name);
        if (classProperty.isPublic())
            classProperties.add(classProperty);
    }
    return classProperties.toArray(new ClassProperty[] {});
}

From source file:com.wavemaker.runtime.data.util.JDBCUtils.java

public static Object runSql(String sql[], String url, String username, String password, String driverClassName,
        Log logger, boolean isDDL) {

    Connection con = getConnection(url, username, password, driverClassName);

    try {/*  ww w.j a  v  a2s.  co  m*/
        try {
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            throw new DataServiceRuntimeException(ex);
        }

        Statement s = con.createStatement();

        try {
            try {
                for (String stmt : sql) {
                    if (logger != null && logger.isInfoEnabled()) {
                        logger.info("Running " + stmt);
                    }
                    s.execute(stmt);
                }
                if (!isDDL) {
                    ResultSet r = s.getResultSet();
                    List<Object> rtn = new ArrayList<Object>();
                    while (r.next()) {
                        // getting only the first col is pretty unuseful
                        rtn.add(r.getObject(1));
                    }
                    return rtn.toArray(new Object[rtn.size()]);
                }
            } catch (Exception ex) {
                if (logger != null && logger.isErrorEnabled()) {
                    logger.error(ex.getMessage());
                }
                throw ex;
            }
        } finally {
            try {
                s.close();
            } catch (Exception ignore) {
            }
        }
    } catch (Exception ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new DataServiceRuntimeException(ex);
        }
    } finally {
        try {
            con.close();
        } catch (Exception ignore) {
        }
    }

    return null;
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.util.ExcelGeneratorUtils.java

/**
 * Creates a dropdown box for each cell in the specified {@code addressList}.
 * //from  w  ww . j av a 2s  .com
 * @param sheet the sheet to add the dropdown box to
 * @param addressList the cell range to add the dropdown box to
 * @param values the values to be shown in dropdown box
 */
public static void createDropdownWithValues(Sheet sheet, CellRangeAddressList addressList,
        List<String> values) {
    DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
    String[] valuesList = values.toArray(new String[values.size()]);
    DataValidationConstraint dvConstraint = dataValidationHelper.createExplicitListConstraint(valuesList);
    DataValidation dataValidation = dataValidationHelper.createValidation(dvConstraint, addressList);
    // There is an error in the interpretation of the argument of setSuppressDropDownArrow in POI 3.9
    // for XSSF Workbooks. The arrow is suppressed if the argument is set to 'false' instead of 'true'.
    // In HSSF Workbooks the method works as designed.
    // Luckily in both cases the default behavior is, that the arrow is displayed. So we can skip the explicit setting of this behavior.
    // SKIP THIS: dataValidation.setSuppressDropDownArrow(false);

    sheet.addValidationData(dataValidation);
}

From source file:ml.shifu.core.util.CommonUtils.java

/**
 * Common split function to ignore special character like '|'. It's better to return a list while many calls in our
 * framework using string[].//from w w  w.  ja  v  a2 s .c  om
 *
 * @throws IllegalArgumentException {@code raw} and {@code delimiter} is null or empty.
 */
public static String[] split(String raw, String delimiter) {
    List<String> split = splitAndReturnList(raw, delimiter);
    return split.toArray(new String[split.size()]);
}

From source file:com.stratio.deep.commons.utils.AnnotationUtils.java

/**
 * Return a pair of Field[] whose left element is
 * the array of keys fields.// ww w.  j a  v  a  2 s.  c om
 * The right element contains the array of all other non-key fields.
 *
 * @param clazz the Class object
 * @return a pair object whose first element contains key fields, and whose second element contains all other columns.
 */
public static Pair<Field[], Field[]> filterKeyFields(Class clazz) {
    Field[] filtered = filterDeepFields(clazz);
    List<Field> keys = new ArrayList<>();
    List<Field> others = new ArrayList<>();

    for (Field field : filtered) {
        if (isKey(field.getAnnotation(DeepField.class))) {
            keys.add(field);
        } else {
            others.add(field);
        }
    }

    return Pair.create(keys.toArray(new Field[keys.size()]), others.toArray(new Field[others.size()]));
}