Skip to content
Snippets Groups Projects
Commit c8d09a54 authored by Benoit Lavenier's avatar Benoit Lavenier
Browse files

Add nuiton-config, and plug it to Unit Test

parent d0f5f14d
Branches
Tags
No related merge requests found
Showing
with 1443 additions and 289 deletions
......@@ -631,8 +631,8 @@ to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
......@@ -652,7 +652,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
......@@ -672,4 +672,3 @@ may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
......@@ -4,6 +4,20 @@ ucoinj
uCoin Java API
To compile :
## Compile
mvn install
\ No newline at end of file
Compilation use [Maven 3](http://maven.apache.org/).
```bash
$ mvn install
```
## Roadmap
In progress :
- GET requests (no auth API)
What TODO Next ?
- Add crypto libray NaCl (Kalium ?)
- POST requests (with auth)
\ No newline at end of file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--parent> <groupId>fr.ifremer</groupId> <artifactId>common</artifactId>
<version>1.1-SNAPSHOT</version> </parent -->
<!--parent> <groupId>fr.ifremer</groupId> <artifactId>common</artifactId> <version>1.1-SNAPSHOT</version> </parent -->
<groupId>io.ucoin</groupId>
<artifactId>ucoinj</artifactId>
......@@ -11,12 +10,13 @@
<name>UCoin Java Client</name>
<properties>
<!-- source file encoding -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- UCoin version -->
<ucoin.version></ucoin.version>
<ucoin.version>0.9.7</ucoin.version>
<!-- Commons versions -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<file.encoding>UTF-8</file.encoding>
<log4j.version>1.2.16</log4j.version>
<slf4j.version>1.7.5</slf4j.version>
......@@ -26,6 +26,9 @@
<xml-apis.version>2.0.2</xml-apis.version>
<gson.version>2.2.2</gson.version>
<nuitonConfigVersion>3.0-rc-2</nuitonConfigVersion>
<nuitonI18nVersion>3.3</nuitonI18nVersion>
<!-- UI versions -->
<wicket.version>6.14.0</wicket.version>
<jquery-ui.version>6.14.0</jquery-ui.version>
......@@ -35,138 +38,60 @@
<servlet-api.version>2.5</servlet-api.version>
<!-- Unit test -->
<junit.version>4.8.1</junit.version>
<junit.version>4.12</junit.version>
<jetty.version>9.0.4.v20130625</jetty.version>
<!-- IDE & Development process -->
<maven-eclipse-plugin.version>2.9</maven-eclipse-plugin.version>
<!--license-maven-plugin config -->
<maven.license.file>${project.basedir}/LICENSE.txt</maven.license.file>
<maven.license.file>${project.basedir}/LICENSE</maven.license.file>
<license.useMissingFile>true</license.useMissingFile>
<license.failIfWarning>true</license.failIfWarning>
<license.organizationName>EIS</license.organizationName>
<license.licenseName>agpl_v3</license.licenseName>
<license.licenseName>gpl_v3</license.licenseName>
<!-- release config -->
<autoVersionSubmodules>true</autoVersionSubmodules>
<goals>deploy</goals>
<arguments></arguments>
<preparationGoals>verify</preparationGoals>
<locales>en,fr</locales>
<!-- I18n configuration -->
<i18n.bundles>fr_FR,en_GB</i18n.bundles>
<i18n.silent>true</i18n.silent>
<!-- by default, use maven 2 source base dir -->
<maven.src.dir>${basedir}/src</maven.src.dir>
<!-- where to generate sources -->
<maven.gen.dir>${project.build.directory}/generated-sources</maven.gen.dir>
</properties>
<licenses>
<license>
<name>Affero General Public License (AGPL)</name>
<url>http://www.gnu.org/licenses/agpl.txt</url>
<name>General Public License (GPL) v3</name>
<url>http://www.gnu.org/licenses/gpl-3.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<inceptionYear>2014</inceptionYear>
<!-- SVN repository -->
<modules>
<module>ucoinj-core</module>
<!-- <module>ucoinj-web</module> -->
</modules>
<scm>
<url>https://github.com/blavenie/ucoinj/</url>
<connection>scm:svn:https://github.com/blavenie/ucoinj/</connection>
<developerConnection>scm:svn:https://github.com/blavenie/ucoinj/</developerConnection>
</scm>
<profiles>
<!-- perform only on a release stage when using the maven-release-plugin -->
<profile>
<id>license-profile</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<defaultGoal>generate-resources</defaultGoal>
<plugins>
<!-- add license and third-party files to build -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<executions>
<execution>
<id>attach-licenses</id>
<goals>
<goal>update-project-license</goal>
<goal>add-third-party</goal>
</goals>
<configuration>
<licenseMerges>
<licenseMerge>
The Apache Software License, Version 2.0|Apache License, Version 2.0|Apache License V2.0|Apache 2|ASF
2.0|apache-2.0|Apache Public License 2.0
</licenseMerge>
<licenseMerge>BSD License|BSD license|BSD</licenseMerge>
<licenseMerge>MIT License|MIT license|MIT</licenseMerge>
<licenseMerge>
Lesser General Public License (LPGL) v 2.1|GNU Lesser General Public License, 2.1|LGPL 2.1
</licenseMerge>
<licenseMerge>
Lesser General Public License (LPGL)|GNU Lesser General Public License|GNU LESSER GENERAL PUBLIC LICENSE|LGPL|lgpl
</licenseMerge>
<licenseMerge>
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0|Common Development and Distribution License (CDDL)
v1.0
</licenseMerge>
<licenseMerge>Indiana University Extreme! Lab Software License, vesion 1.1.1|Indiana University Extreme! Lab Software License</licenseMerge>
</licenseMerges>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- This profile update license stuff with new goal update-file-header -->
<profile>
<id>update-file-header</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<defaultGoal>process-resources</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<executions>
<execution>
<id>update-file-header</id>
<goals>
<goal>update-file-header</goal>
</goals>
<configuration>
<addSvnKeyWords>false</addSvnKeyWords>
<excludes>
<exclude>**/site/**/*.*</exclude>
<exclude>**/misc/**/*.*</exclude>
<exclude>**/webapp/jquery/**/*.*</exclude>
<exclude>**/webapp/META-INF/**/*.*</exclude>
<exclude>**/webapp/WEB-INF/**/*.*</exclude>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/jquery.tokeninput.js</exclude>
<exclude>**/jquery.watermark.js</exclude>
<exclude>**/jquery.qtip.*</exclude>
<!-- since sh scripts must begins by the line #!/bin/sh,
can not use the mojo for the mojo -->
<exclude>**/*.sh</exclude>
</excludes>
</configuration>
<phase>process-resources</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
......@@ -214,6 +139,16 @@
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-config</artifactId>
<version>${nuitonConfigVersion}</version>
</dependency>
<dependency>
<groupId>org.nuiton.i18n</groupId>
<artifactId>nuiton-i18n</artifactId>
<version>${nuitonI18nVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-core</artifactId>
......@@ -316,6 +251,13 @@
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.nuiton.i18n</groupId>
<artifactId>i18n-maven-plugin</artifactId>
<version>${nuitonI18nVersion}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
......@@ -416,21 +358,9 @@
</pluginManagement>
</build>
<!-- Repositories needed to find the dependencies
<repositories>
<repository>
<id>adagio-public-group</id>
<url>http://nexus.e-is.pro/nexus/content/groups/ucoinj</url>
<snapshots>
<enabled>true</enabled>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
<releases>
<enabled>true</enabled>
<checksumPolicy>fail</checksumPolicy>
</releases>
</repository>
</repositories>-->
<!-- Repositories needed to find the dependencies <repositories> <repository> <id>adagio-public-group</id> <url>http://nexus.e-is.pro/nexus/content/groups/ucoinj</url>
<snapshots> <enabled>true</enabled> <checksumPolicy>fail</checksumPolicy> </snapshots> <releases> <enabled>true</enabled> <checksumPolicy>fail</checksumPolicy> </releases>
</repository> </repositories> -->
<pluginRepositories>
<!-- Need for javascript minify maven plugin (yuicompressor-maven-plugin) -->
......@@ -456,8 +386,215 @@
</snapshotRepository>
</distributionManagement>
<modules>
<module>ucoinj-core</module>
<!-- <module>ucoinj-web</module> -->
</modules>
<profiles>
<!-- perform only on a release stage when using the maven-release-plugin -->
<profile>
<id>license-profile</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<defaultGoal>generate-resources</defaultGoal>
<plugins>
<!-- add license and third-party files to build -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<executions>
<execution>
<id>attach-licenses</id>
<goals>
<goal>update-project-license</goal>
<goal>add-third-party</goal>
</goals>
<configuration>
<licenseMerges>
<licenseMerge>
The Apache Software License, Version 2.0|Apache License, Version 2.0|Apache License V2.0|Apache 2|ASF
2.0|apache-2.0|Apache
Public License 2.0
</licenseMerge>
<licenseMerge>BSD License|BSD license|BSD</licenseMerge>
<licenseMerge>MIT License|MIT license|MIT</licenseMerge>
<licenseMerge>
Lesser General Public License (LPGL) v 2.1|GNU Lesser General Public License, 2.1|LGPL 2.1
</licenseMerge>
<licenseMerge>
Lesser General Public License (LPGL)|GNU Lesser General Public License|GNU LESSER GENERAL PUBLIC LICENSE|LGPL|lgpl
</licenseMerge>
<licenseMerge>
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0|Common Development and Distribution License (CDDL)
v1.0
</licenseMerge>
<licenseMerge>Indiana University Extreme! Lab Software License, vesion 1.1.1|Indiana University Extreme! Lab Software License</licenseMerge>
</licenseMerges>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- This profile update license stuff with new goal update-file-header -->
<profile>
<id>update-file-header</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<defaultGoal>process-resources</defaultGoal>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<executions>
<execution>
<id>update-file-header</id>
<goals>
<goal>update-file-header</goal>
</goals>
<configuration>
<addSvnKeyWords>false</addSvnKeyWords>
<excludes>
<exclude>**/site/**/*.*</exclude>
<exclude>**/misc/**/*.*</exclude>
<exclude>**/webapp/jquery/**/*.*</exclude>
<exclude>**/webapp/META-INF/**/*.*</exclude>
<exclude>**/webapp/WEB-INF/**/*.*</exclude>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
<exclude>**/jquery.tokeninput.js</exclude>
<exclude>**/jquery.watermark.js</exclude>
<exclude>**/jquery.qtip.*</exclude>
<!-- since sh scripts must begins by the line #!/bin/sh, can not use the mojo for the mojo -->
<exclude>**/*.sh</exclude>
</excludes>
</configuration>
<phase>process-resources</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>reporting</id>
<activation>
<property>
<name>performRelease</name>
<value>true</value>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-changes-plugin</artifactId>
<executions>
<execution>
<id>check-changes</id>
<phase>verify</phase>
<goals>
<goal>changes-check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>${projectInfoReportsPluginVersion}</version>
<reportSets>
<reportSet>
<reports>
<report>project-team</report>
<report>mailing-list</report>
<report>cim</report>
<report>issue-tracking</report>
<report>license</report>
<report>scm</report>
<report>dependencies</report>
<report>dependency-convergence</report>
<report>dependency-info</report>
<report>plugin-management</report>
<report>plugins</report>
<report>dependency-management</report>
<report>summary</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-changelog-plugin</artifactId>
<!-- FIXME BL : waiting capturing group to be enable (see https://jira.codehaus.org/browse/MCHANGELOG-125) <configuration> <issueLinkUrl>https://forge.ifremer.fr/mantis/view.php?id=%ISSUE%</issueLinkUrl>
<issueIDRegexPattern>[#]([0-9]{4,})</issueIDRegexPattern> </configuration> -->
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-changes-plugin</artifactId>
<configuration>
<aggregated>true</aggregated>
<escapeHTML>false</escapeHTML>
<feedType>rss_2.0</feedType>
<issueLinkTemplatePerSystem>
<default>https://github.com/blavenie/ucoinj/issues/%ISSUE%</default>
</issueLinkTemplatePerSystem>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.1</version>
<reportSets>
<reportSet>
<reports>
<report>dependency-updates-report</report>
<report>plugin-updates-report</report>
<report>property-updates-report</report>
</reports>
</reportSet>
</reportSets>
</plugin>
<plugin>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-maven-report-plugin</artifactId>
<version>3.0</version>
<inherited>false</inherited>
<reportSets>
<reportSet>
<reports>
<report>aggregate-config-report</report>
</reports>
</reportSet>
</reportSets>
<configuration>
<i18nBundleName>ucoinj-i18n</i18nBundleName>
<verbose>true</verbose>
<showOptionDetail>true</showOptionDetail>
<outputEncoding>UTF-8</outputEncoding>
</configuration>
</plugin>
</plugins>
</reporting>
</profile>
</profiles>
</project>
......@@ -12,6 +12,20 @@
<packaging>jar</packaging>
<name>UCoin Java Client :: Core API</name>
<properties>
<i18n.bundleOutputName>ucoinj-core-i18n</i18n.bundleOutputName>
<i18n.generateCsvFile>true</i18n.generateCsvFile>
<i18n.bundleCsvFile>
${maven.gen.dir}/resources/META-INF/${i18n.bundleOutputName}.csv
</i18n.bundleCsvFile>
<config.i18nBundleName>${i18n.bundleOutputName}</config.i18nBundleName>
<maven.jar.main.class>
io.ucoin.client.core.UCoinClientCore
</maven.jar.main.class>
</properties>
<dependencies>
<dependency>
<groupId>log4j</groupId>
......@@ -57,6 +71,14 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-config</artifactId>
</dependency>
<dependency>
<groupId>org.nuiton.i18n</groupId>
<artifactId>nuiton-i18n</artifactId>
</dependency>
<!-- Unit test -->
......@@ -66,4 +88,41 @@
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.nuiton.i18n</groupId>
<artifactId>i18n-maven-plugin</artifactId>
<executions>
<execution>
<id>scan-sources</id>
<configuration>
<entries>
<entry>
<specificGoal>parserValidation</specificGoal>
<basedir>${maven.src.dir}/main/java/</basedir>
<includes>
<param>**/**-validation.xml</param>
</includes>
</entry>
</entries>
</configuration>
<goals>
<goal>parserJava</goal>
<goal>parserValidation</goal>
<goal>gen</goal>
</goals>
</execution>
<execution>
<id>make-bundle</id>
<goals>
<goal>bundle</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package io.ucoin.client.core;
import io.ucoin.client.core.service.BlockchainService;
import io.ucoin.client.core.service.WotService;
import io.ucoin.client.core.config.Configuration;
import io.ucoin.client.core.technical.UCoinTechnicalException;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.config.ApplicationConfig;
import org.nuiton.i18n.I18n;
import org.nuiton.i18n.init.DefaultI18nInitializer;
import org.nuiton.i18n.init.UserI18nInitializer;
public class UCoinClientCore {
private static final Log log = LogFactory.getLog(UCoinClientCore.class);
public static void main(String[] args) {
if (log.isInfoEnabled()) {
log.info("Starting UCOin Java Client :: Core with arguments: " + Arrays.toString(args));
}
// By default, display help
if (args == null || args.length == 0) {
args = new String[] { "--help" };
}
// Could override config file name (useful for dev)
String configFile = "ucoinj.config";
if (System.getProperty(configFile) != null) {
configFile = System.getProperty(configFile);
configFile = configFile.replaceAll("\\\\", "/");
}
// Create configuration
Configuration config = new Configuration(configFile, args) {
protected void addAlias(ApplicationConfig applicationConfig) {
super.addAlias(applicationConfig);
// Add custom alias
};
};
Configuration.setInstance(config);
// Init i18n
try {
initI18n(config);
} catch (IOException e) {
throw new UCoinTechnicalException("i18n initialization failed", e);
}
try {
config.getApplicationConfig().doAllAction();
} catch (Exception e) {
e.printStackTrace();
}
//IOUtils.closeQuietly(ServiceLocator.instance());
}
protected static void initI18n(Configuration config) throws IOException {
// --------------------------------------------------------------------//
// init i18n
// --------------------------------------------------------------------//
File i18nDirectory = new File(config.getDataDirectory(), "i18n");
if (i18nDirectory.exists()) {
// clean i18n cache
FileUtils.cleanDirectory(i18nDirectory);
}
FileUtils.forceMkdir(i18nDirectory);
if (log.isDebugEnabled()) {
log.debug("I18N directory: " + i18nDirectory);
}
Locale i18nLocale = config.getI18nLocale();
if (log.isInfoEnabled()) {
log.info(String.format("Starts i18n with locale [%s] at [%s]",
i18nLocale, i18nDirectory));
}
I18n.init(new UserI18nInitializer(
i18nDirectory, new DefaultI18nInitializer(getI18nBundleName())),
i18nLocale);
}
protected static String getI18nBundleName() {
return "ucoinj-core-i18n";
}
}
package io.ucoin.client.core.action;
/*
* #%L
* SIH-Adagio :: Core for Allegro
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2012 - 2014 Ifremer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Preconditions;
public class CommandLines {
protected CommandLines() {
}
public static String readNotBlankInput(String message) {
String value = readInput(message, null, true);
return value;
}
public static String readInput(String message, String defaultValue, boolean mandatory) {
Scanner scanIn = new Scanner(System.in);
String inputValue = null;
while (inputValue == null) {
System.out.print(message.trim());
if (StringUtils.isNotEmpty(defaultValue)) {
System.out.print(String.format(" [%s]", defaultValue));
}
System.out.print(": ");
inputValue = scanIn.nextLine();
if (StringUtils.isBlank(inputValue)) {
// A default exists: use it
if (StringUtils.isNotEmpty(defaultValue)) {
inputValue = defaultValue;
}
// No default value, but mandatory: prepare for a new iteration
else if (mandatory) {
inputValue = null;
}
}
}
// scanIn.close();
return inputValue;
}
}
package io.ucoin.client.core.action;
/*
* #%L
* SIH-Adagio :: Shared
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2012 - 2014 Ifremer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import io.ucoin.client.core.config.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class CommunityAction {
/* Logger */
private static final Log log = LogFactory.getLog(CommunityAction.class);
public void members() {
Configuration config = Configuration.instance();
}
}
package io.ucoin.client.core.action;
/*
* #%L
* SIH-Adagio :: Shared
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2012 - 2014 Ifremer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
public class HelpAction {
public void show() {
StringBuilder sb = new StringBuilder();
sb.append("Usage: <commands> <options>\n")
.append("with <commands>:\n")
.append(" -h --help Display help\n")
.append(" --schema-update Run database schema update\n")
.append(" --schema-status --output <file> Generate a database status report (pending schema changes)\n")
.append(" --schema-diff --output <file> Generate a database schema diff report (compare database to adagio data model)\n")
.append(" --schema-changelog --output <file> Generate a diff into a changelog XML file (compare database to adagio data model)\n")
.append(" --new-db --output <directory> Generate a empty Allegro database\n")
.append(" --import-ref Import referential data, from the Adagio central database\n")
.append(" --import-data Import raw data, from the Adagio central database\n")
.append("\n")
.append("with <options>:\n")
.append(" -u --user <user> Database user\n")
.append(" -p --password <pwd> Database password\n")
.append(" -db --database <db_url> Database JDBC URL ()\n")
.append("\n")
.append(" -iu --import-user <user> Imported database user\n")
.append(" -ip --import-password <pwd> Imported database password\n")
.append(" -idb --import-database <db_url> Imported database JDBC URL\n");
System.out.println(sb.toString());
}
}
package io.ucoin.client.core.config;
import static org.nuiton.i18n.I18n.t;
import io.ucoin.client.core.technical.UCoinTechnicalException;
import java.io.File;
import java.net.URL;
import java.util.Locale;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.config.ApplicationConfig;
import org.nuiton.config.ApplicationConfigHelper;
import org.nuiton.config.ApplicationConfigProvider;
import org.nuiton.config.ArgumentsParserException;
import org.nuiton.util.version.Version;
import com.google.common.base.Charsets;
/**
* Access to configuration options
* @author Benoit Lavenier <benoit.lavenier@e-is.pro>
* @since 1.0
*/
public class Configuration {
/** Logger. */
private static final Log log = LogFactory.getLog(Configuration.class);
/**
* Delegate application config.
*/
protected final ApplicationConfig applicationConfig;
private static Configuration instance;
public static Configuration instance() {
return instance;
}
public static void setInstance(Configuration instance) {
Configuration.instance = instance;
}
protected final String[] optionKeyToNotSave;
protected File configFile;
public Configuration(ApplicationConfig applicationConfig) {
super();
this.applicationConfig = applicationConfig;
this.optionKeyToNotSave = null;
}
public Configuration(String file, String... args) {
super();
this.applicationConfig = new ApplicationConfig();
this.applicationConfig.setEncoding(Charsets.UTF_8.name());
this.applicationConfig.setConfigFileName(file);
// get all config providers
Set<ApplicationConfigProvider> providers =
ApplicationConfigHelper.getProviders(null,
null,
null,
true);
// load all default options
ApplicationConfigHelper.loadAllDefaultOption(applicationConfig,
providers);
// Load actions
for (ApplicationConfigProvider provider : providers) {
applicationConfig.loadActions(provider.getActions());
}
// Define Alias
addAlias(applicationConfig);
// get all transient and final option keys
Set<String> optionToSkip =
ApplicationConfigHelper.getTransientOptionKeys(providers);
if (log.isDebugEnabled()) {
log.debug("Option that won't be saved: " + optionToSkip);
}
optionKeyToNotSave = optionToSkip.toArray(new String[optionToSkip.size()]);
try {
applicationConfig.parse(args);
} catch (ArgumentsParserException e) {
throw new UCoinTechnicalException(t("ucoinj.config.parse.error"), e);
}
// TODO Review this, this is very dirty to do this...
File appBasedir = applicationConfig.getOptionAsFile(
ConfigurationOption.BASEDIR.getKey());
if (appBasedir == null) {
appBasedir = new File("");
}
if (!appBasedir.isAbsolute()) {
appBasedir = new File(appBasedir.getAbsolutePath());
}
if (appBasedir.getName().equals("..")) {
appBasedir = appBasedir.getParentFile().getParentFile();
}
if (appBasedir.getName().equals(".")) {
appBasedir = appBasedir.getParentFile();
}
if (log.isInfoEnabled()) {
log.info("Application basedir: " + appBasedir);
}
applicationConfig.setOption(
ConfigurationOption.BASEDIR.getKey(),
appBasedir.getAbsolutePath());
}
/**
* Add alias to the given ApplicationConfig. <p/>
* This method could be override to add specific alias
*
* @param applicationConfig
*/
protected void addAlias(ApplicationConfig applicationConfig) {
applicationConfig.addAlias("-h", "--option", ConfigurationOption.NODE_HOST.getKey());
applicationConfig.addAlias("-p", "--option", ConfigurationOption.NODE_PORT.getKey());
applicationConfig.addAlias("-c", "--option", ConfigurationOption.NODE_CURRENCY.getKey());
applicationConfig.addAlias("--salt", "--option", ConfigurationOption.USER_SALT.getKey());
applicationConfig.addAlias("--passwd", "--option", ConfigurationOption.USER_PASSWD.getKey());
}
public File getConfigFile() {
if (configFile == null) {
File dir = getBasedir();
if (dir == null || !dir.exists()) {
dir = new File(applicationConfig.getUserConfigDirectory());
}
configFile = new File(dir, applicationConfig.getConfigFileName());
}
return configFile;
}
/** @return {@link ConfigurationOption#BASEDIR} value */
public File getBasedir() {
File result = applicationConfig.getOptionAsFile(ConfigurationOption.BASEDIR.getKey());
return result;
}
/** @return {@link ConfigurationOption#DATA_DIRECTORY} value */
public File getDataDirectory() {
File result = applicationConfig.getOptionAsFile(ConfigurationOption.DATA_DIRECTORY.getKey());
return result;
}
public ApplicationConfig getApplicationConfig() {
return applicationConfig;
}
public File getTempDirectory() {
return applicationConfig.getOptionAsFile(ConfigurationOption.TMP_DIRECTORY.getKey());
}
public File getCacheDirectory() {
return applicationConfig.getOptionAsFile(ConfigurationOption.CACHE_DIRECTORY.getKey());
}
public Version getVersion() {
return applicationConfig.getOptionAsVersion(ConfigurationOption.VERSION.getKey());
}
public File getI18nDirectory() {
return applicationConfig.getOptionAsFile(
ConfigurationOption.I18N_DIRECTORY.getKey());
}
public Locale getI18nLocale() {
return applicationConfig.getOptionAsLocale(
ConfigurationOption.I18N_LOCALE.getKey());
}
public void setI18nLocale(Locale locale) {
applicationConfig.setOption(ConfigurationOption.I18N_LOCALE.getKey(), locale.toString());
}
public String getNodeCurrency() {
return applicationConfig.getOption(ConfigurationOption.NODE_CURRENCY.getKey());
}
public String getNodeProtocol() {
return applicationConfig.getOption(ConfigurationOption.NODE_PROTOCOL.getKey());
}
public String getNodeHost() {
return applicationConfig.getOption(ConfigurationOption.NODE_HOST.getKey());
}
public int getNodePort() {
return applicationConfig.getOptionAsInt(ConfigurationOption.NODE_PORT.getKey());
}
public URL getNodeUrl() {
return applicationConfig.getOptionAsURL(ConfigurationOption.NODE_URL.getKey());
}
public int getNodeTimeout() {
return applicationConfig.getOptionAsInt(ConfigurationOption.NODE_TIMEOUT.getKey());
}
}
package io.ucoin.client.core.config;
/*
* #%L
* SIH-Adagio :: Shared
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2012 - 2014 Ifremer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import io.ucoin.client.core.action.CommunityAction;
import io.ucoin.client.core.action.HelpAction;
import org.nuiton.config.ConfigActionDef;
public enum ConfigurationAction implements ConfigActionDef {
HELP(HelpAction.class.getName() + "#show", "--help"),
COMMUNITY_MEMBERS(CommunityAction.class.getName() + "#members", "--members");
public String action;
public String[] aliases;
private ConfigurationAction(String action, String... aliases) {
this.action = action;
this.aliases = aliases;
}
@Override
public String getAction() {
return action;
}
@Override
public String[] getAliases() {
return aliases;
}
}
package io.ucoin.client.core.config;
/*
* #%L
* Tutti :: Persistence
* $Id: TuttiConfigurationOption.java 1441 2013-12-09 20:13:47Z tchemit $
* $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/TuttiConfigurationOption.java $
* %%
* Copyright (C) 2012 - 2013 Ifremer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import static org.nuiton.i18n.I18n.n;
import java.io.File;
import java.net.URL;
import java.util.Locale;
import org.nuiton.config.ConfigOptionDef;
import org.nuiton.util.Version;
/**
* All application configuration options.
*
* @author Benoit Lavenier <benoit.lavenier@e-is.pro>
* @since 1.0
*/
public enum ConfigurationOption implements ConfigOptionDef {
// ------------------------------------------------------------------------//
// -- READ-ONLY OPTIONS ---------------------------------------------------//
// ------------------------------------------------------------------------//
BASEDIR(
"ucoinj.basedir",
n("ucoinj.config.option.basedir.description"),
"${user.home}/.ucoinj",
File.class),
DATA_DIRECTORY(
"ucoinj.data.directory",
n("ucoinj.config.option.data.directory.description"),
"${ucoinj.basedir}/data",
File.class),
I18N_DIRECTORY(
"ucoinj.i18n.directory",
n("ucoinj.config.option.i18n.directory.description"),
"${ucoinj.basedir}/i18n",
File.class),
TMP_DIRECTORY(
"ucoinj.tmp.directory",
n("ucoinj.config.option.tmp.directory.description"),
"${ucoinj.data.directory}/temp",
File.class),
CACHE_DIRECTORY(
"ucoinj.cache.directory",
n("ucoinj.config.option.cache.directory.description"),
"${ucoinj.data.directory}/cache",
File.class),
VERSION(
"ucoinj.version",
n("ucoinj.config.option.version.description"),
"1.0",
Version.class),
SITE_URL(
"ucoinj.site.url",
n("ucoinj.config.option.site.url.description"),
"http://ucoin.io/ucoinj",
URL.class),
ORGANIZATION_NAME(
"ucoinj.organizationName",
n("ucoinj.config.option.organizationName.description"),
"e-is.pro",
String.class),
INCEPTION_YEAR(
"ucoinj.inceptionYear",
n("ucoinj.config.option.inceptionYear.description"),
"2011",
Integer.class),
USER_SALT(
"ucoinj.salt",
n("ucoinj.config.option.salt.description"),
"",
String.class),
USER_PASSWD(
"ucoinj.passwd",
n("ucoinj.config.option.passwd.description"),
"",
String.class),
// ------------------------------------------------------------------------//
// -- DATA CONSTANTS --------------------------------------------------//
// ------------------------------------------------------------------------//
// ------------------------------------------------------------------------//
// -- READ-WRITE OPTIONS --------------------------------------------------//
// ------------------------------------------------------------------------//
I18N_LOCALE(
"ucoinj.i18n.locale",
n("ucoinj.config.option.i18n.locale.description"),
Locale.FRANCE.getCountry(),
Locale.class,
false),
NODE_CURRENCY(
"ucoinj.node.currency",
n("ucoinj.config.option.node.currency.description"),
"zeta_brouzouf",
String.class,
false),
NODE_PROTOCOL(
"ucoinj.node.protocol",
n("ucoinj.config.option.node.protocol.description"),
"http",
String.class,
false),
NODE_HOST(
"ucoinj.node.host",
n("ucoinj.config.option.node.host.description"),
"twiced.fr",
String.class,
false),
NODE_PORT(
"ucoinj.node.port",
n("ucoinj.config.option.node.port.description"),
"9101",
Integer.class,
false),
NODE_URL(
"ucoinj.node.url",
n("ucoinj.config.option.node.port.description"),
"${ucoinj.node.protocol}://${ucoinj.node.host}:${ucoinj.node.port}",
URL.class,
false),
NODE_TIMEOUT(
"ucoinj.node.timeout",
n("ucoinj.config.option.node.timeout.description"),
"1500",
Integer.class,
false);
/** Configuration key. */
private final String key;
/** I18n key of option description */
private final String description;
/** Type of option */
private final Class<?> type;
/** Default value of option. */
private String defaultValue;
/** Flag to not keep option value on disk */
private boolean isTransient;
/** Flag to not allow option value modification */
private boolean isFinal;
ConfigurationOption(String key,
String description,
String defaultValue,
Class<?> type,
boolean isTransient) {
this.key = key;
this.description = description;
this.defaultValue = defaultValue;
this.type = type;
this.isTransient = isTransient;
this.isFinal = isTransient;
}
ConfigurationOption(String key,
String description,
String defaultValue,
Class<?> type) {
this(key, description, defaultValue, type, true);
}
@Override
public String getKey() {
return key;
}
@Override
public Class<?> getType() {
return type;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getDefaultValue() {
return defaultValue;
}
@Override
public boolean isTransient() {
return isTransient;
}
@Override
public boolean isFinal() {
return isFinal;
}
@Override
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public void setTransient(boolean newValue) {
// not used
}
@Override
public void setFinal(boolean newValue) {
// not used
}
}
package io.ucoin.client.core.config;
/*
* #%L
* Tutti :: Persistence
* $Id: TuttiConfigurationProvider.java 1418 2013-12-01 21:18:22Z tchemit $
* $HeadURL: http://svn.forge.codelutin.com/svn/tutti/trunk/tutti-persistence/src/main/java/fr/ifremer/tutti/TuttiConfigurationProvider.java $
* %%
* Copyright (C) 2012 - 2013 Ifremer
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import static org.nuiton.i18n.I18n.l;
import java.util.Locale;
import org.nuiton.config.ApplicationConfigProvider;
import org.nuiton.config.ConfigActionDef;
import org.nuiton.config.ConfigOptionDef;
/**
* Config provider (for site generation).
*
* @author Benoit Lavenier <benoit.lavenier@e-is.pro>
*/
public class ConfigurationProvider implements ApplicationConfigProvider {
@Override
public String getName() {
return "ucoinj";
}
@Override
public String getDescription(Locale locale) {
return l(locale, "ucoinj.config");
}
@Override
public ConfigOptionDef[] getOptions() {
return ConfigurationOption.values();
}
@Override
public ConfigActionDef[] getActions() {
return ConfigurationAction.values();
}
}
package io.ucoin.client.core.config;
public class NodeConfig {
private String host;
public NodeConfig() {
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
......@@ -30,16 +30,58 @@ public class BlockchainParameter {
*/
private Integer sigDelay;
/* TODO :
"sigValidity": 2629800,
"sigQty": 3,
"stepMax": 3,
"powZeroMin": 4,
"powPeriod": 0.05,
"incDateMin": 3,
"dtDateMin": 10800
/**
* Maximum age of a valid signature (in seconds) (e.g. 2629800)
*/
private Integer sigValidity;
/**
* Minimum quantity of signatures to be part of the WoT (e.g. 3)
*/
private Integer sigQty;
/**
* Minimum quantity of valid made certifications to be part of the WoT for distance rule
*/
private Integer sigWoT;
/**
* Maximum age of a valid membership (in seconds)
*/
private Integer msValidity;
/**
* Maximum distance between each WoT member and a newcomer
*/
private Integer stepMax;
/**
* Number of blocks used for calculating median time.
*/
private Integer medianTimeBlocks;
/**
* The average time for writing 1 block (wished time)
*/
private Integer avgGenTime;
/**
* The number of blocks required to evaluate again PoWMin value
*/
private Integer dtDiffEval;
/**
* The number of previous blocks to check for personalized difficulty
*/
private Integer blocksRot;
/**
* The percent of previous issuers to reach for personalized difficulty
*/
private Double percentRot;
@Override
public String toString() {
......@@ -49,6 +91,7 @@ public class BlockchainParameter {
.append("dt: ").append(dt).append("\n")
.append("ud0: ").append(ud0).append("\n")
.append("sigDelay: ").append(sigDelay);
// TODO : display missing fields
return sb.toString();
}
......@@ -91,4 +134,84 @@ public class BlockchainParameter {
public void setSigDelay(Integer sigDelay) {
this.sigDelay = sigDelay;
}
public Integer getSigValidity() {
return sigValidity;
}
public void setSigValidity(Integer sigValidity) {
this.sigValidity = sigValidity;
}
public Integer getSigQty() {
return sigQty;
}
public void setSigQty(Integer sigQty) {
this.sigQty = sigQty;
}
public Integer getSigWoT() {
return sigWoT;
}
public void setSigWoT(Integer sigWoT) {
this.sigWoT = sigWoT;
}
public Integer getMsValidity() {
return msValidity;
}
public void setMsValidity(Integer msValidity) {
this.msValidity = msValidity;
}
public Integer getStepMax() {
return stepMax;
}
public void setStepMax(Integer stepMax) {
this.stepMax = stepMax;
}
public Integer getMedianTimeBlocks() {
return medianTimeBlocks;
}
public void setMedianTimeBlocks(Integer medianTimeBlocks) {
this.medianTimeBlocks = medianTimeBlocks;
}
public Integer getAvgGenTime() {
return avgGenTime;
}
public void setAvgGenTime(Integer avgGenTime) {
this.avgGenTime = avgGenTime;
}
public Integer getDtDiffEval() {
return dtDiffEval;
}
public void setDtDiffEval(Integer dtDiffEval) {
this.dtDiffEval = dtDiffEval;
}
public Integer getBlocksRot() {
return blocksRot;
}
public void setBlocksRot(Integer blocksRot) {
this.blocksRot = blocksRot;
}
public Double getPercentRot() {
return percentRot;
}
public void setPercentRot(Double percentRot) {
this.percentRot = percentRot;
}
}
package io.ucoin.client.core.service;
import io.ucoin.client.core.technical.UCoinTechnicalExecption;
import io.ucoin.client.core.config.Configuration;
import io.ucoin.client.core.technical.UCoinTechnicalException;
import io.ucoin.client.core.technical.gson.GsonUtils;
import java.io.Closeable;
......@@ -9,10 +10,8 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
......@@ -41,12 +40,14 @@ public abstract class AbstractService implements Closeable {
protected final Gson gson;
protected final CloseableHttpClient httpClient;
public AbstractService(String nodeURL) {
public AbstractService() {
super();
Configuration config = Configuration.instance();
this.gson = GsonUtils.newBuilder().create();
this.baseTimeOut = 1500;
this.httpClient = initHttpClient();
this.baseUri = initNodeURI(nodeURL);
this.baseTimeOut = config.getNodeTimeout();
this.httpClient = initHttpClient(config);
this.baseUri = initNodeURI(config);
}
@Override
......@@ -56,21 +57,20 @@ public abstract class AbstractService implements Closeable {
/* -- Internal methods -- */
protected CloseableHttpClient initHttpClient() {
protected CloseableHttpClient initHttpClient(Configuration config) {
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig())
// .setDefaultCredentialsProvider(getCredentialsProvider())
.build();
return httpClient;
}
protected URI initNodeURI(String nodeUrl) {
protected URI initNodeURI(Configuration config) {
try {
URL baseUrl = new URL(nodeUrl);
return baseUrl.toURI();
URI nodeURI = config.getNodeUrl().toURI();
return nodeURI;
} catch (URISyntaxException ex) {
throw new UCoinTechnicalExecption(ex);
} catch (MalformedURLException e) {
throw new UCoinTechnicalExecption(e);
throw new UCoinTechnicalException(ex);
}
}
......@@ -112,14 +112,14 @@ public abstract class AbstractService implements Closeable {
}
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_FORBIDDEN:
throw new UCoinTechnicalExecption("ucoin.client.authentication");
throw new UCoinTechnicalException("ucoin.client.authentication");
default:
throw new UCoinTechnicalExecption("ucoin.client.status" + response.getStatusLine().toString());
throw new UCoinTechnicalException("ucoin.client.status" + response.getStatusLine().toString());
}
}
} catch (ConnectException e) {
throw new UCoinTechnicalExecption("ucoin.client.core.connect", e);
throw new UCoinTechnicalException("ucoin.client.core.connect", e);
}
return result;
......@@ -133,7 +133,7 @@ public abstract class AbstractService implements Closeable {
}
if (result == null) {
throw new UCoinTechnicalExecption("ucoin.client.core.emptyResponse");
throw new UCoinTechnicalException("ucoin.client.core.emptyResponse");
}
if (log.isDebugEnabled()) {
......
......@@ -14,8 +14,8 @@ public class BlockchainService extends AbstractService{
public BlockchainService(String nodeURL) {
super(nodeURL);
public BlockchainService() {
super();
}
/**
......
package io.ucoin.client.core.service;
import io.ucoin.client.core.technical.UCoinTechnicalException;
import java.util.ServiceLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ServiceLocator {
/* Logger */
private static final Log log = LogFactory.getLog(ServiceLocator.class);
/**
* The shared instance of this ServiceLocator.
*/
private static ServiceLocator instance = new ServiceLocator();
protected ServiceLocator() {
// shouldn't be instantiated
}
public void init() {
}
/**
* replace the default shared instance of this Class
*
* @param newInstance the new shared service locator instance.
*/
public static void setInstance(ServiceLocator newInstance) {
instance = newInstance;
}
/**
* Gets the shared instance of this Class
*
* @return the shared service locator instance.
*/
public static ServiceLocator instance() {
return instance;
}
public BlockchainService getBlockchainService() {
return getService(BlockchainService.class);
}
/* -- Internal methods -- */
protected <S> S getService(Class<S> clazz) {
ServiceLoader<S> loader = ServiceLoader.load(clazz);
for (S service : loader) {
return service;
}
throw new UCoinTechnicalException("No such service found : " + clazz.getName());
}
}
......@@ -3,7 +3,7 @@ package io.ucoin.client.core.service;
import io.ucoin.client.core.model.WotLookupResult;
import io.ucoin.client.core.model.WotLookupResults;
import io.ucoin.client.core.model.WotLookupUId;
import io.ucoin.client.core.technical.UCoinTechnicalExecption;
import io.ucoin.client.core.technical.UCoinTechnicalException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.logging.Log;
......@@ -14,8 +14,8 @@ public class WotService extends AbstractService {
private static final Log log = LogFactory.getLog(WotService.class);
public WotService(String nodeURL) {
super(nodeURL);
public WotService() {
super();
}
public WotLookupResults find(String uidPattern) throws Exception {
......@@ -44,7 +44,7 @@ public class WotService extends AbstractService {
WotLookupUId uniqueResult = getUid(lookupResults, uid);
if (uniqueResult == null) {
throw new UCoinTechnicalExecption("User not found, with uid=" + uid);
throw new UCoinTechnicalException("User not found, with uid=" + uid);
}
return uniqueResult;
......
......@@ -6,27 +6,27 @@ package io.ucoin.client.core.technical;
* @since
*
*/
public class UCoinTechnicalExecption extends RuntimeException{
public class UCoinTechnicalException extends RuntimeException{
private static final long serialVersionUID = -6715624222174163366L;
public UCoinTechnicalExecption() {
public UCoinTechnicalException() {
super();
}
public UCoinTechnicalExecption(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
public UCoinTechnicalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UCoinTechnicalExecption(String message, Throwable cause) {
public UCoinTechnicalException(String message, Throwable cause) {
super(message, cause);
}
public UCoinTechnicalExecption(String message) {
public UCoinTechnicalException(String message) {
super(message);
}
public UCoinTechnicalExecption(Throwable cause) {
public UCoinTechnicalException(Throwable cause) {
super(cause);
}
......
package io.ucoin.client.core.technical.crypto;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.apache.commons.codec.binary.Base64;
public class CryptoUtils {
public static byte[] generateKeys(String salt, String password) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
//keyGen.initialize(512);
byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
return encodeBase64(publicKey);
/*.getEncoded();
StringBuilder result = new StringBuilder();
for (int i = 0; i < publicKey.length; ++i) {
result.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1));
}
return encodeBase64(result.toString());*/
}
/**
* Use Ed55219 pattern
* @param data
* @param password
* @param salt
* @param noIterations
* @return
*/
public static byte[] encrypt(byte[] data, char[] password,
byte[] salt, int noIterations) {
try {
String method = "PBEWithMD5AndTripleDES";
SecretKeyFactory kf = SecretKeyFactory.getInstance(method);
PBEKeySpec keySpec = new PBEKeySpec(password);
SecretKey key = kf.generateSecret(keySpec);
Cipher ciph = Cipher.getInstance(method);
PBEParameterSpec params = new PBEParameterSpec(salt, noIterations);
return ciph.doFinal(data);
} catch (Exception e) {
throw new RuntimeException("Spurious encryption error");
}
}
public static byte[] encodeBase64(byte[] data) {
byte[] encodedBytes = Base64.encodeBase64(data);
return encodedBytes;
}
// TODO: add methids to crypt/decrypt
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment