Example usage for org.apache.commons.lang ArrayUtils toPrimitive

List of usage examples for org.apache.commons.lang ArrayUtils toPrimitive

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils toPrimitive.

Prototype

public static boolean[] toPrimitive(Boolean[] array) 

Source Link

Document

Converts an array of object Booleans to primitives.

Usage

From source file:uk.ac.diamond.scisoft.ncd.core.utils.NcdDataUtils.java

/**
 * Method for parsing input string for multidimensional frame selection
 * // w  w w. j  a  v a2s . com
 * @param format
 *          String containing information on grid slice selection
 * @param frames
 *          Dimensions of the input dataset
 * @return
 *          Array with list of selected grid points in every dimension
 */
public static ArrayList<int[]> createSliceList(String format, int[] frames) {
    String[] dimFormat = format.split(";", -1);
    int dims = dimFormat.length;
    if (dims < frames.length) {
        for (int i = 0; i < frames.length - dims; i++)
            format += ";";
        dimFormat = format.split(";", -1);
        dims = dimFormat.length;
    }
    ArrayList<int[]> tmpList = new ArrayList<int[]>();

    // Loop over axes index
    for (int i = 0; i < frames.length; i++) {

        ArrayList<Integer> tmpSel = new ArrayList<Integer>();
        String tmpFormat = dimFormat[i];

        if (tmpFormat.equals("")) {
            tmpList.add(IntegerDataset.createRange(frames[i]).getData());
            continue;
        }

        String[] tmpFormatComma = tmpFormat.split(",");

        // Loop over list of indexes on the selected axis
        for (int j = 0; j < tmpFormatComma.length; j++) {

            if (tmpFormatComma[j].equals("")) {
                continue;
            }

            String[] tmpFormatDash = tmpFormatComma[j].split("-");
            String firstValue = tmpFormatDash[0];
            String lastValue = tmpFormatDash[tmpFormatDash.length - 1];
            int sliceStart = 0;
            int sliceEnd = frames[i];

            if (!(firstValue.isEmpty()) && integerValidator.isValid(firstValue))
                sliceStart = Math.max(0, Integer.valueOf(firstValue));

            if (!(lastValue.isEmpty()) && integerValidator.isValid(lastValue))
                sliceEnd = Math.min(frames[i], Integer.valueOf(lastValue) + 1);

            int[] slice = IntegerDataset.createRange(sliceStart, sliceEnd, 1).getData();
            for (int l = 0; l < slice.length; l++)
                tmpSel.add(slice[l]);
        }
        if (tmpSel.isEmpty())
            tmpList.add(IntegerDataset.createRange(frames[i]).getData());
        else
            tmpList.add(ArrayUtils.toPrimitive(tmpSel.toArray(new Integer[] {})));
    }

    return tmpList;

}

From source file:uk.ac.diamond.scisoft.ncd.core.utils.NcdDataUtils.java

/**
 * Method for parsing input string for grid axes selection
 * /* w  ww  .  j a va  2s  . c o  m*/
 * @param format
 *          String containing information on grid slice selection
 * @param axes
 *          Maximum grid axis index
 * @return
 *          Array with list of selected grid axis
 */
public static int[] createGridAxesList(String format, int axes) {

    String[] tmpFormatComma = format.split(",");

    ArrayList<Integer> tmpSel = new ArrayList<Integer>();
    for (int j = 0; j < tmpFormatComma.length; j++) {

        if (tmpFormatComma[j].equals("")) {
            continue;
        }

        String[] tmpFormatDash = tmpFormatComma[j].split("-");
        String firstValue = tmpFormatDash[0];
        String lastValue = tmpFormatDash[tmpFormatDash.length - 1];
        int sliceStart = 1;
        int sliceEnd = axes;

        if (!(firstValue.isEmpty()) && integerValidator.isValid(firstValue))
            sliceStart = Math.max(1, Integer.valueOf(firstValue));

        if (!(lastValue.isEmpty()) && integerValidator.isValid(lastValue))
            sliceEnd = Math.min(axes, Integer.valueOf(lastValue) + 1);

        int[] slice = IntegerDataset.createRange(sliceStart, sliceEnd, 1).getData();
        for (int l = 0; l < slice.length; l++)
            tmpSel.add(slice[l]);
    }
    if (tmpSel.isEmpty())
        return IntegerDataset.createRange(1, axes, 1).getData();

    return ArrayUtils.toPrimitive(tmpSel.toArray(new Integer[] {}));
}

From source file:uk.ac.diamond.scisoft.ncd.core.utils.NcdDataUtils.java

public static Dataset[] matchDataDimensions(Dataset data, Dataset bgData) {
    int bgRank = bgData.getRank();
    int[] bgShape = bgData.getShape();
    int rank = data.getRank();
    int[] shape = data.getShape();

    ArrayList<Integer> matchBgDims = new ArrayList<Integer>();
    ArrayList<Integer> nomatchBgDims = new ArrayList<Integer>();
    for (int i = 0; i < bgRank; i++) {
        nomatchBgDims.add(i);//w w w  . ja v a2  s .com
    }
    ArrayList<Integer> matchDataDims = new ArrayList<Integer>();
    ArrayList<Integer> nomatchDataDims = new ArrayList<Integer>();
    for (int i = 0; i < rank; i++) {
        nomatchDataDims.add(i);
    }

    for (int i = 0; i < Math.min(bgRank, rank); i++) {
        if (bgShape[bgRank - i - 1] == shape[rank - i - 1]) {
            matchDataDims.add(new Integer(rank - i - 1));
            matchBgDims.add(new Integer(bgRank - i - 1));
            nomatchDataDims.remove(new Integer(rank - i - 1));
            nomatchBgDims.remove(new Integer(bgRank - i - 1));
        }
    }

    Collections.reverse(matchDataDims);
    nomatchDataDims.addAll(matchDataDims);
    data = DatasetUtils.transpose(data, ArrayUtils.toPrimitive(nomatchDataDims.toArray(new Integer[] {})));

    Collections.reverse(matchBgDims);
    nomatchBgDims.addAll(matchBgDims);
    bgData = DatasetUtils.transpose(bgData, ArrayUtils.toPrimitive(nomatchBgDims.toArray(new Integer[] {})));

    // Calculate permutations to restore original data shapes after processing
    IntegerDataset revPermData = new IntegerDataset(nomatchDataDims.size());
    for (int i = 0; i < nomatchDataDims.size(); i++) {
        revPermData.set(nomatchDataDims.indexOf(i), i);
    }
    IntegerDataset revPermBg = new IntegerDataset(nomatchBgDims.size());
    for (int i = 0; i < nomatchBgDims.size(); i++) {
        revPermBg.set(nomatchBgDims.indexOf(i), i);
    }
    return new Dataset[] { data, bgData, revPermData, revPermBg };
}

From source file:uk.ac.diamond.scisoft.ncd.passerelle.actors.forkjoin.NcdImageStatsForkJoinTransformer.java

private void generatePointROIList() {
    int[] imageShape = (int[]) ConvertUtils
            .convert(Arrays.copyOfRange(frames, frames.length - dimension, frames.length), int[].class);

    UniformIntegerDistribution randX = new UniformIntegerDistribution(0, imageShape[1] - 1);
    UniformIntegerDistribution randY = new UniformIntegerDistribution(0, imageShape[0] - 1);

    while (points.size() < numSamples) {
        int[] point = new int[] { randY.sample(), randX.sample() };
        PointROI pointROI = new PointROI(point);
        if (intSector == null || intSector.containsPoint(point[1], point[0])) {
            if (mask == null || mask.getBoolean(point)) {
                points.append(pointROI);
                double radius = distance.compute(intSector.getPoint(), new double[] { point[0], point[1] });
                radiiMap.put(new Pair<Integer, Integer>(point[1], point[0]), radius);
            }//ww w.j a v a 2 s.  co m
        }
    }

    // Calculate resolution bins 
    double[] sortedRadii = ArrayUtils.toPrimitive(radiiMap.values().toArray(new Double[] {}));
    Arrays.sort(sortedRadii);

    percentile.setData(sortedRadii);
    percentiles[0] = 0;
    percentiles[numBins] = Double.MAX_VALUE;
    for (int i = 1; i < numBins; i++) {
        double p = i * 100.0 / numBins;
        percentiles[i] = percentile.evaluate(p);
    }

    // Subdivide points into resolution bins
    for (int bin = 0; bin < numBins; bin++) {
        HashSet<Pair<Integer, Integer>> pointSet = new HashSet<Pair<Integer, Integer>>();
        for (Entry<Pair<Integer, Integer>, Double> element : radiiMap.entrySet()) {
            double radius = element.getValue();
            if (radius > percentiles[bin] && radius < percentiles[bin + 1]) {
                pointSet.add(element.getKey());
                radiiMap.remove(element);
            }
        }
        resBins.add(pointSet);
    }
}

From source file:uk.ac.diamond.scisoft.ncd.reduction.LazyBackgroundSubtraction.java

public void preprocess(int dim, long[] frames, int frameBatch) throws HDF5Exception {
    if (bgFrames != null) {
        if (!Arrays.equals(bgFrames, frames)) {
            ArrayList<Integer> bgAverageIndices = new ArrayList<Integer>();
            int bgRank = bgFrames.length;
            for (int i = (bgRank - dim - 1); i >= 0; i--) {
                int fi = i - bgRank + frames.length;
                if ((bgFrames[i] != 1) && (fi < 0 || (bgFrames[i] != frames[fi]))) {
                    bgAverageIndices.add(i + 1);
                    bgFrames[i] = 1;// w w w  .j a  v a2s  .c  o  m
                }
            }
            if (bgAverageIndices.size() > 0) {
                LazyAverage lazyAverage = new LazyAverage();
                lazyAverage
                        .setAverageIndices(ArrayUtils.toPrimitive(bgAverageIndices.toArray(new Integer[] {})));
                lazyAverage.configure(dim, bgFrames_int, bg_group_id, frameBatch);
                lazyAverage.execute(bgIds, bgErrorsIds);
                if (bgIds != null) {
                    lazyAverage.writeNcdMetadata(bgIds.datagroup_id);
                    if (qaxis != null) {
                        lazyAverage.setQaxis(qaxis, qaxisUnit);
                        lazyAverage.writeQaxisData(bgFrames.length, bgIds.datagroup_id);
                    }
                }

                bgFrames_int = (int[]) ConvertUtils.convert(bgFrames, int[].class);
            }
        }

        // Make link to the background dataset and store background filename
        H5.H5Lcreate_external(bgFile, "/entry1/" + bgDetector + "/data", bg_group_id, "background",
                HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT);
        H5.H5Lcreate_external(bgFile, "/entry1/" + bgDetector + "/errors", bg_group_id, "background_errors",
                HDF5Constants.H5P_DEFAULT, HDF5Constants.H5P_DEFAULT);
    }
}

From source file:uk.ac.diamond.scisoft.xpdf.views.SampleParametersTest.java

@Test
public void testWriteNX() {

    String filename = "/tmp/sample.nxs";
    NexusFileBuilder builder = new DefaultNexusFileBuilder(filename);
    NXsample nxample = sample.getNXsample(builder);

    int nCompo = sample.getPhases().size();

    assertEquals("NX name incorrect", sample.getName(), nxample.getNameScalar());
    assertEquals("NX description incorrect",
            sample.getName() + ", " + sample.getComposition() + ", " + sample.getShapeName(),
            nxample.getDescriptionScalar());
    assertEquals("NX component names incorrect", new StringDataset(sample.getPhases().stream()
            .map(a -> a.getName()).collect(Collectors.toList()).toArray(new String[nCompo])),
            nxample.getComponent());//from w  w  w.j ava  2  s  . co m
    assertEquals("NX component formulae incorrect",
            new StringDataset(sample.getPhases().stream().map(a -> a.getComposition().getHallNotation(false))
                    .collect(Collectors.toList()).toArray(new String[nCompo]), new int[] { nCompo, 1 }),
            nxample.getChemical_formula());
    assertEquals("NX formula weight incorrect",
            new DoubleDataset(
                    ArrayUtils.toPrimitive(
                            sample.getPhases().stream().map(a -> a.getComposition().getFormulaMass())
                                    .collect(Collectors.toList()).toArray(new Double[nCompo])),
                    new int[] { nCompo }),
            nxample.getDataset("chemical_formula_weight"));
    // unit cell parameters...
    assertEquals("NX unit cell volume incorrect",
            new DoubleDataset(ArrayUtils.toPrimitive(sample.getPhases().stream().map(a -> a.getUnitCellVolume())
                    .collect(Collectors.toList()).toArray(new Double[nCompo])), new int[] { nCompo }),
            nxample.getUnit_cell_volume());
    assertEquals("NX unit cell class incorrect",
            new StringDataset(sample.getPhases().stream().map(a -> a.getCrystalSystem().getName())
                    .collect(Collectors.toList()).toArray(new String[nCompo]), new int[] { nCompo }),
            nxample.getUnit_cell_class());
    assertEquals("NX unit cell space group incorrect",
            new StringDataset(sample.getPhases().stream()
                    .map(a -> a.getSpaceGroup().getNumber() + ": " + a.getSpaceGroup().getName())
                    .collect(Collectors.toList()).toArray(new String[nCompo]), new int[] { nCompo }),
            nxample.getUnit_cell_group());
    assertEquals("NX theoretical densities incorrect",
            new DoubleDataset(ArrayUtils.toPrimitive(sample.getPhases().stream().map(a -> a.getDensity())
                    .collect(Collectors.toList()).toArray(new Double[nCompo])), new int[] { nCompo }),
            nxample.getDataset("theoretical_density"));

}

From source file:uk.ac.diamond.scisoft.xpdf.views.XPDFSampleParameters.java

/**
 * Creates a NeXus data structure from the sample.
 * <p>/* w  w w . j a  v a  2 s  . c o m*/
 * Creates an XPDF NeXus data structure, using the supplied Nexus File
 * Builder, as specified. Only works for samples, for now.
 * @param builder
 *             the {@link NexusFileBuilder} to write the sample data to
 */
public NXsample getNXsample(NexusFileBuilder builder) {

    if (!isSample())
        return null;

    NexusNodeFactory noder = builder.getNodeFactory();
    NXsample sample = noder.createNXsample();
    NXentry sampleEntry;
    try {
        sampleEntry = builder.newEntry("entry1").getNXentry();
    } catch (NexusException nE) {
        System.err.println("Failed to create new entry with NeXus file builder: " + nE.toString());
        return null;
    }
    sampleEntry.setSample(sample);

    // begin building
    sample.setNameScalar(getName());
    //      sample.setShort_titleScalar(getName());
    sample.setDescriptionScalar(getName() + ", " + getComposition() + ", " + getShapeName());
    // comments
    // QR code
    // components
    int nComp = phases.size();
    // Use Java 8 streams to get the contents of the phases from the list of phases
    sample.setComponent(new StringDataset(
            phases.stream().map(a -> a.getName()).collect(Collectors.toList()).toArray(new String[nComp]),
            new int[] { nComp }));
    sample.setChemical_formula(
            new StringDataset(phases.stream().map(a -> a.getComposition().getHallNotation(false))
                    .collect(Collectors.toList()).toArray(new String[nComp]), new int[] { nComp, 1 }));
    sample.setField("chemical_formula_weight",
            new DoubleDataset(
                    ArrayUtils.toPrimitive(phases.stream().map(a -> a.getComposition().getFormulaMass())
                            .collect(Collectors.toList()).toArray(new Double[nComp])),
                    new int[] { nComp }));
    // TODO: z_formula_per_unit_cell
    // Unit cell parameters; is there a way to make an array of arrays into a Dataset?
    double[] unitCellParams = new double[nComp * 2 * nDim];
    for (int i = 0; i < phases.size(); i++)
        for (int j = 0; j < nDim; j++) {
            unitCellParams[i * 2 * nDim + j] = phases.get(i).getUnitCellLength(j);
            unitCellParams[i * 2 * nDim + j + nDim] = phases.get(i).getUnitCellAngle(j);
        }
    sample.setUnit_cell(new DoubleDataset(unitCellParams, new int[] { nComp, 2 * nDim }));
    String aa = "angstrom", oo = "degrees";
    sample.setAttribute("unit_cell", "units",
            new StringDataset(new String[] { aa, aa, aa, oo, oo, oo }, new int[] { 2 * nDim }));
    sample.setAttribute("unit_cell", "signal", 0);
    sample.setUnit_cell_volume(
            new DoubleDataset(ArrayUtils.toPrimitive(phases.stream().map(a -> a.getUnitCellVolume())
                    .collect(Collectors.toList()).toArray(new Double[nComp])), new int[] { nComp }));
    sample.setAttribute("unit_cell_volume", "units", aa + "");
    sample.setUnit_cell_class(new StringDataset(phases.stream().map(a -> a.getCrystalSystem().getName())
            .collect(Collectors.toList()).toArray(new String[nComp]), new int[] { nComp }));
    sample.setUnit_cell_group(new StringDataset(
            phases.stream().map(a -> a.getSpaceGroup().getNumber() + ": " + a.getSpaceGroup().getName())
                    .collect(Collectors.toList()).toArray(new String[nComp]),
            new int[] { nComp }));

    // TODO: Crystal structure

    // Densities and volume fractions and concentrations
    DoubleDataset theoreticalDensities = new DoubleDataset(ArrayUtils.toPrimitive(
            phases.stream().map(a -> a.getDensity()).collect(Collectors.toList()).toArray(new Double[nComp])),
            new int[] { nComp });
    sample.setField("theoretical_density", theoreticalDensities);
    sample.setAttribute("theoretical_density", "units", "g cm?");
    // Assuming volume fraction of the total volume, not the non-void volume.
    // TODO: sort out mass versus volume fractions
    // mass fractions of the non-void matter
    DoubleDataset massFractions = new DoubleDataset(
            ArrayUtils.toPrimitive(fractions.toArray(new Double[nComp])), new int[] { nComp });

    // The overall density of the powder is the sum of masses divided by the sum of masses divided by densities
    double overallDensity = ((double) massFractions.sum())
            / ((double) Maths.divide(massFractions, theoreticalDensities).sum());
    // The net density is the density of the powder times the volume fraction
    sample.setDensityScalar(overallDensity * this.getPackingFraction());

    // volume fraction of the phase in the powder
    DoubleDataset volumeFractions = (DoubleDataset) Maths
            .multiply(Maths.divide(massFractions, theoreticalDensities), overallDensity);
    // volume fraction of the overall volume
    volumeFractions.imultiply(this.getPackingFraction());
    // concentrations: mass divided by total volume
    DoubleDataset concentrations = (DoubleDataset) Maths.multiply(theoreticalDensities, volumeFractions);
    sample.setConcentration(concentrations);
    sample.setVolume_fraction(volumeFractions);
    // total mass of the sample

    // Actual beam added during data collection, proposed beam not contained in this class
    {
        // TODO: Theoretical PDF not yet calculable 
    }
    {
        // Container not yet defined
    }
    // Dark frame added during data collection
    // Calibration added during data collection (at least of the calibration)
    // Mask added during data collection
    // Sample images added during data collection
    return sample;
}

From source file:utils.DBSCAN.MyDoubleArrayDBS.java

public MyDoubleArrayDBS(Double[] data) {
    super(ArrayUtils.toPrimitive(data));
}

From source file:v201109.GetAllAccountChanges.java

public static void main(String[] args) {
    try {/*from  w  w  w . ja  v a2 s. c  om*/
        // Log SOAP XML request and response.
        AdWordsServiceLogger.log();

        // Get AdWordsUser from "~/adwords.properties".
        AdWordsUser user = new AdWordsUser();

        // Get the CampaignService.
        CampaignServiceInterface campaignService = user.getService(AdWordsService.V201109.CAMPAIGN_SERVICE);

        // Get the CustomerSyncService.
        CustomerSyncServiceInterface customerSyncService = user
                .getService(AdWordsService.V201109.CUSTOMER_SYNC_SERVICE);

        // Get a list of all campaign IDs.
        List<Long> campaignIds = new ArrayList<Long>();
        Selector selector = new Selector();
        selector.setFields(new String[] { "Id" });
        CampaignPage campaigns = campaignService.get(selector);
        if (campaigns.getEntries() != null) {
            for (Campaign campaign : campaigns.getEntries()) {
                campaignIds.add(campaign.getId());
            }
        }

        // Create date time range for the past 24 hours.
        DateTimeRange dateTimeRange = new DateTimeRange();
        dateTimeRange.setMin(new SimpleDateFormat("yyyyMMdd hhmmss")
                .format(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24)));
        dateTimeRange.setMax(new SimpleDateFormat("yyyyMMdd hhmmss").format(new Date()));

        // Create selector.
        CustomerSyncSelector customerSyncSelector = new CustomerSyncSelector();
        customerSyncSelector.setDateTimeRange(dateTimeRange);
        customerSyncSelector.setCampaignIds(ArrayUtils.toPrimitive(campaignIds.toArray(new Long[] {})));

        // Get all account changes for campaign.
        CustomerChangeData accountChanges = customerSyncService.get(customerSyncSelector);

        // Display changes.
        if (accountChanges != null && accountChanges.getChangedCampaigns() != null) {
            System.out.println("Most recent change: " + accountChanges.getLastChangeTimestamp() + "\n");
            for (CampaignChangeData campaignChanges : accountChanges.getChangedCampaigns()) {
                System.out
                        .println("Campaign with id \"" + campaignChanges.getCampaignId() + "\" was changed: ");
                System.out.println("\tCampaign changed status: " + campaignChanges.getCampaignChangeStatus());
                if (campaignChanges.getCampaignChangeStatus() != ChangeStatus.NEW) {
                    System.out.println("\tAdded ad extensions: "
                            + getFormattedList(campaignChanges.getAddedAdExtensions()));
                    System.out.println("\tAdded campaign criteria: "
                            + getFormattedList(campaignChanges.getAddedCampaignCriteria()));
                    System.out.println(
                            "\tAdded campaign targeting: " + campaignChanges.getCampaignTargetingChanged());
                    System.out.println("\tDeleted ad extensions: "
                            + getFormattedList(campaignChanges.getDeletedAdExtensions()));
                    System.out.println("\tDeleted campaign criteria: "
                            + getFormattedList(campaignChanges.getDeletedCampaignCriteria()));

                    if (campaignChanges.getChangedAdGroups() != null) {
                        for (AdGroupChangeData adGroupChanges : campaignChanges.getChangedAdGroups()) {
                            System.out.println("\tAd goup with id \"" + adGroupChanges.getAdGroupId()
                                    + "\" was changed: ");
                            System.out.println(
                                    "\t\tAd goup changed status: " + adGroupChanges.getAdGroupChangeStatus());
                            if (adGroupChanges.getAdGroupChangeStatus() != ChangeStatus.NEW) {
                                System.out.println(
                                        "\t\tAds changed: " + getFormattedList(adGroupChanges.getChangedAds()));
                                System.out.println("\t\tCriteria changed: "
                                        + getFormattedList(adGroupChanges.getChangedCriteria()));
                                System.out.println("\t\tCriteria deleted: "
                                        + getFormattedList(adGroupChanges.getDeletedCriteria()));
                            }
                        }
                    }
                }
                System.out.println("");
            }
        } else {
            System.out.println("No account changes were found.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:v201109_1.GetAllAccountChanges.java

public static void main(String[] args) {
    try {//ww  w . j  a v  a 2  s. co m
        // Log SOAP XML request and response.
        AdWordsServiceLogger.log();

        // Get AdWordsUser from "~/adwords.properties".
        AdWordsUser user = new AdWordsUser();

        // Get the CampaignService.
        CampaignServiceInterface campaignService = user.getService(AdWordsService.V201109_1.CAMPAIGN_SERVICE);

        // Get the CustomerSyncService.
        CustomerSyncServiceInterface customerSyncService = user
                .getService(AdWordsService.V201109_1.CUSTOMER_SYNC_SERVICE);

        // Get a list of all campaign IDs.
        List<Long> campaignIds = new ArrayList<Long>();
        Selector selector = new Selector();
        selector.setFields(new String[] { "Id" });
        CampaignPage campaigns = campaignService.get(selector);
        if (campaigns.getEntries() != null) {
            for (Campaign campaign : campaigns.getEntries()) {
                campaignIds.add(campaign.getId());
            }
        }

        // Create date time range for the past 24 hours.
        DateTimeRange dateTimeRange = new DateTimeRange();
        dateTimeRange.setMin(new SimpleDateFormat("yyyyMMdd hhmmss")
                .format(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24)));
        dateTimeRange.setMax(new SimpleDateFormat("yyyyMMdd hhmmss").format(new Date()));

        // Create selector.
        CustomerSyncSelector customerSyncSelector = new CustomerSyncSelector();
        customerSyncSelector.setDateTimeRange(dateTimeRange);
        customerSyncSelector.setCampaignIds(ArrayUtils.toPrimitive(campaignIds.toArray(new Long[] {})));

        // Get all account changes for campaign.
        CustomerChangeData accountChanges = customerSyncService.get(customerSyncSelector);

        // Display changes.
        if (accountChanges != null && accountChanges.getChangedCampaigns() != null) {
            System.out.println("Most recent change: " + accountChanges.getLastChangeTimestamp() + "\n");
            for (CampaignChangeData campaignChanges : accountChanges.getChangedCampaigns()) {
                System.out
                        .println("Campaign with id \"" + campaignChanges.getCampaignId() + "\" was changed: ");
                System.out.println("\tCampaign changed status: " + campaignChanges.getCampaignChangeStatus());
                if (campaignChanges.getCampaignChangeStatus() != ChangeStatus.NEW) {
                    System.out.println("\tAdded ad extensions: "
                            + getFormattedList(campaignChanges.getAddedAdExtensions()));
                    System.out.println("\tAdded campaign criteria: "
                            + getFormattedList(campaignChanges.getAddedCampaignCriteria()));
                    System.out.println(
                            "\tAdded campaign targeting: " + campaignChanges.getCampaignTargetingChanged());
                    System.out.println("\tDeleted ad extensions: "
                            + getFormattedList(campaignChanges.getDeletedAdExtensions()));
                    System.out.println("\tDeleted campaign criteria: "
                            + getFormattedList(campaignChanges.getDeletedCampaignCriteria()));

                    if (campaignChanges.getChangedAdGroups() != null) {
                        for (AdGroupChangeData adGroupChanges : campaignChanges.getChangedAdGroups()) {
                            System.out.println("\tAd goup with id \"" + adGroupChanges.getAdGroupId()
                                    + "\" was changed: ");
                            System.out.println(
                                    "\t\tAd goup changed status: " + adGroupChanges.getAdGroupChangeStatus());
                            if (adGroupChanges.getAdGroupChangeStatus() != ChangeStatus.NEW) {
                                System.out.println(
                                        "\t\tAds changed: " + getFormattedList(adGroupChanges.getChangedAds()));
                                System.out.println("\t\tCriteria changed: "
                                        + getFormattedList(adGroupChanges.getChangedCriteria()));
                                System.out.println("\t\tCriteria deleted: "
                                        + getFormattedList(adGroupChanges.getDeletedCriteria()));
                            }
                        }
                    }
                }
                System.out.println("");
            }
        } else {
            System.out.println("No account changes were found.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}