Search in sources :

Example 6 with CSVWriter

use of com.opencsv.CSVWriter in project ice by JBEI.

the class SampleCSV method generate.

public String generate() throws IOException {
    try {
        String[] header = reader.readNext();
        int headerLength = header.length;
        EntryDAO dao = DAOFactory.getEntryDAO();
        Path path = Paths.get(Utils.getConfigValue(ConfigurationKey.TEMPORARY_DIRECTORY), UUID.randomUUID().toString());
        FileWriter fileWriter = new FileWriter(path.toFile());
        BufferedWriter writer = new BufferedWriter(fileWriter);
        CSVWriter csvWriter = new CSVWriter(writer);
        csvWriter.writeNext(new String[] { "Well", "PartID (Strain)" });
        for (String[] line : reader) {
            if (line.length != headerLength) {
                Logger.info("Skipping line");
                continue;
            }
            String alias = line[0];
            String name = line[1];
            List<Entry> entries = dao.getMatching(name, alias, EntryType.PLASMID);
            if (entries.size() != 1) {
                Logger.error(entries.size() + " found for " + name + " " + alias);
                continue;
            }
            Entry plasmid = entries.get(0);
            List<Entry> parents = dao.getParents(plasmid.getId());
            if (parents.size() != 1) {
                Logger.error("Found " + parents.size() + " for " + name + " " + alias);
                continue;
            }
            Entry strain = parents.get(0);
            String locationLine = line[headerLength - 1];
            locationLine = locationLine.substring(locationLine.lastIndexOf('-') + 1);
            if (locationLine.length() == 2)
                locationLine = locationLine.charAt(0) + "0" + locationLine.charAt(1);
            csvWriter.writeNext(new String[] { locationLine, strain.getPartNumber() });
        }
        csvWriter.close();
        return path.getFileName().toString();
    } catch (CsvValidationException e) {
        throw new IOException(e);
    }
}
Also used : Path(java.nio.file.Path) Entry(org.jbei.ice.storage.model.Entry) HasEntry(org.jbei.ice.lib.entry.HasEntry) CsvValidationException(com.opencsv.exceptions.CsvValidationException) CSVWriter(com.opencsv.CSVWriter) EntryDAO(org.jbei.ice.storage.hibernate.dao.EntryDAO)

Example 7 with CSVWriter

use of com.opencsv.CSVWriter in project SIMVA-SoS by SESoS.

the class Executor method Perform_Debug_Experiment.

public static void Perform_Debug_Experiment(NormalDistributor distributor, Simulator sim, String caseName) throws IOException {
    int endTick = 6000;
    for (double alpha_beta : ARR_ALPHA_BETA) {
        Date nowDate = new Date();
        SimpleDateFormat transFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String pre = transFormat.format(nowDate);
        String outputName = caseName + "_result/" + pre + caseName + String.format("%.3f", alpha_beta) + "_debug.csv";
        CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8"), ',', '"');
        // Initialize Patient map
        sim.getScenario().init();
        // 매번 다른 distribution 이 필요함
        ArrayList<Integer> list = new ArrayList<>();
        list.clear();
        list = distributor.getDistributionArray(500);
        sim.setActionPlan(list);
        // Simulation!
        sim.execute();
        SIMResult res = sim.getResult();
        HashMap<Integer, DebugTick> debugTraces = sim.getDebugTraces();
        sim.reset();
        sim.setActionPlan(list);
        cw.close();
    }
}
Also used : CSVWriter(com.opencsv.CSVWriter) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) SimpleDateFormat(java.text.SimpleDateFormat)

Example 8 with CSVWriter

use of com.opencsv.CSVWriter in project SIMVA-SoS by SESoS.

the class RobotMain method main.

public static void main(String[] args) throws IOException {
    RobotScenario robot = new RobotScenario(0);
    Simulator sim = new Simulator(robot);
    BaseChecker checker = new BaseChecker();
    checker.init(sim.getScenario().getEndTick(), 3, BaseChecker.comparisonType.EQUAL_TO);
    SPRTMethod sprt = new SPRTMethod(0.05, 0.05, 0.01);
    sprt.setLessCheck();
    for (int j = 0; j < 10; j++) {
        String outputName = "robot_result/SIM_robot_" + (j + 1) + ".csv";
        CSVWriter cw = new CSVWriter(new OutputStreamWriter(new FileOutputStream(outputName), "UTF-8"), ',', '"');
        cw.writeNext(new String[] { "prob", "num_of_samples", "result" });
        ArrayList<RobotResult> resList = new ArrayList<>();
        for (int trial = 1; trial <= 200; trial++) {
            for (int i = 1; i < 100; i++) {
                double theta = 0.01 * i;
                sprt.setExpression(theta);
                while (!sprt.checkStopCondition()) {
                    sim.execute();
                    System.out.println(checker.evaluateSample(sim.getResult()));
                    int result = checker.evaluateSample(sim.getResult());
                    if (result == 1)
                        result = 0;
                    else
                        result = 1;
                    sprt.updateResult(result);
                    sim.reset();
                }
                // Result
                boolean h0 = sprt.getResult();
                int numSamples = sprt.getNumSamples();
                sprt.reset();
                if (h0)
                    System.out.print("T");
                else
                    System.out.print("F");
                if (resList.size() < 99)
                    resList.add(new RobotResult(h0, numSamples, theta));
                else {
                    RobotResult res = resList.get(i - 1);
                    res.updateResult(numSamples);
                    resList.set(i - 1, res);
                }
            }
            System.out.println();
        }
        for (RobotResult r : resList) {
            System.out.print(".");
            cw.writeNext(r.getArr());
        }
        System.out.println();
        cw.close();
    }
}
Also used : SPRTMethod(kr.ac.kaist.se.simulator.method.SPRTMethod) ArrayList(java.util.ArrayList) CSVWriter(com.opencsv.CSVWriter) BaseChecker(kr.ac.kaist.se.mc.BaseChecker) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) Simulator(kr.ac.kaist.se.simulator.Simulator)

Example 9 with CSVWriter

use of com.opencsv.CSVWriter in project ice by JBEI.

the class EntriesAsCSV method writeList.

/**
     * Iterate through list of entries and extract values
     *
     * @param userId identifier of user making request
     * @throws IOException on Exception write values to file
     */
private void writeList(String userId, EntryField... fields) throws IOException {
    // filter entries based on what the user is allowed to see if the user is not an admin
    Account account = this.accountDAO.getByEmail(userId);
    if (account.getType() != AccountType.ADMIN) {
        List<Group> accountGroups = new GroupController().getAllGroups(account);
        entries = permissionDAO.getCanReadEntries(account, accountGroups, entries);
    }
    if (entries == null) {
        Logger.warn("No entries to convert to csv format");
        return;
    }
    // write headers
    Path tmpPath = Paths.get(Utils.getConfigValue(ConfigurationKey.TEMPORARY_DIRECTORY));
    File tmpFile = File.createTempFile("ice-", ".csv", tmpPath.toFile());
    csvPath = tmpFile.toPath();
    FileWriter fileWriter = new FileWriter(tmpFile);
    if (fields == null || fields.length == 0)
        fields = getEntryFields();
    String[] headers = getCSVHeaders(fields);
    Set<Long> sequenceSet = new HashSet<>();
    try (CSVWriter writer = new CSVWriter(fileWriter)) {
        writer.writeNext(headers);
        // write entry fields
        for (long entryId : entries) {
            Entry entry = dao.get(entryId);
            //  get contents and write data out
            String[] line = new String[fields.length + 3];
            line[0] = entry.getCreationTime().toString();
            line[1] = entry.getPartNumber();
            int i = 1;
            for (EntryField field : fields) {
                line[i + 1] = EntryUtil.entryFieldToValue(entry, field);
                i += 1;
            }
            if (this.includeSequences && sequenceDAO.hasSequence(entryId)) {
                line[i + 1] = getSequenceName(entry);
                sequenceSet.add(entryId);
            } else {
                line[i + 1] = "";
            }
            writer.writeNext(line);
        }
    }
    writeZip(userId, sequenceSet);
}
Also used : Path(java.nio.file.Path) Account(org.jbei.ice.storage.model.Account) Group(org.jbei.ice.storage.model.Group) GroupController(org.jbei.ice.lib.group.GroupController) CSVWriter(com.opencsv.CSVWriter) EntryField(org.jbei.ice.lib.dto.entry.EntryField) Entry(org.jbei.ice.storage.model.Entry) ZipEntry(java.util.zip.ZipEntry) HashSet(java.util.HashSet)

Example 10 with CSVWriter

use of com.opencsv.CSVWriter in project opennms by OpenNMS.

the class ExportAssetsServlet method doGet.

/**
 * {@inheritDoc}
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Asset[] assets = null;
    try {
        assets = this.model.getAllAssets();
    } catch (SQLException e) {
        throw new ServletException("Database exception", e);
    }
    response.setContentType("text/plain");
    CSVWriter out = new CSVWriter(response.getWriter());
    String[] header = { "Node Label", "Node ID", "Category", "Manufacturer", "Vendor", "Model Number", "Serial Number", "Description", "Circuit ID", "Asset Number", "Operating System", "Rack", "Slot", "Port", "Region", "Division", "Department", "Address 1", "Address 2", "City", "State", "Zip", "Building", "Floor", "Room", "Vendor Phone", "Vendor Fax", "Date Installed", "Lease", "Lease Expires", "Support Phone", "Maint Contract", "Vendor Asset Number", "Maint Contract Expires", "Display Category", "Notification Category", "Poller Category", "Threshold Category", "Username", "Password", "Enable", "Connection", "Auto Enable", "Comments", "Cpu", "Ram", "Storage Controller", "HDD 1", "HDD 2", "HDD 3", "HDD 4", "HDD 5", "HDD 6", "Number of power supplies", "Inputpower", "Additional hardware", "Admin", "SNMP Community", "Rack unit height", "Country", "Longitude", "Latitude" };
    out.writeNext(header);
    // print a single line for each asset
    for (int i = 0; i < assets.length; i++) {
        Asset asset = assets[i];
        ArrayList<String> entries = new ArrayList<>();
        entries.add(NetworkElementFactory.getInstance(getServletContext()).getNodeLabel(asset.getNodeId()));
        entries.add(Integer.toString(asset.getNodeId()));
        entries.add(asset.getCategory());
        entries.add(asset.getManufacturer());
        entries.add(asset.getVendor());
        entries.add(asset.getModelNumber());
        entries.add(asset.getSerialNumber());
        entries.add(asset.getDescription());
        entries.add(asset.getCircuitId());
        entries.add(asset.getAssetNumber());
        entries.add(asset.getOperatingSystem());
        entries.add(asset.getRack());
        entries.add(asset.getSlot());
        entries.add(asset.getPort());
        entries.add(asset.getRegion());
        entries.add(asset.getDivision());
        entries.add(asset.getDepartment());
        entries.add(asset.getAddress1());
        entries.add(asset.getAddress2());
        entries.add(asset.getCity());
        entries.add(asset.getState());
        entries.add(asset.getZip());
        entries.add(asset.getBuilding());
        entries.add(asset.getFloor());
        entries.add(asset.getRoom());
        entries.add(asset.getVendorPhone());
        entries.add(asset.getVendorFax());
        entries.add(asset.getDateInstalled());
        entries.add(asset.getLease());
        entries.add(asset.getLeaseExpires());
        entries.add(asset.getSupportPhone());
        entries.add(asset.getMaintContract());
        entries.add(asset.getVendorAssetNumber());
        entries.add(asset.getMaintContractExpires());
        entries.add(asset.getDisplayCategory());
        entries.add(asset.getNotifyCategory());
        entries.add(asset.getPollerCategory());
        entries.add(asset.getThresholdCategory());
        entries.add(asset.getUsername());
        entries.add(asset.getPassword());
        entries.add(asset.getEnable());
        entries.add(asset.getConnection());
        entries.add(asset.getAutoenable());
        entries.add(asset.getComments());
        entries.add(asset.getCpu());
        entries.add(asset.getRam());
        entries.add(asset.getStoragectrl());
        entries.add(asset.getHdd1());
        entries.add(asset.getHdd2());
        entries.add(asset.getHdd3());
        entries.add(asset.getHdd4());
        entries.add(asset.getHdd5());
        entries.add(asset.getHdd6());
        entries.add(asset.getNumpowersupplies());
        entries.add(asset.getInputpower());
        entries.add(asset.getAdditionalhardware());
        entries.add(asset.getAdmin());
        entries.add(asset.getSnmpcommunity());
        entries.add(asset.getRackunitheight());
        entries.add(asset.getCountry());
        entries.add(asset.getLongitude());
        entries.add(asset.getLatitude());
        out.writeNext(entries.toArray(new String[0]));
    }
    out.close();
}
Also used : ServletException(javax.servlet.ServletException) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) CSVWriter(com.opencsv.CSVWriter)

Aggregations

CSVWriter (com.opencsv.CSVWriter)21 OutputStreamWriter (java.io.OutputStreamWriter)7 FileOutputStream (java.io.FileOutputStream)5 FileWriter (java.io.FileWriter)5 File (java.io.File)4 Path (java.nio.file.Path)4 ArrayList (java.util.ArrayList)4 Entry (org.jbei.ice.storage.model.Entry)4 IOException (java.io.IOException)3 Writer (java.io.Writer)3 HashSet (java.util.HashSet)3 SPRTMethod (kr.ac.kaist.se.simulator.method.SPRTMethod)3 GroupController (org.jbei.ice.lib.group.GroupController)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 StringWriter (java.io.StringWriter)2 SimpleDateFormat (java.text.SimpleDateFormat)2 ZipEntry (java.util.zip.ZipEntry)2 BaseChecker (kr.ac.kaist.se.mc.BaseChecker)2 Simulator (kr.ac.kaist.se.simulator.Simulator)2 EntryFieldLabel (org.jbei.ice.lib.dto.entry.EntryFieldLabel)2