Search in sources :

Example 1 with Main

use of com.icodici.universa.node2.Main in project SoftUni by kostovhg.

the class p14_ExportToExcel method main.

public static void main(String[] args) throws IOException {
    ArrayList<Object[]> allLines = new ArrayList<>();
    allLines.add(new Object[] { "FN", "First name", "Last Name", "Email", "Age", "Group", "Grade1", "Grade2", "Grade3", "Grade4", "Phones" });
    new BufferedReader(new FileReader("StudentsData.txt")).lines().map(x -> x.split("\\t")).filter(x -> !x[0].equals("FN")).forEach(allLines::add);
    // Create workbook and worksheet object
    int rowStart = 2;
    int columnStart = 0;
    int totalRows = allLines.size();
    int totalCols = allLines.get(0).length;
    int rowEnd = totalRows + rowStart - 1;
    int colEnd = totalCols + columnStart - 1;
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("SoftUniOOPCourseResults");
    CellStyle style1 = workbook.createCellStyle();
    style1.setAlignment(HorizontalAlignment.RIGHT);
    XSSFDataFormat intFormat = workbook.createDataFormat();
    style1.setDataFormat(intFormat.getFormat("0"));
    CellStyle style2 = workbook.createCellStyle();
    XSSFDataFormat strFormat = workbook.createDataFormat();
    style2.setDataFormat(strFormat.getFormat("General"));
    style2.setAlignment(HorizontalAlignment.LEFT);
    XSSFRow row;
    XSSFCell cell;
    // Create an object of type XSSFTable
    XSSFTable myTable = sheet.createTable();
    // Get CTTable object
    CTTable cttable = myTable.getCTTable();
    cttable.setTotalsRowShown(false);
    // Define the required style1 for the table
    CTTableStyleInfo table_style = cttable.addNewTableStyleInfo();
    table_style.setName("TableStyleLight14");
    // Set table style option
    table_style.setShowColumnStripes(false);
    table_style.setShowRowStripes(true);
    // define the data range including headers
    AreaReference my_data_range = new AreaReference(new CellReference(rowStart, columnStart), new CellReference(rowEnd, colEnd));
    // Set range to the table
    cttable.setRef(my_data_range.formatAsString());
    cttable.setDisplayName("Students");
    cttable.setName("Students");
    cttable.setId(1L);
    CTTableColumns columns = cttable.addNewTableColumns();
    CTAutoFilter autoFilter = cttable.addNewAutoFilter();
    columns.setCount(totalCols);
    // Define Header Information for the table
    for (int i = columnStart; i <= colEnd; i++) {
        CTTableColumn column = columns.addNewTableColumn();
        column.setName(allLines.get(0)[i].toString());
        column.setId(i + 1);
    }
    sheet.setAutoFilter(new CellRangeAddress(rowStart, rowStart, columnStart, colEnd));
    // Add remaining Table data
    row = sheet.createRow((short) 0);
    cell = row.createCell((short) 0);
    sheet.addMergedRegion(new CellRangeAddress(0, rowStart - 1, columnStart, colEnd));
    cell.setCellValue("SoftUni OOP Course Results");
    CellStyle bolded = workbook.createCellStyle();
    bolded.setAlignment(HorizontalAlignment.CENTER);
    XSSFFont myFont = workbook.createFont();
    myFont.setBold(true);
    myFont.setFontHeightInPoints((short) 30);
    bolded.setFont(myFont);
    cell.setCellStyle(bolded);
    int rowNum = rowStart;
    for (Object[] datatype : allLines) {
        XSSFRow inRow = sheet.createRow(rowNum++);
        int colNum = columnStart;
        for (Object field : datatype) {
            XSSFCell inCell = inRow.createCell(colNum++);
            if (isInt(field)) {
                inCell.setCellStyle(style1);
                inCell.setCellType(CellType.NUMERIC);
                inCell.setCellValue((Double) field);
            } else {
                inCell.setCellStyle(style2);
                inCell.setCellType(CellType.STRING);
                inCell.setCellValue((String) field);
            }
        }
    }
    for (int i = 1; i <= 11; i++) {
        sheet.autoSizeColumn(i);
    }
    try {
        FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
        workbook.write(outputStream);
        workbook.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Done");
}
Also used : org.apache.poi.ss.usermodel(org.apache.poi.ss.usermodel) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress) org.apache.poi.xssf.usermodel(org.apache.poi.xssf.usermodel) AreaReference(org.apache.poi.ss.util.AreaReference) java.io(java.io) org.openxmlformats.schemas.spreadsheetml.x2006.main(org.openxmlformats.schemas.spreadsheetml.x2006.main) CellReference(org.apache.poi.ss.util.CellReference) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) CellReference(org.apache.poi.ss.util.CellReference) AreaReference(org.apache.poi.ss.util.AreaReference) CellRangeAddress(org.apache.poi.ss.util.CellRangeAddress)

Example 2 with Main

use of com.icodici.universa.node2.Main in project universa by UniversaBlockchain.

the class MainTest method dbSanitationTest.

@Test
public void dbSanitationTest() throws Exception {
    final int NODE_COUNT = 4;
    PrivateKey myKey = TestKeys.privateKey(NODE_COUNT);
    List<String> dbUrls = new ArrayList<>();
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t1");
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t2");
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t3");
    dbUrls.add("jdbc:postgresql://localhost:5432/universa_node_t4");
    List<Ledger> ledgers = new ArrayList<>();
    dbUrls.stream().forEach(url -> {
        try {
            clearLedger(url);
            PostgresLedger ledger = new PostgresLedger(url);
            ledgers.add(ledger);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    Random random = new Random(123);
    List<Contract> origins = new ArrayList<>();
    List<Contract> newRevisions = new ArrayList<>();
    List<Contract> newContracts = new ArrayList<>();
    final int N = 100;
    for (int i = 0; i < N; i++) {
        Contract origin = new Contract(myKey);
        origin.seal();
        origins.add(origin);
        Contract newRevision = origin.createRevision(myKey);
        if (i < N / 2) {
            // ACCEPTED
            newRevision.setOwnerKeys(TestKeys.privateKey(NODE_COUNT + 1).getPublicKey());
        } else {
        // DECLINED
        // State is equal
        }
        Contract newContract = new Contract(myKey);
        newRevision.addNewItems(newContract);
        newRevision.seal();
        newContracts.add(newContract);
        newRevisions.add(newRevision);
        int unfinishedNodesCount = random.nextInt(2) + 1;
        Set<Integer> unfinishedNodesNumbers = new HashSet<>();
        while (unfinishedNodesCount > unfinishedNodesNumbers.size()) {
            unfinishedNodesNumbers.add(random.nextInt(NODE_COUNT) + 1);
        }
        System.out.println("item# " + newRevision.getId().toBase64String().substring(0, 6) + " nodes " + unfinishedNodesNumbers.toString());
        int finalI = i;
        for (int j = 0; j < NODE_COUNT; j++) {
            boolean finished = !unfinishedNodesNumbers.contains(j + 1);
            Ledger ledger = ledgers.get(j);
            StateRecord originRecord = ledger.findOrCreate(origin.getId());
            originRecord.setExpiresAt(origin.getExpiresAt());
            originRecord.setCreatedAt(origin.getCreatedAt());
            StateRecord newRevisionRecord = ledger.findOrCreate(newRevision.getId());
            newRevisionRecord.setExpiresAt(newRevision.getExpiresAt());
            newRevisionRecord.setCreatedAt(newRevision.getCreatedAt());
            StateRecord newContractRecord = ledger.findOrCreate(newContract.getId());
            newContractRecord.setExpiresAt(newContract.getExpiresAt());
            newContractRecord.setCreatedAt(newContract.getCreatedAt());
            if (finished) {
                if (finalI < N / 2) {
                    originRecord.setState(ItemState.REVOKED);
                    newContractRecord.setState(ItemState.APPROVED);
                    newRevisionRecord.setState(ItemState.APPROVED);
                } else {
                    originRecord.setState(ItemState.APPROVED);
                    newContractRecord.setState(ItemState.UNDEFINED);
                    newRevisionRecord.setState(ItemState.DECLINED);
                }
            } else {
                originRecord.setState(ItemState.LOCKED);
                originRecord.setLockedByRecordId(newRevisionRecord.getRecordId());
                newContractRecord.setState(ItemState.LOCKED_FOR_CREATION);
                newContractRecord.setLockedByRecordId(newRevisionRecord.getRecordId());
                newRevisionRecord.setState(finalI < N / 2 ? ItemState.PENDING_POSITIVE : ItemState.PENDING_NEGATIVE);
            }
            originRecord.save();
            ledger.putItem(originRecord, origin, Instant.now().plusSeconds(3600 * 24));
            newRevisionRecord.save();
            ledger.putItem(newRevisionRecord, newRevision, Instant.now().plusSeconds(3600 * 24));
            if (newContractRecord.getState() == ItemState.UNDEFINED) {
                newContractRecord.destroy();
            } else {
                newContractRecord.save();
            }
        }
    }
    ledgers.stream().forEach(ledger -> ledger.close());
    ledgers.clear();
    List<Main> mm = new ArrayList<>();
    List<Client> clients = new ArrayList<>();
    for (int i = 0; i < NODE_COUNT; i++) {
        Main m = createMain("node" + (i + 1), false);
        mm.add(m);
        Client client = new Client(TestKeys.privateKey(i), m.myInfo, null);
        clients.add(client);
    }
    while (true) {
        try {
            for (int i = 0; i < NODE_COUNT; i++) {
                clients.get(i).getState(newRevisions.get(0));
            }
            break;
        } catch (ClientError e) {
            Thread.sleep(1000);
            mm.stream().forEach(m -> System.out.println("node#" + m.myInfo.getNumber() + " is " + (m.node.isSanitating() ? "" : "not ") + "sanitating"));
        }
    }
    Contract contract = new Contract(TestKeys.privateKey(3));
    contract.seal();
    ItemResult ir = clients.get(0).register(contract.getPackedTransaction(), 10000);
    ir.errors.toString();
    for (int i = 0; i < N; i++) {
        ItemResult rr = clients.get(i % NODE_COUNT).getState(newRevisions.get(i).getId());
        ItemState targetState = i < N / 2 ? ItemState.APPROVED : ItemState.DECLINED;
        assertEquals(rr.state, targetState);
    }
    Thread.sleep(1000);
    mm.stream().forEach(m -> m.shutdown());
    Thread.sleep(1000);
    dbUrls.stream().forEach(url -> {
        try {
            PostgresLedger ledger = new PostgresLedger(url);
            assertTrue(ledger.findUnfinished().isEmpty());
            ledger.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}
Also used : java.util(java.util) ModifyDataPermission(com.icodici.universa.contract.permissions.ModifyDataPermission) com.icodici.universa.node(com.icodici.universa.node) Data(javax.xml.crypto.Data) ZonedDateTime(java.time.ZonedDateTime) Binder(net.sergeych.tools.Binder) ChangeOwnerPermission(com.icodici.universa.contract.permissions.ChangeOwnerPermission) SimpleRole(com.icodici.universa.contract.roles.SimpleRole) SQLException(java.sql.SQLException) java.net(java.net) PublicKey(com.icodici.crypto.PublicKey) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestKeys(com.icodici.universa.node.network.TestKeys) com.icodici.universa.contract(com.icodici.universa.contract) After(org.junit.After) Duration(java.time.Duration) com.icodici.universa.node2.network(com.icodici.universa.node2.network) Path(java.nio.file.Path) Role(com.icodici.universa.contract.roles.Role) LogPrinter(net.sergeych.utils.LogPrinter) PrivateKey(com.icodici.crypto.PrivateKey) ListRole(com.icodici.universa.contract.roles.ListRole) Semaphore(java.util.concurrent.Semaphore) Do(net.sergeych.tools.Do) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) IOException(java.io.IOException) Bytes(net.sergeych.utils.Bytes) PreparedStatement(java.sql.PreparedStatement) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) DbPool(com.icodici.db.DbPool) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Approvable(com.icodici.universa.Approvable) Base64(net.sergeych.utils.Base64) BufferedLogger(net.sergeych.tools.BufferedLogger) HashId(com.icodici.universa.HashId) Ignore(org.junit.Ignore) PooledDb(com.icodici.db.PooledDb) RoleLink(com.icodici.universa.contract.roles.RoleLink) FileReader(java.io.FileReader) Assert(org.junit.Assert) Boss(net.sergeych.boss.Boss) PrivateKey(com.icodici.crypto.PrivateKey) SQLException(java.sql.SQLException) IOException(java.io.IOException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Test(org.junit.Test)

Example 3 with Main

use of com.icodici.universa.node2.Main in project universa by UniversaBlockchain.

the class CLIMain method checkContract.

/**
 * Check contract for errors. Print errors if found.
 *
 * @param contract - contract to check.
 */
private static void checkContract(Contract contract) {
    // First, check the sealed state
    if (!contract.isOk()) {
        reporter.message("The capsule is not sealed properly:");
        contract.getErrors().forEach(e -> reporter.error(e.getError().toString(), e.getObjectName(), e.getMessage()));
    }
    Yaml yaml = new Yaml();
    if (reporter.isVerboseMode()) {
        report("api level:   " + contract.getApiLevel());
        report("contract id: " + contract.getId().toBase64String());
        report("issued:      " + contract.getIssuedAt());
        report("revision:    " + contract.getRevision());
        report("created:     " + contract.getCreatedAt());
        report("expires:     " + contract.getExpiresAt());
        System.out.println();
        Set<PublicKey> keys = contract.getSealedByKeys();
        contract.getRevoking().forEach(r -> {
            try {
                ClientNetwork n = getClientNetwork();
                System.out.println();
                report("revoking item exists: " + r.getId().toBase64String());
                report("\tstate: " + n.check(r.getId()));
                HashId origin = r.getOrigin();
                boolean m = origin.equals(contract.getOrigin());
                report("\tOrigin: " + origin);
                report("\t" + (m ? "matches main contract origin" : "does not match main contract origin"));
                if (r.canBeRevoked(keys)) {
                    report("\trevocation is allowed");
                } else
                    reporter.error(Errors.BAD_REVOKE.name(), r.getId().toString(), "revocation not allowed");
            } catch (Exception clientError) {
                clientError.printStackTrace();
            }
        });
        contract.getNewItems().forEach(n -> {
            System.out.println();
            report("New item exists:      " + n.getId().toBase64String());
            Contract nc = (Contract) n;
            boolean m = nc.getOrigin().equals(contract.getOrigin());
            report("\tOrigin: " + ((Contract) n).getOrigin());
            report("\t" + (m ? "matches main contract origin" : "does not match main contract origin"));
        });
        if (keys.size() > 0) {
            report("\nSignature contains " + keys.size() + " valid key(s):\n");
            keys.forEach(k -> {
                KeyInfo i = k.info();
                report("\t✔︎ " + i.getAlgorythm() + ":" + i.getKeyLength() * 8 + ":" + i.getBase64Tag());
            });
            report("\nWhich can play roles:\n");
            contract.getRoles().forEach((name, role) -> {
                String canPlay = role.isAllowedForKeys(keys) ? "✔" : "✘";
                report("\t" + canPlay + " " + role.getName());
            });
            report("\nAnd have permissions:\n");
            contract.getPermissions().values().forEach(perm -> {
                String canPlay = perm.isAllowedForKeys(keys) ? "✔" : "✘";
                report("\t" + canPlay + " " + perm.getName());
                Binder x = DefaultBiMapper.serialize(perm.getParams());
                BufferedReader br = new BufferedReader(new StringReader(yaml.dumpAsMap(x)));
                try {
                    for (String line; (line = br.readLine()) != null; ) {
                        report("\t    " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            reporter.newLine();
        }
    }
    Multimap<String, Permission> permissions = contract.getPermissions();
    Collection<Permission> sjs = permissions.get("split_join");
    if (sjs != null) {
        sjs.forEach(sj -> checkSj(contract, sj));
    }
    try {
        contract.check();
    } catch (Quantiser.QuantiserException e) {
        addError("QUANTIZER_COST_LIMIT", contract.toString(), e.getMessage());
    } catch (Exception e) {
        addError(Errors.FAILURE.name(), contract.toString(), e.getMessage());
    }
    addErrors(contract.getErrors());
    if (contract.getErrors().size() == 0) {
        report("Contract is valid");
    }
}
Also used : PublicKey(com.icodici.crypto.PublicKey) Quantiser(com.icodici.universa.node2.Quantiser) Yaml(org.yaml.snakeyaml.Yaml) BackingStoreException(java.util.prefs.BackingStoreException) OptionException(joptsimple.OptionException) Binder(net.sergeych.tools.Binder) KeyInfo(com.icodici.crypto.KeyInfo) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Permission(com.icodici.universa.contract.permissions.Permission) Contract(com.icodici.universa.contract.Contract)

Example 4 with Main

use of com.icodici.universa.node2.Main in project universa by UniversaBlockchain.

the class CLIMainTest method createMain.

static Main createMain(String name, boolean nolog) throws InterruptedException {
    String path = new File("src/test_node_config_v2/" + name).getAbsolutePath();
    System.out.println(path);
    String[] args = new String[] { "--test", "--config", path, nolog ? "--nolog" : "" };
    Main main = new Main(args);
    main.config.setTransactionUnitsIssuerKeyData(Bytes.fromHex("1E 08 1C 01 00 01 C4 00 01 B9 C7 CB 1B BA 3C 30 80 D0 8B 29 54 95 61 41 39 9E C6 BB 15 56 78 B8 72 DC 97 58 9F 83 8E A0 B7 98 9E BB A9 1D 45 A1 6F 27 2F 61 E0 26 78 D4 9D A9 C2 2F 29 CB B6 F7 9F 97 60 F3 03 ED 5C 58 27 27 63 3B D3 32 B5 82 6A FB 54 EA 26 14 E9 17 B6 4C 5D 60 F7 49 FB E3 2F 26 52 16 04 A6 5E 6E 78 D1 78 85 4D CD 7B 71 EB 2B FE 31 39 E9 E0 24 4F 58 3A 1D AE 1B DA 41 CA 8C 42 2B 19 35 4B 11 2E 45 02 AD AA A2 55 45 33 39 A9 FD D1 F3 1F FA FE 54 4C 2E EE F1 75 C9 B4 1A 27 5C E9 C0 42 4D 08 AD 3E A2 88 99 A3 A2 9F 70 9E 93 A3 DF 1C 75 E0 19 AB 1F E0 82 4D FF 24 DA 5D B4 22 A0 3C A7 79 61 41 FD B7 02 5C F9 74 6F 2C FE 9A DD 36 44 98 A2 37 67 15 28 E9 81 AC 40 CE EF 05 AA 9E 36 8F 56 DA 97 10 E4 10 6A 32 46 16 D0 3B 6F EF 80 41 F3 CC DA 14 74 D1 BF 63 AC 28 E0 F1 04 69 63 F7"));
    main.config.getKeysWhiteList().add(main.config.getTransactionUnitsIssuerKey());
    main.waitReady();
    return main;
}
Also used : File(java.io.File) Main(com.icodici.universa.node2.Main)

Example 5 with Main

use of com.icodici.universa.node2.Main in project universa by UniversaBlockchain.

the class CLIMainTest method createLocalNetwork.

public static void createLocalNetwork() throws Exception {
    for (int i = 0; i < 3; i++) localNodes.add(createMain("node" + (i + 1), false));
    Main main = localNodes.get(0);
    assertEquals("http://localhost:8080", main.myInfo.internalUrlString());
    assertEquals("http://localhost:8080", main.myInfo.publicUrlString());
    assertEquals(main.cache, main.node.getCache());
}
Also used : Main(com.icodici.universa.node2.Main)

Aggregations

PublicKey (com.icodici.crypto.PublicKey)2 Main (com.icodici.universa.node2.Main)2 File (java.io.File)2 Binder (net.sergeych.tools.Binder)2 KeyInfo (com.icodici.crypto.KeyInfo)1 PrivateKey (com.icodici.crypto.PrivateKey)1 DbPool (com.icodici.db.DbPool)1 PooledDb (com.icodici.db.PooledDb)1 Approvable (com.icodici.universa.Approvable)1 HashId (com.icodici.universa.HashId)1 com.icodici.universa.contract (com.icodici.universa.contract)1 Contract (com.icodici.universa.contract.Contract)1 ChangeOwnerPermission (com.icodici.universa.contract.permissions.ChangeOwnerPermission)1 ModifyDataPermission (com.icodici.universa.contract.permissions.ModifyDataPermission)1 Permission (com.icodici.universa.contract.permissions.Permission)1 ListRole (com.icodici.universa.contract.roles.ListRole)1 Role (com.icodici.universa.contract.roles.Role)1 RoleLink (com.icodici.universa.contract.roles.RoleLink)1 SimpleRole (com.icodici.universa.contract.roles.SimpleRole)1 com.icodici.universa.node (com.icodici.universa.node)1