repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/GitRiver.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
| import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.river.AbstractRiverComponent;
import org.elasticsearch.river.River;
import org.elasticsearch.river.RiverIndexName;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.river.RiverSettings;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap; | package com.bazoud.elasticsearch.river.git;
/**
* @author Olivier Bazoud
*/
public class GitRiver extends AbstractRiverComponent implements River {
private Client client;
private volatile Thread indexerThread;
private volatile boolean closed;
@Inject
private FunctionFlowFactory functionFlowFactory;
| // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/GitRiver.java
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.beanutils.BeanUtilsBean2;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.indices.IndexAlreadyExistsException;
import org.elasticsearch.river.AbstractRiverComponent;
import org.elasticsearch.river.River;
import org.elasticsearch.river.RiverIndexName;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.river.RiverSettings;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.google.common.base.CaseFormat;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
package com.bazoud.elasticsearch.river.git;
/**
* @author Olivier Bazoud
*/
public class GitRiver extends AbstractRiverComponent implements River {
private Client client;
private volatile Thread indexerThread;
private volatile boolean closed;
@Inject
private FunctionFlowFactory functionFlowFactory;
| private Context context = new Context(); |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexCommit.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Identity.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Identity {
// private String name;
// private String emailAddress;
// private Date when;
// private TimeZone timeZone;
// private int timeZoneOffset;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexCommit.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexCommit implements Id {
// private String id;
// private String sha1;
// private String project;
// private Identity author;
// private Identity committer;
// private String subject;
// private String messsage;
// private String encoding;
// private List<String> issues = new ArrayList<String>();
// private List<Parent> parents = new ArrayList<Parent>();
// private String diff;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Parent.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Parent {
// private String id;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
| import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Identity;
import com.bazoud.elasticsearch.river.git.beans.IndexCommit;
import com.bazoud.elasticsearch.river.git.beans.Parent;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.COMMIT; | package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class RevCommitToIndexCommit extends MyFunction<RevCommit, IndexCommit> {
private static ESLogger logger = Loggers.getLogger(RevCommitToIndexCommit.class);
private RevWalk walk; | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Identity.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Identity {
// private String name;
// private String emailAddress;
// private Date when;
// private TimeZone timeZone;
// private int timeZoneOffset;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexCommit.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexCommit implements Id {
// private String id;
// private String sha1;
// private String project;
// private Identity author;
// private Identity committer;
// private String subject;
// private String messsage;
// private String encoding;
// private List<String> issues = new ArrayList<String>();
// private List<Parent> parents = new ArrayList<Parent>();
// private String diff;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Parent.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Parent {
// private String id;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexCommit.java
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Identity;
import com.bazoud.elasticsearch.river.git.beans.IndexCommit;
import com.bazoud.elasticsearch.river.git.beans.Parent;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.COMMIT;
package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class RevCommitToIndexCommit extends MyFunction<RevCommit, IndexCommit> {
private static ESLogger logger = Loggers.getLogger(RevCommitToIndexCommit.class);
private RevWalk walk; | private Context context; |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexCommit.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Identity.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Identity {
// private String name;
// private String emailAddress;
// private Date when;
// private TimeZone timeZone;
// private int timeZoneOffset;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexCommit.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexCommit implements Id {
// private String id;
// private String sha1;
// private String project;
// private Identity author;
// private Identity committer;
// private String subject;
// private String messsage;
// private String encoding;
// private List<String> issues = new ArrayList<String>();
// private List<Parent> parents = new ArrayList<Parent>();
// private String diff;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Parent.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Parent {
// private String id;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
| import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Identity;
import com.bazoud.elasticsearch.river.git.beans.IndexCommit;
import com.bazoud.elasticsearch.river.git.beans.Parent;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.COMMIT; | package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class RevCommitToIndexCommit extends MyFunction<RevCommit, IndexCommit> {
private static ESLogger logger = Loggers.getLogger(RevCommitToIndexCommit.class);
private RevWalk walk;
private Context context;
public RevCommitToIndexCommit(Context context, RevWalk walk) {
this.context = context;
this.walk = walk;
}
@Override
public IndexCommit doApply(RevCommit revCommit) throws Throwable {
return IndexCommit.indexCommit()
.id(String.format("%s|%s|%s", COMMIT.name().toLowerCase(), context.getName(), revCommit.getId().name()))
.sha1(revCommit.getId().name())
.project(context.getName())
.author( | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Identity.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Identity {
// private String name;
// private String emailAddress;
// private Date when;
// private TimeZone timeZone;
// private int timeZoneOffset;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexCommit.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexCommit implements Id {
// private String id;
// private String sha1;
// private String project;
// private Identity author;
// private Identity committer;
// private String subject;
// private String messsage;
// private String encoding;
// private List<String> issues = new ArrayList<String>();
// private List<Parent> parents = new ArrayList<Parent>();
// private String diff;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Parent.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Parent {
// private String id;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexCommit.java
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Identity;
import com.bazoud.elasticsearch.river.git.beans.IndexCommit;
import com.bazoud.elasticsearch.river.git.beans.Parent;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.COMMIT;
package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class RevCommitToIndexCommit extends MyFunction<RevCommit, IndexCommit> {
private static ESLogger logger = Loggers.getLogger(RevCommitToIndexCommit.class);
private RevWalk walk;
private Context context;
public RevCommitToIndexCommit(Context context, RevWalk walk) {
this.context = context;
this.walk = walk;
}
@Override
public IndexCommit doApply(RevCommit revCommit) throws Throwable {
return IndexCommit.indexCommit()
.id(String.format("%s|%s|%s", COMMIT.name().toLowerCase(), context.getName(), revCommit.getId().name()))
.sha1(revCommit.getId().name())
.project(context.getName())
.author( | Identity.identity() |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexCommit.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Identity.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Identity {
// private String name;
// private String emailAddress;
// private Date when;
// private TimeZone timeZone;
// private int timeZoneOffset;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexCommit.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexCommit implements Id {
// private String id;
// private String sha1;
// private String project;
// private Identity author;
// private Identity committer;
// private String subject;
// private String messsage;
// private String encoding;
// private List<String> issues = new ArrayList<String>();
// private List<Parent> parents = new ArrayList<Parent>();
// private String diff;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Parent.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Parent {
// private String id;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
| import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Identity;
import com.bazoud.elasticsearch.river.git.beans.IndexCommit;
import com.bazoud.elasticsearch.river.git.beans.Parent;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.COMMIT; | public IndexCommit doApply(RevCommit revCommit) throws Throwable {
return IndexCommit.indexCommit()
.id(String.format("%s|%s|%s", COMMIT.name().toLowerCase(), context.getName(), revCommit.getId().name()))
.sha1(revCommit.getId().name())
.project(context.getName())
.author(
Identity.identity()
.name(revCommit.getAuthorIdent().getName())
.emailAddress(revCommit.getAuthorIdent().getEmailAddress())
.when(revCommit.getAuthorIdent().getWhen())
.timeZone(revCommit.getAuthorIdent().getTimeZone())
.timeZoneOffset(revCommit.getAuthorIdent().getTimeZoneOffset())
.build()
)
.committer(
Identity.identity()
.name(revCommit.getCommitterIdent().getName())
.emailAddress(revCommit.getCommitterIdent().getEmailAddress())
.when(revCommit.getCommitterIdent().getWhen())
.timeZone(revCommit.getCommitterIdent().getTimeZone())
.timeZoneOffset(revCommit.getCommitterIdent().getTimeZoneOffset())
.build()
)
.subject(revCommit.getShortMessage())
.messsage(revCommit.getFullMessage())
.encoding(revCommit.getEncoding().name())
.issues(parseIssues(context, revCommit.getFullMessage()))
.parents(
FluentIterable
.from(Arrays.asList(revCommit.getParents())) | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Identity.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Identity {
// private String name;
// private String emailAddress;
// private Date when;
// private TimeZone timeZone;
// private int timeZoneOffset;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexCommit.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexCommit implements Id {
// private String id;
// private String sha1;
// private String project;
// private Identity author;
// private Identity committer;
// private String subject;
// private String messsage;
// private String encoding;
// private List<String> issues = new ArrayList<String>();
// private List<Parent> parents = new ArrayList<Parent>();
// private String diff;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Parent.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Parent {
// private String id;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/RevCommitToIndexCommit.java
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.RawTextComparator;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Identity;
import com.bazoud.elasticsearch.river.git.beans.IndexCommit;
import com.bazoud.elasticsearch.river.git.beans.Parent;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Ordering;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.COMMIT;
public IndexCommit doApply(RevCommit revCommit) throws Throwable {
return IndexCommit.indexCommit()
.id(String.format("%s|%s|%s", COMMIT.name().toLowerCase(), context.getName(), revCommit.getId().name()))
.sha1(revCommit.getId().name())
.project(context.getName())
.author(
Identity.identity()
.name(revCommit.getAuthorIdent().getName())
.emailAddress(revCommit.getAuthorIdent().getEmailAddress())
.when(revCommit.getAuthorIdent().getWhen())
.timeZone(revCommit.getAuthorIdent().getTimeZone())
.timeZoneOffset(revCommit.getAuthorIdent().getTimeZoneOffset())
.build()
)
.committer(
Identity.identity()
.name(revCommit.getCommitterIdent().getName())
.emailAddress(revCommit.getCommitterIdent().getEmailAddress())
.when(revCommit.getCommitterIdent().getWhen())
.timeZone(revCommit.getCommitterIdent().getTimeZone())
.timeZoneOffset(revCommit.getCommitterIdent().getTimeZoneOffset())
.build()
)
.subject(revCommit.getShortMessage())
.messsage(revCommit.getFullMessage())
.encoding(revCommit.getEncoding().name())
.issues(parseIssues(context, revCommit.getFullMessage()))
.parents(
FluentIterable
.from(Arrays.asList(revCommit.getParents())) | .transform(new Function<RevCommit, Parent>() { |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexTag.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexTag implements Id {
// private String id;
// private String tag;
// private String ref;
// private String sha1;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
| import java.util.Map;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.IndexTag;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG; | package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class); | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/IndexTag.java
// @Data
// @Builder
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class IndexTag implements Id {
// private String id;
// private String tag;
// private String ref;
// private String sha1;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/functions/TagToIndexTag.java
import java.util.Map;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.IndexTag;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import static com.bazoud.elasticsearch.river.git.IndexedDocumentType.TAG;
package com.bazoud.elasticsearch.river.git.flow.functions;
/**
* @author Olivier Bazoud
*/
public class TagToIndexTag extends MyFunction<Map.Entry<String, Ref>, IndexTag> {
private static ESLogger logger = Loggers.getLogger(TagToIndexTag.class); | private Context context; |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Id.java
// public interface Id {
// String getId();
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitor.java
// public interface Visitor<T> {
// void before();
//
// void visit(T input) throws Exception;
//
// void after();
// }
| import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Id;
import com.bazoud.elasticsearch.river.git.guava.Visitor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import static org.elasticsearch.client.Requests.indexRequest; | package com.bazoud.elasticsearch.river.git.flow.visitors;
/**
* @author Olivier Bazoud
*/
public class BulkVisitor<T extends Id> implements Visitor<T> {
private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
private BulkRequestBuilder bulk; | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Id.java
// public interface Id {
// String getId();
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/Visitor.java
// public interface Visitor<T> {
// void before();
//
// void visit(T input) throws Exception;
//
// void after();
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/visitors/BulkVisitor.java
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.beans.Id;
import com.bazoud.elasticsearch.river.git.guava.Visitor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import static org.elasticsearch.client.Requests.indexRequest;
package com.bazoud.elasticsearch.river.git.flow.visitors;
/**
* @author Olivier Bazoud
*/
public class BulkVisitor<T extends Id> implements Visitor<T> {
private static ESLogger logger = Loggers.getLogger(BulkVisitor.class);
private BulkRequestBuilder bulk; | private Context context; |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/river/git/flow/CloneRepositoryFunction.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/jgit/LoggingProgressMonitor.java
// public class LoggingProgressMonitor implements ProgressMonitor {
// private ESLogger logger;
//
// public LoggingProgressMonitor(ESLogger logger) {
// this.logger = logger;
// }
//
// @Override
// public void start(int totalTasks) {
// }
//
// @Override
// public void beginTask(String title, int totalWork) {
// logger.info(title);
// }
//
// @Override
// public void update(int completed) {
// }
//
// @Override
// public void endTask() {
// }
//
// @Override
// public boolean isCancelled() {
// return false;
// }
// }
| import java.util.Collection;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.jgit.LoggingProgressMonitor;
import static org.eclipse.jgit.lib.Constants.R_HEADS; | package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class CloneRepositoryFunction extends MyFunction<Context, Context> {
private static ESLogger logger = Loggers.getLogger(CloneRepositoryFunction.class);
@Override
public Context doApply(Context context) throws Throwable {
logger.info("Cloning the '{}' repository at path: '{}'", context.getName(), context.getProjectPath());
Git git = Git.cloneRepository()
.setBare(true)
.setNoCheckout(true)
.setCloneAllBranches(true)
.setDirectory(context.getProjectPath())
.setURI(context.getUri()) | // Path: src/main/java/com/bazoud/elasticsearch/river/git/beans/Context.java
// @Data
// @SuppressWarnings("PMD.UnusedPrivateField")
// public class Context {
// private String name;
// private String uri;
// private File projectPath;
// private Repository repository;
// private String workingDir =
// System.getProperty("user.home") + File.separator + ".elasticsearch-river-git";
// private Collection<Ref> refs;
// private Client client;
// private Optional<Pattern> issuePattern = Optional.absent();
// private String issueRegex;
// private boolean indexingDiff;
// private long updateRate = TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES);
// private String type = "git";
// private String riverName;
// private String riverIndexName;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/guava/MyFunction.java
// public abstract class MyFunction<F, T> implements Function<F, T> {
// private static ESLogger logger = Loggers.getLogger(MyFunction.class);
//
// @Override
// public T apply(F input) {
// T output = null;
// try {
// output = doApply(input);
// } catch (Throwable e) {
// logger.error(this.getClass().getName(), e);
// Throwables.propagate(e);
// }
// return output;
// }
//
// public abstract T doApply(F input) throws Throwable;
// }
//
// Path: src/main/java/com/bazoud/elasticsearch/river/git/jgit/LoggingProgressMonitor.java
// public class LoggingProgressMonitor implements ProgressMonitor {
// private ESLogger logger;
//
// public LoggingProgressMonitor(ESLogger logger) {
// this.logger = logger;
// }
//
// @Override
// public void start(int totalTasks) {
// }
//
// @Override
// public void beginTask(String title, int totalWork) {
// logger.info(title);
// }
//
// @Override
// public void update(int completed) {
// }
//
// @Override
// public void endTask() {
// }
//
// @Override
// public boolean isCancelled() {
// return false;
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/river/git/flow/CloneRepositoryFunction.java
import java.util.Collection;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import com.bazoud.elasticsearch.river.git.beans.Context;
import com.bazoud.elasticsearch.river.git.guava.MyFunction;
import com.bazoud.elasticsearch.river.git.jgit.LoggingProgressMonitor;
import static org.eclipse.jgit.lib.Constants.R_HEADS;
package com.bazoud.elasticsearch.river.git.flow;
/**
* @author Olivier Bazoud
*/
public class CloneRepositoryFunction extends MyFunction<Context, Context> {
private static ESLogger logger = Loggers.getLogger(CloneRepositoryFunction.class);
@Override
public Context doApply(Context context) throws Throwable {
logger.info("Cloning the '{}' repository at path: '{}'", context.getName(), context.getProjectPath());
Git git = Git.cloneRepository()
.setBare(true)
.setNoCheckout(true)
.setCloneAllBranches(true)
.setDirectory(context.getProjectPath())
.setURI(context.getUri()) | .setProgressMonitor(new LoggingProgressMonitor(logger)) |
obazoud/elasticsearch-river-git | src/main/java/com/bazoud/elasticsearch/plugin/river/git/GitRiverPlugin.java | // Path: src/main/java/com/bazoud/elasticsearch/river/git/GitRiverModule.java
// public class GitRiverModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(River.class).to(GitRiver.class).asEagerSingleton();
// bind(FunctionFlowFactory.class).toInstance(new FunctionFlowFactory());
// }
// }
| import org.elasticsearch.common.inject.Module;
import org.elasticsearch.plugins.AbstractPlugin;
import org.elasticsearch.river.RiversModule;
import com.bazoud.elasticsearch.river.git.GitRiverModule; | package com.bazoud.elasticsearch.plugin.river.git;
/**
* @author Olivier Bazoud
*/
public class GitRiverPlugin extends AbstractPlugin {
public static final String RIVER_TYPE = "git";
@Override
public String name() {
return "git-river";
}
@Override
public String description() {
return "Git River Plugin";
}
@Override
public void processModule(Module module) {
if (module instanceof RiversModule) { | // Path: src/main/java/com/bazoud/elasticsearch/river/git/GitRiverModule.java
// public class GitRiverModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(River.class).to(GitRiver.class).asEagerSingleton();
// bind(FunctionFlowFactory.class).toInstance(new FunctionFlowFactory());
// }
// }
// Path: src/main/java/com/bazoud/elasticsearch/plugin/river/git/GitRiverPlugin.java
import org.elasticsearch.common.inject.Module;
import org.elasticsearch.plugins.AbstractPlugin;
import org.elasticsearch.river.RiversModule;
import com.bazoud.elasticsearch.river.git.GitRiverModule;
package com.bazoud.elasticsearch.plugin.river.git;
/**
* @author Olivier Bazoud
*/
public class GitRiverPlugin extends AbstractPlugin {
public static final String RIVER_TYPE = "git";
@Override
public String name() {
return "git-river";
}
@Override
public String description() {
return "Git River Plugin";
}
@Override
public void processModule(Module module) {
if (module instanceof RiversModule) { | ((RiversModule) module).registerRiver(RIVER_TYPE, GitRiverModule.class); |
stefanhaustein/expressionparser | demo/basic/src/main/java/org/kobjects/expressionparser/demo/basic/Basic.java | // Path: core/src/main/java/org/kobjects/expressionparser/ParsingException.java
// public class ParsingException extends RuntimeException {
// final public int start;
// final public int end;
// public ParsingException(int start, int end, String text, Exception base) {
// super(text, base);
// this.start = start;
// this.end = end;
// }
// }
| import org.kobjects.expressionparser.ParsingException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays; | package org.kobjects.expressionparser.demo.basic;
public class Basic {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Interpreter interpreter = new Interpreter(reader);
System.out.println(" **** EXPRESSION PARSER BASIC DEMO V1 ****\n");
System.out.println(" " + (Runtime.getRuntime().totalMemory() / 1024) + "K SYSTEM "
+ Runtime.getRuntime().freeMemory() + " BASIC BYTES FREE\n");
boolean prompt = true;
while (true) {
if (prompt) {
System.out.println("\nREADY.");
}
String line = reader.readLine();
if (line == null) {
break;
}
prompt = true;
try {
prompt = interpreter.processInputLine(line); | // Path: core/src/main/java/org/kobjects/expressionparser/ParsingException.java
// public class ParsingException extends RuntimeException {
// final public int start;
// final public int end;
// public ParsingException(int start, int end, String text, Exception base) {
// super(text, base);
// this.start = start;
// this.end = end;
// }
// }
// Path: demo/basic/src/main/java/org/kobjects/expressionparser/demo/basic/Basic.java
import org.kobjects.expressionparser.ParsingException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
package org.kobjects.expressionparser.demo.basic;
public class Basic {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Interpreter interpreter = new Interpreter(reader);
System.out.println(" **** EXPRESSION PARSER BASIC DEMO V1 ****\n");
System.out.println(" " + (Runtime.getRuntime().totalMemory() / 1024) + "K SYSTEM "
+ Runtime.getRuntime().freeMemory() + " BASIC BYTES FREE\n");
boolean prompt = true;
while (true) {
if (prompt) {
System.out.println("\nREADY.");
}
String line = reader.readLine();
if (line == null) {
break;
}
prompt = true;
try {
prompt = interpreter.processInputLine(line); | } catch (ParsingException e) { |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/ProjectRecord.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Project.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Project extends TableImpl<ProjectRecord> {
//
// private static final long serialVersionUID = -1798885207;
//
// /**
// * The reference instance of <code>public.project</code>
// */
// public static final Project PROJECT = new Project();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<ProjectRecord> getRecordType() {
// return ProjectRecord.class;
// }
//
// /**
// * The column <code>public.project.pid</code>.
// */
// public final TableField<ProjectRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('project_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.project.name</code>.
// */
// public final TableField<ProjectRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.project.datestarted</code>.
// */
// public final TableField<ProjectRecord, Date> DATESTARTED = createField("datestarted", org.jooq.impl.SQLDataType.DATE, this, "");
//
// /**
// * Create a <code>public.project</code> table reference
// */
// public Project() {
// this("project", null);
// }
//
// /**
// * Create an aliased <code>public.project</code> table reference
// */
// public Project(String alias) {
// this(alias, PROJECT);
// }
//
// private Project(String alias, Table<ProjectRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Project(String alias, Table<ProjectRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<ProjectRecord, Integer> getIdentity() {
// return Keys.IDENTITY_PROJECT;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<ProjectRecord> getPrimaryKey() {
// return Keys.PROJECT_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<ProjectRecord>> getKeys() {
// return Arrays.<UniqueKey<ProjectRecord>>asList(Keys.PROJECT_PKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Project as(String alias) {
// return new Project(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Project rename(String name) {
// return new Project(name, null);
// }
// }
| import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Project;
import java.sql.Date;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl; | @Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, Date> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, Date> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Project.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Project extends TableImpl<ProjectRecord> {
//
// private static final long serialVersionUID = -1798885207;
//
// /**
// * The reference instance of <code>public.project</code>
// */
// public static final Project PROJECT = new Project();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<ProjectRecord> getRecordType() {
// return ProjectRecord.class;
// }
//
// /**
// * The column <code>public.project.pid</code>.
// */
// public final TableField<ProjectRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('project_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.project.name</code>.
// */
// public final TableField<ProjectRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.project.datestarted</code>.
// */
// public final TableField<ProjectRecord, Date> DATESTARTED = createField("datestarted", org.jooq.impl.SQLDataType.DATE, this, "");
//
// /**
// * Create a <code>public.project</code> table reference
// */
// public Project() {
// this("project", null);
// }
//
// /**
// * Create an aliased <code>public.project</code> table reference
// */
// public Project(String alias) {
// this(alias, PROJECT);
// }
//
// private Project(String alias, Table<ProjectRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Project(String alias, Table<ProjectRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<ProjectRecord, Integer> getIdentity() {
// return Keys.IDENTITY_PROJECT;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<ProjectRecord> getPrimaryKey() {
// return Keys.PROJECT_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<ProjectRecord>> getKeys() {
// return Arrays.<UniqueKey<ProjectRecord>>asList(Keys.PROJECT_PKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Project as(String alias) {
// return new Project(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Project rename(String name) {
// return new Project(name, null);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/ProjectRecord.java
import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Project;
import java.sql.Date;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, Date> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, Date> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | return Project.PROJECT.PID; |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/Routines.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/routines/RegisterEmployee.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class RegisterEmployee extends AbstractRoutine<java.lang.Void> {
//
// private static final long serialVersionUID = -1642852;
//
// /**
// * The parameter <code>public.register_employee._name</code>.
// */
// public static final Parameter<String> _NAME = createParameter("_name", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._surname</code>.
// */
// public static final Parameter<String> _SURNAME = createParameter("_surname", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._email</code>.
// */
// public static final Parameter<String> _EMAIL = createParameter("_email", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._salary</code>.
// */
// public static final Parameter<BigDecimal> _SALARY = createParameter("_salary", org.jooq.impl.SQLDataType.NUMERIC, false, false);
//
// /**
// * The parameter <code>public.register_employee._department_name</code>.
// */
// public static final Parameter<String> _DEPARTMENT_NAME = createParameter("_department_name", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._company_name</code>.
// */
// public static final Parameter<String> _COMPANY_NAME = createParameter("_company_name", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee.employee_id</code>.
// */
// public static final Parameter<Integer> EMPLOYEE_ID = createParameter("employee_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
//
// /**
// * The parameter <code>public.register_employee.department_id</code>.
// */
// public static final Parameter<Integer> DEPARTMENT_ID = createParameter("department_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
//
// /**
// * The parameter <code>public.register_employee.company_id</code>.
// */
// public static final Parameter<Integer> COMPANY_ID = createParameter("company_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
//
// /**
// * Create a new routine call instance
// */
// public RegisterEmployee() {
// super("register_employee", Public.PUBLIC);
//
// addInParameter(_NAME);
// addInParameter(_SURNAME);
// addInParameter(_EMAIL);
// addInParameter(_SALARY);
// addInParameter(_DEPARTMENT_NAME);
// addInParameter(_COMPANY_NAME);
// addOutParameter(EMPLOYEE_ID);
// addOutParameter(DEPARTMENT_ID);
// addOutParameter(COMPANY_ID);
// }
//
// /**
// * Set the <code>_name</code> parameter IN value to the routine
// */
// public void set_Name(String value) {
// setValue(_NAME, value);
// }
//
// /**
// * Set the <code>_surname</code> parameter IN value to the routine
// */
// public void set_Surname(String value) {
// setValue(_SURNAME, value);
// }
//
// /**
// * Set the <code>_email</code> parameter IN value to the routine
// */
// public void set_Email(String value) {
// setValue(_EMAIL, value);
// }
//
// /**
// * Set the <code>_salary</code> parameter IN value to the routine
// */
// public void set_Salary(BigDecimal value) {
// setValue(_SALARY, value);
// }
//
// /**
// * Set the <code>_department_name</code> parameter IN value to the routine
// */
// public void set_DepartmentName(String value) {
// setValue(_DEPARTMENT_NAME, value);
// }
//
// /**
// * Set the <code>_company_name</code> parameter IN value to the routine
// */
// public void set_CompanyName(String value) {
// setValue(_COMPANY_NAME, value);
// }
//
// /**
// * Get the <code>employee_id</code> parameter OUT value from the routine
// */
// public Integer getEmployeeId() {
// return get(EMPLOYEE_ID);
// }
//
// /**
// * Get the <code>department_id</code> parameter OUT value from the routine
// */
// public Integer getDepartmentId() {
// return get(DEPARTMENT_ID);
// }
//
// /**
// * Get the <code>company_id</code> parameter OUT value from the routine
// */
// public Integer getCompanyId() {
// return get(COMPANY_ID);
// }
// }
| import javax.annotation.Generated;
import java.math.BigDecimal;
import com.clevergang.dbtests.repository.impl.jooq.generated.routines.RegisterEmployee;
import org.jooq.Configuration; | /**
* This class is generated by jOOQ
*/
package com.clevergang.dbtests.repository.impl.jooq.generated;
/**
* Convenience access to all stored procedures and functions in public
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Routines {
/**
* Call <code>public.register_employee</code>
*/ | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/routines/RegisterEmployee.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class RegisterEmployee extends AbstractRoutine<java.lang.Void> {
//
// private static final long serialVersionUID = -1642852;
//
// /**
// * The parameter <code>public.register_employee._name</code>.
// */
// public static final Parameter<String> _NAME = createParameter("_name", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._surname</code>.
// */
// public static final Parameter<String> _SURNAME = createParameter("_surname", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._email</code>.
// */
// public static final Parameter<String> _EMAIL = createParameter("_email", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._salary</code>.
// */
// public static final Parameter<BigDecimal> _SALARY = createParameter("_salary", org.jooq.impl.SQLDataType.NUMERIC, false, false);
//
// /**
// * The parameter <code>public.register_employee._department_name</code>.
// */
// public static final Parameter<String> _DEPARTMENT_NAME = createParameter("_department_name", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee._company_name</code>.
// */
// public static final Parameter<String> _COMPANY_NAME = createParameter("_company_name", org.jooq.impl.SQLDataType.CLOB, false, false);
//
// /**
// * The parameter <code>public.register_employee.employee_id</code>.
// */
// public static final Parameter<Integer> EMPLOYEE_ID = createParameter("employee_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
//
// /**
// * The parameter <code>public.register_employee.department_id</code>.
// */
// public static final Parameter<Integer> DEPARTMENT_ID = createParameter("department_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
//
// /**
// * The parameter <code>public.register_employee.company_id</code>.
// */
// public static final Parameter<Integer> COMPANY_ID = createParameter("company_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
//
// /**
// * Create a new routine call instance
// */
// public RegisterEmployee() {
// super("register_employee", Public.PUBLIC);
//
// addInParameter(_NAME);
// addInParameter(_SURNAME);
// addInParameter(_EMAIL);
// addInParameter(_SALARY);
// addInParameter(_DEPARTMENT_NAME);
// addInParameter(_COMPANY_NAME);
// addOutParameter(EMPLOYEE_ID);
// addOutParameter(DEPARTMENT_ID);
// addOutParameter(COMPANY_ID);
// }
//
// /**
// * Set the <code>_name</code> parameter IN value to the routine
// */
// public void set_Name(String value) {
// setValue(_NAME, value);
// }
//
// /**
// * Set the <code>_surname</code> parameter IN value to the routine
// */
// public void set_Surname(String value) {
// setValue(_SURNAME, value);
// }
//
// /**
// * Set the <code>_email</code> parameter IN value to the routine
// */
// public void set_Email(String value) {
// setValue(_EMAIL, value);
// }
//
// /**
// * Set the <code>_salary</code> parameter IN value to the routine
// */
// public void set_Salary(BigDecimal value) {
// setValue(_SALARY, value);
// }
//
// /**
// * Set the <code>_department_name</code> parameter IN value to the routine
// */
// public void set_DepartmentName(String value) {
// setValue(_DEPARTMENT_NAME, value);
// }
//
// /**
// * Set the <code>_company_name</code> parameter IN value to the routine
// */
// public void set_CompanyName(String value) {
// setValue(_COMPANY_NAME, value);
// }
//
// /**
// * Get the <code>employee_id</code> parameter OUT value from the routine
// */
// public Integer getEmployeeId() {
// return get(EMPLOYEE_ID);
// }
//
// /**
// * Get the <code>department_id</code> parameter OUT value from the routine
// */
// public Integer getDepartmentId() {
// return get(DEPARTMENT_ID);
// }
//
// /**
// * Get the <code>company_id</code> parameter OUT value from the routine
// */
// public Integer getCompanyId() {
// return get(COMPANY_ID);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/Routines.java
import javax.annotation.Generated;
import java.math.BigDecimal;
import com.clevergang.dbtests.repository.impl.jooq.generated.routines.RegisterEmployee;
import org.jooq.Configuration;
/**
* This class is generated by jOOQ
*/
package com.clevergang.dbtests.repository.impl.jooq.generated;
/**
* Convenience access to all stored procedures and functions in public
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Routines {
/**
* Call <code>public.register_employee</code>
*/ | public static RegisterEmployee registerEmployee(Configuration configuration, String _Name, String _Surname, String _Email, BigDecimal _Salary, String _DepartmentName, String _CompanyName) { |
bwajtr/java-persistence-frameworks-comparison | src/test/java/com/clevergang/dbtests/MyBatisScenariosTest.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/mybatis/MyBatisDataRepositoryImpl.java
// @Repository
// public class MyBatisDataRepositoryImpl implements DataRepository {
//
// private final DataRepositoryMapper sql;
// private final SqlSession batchOperations;
//
// @SuppressWarnings("SpringJavaAutowiringInspection")
// @Autowired
// public MyBatisDataRepositoryImpl(DataRepositoryMapper sql, @Qualifier("batch-operations") SqlSession batchOperations) {
// this.sql = sql;
// this.batchOperations = batchOperations;
// }
//
// @Override
// public Company findCompany(Integer pid) {
// return sql.findCompany(pid);
// }
//
// @Override
// public Company findCompanyUsingSimpleStaticStatement(Integer pid) {
// /*
// * !!!!! NOTE THAT you can actually use parameters for SQL with statementType=STATEMENT, but you have to use ${pid} notation
// * (notice $ instead of #) in the mapping xml!
// */
// return sql.findCompanyStatic(pid);
// }
//
// @Override
// public void removeProject(Integer pid) {
// sql.removeProject(pid);
// }
//
// @Override
// public Department findDepartment(Integer pid) {
// return sql.findDepartment(pid);
// }
//
// @Override
// public List<Department> findDepartmentsOfCompany(Company company) {
// return sql.findDepartmentsOfCompany(company);
// }
//
// @Override
// public void deleteDepartments(List<Department> departmentsToDelete) {
// sql.deleteDepartments(departmentsToDelete);
// }
//
// @Override
// public void updateDepartments(List<Department> departmentsToUpdate) {
// DataRepositoryMapper batchSql = batchOperations.getMapper(DataRepositoryMapper.class);
// departmentsToUpdate.forEach(batchSql::updateDepartment);
// // we have to flush statements here - the records would be updated only at the end of the transaction otherwise
// batchOperations.flushStatements();
// }
//
// @Override
// public void insertDepartments(List<Department> departmentsToInsert) {
// DataRepositoryMapper batchSql = batchOperations.getMapper(DataRepositoryMapper.class);
// departmentsToInsert.forEach(batchSql::insertDepartment);
// // we have to flush statements here - the records would be inserted only at the end of the transaction otherwise
// batchOperations.flushStatements();
// }
//
// @Override
// public Project findProject(Integer pid) {
// return sql.findProject(pid);
// }
//
// @Override
// public Integer insertProject(Project project) {
// sql.insertProject(project);
// return project.getPid();
// }
//
// @Override
// public List<Integer> insertProjects(List<Project> projects) {
// DataRepositoryMapper batchSql = batchOperations.getMapper(DataRepositoryMapper.class);
// projects.forEach(batchSql::insertProject);
// // we have to flush statements here - the records would be inserted only at the end of the transaction otherwise
// batchOperations.flushStatements();
//
// // MyBatis can actually return the PIDs from batch operation
// return projects.stream().map(Project::getPid).collect(Collectors.toList());
// }
//
// @Override
// public List<ProjectsWithCostsGreaterThanOutput> getProjectsWithCostsGreaterThan(int totalCostBoundary) {
// return sql.getProjectsWithCostsGreaterThan(totalCostBoundary);
// }
//
// @Override
// public Employee findEmployee(Integer pid) {
// return sql.findEmployee(pid);
// }
//
// @Override
// public List<Employee> employeesWithSalaryGreaterThan(Integer minSalary) {
// return sql.employeesWithSalaryGreaterThan(minSalary);
// }
//
// @Override
// public void updateEmployee(Employee employeeToUpdate) {
// sql.updateEmployee(employeeToUpdate);
// }
//
// @Override
// public RegisterEmployeeOutput callRegisterEmployee(String name, String surname, String email, BigDecimal salary, String departmentName, String companyName) {
// return sql.callRegisterEmployee(name, surname, email, salary, departmentName, companyName);
// }
//
// @Override
// public Integer getProjectsCount() {
// return sql.getProjectsCount();
// }
// }
| import com.clevergang.dbtests.repository.impl.mybatis.MyBatisDataRepositoryImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional; | package com.clevergang.dbtests;
/**
* @author Bretislav Wajtr
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = DbTestsApplication.class)
@Transactional
@Rollback
public class MyBatisScenariosTest {
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired | // Path: src/main/java/com/clevergang/dbtests/repository/impl/mybatis/MyBatisDataRepositoryImpl.java
// @Repository
// public class MyBatisDataRepositoryImpl implements DataRepository {
//
// private final DataRepositoryMapper sql;
// private final SqlSession batchOperations;
//
// @SuppressWarnings("SpringJavaAutowiringInspection")
// @Autowired
// public MyBatisDataRepositoryImpl(DataRepositoryMapper sql, @Qualifier("batch-operations") SqlSession batchOperations) {
// this.sql = sql;
// this.batchOperations = batchOperations;
// }
//
// @Override
// public Company findCompany(Integer pid) {
// return sql.findCompany(pid);
// }
//
// @Override
// public Company findCompanyUsingSimpleStaticStatement(Integer pid) {
// /*
// * !!!!! NOTE THAT you can actually use parameters for SQL with statementType=STATEMENT, but you have to use ${pid} notation
// * (notice $ instead of #) in the mapping xml!
// */
// return sql.findCompanyStatic(pid);
// }
//
// @Override
// public void removeProject(Integer pid) {
// sql.removeProject(pid);
// }
//
// @Override
// public Department findDepartment(Integer pid) {
// return sql.findDepartment(pid);
// }
//
// @Override
// public List<Department> findDepartmentsOfCompany(Company company) {
// return sql.findDepartmentsOfCompany(company);
// }
//
// @Override
// public void deleteDepartments(List<Department> departmentsToDelete) {
// sql.deleteDepartments(departmentsToDelete);
// }
//
// @Override
// public void updateDepartments(List<Department> departmentsToUpdate) {
// DataRepositoryMapper batchSql = batchOperations.getMapper(DataRepositoryMapper.class);
// departmentsToUpdate.forEach(batchSql::updateDepartment);
// // we have to flush statements here - the records would be updated only at the end of the transaction otherwise
// batchOperations.flushStatements();
// }
//
// @Override
// public void insertDepartments(List<Department> departmentsToInsert) {
// DataRepositoryMapper batchSql = batchOperations.getMapper(DataRepositoryMapper.class);
// departmentsToInsert.forEach(batchSql::insertDepartment);
// // we have to flush statements here - the records would be inserted only at the end of the transaction otherwise
// batchOperations.flushStatements();
// }
//
// @Override
// public Project findProject(Integer pid) {
// return sql.findProject(pid);
// }
//
// @Override
// public Integer insertProject(Project project) {
// sql.insertProject(project);
// return project.getPid();
// }
//
// @Override
// public List<Integer> insertProjects(List<Project> projects) {
// DataRepositoryMapper batchSql = batchOperations.getMapper(DataRepositoryMapper.class);
// projects.forEach(batchSql::insertProject);
// // we have to flush statements here - the records would be inserted only at the end of the transaction otherwise
// batchOperations.flushStatements();
//
// // MyBatis can actually return the PIDs from batch operation
// return projects.stream().map(Project::getPid).collect(Collectors.toList());
// }
//
// @Override
// public List<ProjectsWithCostsGreaterThanOutput> getProjectsWithCostsGreaterThan(int totalCostBoundary) {
// return sql.getProjectsWithCostsGreaterThan(totalCostBoundary);
// }
//
// @Override
// public Employee findEmployee(Integer pid) {
// return sql.findEmployee(pid);
// }
//
// @Override
// public List<Employee> employeesWithSalaryGreaterThan(Integer minSalary) {
// return sql.employeesWithSalaryGreaterThan(minSalary);
// }
//
// @Override
// public void updateEmployee(Employee employeeToUpdate) {
// sql.updateEmployee(employeeToUpdate);
// }
//
// @Override
// public RegisterEmployeeOutput callRegisterEmployee(String name, String surname, String email, BigDecimal salary, String departmentName, String companyName) {
// return sql.callRegisterEmployee(name, surname, email, salary, departmentName, companyName);
// }
//
// @Override
// public Integer getProjectsCount() {
// return sql.getProjectsCount();
// }
// }
// Path: src/test/java/com/clevergang/dbtests/MyBatisScenariosTest.java
import com.clevergang.dbtests.repository.impl.mybatis.MyBatisDataRepositoryImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
package com.clevergang.dbtests;
/**
* @author Bretislav Wajtr
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = DbTestsApplication.class)
@Transactional
@Rollback
public class MyBatisScenariosTest {
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired | private MyBatisDataRepositoryImpl myBatisDataRepository; |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/Scenarios.java | // Path: src/main/java/com/clevergang/dbtests/repository/api/DataRepository.java
// public interface DataRepository {
//
// // Companies
//
// /**
// * @param pid Primary key of the company record to be found
// * @return Should return full record of the Company record identified by pid
// */
// Company findCompany(Integer pid);
//
// /**
// * @param pid Primary key of the company record to be found
// * @return Should return full record of the Company record identified by pid. A static (non-prepared) statement should be used for that.
// */
// Company findCompanyUsingSimpleStaticStatement(Integer pid);
//
// // Departments
//
// /**
// * @param pid Primary key of the Department record to be found
// * @return Should return full record of the Department record identified by pid
// */
// Department findDepartment(Integer pid);
//
// /**
// * Should return full records of all Departments assigned to the Company (passed in as parameter).
// * @param company Full Company record
// * @return List of Departments, ordered by PID ascending
// */
// List<Department> findDepartmentsOfCompany(Company company);
//
// /**
// * Should immediately delete Departments passed in as parameter from database. Should do it in most efficient way (preferably as batch operation).
// * We expect that the deletions were already performed in database upon return from this method.
// *
// * @param departmentsToDelete Full records of Departments to be deleted
// */
// void deleteDepartments(List<Department> departmentsToDelete);
//
// /**
// * Should immediately update Department records passed in as parameter. Should do it in most efficient way (preferably as batch operation).
// * We expect that the updates were already performed in database upon return from this method (meaning all required SQL statements were already
// * executed and are not deferred to a later time).
// *
// * @param departmentsToUpdate Full records of Departments to be updated. Update all fields of Department, identified by Department.getPid()
// */
// void updateDepartments(List<Department> departmentsToUpdate);
//
// /**
// * Should immediately insert Department records passed in as parameter. Should do it in most efficient way (preferably as batch operation).
// * We expect that the inserts were already performed in database upon return from this method (meaning all required SQL statements were already
// * executed and are not deferred to a later time).
// *
// * @param departmentsToInsert Full records of Departments to be inserted. Records should have getPid()==null
// */
// void insertDepartments(List<Department> departmentsToInsert);
//
//
//
//
// // Projects
//
// /**
// * @param pid Primary key of the project record to be found
// * @return Should return full record of the Project record identified by pid
// */
// Project findProject(Integer pid);
//
// /**
// * Insert project and return PID of newly created item
// *
// * @param project Project to be inserted
// * @return PID of new record in database
// */
// Integer insertProject(Project project);
//
// /**
// * Should immediately insert Project records passed in as parameter. Should do it in most efficient way (preferably as batch operation).
// * We expect that the inserts were already performed in database upon return from this method (meaning all required SQL statements were already
// * executed and are not deferred to a later time).
// *
// * @param projects New projects to insert
// * @return List of PIDs of newly created records.
// */
// List<Integer> insertProjects(List<Project> projects);
//
// /**
// * Execute following query: get all projects, where the total cost of the project per month is greater than parameter totalCostBoundary. In the same result set
// * get all companies participating on such project along with cost of the project for the company.
// */
// List<ProjectsWithCostsGreaterThanOutput> getProjectsWithCostsGreaterThan(int totalCostBoundary);
//
//
//
// // Employees
//
// /**
// * @param pid Primary key of the employee record to be found
// * @return Should return full record of the Employee record identified by pid
// */
// Employee findEmployee(Integer pid);
//
//
// /**
// * Execute following query and return all Employee records satisfying following condition: salary of the employee
// * is greater than parameter minSalary
// */
// List<Employee> employeesWithSalaryGreaterThan(Integer minSalary);
//
//
// /**
// * Should immediately update Employee record passed in as parameter. Should do it in most efficient way.
// * We expect that the update was already performed in database upon return from this method (meaning SQL statement was already
// * executed and is not deferred to a later time).
// *
// * @param employeeToUpdate Full records of Employee to be updated. Update all fields of Employee, identified by Employee.getPid()
// */
// void updateEmployee(Employee employeeToUpdate);
//
//
// /**
// * Register new employee and create company and department if required - use stored procedure register_employee (see register_employee.sql)
// * to perform the operation.
// *
// * @return Newly created PIDs of records (output of the stored procedure)
// */
// RegisterEmployeeOutput callRegisterEmployee(String name, String surname, String email, BigDecimal salary,
// String departmentName, String companyName);
//
// /**
// * @return Return count of records in Project table
// */
// Integer getProjectsCount();
//
// /**
// * Removes project record from database based on primary key
// * @param pid Primary key of the project to be removed
// */
// void removeProject(Integer pid);
//
// }
| import com.clevergang.dbtests.repository.api.DataRepository;
import com.clevergang.dbtests.repository.api.data.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList; | package com.clevergang.dbtests;
/**
* Implementation of the scenarios. Note that the scenarios are always the same, what changes is the
* DB API implementation. To make things little bit easier for us we do not autowire the
* DB API implementation, but we pass it to the constructor of the Scenarios class instead - this
* isn't typical pattern we use in production code.
*
* @author Bretislav Wajtr
*/
@SuppressWarnings("WeakerAccess")
public class Scenarios {
private static final Logger logger = LoggerFactory.getLogger(Scenarios.class);
| // Path: src/main/java/com/clevergang/dbtests/repository/api/DataRepository.java
// public interface DataRepository {
//
// // Companies
//
// /**
// * @param pid Primary key of the company record to be found
// * @return Should return full record of the Company record identified by pid
// */
// Company findCompany(Integer pid);
//
// /**
// * @param pid Primary key of the company record to be found
// * @return Should return full record of the Company record identified by pid. A static (non-prepared) statement should be used for that.
// */
// Company findCompanyUsingSimpleStaticStatement(Integer pid);
//
// // Departments
//
// /**
// * @param pid Primary key of the Department record to be found
// * @return Should return full record of the Department record identified by pid
// */
// Department findDepartment(Integer pid);
//
// /**
// * Should return full records of all Departments assigned to the Company (passed in as parameter).
// * @param company Full Company record
// * @return List of Departments, ordered by PID ascending
// */
// List<Department> findDepartmentsOfCompany(Company company);
//
// /**
// * Should immediately delete Departments passed in as parameter from database. Should do it in most efficient way (preferably as batch operation).
// * We expect that the deletions were already performed in database upon return from this method.
// *
// * @param departmentsToDelete Full records of Departments to be deleted
// */
// void deleteDepartments(List<Department> departmentsToDelete);
//
// /**
// * Should immediately update Department records passed in as parameter. Should do it in most efficient way (preferably as batch operation).
// * We expect that the updates were already performed in database upon return from this method (meaning all required SQL statements were already
// * executed and are not deferred to a later time).
// *
// * @param departmentsToUpdate Full records of Departments to be updated. Update all fields of Department, identified by Department.getPid()
// */
// void updateDepartments(List<Department> departmentsToUpdate);
//
// /**
// * Should immediately insert Department records passed in as parameter. Should do it in most efficient way (preferably as batch operation).
// * We expect that the inserts were already performed in database upon return from this method (meaning all required SQL statements were already
// * executed and are not deferred to a later time).
// *
// * @param departmentsToInsert Full records of Departments to be inserted. Records should have getPid()==null
// */
// void insertDepartments(List<Department> departmentsToInsert);
//
//
//
//
// // Projects
//
// /**
// * @param pid Primary key of the project record to be found
// * @return Should return full record of the Project record identified by pid
// */
// Project findProject(Integer pid);
//
// /**
// * Insert project and return PID of newly created item
// *
// * @param project Project to be inserted
// * @return PID of new record in database
// */
// Integer insertProject(Project project);
//
// /**
// * Should immediately insert Project records passed in as parameter. Should do it in most efficient way (preferably as batch operation).
// * We expect that the inserts were already performed in database upon return from this method (meaning all required SQL statements were already
// * executed and are not deferred to a later time).
// *
// * @param projects New projects to insert
// * @return List of PIDs of newly created records.
// */
// List<Integer> insertProjects(List<Project> projects);
//
// /**
// * Execute following query: get all projects, where the total cost of the project per month is greater than parameter totalCostBoundary. In the same result set
// * get all companies participating on such project along with cost of the project for the company.
// */
// List<ProjectsWithCostsGreaterThanOutput> getProjectsWithCostsGreaterThan(int totalCostBoundary);
//
//
//
// // Employees
//
// /**
// * @param pid Primary key of the employee record to be found
// * @return Should return full record of the Employee record identified by pid
// */
// Employee findEmployee(Integer pid);
//
//
// /**
// * Execute following query and return all Employee records satisfying following condition: salary of the employee
// * is greater than parameter minSalary
// */
// List<Employee> employeesWithSalaryGreaterThan(Integer minSalary);
//
//
// /**
// * Should immediately update Employee record passed in as parameter. Should do it in most efficient way.
// * We expect that the update was already performed in database upon return from this method (meaning SQL statement was already
// * executed and is not deferred to a later time).
// *
// * @param employeeToUpdate Full records of Employee to be updated. Update all fields of Employee, identified by Employee.getPid()
// */
// void updateEmployee(Employee employeeToUpdate);
//
//
// /**
// * Register new employee and create company and department if required - use stored procedure register_employee (see register_employee.sql)
// * to perform the operation.
// *
// * @return Newly created PIDs of records (output of the stored procedure)
// */
// RegisterEmployeeOutput callRegisterEmployee(String name, String surname, String email, BigDecimal salary,
// String departmentName, String companyName);
//
// /**
// * @return Return count of records in Project table
// */
// Integer getProjectsCount();
//
// /**
// * Removes project record from database based on primary key
// * @param pid Primary key of the project to be removed
// */
// void removeProject(Integer pid);
//
// }
// Path: src/main/java/com/clevergang/dbtests/Scenarios.java
import com.clevergang.dbtests.repository.api.DataRepository;
import com.clevergang.dbtests.repository.api.data.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
package com.clevergang.dbtests;
/**
* Implementation of the scenarios. Note that the scenarios are always the same, what changes is the
* DB API implementation. To make things little bit easier for us we do not autowire the
* DB API implementation, but we pass it to the constructor of the Scenarios class instead - this
* isn't typical pattern we use in production code.
*
* @author Bretislav Wajtr
*/
@SuppressWarnings("WeakerAccess")
public class Scenarios {
private static final Logger logger = LoggerFactory.getLogger(Scenarios.class);
| private final DataRepository repository; |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/routines/RegisterEmployee.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/Public.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Public extends SchemaImpl {
//
// private static final long serialVersionUID = 1615711012;
//
// /**
// * The reference instance of <code>public</code>
// */
// public static final Public PUBLIC = new Public();
//
// /**
// * The table <code>public.company</code>.
// */
// public final Company COMPANY = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Company.COMPANY;
//
// /**
// * The table <code>public.department</code>.
// */
// public final Department DEPARTMENT = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Department.DEPARTMENT;
//
// /**
// * The table <code>public.employee</code>.
// */
// public final Employee EMPLOYEE = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Employee.EMPLOYEE;
//
// /**
// * The table <code>public.project</code>.
// */
// public final Project PROJECT = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Project.PROJECT;
//
// /**
// * The table <code>public.projectemployee</code>.
// */
// public final Projectemployee PROJECTEMPLOYEE = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Projectemployee.PROJECTEMPLOYEE;
//
// /**
// * No further instances allowed
// */
// private Public() {
// super("public", null);
// }
//
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Catalog getCatalog() {
// return DefaultCatalog.DEFAULT_CATALOG;
// }
//
// @Override
// public final List<Sequence<?>> getSequences() {
// List result = new ArrayList();
// result.addAll(getSequences0());
// return result;
// }
//
// private final List<Sequence<?>> getSequences0() {
// return Arrays.<Sequence<?>>asList(
// Sequences.COMPANY_PID_SEQ,
// Sequences.DEPARTMENT_PID_SEQ,
// Sequences.EMPLOYEE_PID_SEQ,
// Sequences.PROJECT_PID_SEQ);
// }
//
// @Override
// public final List<Table<?>> getTables() {
// List result = new ArrayList();
// result.addAll(getTables0());
// return result;
// }
//
// private final List<Table<?>> getTables0() {
// return Arrays.<Table<?>>asList(
// Company.COMPANY,
// Department.DEPARTMENT,
// Employee.EMPLOYEE,
// Project.PROJECT,
// Projectemployee.PROJECTEMPLOYEE);
// }
// }
| import com.clevergang.dbtests.repository.impl.jooq.generated.Public;
import org.jooq.Parameter;
import org.jooq.impl.AbstractRoutine;
import javax.annotation.Generated;
import java.math.BigDecimal; | /**
* This class is generated by jOOQ
*/
package com.clevergang.dbtests.repository.impl.jooq.generated.routines;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class RegisterEmployee extends AbstractRoutine<java.lang.Void> {
private static final long serialVersionUID = -1642852;
/**
* The parameter <code>public.register_employee._name</code>.
*/
public static final Parameter<String> _NAME = createParameter("_name", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._surname</code>.
*/
public static final Parameter<String> _SURNAME = createParameter("_surname", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._email</code>.
*/
public static final Parameter<String> _EMAIL = createParameter("_email", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._salary</code>.
*/
public static final Parameter<BigDecimal> _SALARY = createParameter("_salary", org.jooq.impl.SQLDataType.NUMERIC, false, false);
/**
* The parameter <code>public.register_employee._department_name</code>.
*/
public static final Parameter<String> _DEPARTMENT_NAME = createParameter("_department_name", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._company_name</code>.
*/
public static final Parameter<String> _COMPANY_NAME = createParameter("_company_name", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee.employee_id</code>.
*/
public static final Parameter<Integer> EMPLOYEE_ID = createParameter("employee_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
/**
* The parameter <code>public.register_employee.department_id</code>.
*/
public static final Parameter<Integer> DEPARTMENT_ID = createParameter("department_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
/**
* The parameter <code>public.register_employee.company_id</code>.
*/
public static final Parameter<Integer> COMPANY_ID = createParameter("company_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
/**
* Create a new routine call instance
*/
public RegisterEmployee() { | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/Public.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Public extends SchemaImpl {
//
// private static final long serialVersionUID = 1615711012;
//
// /**
// * The reference instance of <code>public</code>
// */
// public static final Public PUBLIC = new Public();
//
// /**
// * The table <code>public.company</code>.
// */
// public final Company COMPANY = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Company.COMPANY;
//
// /**
// * The table <code>public.department</code>.
// */
// public final Department DEPARTMENT = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Department.DEPARTMENT;
//
// /**
// * The table <code>public.employee</code>.
// */
// public final Employee EMPLOYEE = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Employee.EMPLOYEE;
//
// /**
// * The table <code>public.project</code>.
// */
// public final Project PROJECT = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Project.PROJECT;
//
// /**
// * The table <code>public.projectemployee</code>.
// */
// public final Projectemployee PROJECTEMPLOYEE = com.clevergang.dbtests.repository.impl.jooq.generated.tables.Projectemployee.PROJECTEMPLOYEE;
//
// /**
// * No further instances allowed
// */
// private Public() {
// super("public", null);
// }
//
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Catalog getCatalog() {
// return DefaultCatalog.DEFAULT_CATALOG;
// }
//
// @Override
// public final List<Sequence<?>> getSequences() {
// List result = new ArrayList();
// result.addAll(getSequences0());
// return result;
// }
//
// private final List<Sequence<?>> getSequences0() {
// return Arrays.<Sequence<?>>asList(
// Sequences.COMPANY_PID_SEQ,
// Sequences.DEPARTMENT_PID_SEQ,
// Sequences.EMPLOYEE_PID_SEQ,
// Sequences.PROJECT_PID_SEQ);
// }
//
// @Override
// public final List<Table<?>> getTables() {
// List result = new ArrayList();
// result.addAll(getTables0());
// return result;
// }
//
// private final List<Table<?>> getTables0() {
// return Arrays.<Table<?>>asList(
// Company.COMPANY,
// Department.DEPARTMENT,
// Employee.EMPLOYEE,
// Project.PROJECT,
// Projectemployee.PROJECTEMPLOYEE);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/routines/RegisterEmployee.java
import com.clevergang.dbtests.repository.impl.jooq.generated.Public;
import org.jooq.Parameter;
import org.jooq.impl.AbstractRoutine;
import javax.annotation.Generated;
import java.math.BigDecimal;
/**
* This class is generated by jOOQ
*/
package com.clevergang.dbtests.repository.impl.jooq.generated.routines;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class RegisterEmployee extends AbstractRoutine<java.lang.Void> {
private static final long serialVersionUID = -1642852;
/**
* The parameter <code>public.register_employee._name</code>.
*/
public static final Parameter<String> _NAME = createParameter("_name", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._surname</code>.
*/
public static final Parameter<String> _SURNAME = createParameter("_surname", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._email</code>.
*/
public static final Parameter<String> _EMAIL = createParameter("_email", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._salary</code>.
*/
public static final Parameter<BigDecimal> _SALARY = createParameter("_salary", org.jooq.impl.SQLDataType.NUMERIC, false, false);
/**
* The parameter <code>public.register_employee._department_name</code>.
*/
public static final Parameter<String> _DEPARTMENT_NAME = createParameter("_department_name", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee._company_name</code>.
*/
public static final Parameter<String> _COMPANY_NAME = createParameter("_company_name", org.jooq.impl.SQLDataType.CLOB, false, false);
/**
* The parameter <code>public.register_employee.employee_id</code>.
*/
public static final Parameter<Integer> EMPLOYEE_ID = createParameter("employee_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
/**
* The parameter <code>public.register_employee.department_id</code>.
*/
public static final Parameter<Integer> DEPARTMENT_ID = createParameter("department_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
/**
* The parameter <code>public.register_employee.company_id</code>.
*/
public static final Parameter<Integer> COMPANY_ID = createParameter("company_id", org.jooq.impl.SQLDataType.INTEGER, false, false);
/**
* Create a new routine call instance
*/
public RegisterEmployee() { | super("register_employee", Public.PUBLIC); |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/EmployeeRecord.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Employee.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Employee extends TableImpl<EmployeeRecord> {
//
// private static final long serialVersionUID = -2096947570;
//
// /**
// * The reference instance of <code>public.employee</code>
// */
// public static final Employee EMPLOYEE = new Employee();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<EmployeeRecord> getRecordType() {
// return EmployeeRecord.class;
// }
//
// /**
// * The column <code>public.employee.pid</code>.
// */
// public final TableField<EmployeeRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('employee_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.employee.department_pid</code>.
// */
// public final TableField<EmployeeRecord, Integer> DEPARTMENT_PID = createField("department_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.employee.name</code>.
// */
// public final TableField<EmployeeRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.employee.surname</code>.
// */
// public final TableField<EmployeeRecord, String> SURNAME = createField("surname", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.employee.email</code>.
// */
// public final TableField<EmployeeRecord, String> EMAIL = createField("email", org.jooq.impl.SQLDataType.CLOB, this, "");
//
// /**
// * The column <code>public.employee.salary</code>.
// */
// public final TableField<EmployeeRecord, BigDecimal> SALARY = createField("salary", org.jooq.impl.SQLDataType.NUMERIC.precision(10, 2), this, "");
//
// /**
// * Create a <code>public.employee</code> table reference
// */
// public Employee() {
// this("employee", null);
// }
//
// /**
// * Create an aliased <code>public.employee</code> table reference
// */
// public Employee(String alias) {
// this(alias, EMPLOYEE);
// }
//
// private Employee(String alias, Table<EmployeeRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Employee(String alias, Table<EmployeeRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<EmployeeRecord, Integer> getIdentity() {
// return Keys.IDENTITY_EMPLOYEE;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<EmployeeRecord> getPrimaryKey() {
// return Keys.EMPLOYEE_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<EmployeeRecord>> getKeys() {
// return Arrays.<UniqueKey<EmployeeRecord>>asList(Keys.EMPLOYEE_PKEY, Keys.EMPLOYEE_NAME_SURNAME_UNIQUE);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<ForeignKey<EmployeeRecord, ?>> getReferences() {
// return Arrays.<ForeignKey<EmployeeRecord, ?>>asList(Keys.EMPLOYEE__EMPLOYEE_DEPARTMENT_PID_FKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Employee as(String alias) {
// return new Employee(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Employee rename(String name) {
// return new Employee(name, null);
// }
// }
| import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Employee;
import java.math.BigDecimal;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record6;
import org.jooq.Row6;
import org.jooq.impl.UpdatableRecordImpl; | @Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record6 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row6<Integer, Integer, String, String, String, BigDecimal> fieldsRow() {
return (Row6) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row6<Integer, Integer, String, String, String, BigDecimal> valuesRow() {
return (Row6) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Employee.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Employee extends TableImpl<EmployeeRecord> {
//
// private static final long serialVersionUID = -2096947570;
//
// /**
// * The reference instance of <code>public.employee</code>
// */
// public static final Employee EMPLOYEE = new Employee();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<EmployeeRecord> getRecordType() {
// return EmployeeRecord.class;
// }
//
// /**
// * The column <code>public.employee.pid</code>.
// */
// public final TableField<EmployeeRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('employee_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.employee.department_pid</code>.
// */
// public final TableField<EmployeeRecord, Integer> DEPARTMENT_PID = createField("department_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.employee.name</code>.
// */
// public final TableField<EmployeeRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.employee.surname</code>.
// */
// public final TableField<EmployeeRecord, String> SURNAME = createField("surname", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.employee.email</code>.
// */
// public final TableField<EmployeeRecord, String> EMAIL = createField("email", org.jooq.impl.SQLDataType.CLOB, this, "");
//
// /**
// * The column <code>public.employee.salary</code>.
// */
// public final TableField<EmployeeRecord, BigDecimal> SALARY = createField("salary", org.jooq.impl.SQLDataType.NUMERIC.precision(10, 2), this, "");
//
// /**
// * Create a <code>public.employee</code> table reference
// */
// public Employee() {
// this("employee", null);
// }
//
// /**
// * Create an aliased <code>public.employee</code> table reference
// */
// public Employee(String alias) {
// this(alias, EMPLOYEE);
// }
//
// private Employee(String alias, Table<EmployeeRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Employee(String alias, Table<EmployeeRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<EmployeeRecord, Integer> getIdentity() {
// return Keys.IDENTITY_EMPLOYEE;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<EmployeeRecord> getPrimaryKey() {
// return Keys.EMPLOYEE_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<EmployeeRecord>> getKeys() {
// return Arrays.<UniqueKey<EmployeeRecord>>asList(Keys.EMPLOYEE_PKEY, Keys.EMPLOYEE_NAME_SURNAME_UNIQUE);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<ForeignKey<EmployeeRecord, ?>> getReferences() {
// return Arrays.<ForeignKey<EmployeeRecord, ?>>asList(Keys.EMPLOYEE__EMPLOYEE_DEPARTMENT_PID_FKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Employee as(String alias) {
// return new Employee(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Employee rename(String name) {
// return new Employee(name, null);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/EmployeeRecord.java
import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Employee;
import java.math.BigDecimal;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record6;
import org.jooq.Row6;
import org.jooq.impl.UpdatableRecordImpl;
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record6 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row6<Integer, Integer, String, String, String, BigDecimal> fieldsRow() {
return (Row6) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row6<Integer, Integer, String, String, String, BigDecimal> valuesRow() {
return (Row6) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | return Employee.EMPLOYEE.PID; |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/CompanyRecord.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Company.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Company extends TableImpl<CompanyRecord> {
//
// private static final long serialVersionUID = 662824552;
//
// /**
// * The reference instance of <code>public.company</code>
// */
// public static final Company COMPANY = new Company();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<CompanyRecord> getRecordType() {
// return CompanyRecord.class;
// }
//
// /**
// * The column <code>public.company.pid</code>.
// */
// public final TableField<CompanyRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('company_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.company.name</code>.
// */
// public final TableField<CompanyRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.company.address</code>.
// */
// public final TableField<CompanyRecord, String> ADDRESS = createField("address", org.jooq.impl.SQLDataType.CLOB, this, "");
//
// /**
// * Create a <code>public.company</code> table reference
// */
// public Company() {
// this("company", null);
// }
//
// /**
// * Create an aliased <code>public.company</code> table reference
// */
// public Company(String alias) {
// this(alias, COMPANY);
// }
//
// private Company(String alias, Table<CompanyRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Company(String alias, Table<CompanyRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<CompanyRecord, Integer> getIdentity() {
// return Keys.IDENTITY_COMPANY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<CompanyRecord> getPrimaryKey() {
// return Keys.COMPANY_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<CompanyRecord>> getKeys() {
// return Arrays.<UniqueKey<CompanyRecord>>asList(Keys.COMPANY_PKEY, Keys.COMPANY_NAME_KEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Company as(String alias) {
// return new Company(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Company rename(String name) {
// return new Company(name, null);
// }
// }
| import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Company;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl; | @Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, String> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, String> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Company.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Company extends TableImpl<CompanyRecord> {
//
// private static final long serialVersionUID = 662824552;
//
// /**
// * The reference instance of <code>public.company</code>
// */
// public static final Company COMPANY = new Company();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<CompanyRecord> getRecordType() {
// return CompanyRecord.class;
// }
//
// /**
// * The column <code>public.company.pid</code>.
// */
// public final TableField<CompanyRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('company_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.company.name</code>.
// */
// public final TableField<CompanyRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * The column <code>public.company.address</code>.
// */
// public final TableField<CompanyRecord, String> ADDRESS = createField("address", org.jooq.impl.SQLDataType.CLOB, this, "");
//
// /**
// * Create a <code>public.company</code> table reference
// */
// public Company() {
// this("company", null);
// }
//
// /**
// * Create an aliased <code>public.company</code> table reference
// */
// public Company(String alias) {
// this(alias, COMPANY);
// }
//
// private Company(String alias, Table<CompanyRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Company(String alias, Table<CompanyRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<CompanyRecord, Integer> getIdentity() {
// return Keys.IDENTITY_COMPANY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<CompanyRecord> getPrimaryKey() {
// return Keys.COMPANY_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<CompanyRecord>> getKeys() {
// return Arrays.<UniqueKey<CompanyRecord>>asList(Keys.COMPANY_PKEY, Keys.COMPANY_NAME_KEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Company as(String alias) {
// return new Company(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Company rename(String name) {
// return new Company(name, null);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/CompanyRecord.java
import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Company;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, String> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, String> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | return Company.COMPANY.PID; |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/DepartmentRecord.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Department.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Department extends TableImpl<DepartmentRecord> {
//
// private static final long serialVersionUID = 1675244566;
//
// /**
// * The reference instance of <code>public.department</code>
// */
// public static final Department DEPARTMENT = new Department();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<DepartmentRecord> getRecordType() {
// return DepartmentRecord.class;
// }
//
// /**
// * The column <code>public.department.pid</code>.
// */
// public final TableField<DepartmentRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('department_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.department.company_pid</code>.
// */
// public final TableField<DepartmentRecord, Integer> COMPANY_PID = createField("company_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.department.name</code>.
// */
// public final TableField<DepartmentRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * Create a <code>public.department</code> table reference
// */
// public Department() {
// this("department", null);
// }
//
// /**
// * Create an aliased <code>public.department</code> table reference
// */
// public Department(String alias) {
// this(alias, DEPARTMENT);
// }
//
// private Department(String alias, Table<DepartmentRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Department(String alias, Table<DepartmentRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<DepartmentRecord, Integer> getIdentity() {
// return Keys.IDENTITY_DEPARTMENT;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<DepartmentRecord> getPrimaryKey() {
// return Keys.DEPARTMENT_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<DepartmentRecord>> getKeys() {
// return Arrays.<UniqueKey<DepartmentRecord>>asList(Keys.DEPARTMENT_PKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<ForeignKey<DepartmentRecord, ?>> getReferences() {
// return Arrays.<ForeignKey<DepartmentRecord, ?>>asList(Keys.DEPARTMENT__DEPARTMENT_COMPANY_PID_FKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Department as(String alias) {
// return new Department(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Department rename(String name) {
// return new Department(name, null);
// }
// }
| import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Department;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl; | @Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, Integer, String> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, Integer, String> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Department.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Department extends TableImpl<DepartmentRecord> {
//
// private static final long serialVersionUID = 1675244566;
//
// /**
// * The reference instance of <code>public.department</code>
// */
// public static final Department DEPARTMENT = new Department();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<DepartmentRecord> getRecordType() {
// return DepartmentRecord.class;
// }
//
// /**
// * The column <code>public.department.pid</code>.
// */
// public final TableField<DepartmentRecord, Integer> PID = createField("pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.field("nextval('department_pid_seq'::regclass)", org.jooq.impl.SQLDataType.INTEGER)), this, "");
//
// /**
// * The column <code>public.department.company_pid</code>.
// */
// public final TableField<DepartmentRecord, Integer> COMPANY_PID = createField("company_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.department.name</code>.
// */
// public final TableField<DepartmentRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
//
// /**
// * Create a <code>public.department</code> table reference
// */
// public Department() {
// this("department", null);
// }
//
// /**
// * Create an aliased <code>public.department</code> table reference
// */
// public Department(String alias) {
// this(alias, DEPARTMENT);
// }
//
// private Department(String alias, Table<DepartmentRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Department(String alias, Table<DepartmentRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Identity<DepartmentRecord, Integer> getIdentity() {
// return Keys.IDENTITY_DEPARTMENT;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<DepartmentRecord> getPrimaryKey() {
// return Keys.DEPARTMENT_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<DepartmentRecord>> getKeys() {
// return Arrays.<UniqueKey<DepartmentRecord>>asList(Keys.DEPARTMENT_PKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<ForeignKey<DepartmentRecord, ?>> getReferences() {
// return Arrays.<ForeignKey<DepartmentRecord, ?>>asList(Keys.DEPARTMENT__DEPARTMENT_COMPANY_PID_FKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Department as(String alias) {
// return new Department(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Department rename(String name) {
// return new Department(name, null);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/DepartmentRecord.java
import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Department;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, Integer, String> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, Integer, String> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | return Department.DEPARTMENT.PID; |
bwajtr/java-persistence-frameworks-comparison | src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/ProjectemployeeRecord.java | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Projectemployee.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Projectemployee extends TableImpl<ProjectemployeeRecord> {
//
// private static final long serialVersionUID = 821784743;
//
// /**
// * The reference instance of <code>public.projectemployee</code>
// */
// public static final Projectemployee PROJECTEMPLOYEE = new Projectemployee();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<ProjectemployeeRecord> getRecordType() {
// return ProjectemployeeRecord.class;
// }
//
// /**
// * The column <code>public.projectemployee.project_pid</code>.
// */
// public final TableField<ProjectemployeeRecord, Integer> PROJECT_PID = createField("project_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.projectemployee.employee_pid</code>.
// */
// public final TableField<ProjectemployeeRecord, Integer> EMPLOYEE_PID = createField("employee_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * Create a <code>public.projectemployee</code> table reference
// */
// public Projectemployee() {
// this("projectemployee", null);
// }
//
// /**
// * Create an aliased <code>public.projectemployee</code> table reference
// */
// public Projectemployee(String alias) {
// this(alias, PROJECTEMPLOYEE);
// }
//
// private Projectemployee(String alias, Table<ProjectemployeeRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Projectemployee(String alias, Table<ProjectemployeeRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<ProjectemployeeRecord> getPrimaryKey() {
// return Keys.PROJECTEMPLOYEE_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<ProjectemployeeRecord>> getKeys() {
// return Arrays.<UniqueKey<ProjectemployeeRecord>>asList(Keys.PROJECTEMPLOYEE_PKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<ForeignKey<ProjectemployeeRecord, ?>> getReferences() {
// return Arrays.<ForeignKey<ProjectemployeeRecord, ?>>asList(Keys.PROJECTEMPLOYEE__PROJECTEMPLOYEE_PROJECT_PID_FKEY, Keys.PROJECTEMPLOYEE__PROJECTEMPLOYEE_EMPLOYEE_PID_FKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Projectemployee as(String alias) {
// return new Projectemployee(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Projectemployee rename(String name) {
// return new Projectemployee(name, null);
// }
// }
| import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Projectemployee;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record2;
import org.jooq.Row2;
import org.jooq.impl.UpdatableRecordImpl; | @Override
public Record2<Integer, Integer> key() {
return (Record2) super.key();
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row2<Integer, Integer> fieldsRow() {
return (Row2) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row2<Integer, Integer> valuesRow() {
return (Row2) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | // Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/Projectemployee.java
// @Generated(
// value = {
// "http://www.jooq.org",
// "jOOQ version:3.8.4"
// },
// comments = "This class is generated by jOOQ"
// )
// @SuppressWarnings({ "all", "unchecked", "rawtypes" })
// public class Projectemployee extends TableImpl<ProjectemployeeRecord> {
//
// private static final long serialVersionUID = 821784743;
//
// /**
// * The reference instance of <code>public.projectemployee</code>
// */
// public static final Projectemployee PROJECTEMPLOYEE = new Projectemployee();
//
// /**
// * The class holding records for this type
// */
// @Override
// public Class<ProjectemployeeRecord> getRecordType() {
// return ProjectemployeeRecord.class;
// }
//
// /**
// * The column <code>public.projectemployee.project_pid</code>.
// */
// public final TableField<ProjectemployeeRecord, Integer> PROJECT_PID = createField("project_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * The column <code>public.projectemployee.employee_pid</code>.
// */
// public final TableField<ProjectemployeeRecord, Integer> EMPLOYEE_PID = createField("employee_pid", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
//
// /**
// * Create a <code>public.projectemployee</code> table reference
// */
// public Projectemployee() {
// this("projectemployee", null);
// }
//
// /**
// * Create an aliased <code>public.projectemployee</code> table reference
// */
// public Projectemployee(String alias) {
// this(alias, PROJECTEMPLOYEE);
// }
//
// private Projectemployee(String alias, Table<ProjectemployeeRecord> aliased) {
// this(alias, aliased, null);
// }
//
// private Projectemployee(String alias, Table<ProjectemployeeRecord> aliased, Field<?>[] parameters) {
// super(alias, null, aliased, parameters, "");
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Schema getSchema() {
// return Public.PUBLIC;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public UniqueKey<ProjectemployeeRecord> getPrimaryKey() {
// return Keys.PROJECTEMPLOYEE_PKEY;
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<UniqueKey<ProjectemployeeRecord>> getKeys() {
// return Arrays.<UniqueKey<ProjectemployeeRecord>>asList(Keys.PROJECTEMPLOYEE_PKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public List<ForeignKey<ProjectemployeeRecord, ?>> getReferences() {
// return Arrays.<ForeignKey<ProjectemployeeRecord, ?>>asList(Keys.PROJECTEMPLOYEE__PROJECTEMPLOYEE_PROJECT_PID_FKEY, Keys.PROJECTEMPLOYEE__PROJECTEMPLOYEE_EMPLOYEE_PID_FKEY);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public Projectemployee as(String alias) {
// return new Projectemployee(alias, this);
// }
//
// /**
// * Rename this table
// */
// public Projectemployee rename(String name) {
// return new Projectemployee(name, null);
// }
// }
// Path: src/main/java/com/clevergang/dbtests/repository/impl/jooq/generated/tables/records/ProjectemployeeRecord.java
import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Projectemployee;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record2;
import org.jooq.Row2;
import org.jooq.impl.UpdatableRecordImpl;
@Override
public Record2<Integer, Integer> key() {
return (Record2) super.key();
}
// -------------------------------------------------------------------------
// Record2 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row2<Integer, Integer> fieldsRow() {
return (Row2) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row2<Integer, Integer> valuesRow() {
return (Row2) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() { | return Projectemployee.PROJECTEMPLOYEE.PROJECT_PID; |
jpatanooga/KnittingBoar | src/test/java/com/cloudera/knittingboar/records/TestTwentyNewsgroupsCustomRecordParseOLRRun.java | // Path: src/main/java/com/cloudera/knittingboar/io/InputRecordsSplit.java
// public class InputRecordsSplit {
//
// TextInputFormat input_format = null;
// InputSplit split = null;
// JobConf jobConf = null;
//
// RecordReader<LongWritable,Text> reader = null;
// LongWritable key = null;
//
// final Reporter voidReporter = Reporter.NULL;
//
// public InputRecordsSplit(JobConf jobConf, InputSplit split)
// throws IOException {
//
// this.jobConf = jobConf;
// this.split = split;
// this.input_format = new TextInputFormat();
//
// // RecordReader<LongWritable, Text> reader =
// // format.getRecordReader(splits[x], job, reporter);
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
// this.key = reader.createKey();
// // Text value = reader.createValue();
//
// }
//
// /**
// *
// * just a dead simple way to do this
// *
// * - functionality from TestTextInputFormat::readSplit()
// *
// * If returns true, then csv_line contains the next line If returns false,
// * then there is no next record
// *
// * Will terminate when it hits the end of the split based on the information
// * provided in the split class to the constructor and the TextInputFormat
// *
// * @param csv_line
// * @throws IOException
// */
// public boolean next(Text csv_line) throws IOException {
//
// return reader.next(key, csv_line);
//
// }
//
// public void ResetToStartOfSplit() throws IOException {
//
// // I'mma cheatin here. sue me.
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
//
// }
//
// }
//
// Path: src/test/java/com/cloudera/knittingboar/utils/TestingUtils.java
// public class TestingUtils {
//
// public static void copyDecompressed(String resource, File output)
// throws IOException {
// URL input = Resources.getResource(resource);
// ByteStreams.copy(new GZIPInputStream(input.openStream()),
// new FileOutputStream(output));
// }
//
// }
| import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.mahout.classifier.sgd.L1;
import org.apache.mahout.classifier.sgd.OnlineLogisticRegression;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.cloudera.knittingboar.io.InputRecordsSplit;
import com.cloudera.knittingboar.utils.TestingUtils;
import com.google.common.io.Files; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.knittingboar.records;
public class TestTwentyNewsgroupsCustomRecordParseOLRRun {
private static final Log LOG = LogFactory
.getLog(TestTwentyNewsgroupsCustomRecordParseOLRRun.class.getName());
private static final int FEATURES = 10000;
private JobConf defaultConf;
private FileSystem localFs;
private File baseDir;
private Path workDir;
private String inputFileName;
@Before
public void setup() throws Exception {
defaultConf = new JobConf();
defaultConf.set("fs.defaultFS", "file:///");
localFs = FileSystem.getLocal(defaultConf);
inputFileName = "kboar-shard-0.txt";
baseDir = Files.createTempDir();
File inputFile = new File(baseDir, inputFileName); | // Path: src/main/java/com/cloudera/knittingboar/io/InputRecordsSplit.java
// public class InputRecordsSplit {
//
// TextInputFormat input_format = null;
// InputSplit split = null;
// JobConf jobConf = null;
//
// RecordReader<LongWritable,Text> reader = null;
// LongWritable key = null;
//
// final Reporter voidReporter = Reporter.NULL;
//
// public InputRecordsSplit(JobConf jobConf, InputSplit split)
// throws IOException {
//
// this.jobConf = jobConf;
// this.split = split;
// this.input_format = new TextInputFormat();
//
// // RecordReader<LongWritable, Text> reader =
// // format.getRecordReader(splits[x], job, reporter);
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
// this.key = reader.createKey();
// // Text value = reader.createValue();
//
// }
//
// /**
// *
// * just a dead simple way to do this
// *
// * - functionality from TestTextInputFormat::readSplit()
// *
// * If returns true, then csv_line contains the next line If returns false,
// * then there is no next record
// *
// * Will terminate when it hits the end of the split based on the information
// * provided in the split class to the constructor and the TextInputFormat
// *
// * @param csv_line
// * @throws IOException
// */
// public boolean next(Text csv_line) throws IOException {
//
// return reader.next(key, csv_line);
//
// }
//
// public void ResetToStartOfSplit() throws IOException {
//
// // I'mma cheatin here. sue me.
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
//
// }
//
// }
//
// Path: src/test/java/com/cloudera/knittingboar/utils/TestingUtils.java
// public class TestingUtils {
//
// public static void copyDecompressed(String resource, File output)
// throws IOException {
// URL input = Resources.getResource(resource);
// ByteStreams.copy(new GZIPInputStream(input.openStream()),
// new FileOutputStream(output));
// }
//
// }
// Path: src/test/java/com/cloudera/knittingboar/records/TestTwentyNewsgroupsCustomRecordParseOLRRun.java
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.mahout.classifier.sgd.L1;
import org.apache.mahout.classifier.sgd.OnlineLogisticRegression;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.cloudera.knittingboar.io.InputRecordsSplit;
import com.cloudera.knittingboar.utils.TestingUtils;
import com.google.common.io.Files;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.knittingboar.records;
public class TestTwentyNewsgroupsCustomRecordParseOLRRun {
private static final Log LOG = LogFactory
.getLog(TestTwentyNewsgroupsCustomRecordParseOLRRun.class.getName());
private static final int FEATURES = 10000;
private JobConf defaultConf;
private FileSystem localFs;
private File baseDir;
private Path workDir;
private String inputFileName;
@Before
public void setup() throws Exception {
defaultConf = new JobConf();
defaultConf.set("fs.defaultFS", "file:///");
localFs = FileSystem.getLocal(defaultConf);
inputFileName = "kboar-shard-0.txt";
baseDir = Files.createTempDir();
File inputFile = new File(baseDir, inputFileName); | TestingUtils.copyDecompressed(inputFileName + ".gz", inputFile); |
jpatanooga/KnittingBoar | src/test/java/com/cloudera/knittingboar/records/TestTwentyNewsgroupsCustomRecordParseOLRRun.java | // Path: src/main/java/com/cloudera/knittingboar/io/InputRecordsSplit.java
// public class InputRecordsSplit {
//
// TextInputFormat input_format = null;
// InputSplit split = null;
// JobConf jobConf = null;
//
// RecordReader<LongWritable,Text> reader = null;
// LongWritable key = null;
//
// final Reporter voidReporter = Reporter.NULL;
//
// public InputRecordsSplit(JobConf jobConf, InputSplit split)
// throws IOException {
//
// this.jobConf = jobConf;
// this.split = split;
// this.input_format = new TextInputFormat();
//
// // RecordReader<LongWritable, Text> reader =
// // format.getRecordReader(splits[x], job, reporter);
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
// this.key = reader.createKey();
// // Text value = reader.createValue();
//
// }
//
// /**
// *
// * just a dead simple way to do this
// *
// * - functionality from TestTextInputFormat::readSplit()
// *
// * If returns true, then csv_line contains the next line If returns false,
// * then there is no next record
// *
// * Will terminate when it hits the end of the split based on the information
// * provided in the split class to the constructor and the TextInputFormat
// *
// * @param csv_line
// * @throws IOException
// */
// public boolean next(Text csv_line) throws IOException {
//
// return reader.next(key, csv_line);
//
// }
//
// public void ResetToStartOfSplit() throws IOException {
//
// // I'mma cheatin here. sue me.
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
//
// }
//
// }
//
// Path: src/test/java/com/cloudera/knittingboar/utils/TestingUtils.java
// public class TestingUtils {
//
// public static void copyDecompressed(String resource, File output)
// throws IOException {
// URL input = Resources.getResource(resource);
// ByteStreams.copy(new GZIPInputStream(input.openStream()),
// new FileOutputStream(output));
// }
//
// }
| import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.mahout.classifier.sgd.L1;
import org.apache.mahout.classifier.sgd.OnlineLogisticRegression;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.cloudera.knittingboar.io.InputRecordsSplit;
import com.cloudera.knittingboar.utils.TestingUtils;
import com.google.common.io.Files; | // stepOffset, decay, and alpha --- describe how the learning rate decreases
// lambda: amount of regularization
// learningRate: amount of initial learning rate
@SuppressWarnings("resource")
OnlineLogisticRegression learningAlgorithm = new OnlineLogisticRegression(
20, FEATURES, new L1()).alpha(1).stepOffset(1000).decayExponent(0.9)
.lambda(3.0e-5).learningRate(20);
FileInputFormat.setInputPaths(job, workDir);
// try splitting the file in a variety of sizes
TextInputFormat format = new TextInputFormat();
format.configure(job);
Text value = new Text();
int numSplits = 1;
InputSplit[] splits = format.getSplits(job, numSplits);
LOG.info("requested " + numSplits + " splits, splitting: got = "
+ splits.length);
LOG.info("---- debug splits --------- ");
rec_factory.Debug();
int total_read = 0;
for (int x = 0; x < splits.length; x++) {
LOG.info("> Split [" + x + "]: " + splits[x].getLength());
int count = 0; | // Path: src/main/java/com/cloudera/knittingboar/io/InputRecordsSplit.java
// public class InputRecordsSplit {
//
// TextInputFormat input_format = null;
// InputSplit split = null;
// JobConf jobConf = null;
//
// RecordReader<LongWritable,Text> reader = null;
// LongWritable key = null;
//
// final Reporter voidReporter = Reporter.NULL;
//
// public InputRecordsSplit(JobConf jobConf, InputSplit split)
// throws IOException {
//
// this.jobConf = jobConf;
// this.split = split;
// this.input_format = new TextInputFormat();
//
// // RecordReader<LongWritable, Text> reader =
// // format.getRecordReader(splits[x], job, reporter);
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
// this.key = reader.createKey();
// // Text value = reader.createValue();
//
// }
//
// /**
// *
// * just a dead simple way to do this
// *
// * - functionality from TestTextInputFormat::readSplit()
// *
// * If returns true, then csv_line contains the next line If returns false,
// * then there is no next record
// *
// * Will terminate when it hits the end of the split based on the information
// * provided in the split class to the constructor and the TextInputFormat
// *
// * @param csv_line
// * @throws IOException
// */
// public boolean next(Text csv_line) throws IOException {
//
// return reader.next(key, csv_line);
//
// }
//
// public void ResetToStartOfSplit() throws IOException {
//
// // I'mma cheatin here. sue me.
// this.reader = input_format.getRecordReader(this.split, this.jobConf,
// voidReporter);
//
// }
//
// }
//
// Path: src/test/java/com/cloudera/knittingboar/utils/TestingUtils.java
// public class TestingUtils {
//
// public static void copyDecompressed(String resource, File output)
// throws IOException {
// URL input = Resources.getResource(resource);
// ByteStreams.copy(new GZIPInputStream(input.openStream()),
// new FileOutputStream(output));
// }
//
// }
// Path: src/test/java/com/cloudera/knittingboar/records/TestTwentyNewsgroupsCustomRecordParseOLRRun.java
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.mahout.classifier.sgd.L1;
import org.apache.mahout.classifier.sgd.OnlineLogisticRegression;
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.cloudera.knittingboar.io.InputRecordsSplit;
import com.cloudera.knittingboar.utils.TestingUtils;
import com.google.common.io.Files;
// stepOffset, decay, and alpha --- describe how the learning rate decreases
// lambda: amount of regularization
// learningRate: amount of initial learning rate
@SuppressWarnings("resource")
OnlineLogisticRegression learningAlgorithm = new OnlineLogisticRegression(
20, FEATURES, new L1()).alpha(1).stepOffset(1000).decayExponent(0.9)
.lambda(3.0e-5).learningRate(20);
FileInputFormat.setInputPaths(job, workDir);
// try splitting the file in a variety of sizes
TextInputFormat format = new TextInputFormat();
format.configure(job);
Text value = new Text();
int numSplits = 1;
InputSplit[] splits = format.getSplits(job, numSplits);
LOG.info("requested " + numSplits + " splits, splitting: got = "
+ splits.length);
LOG.info("---- debug splits --------- ");
rec_factory.Debug();
int total_read = 0;
for (int x = 0; x < splits.length; x++) {
LOG.info("> Split [" + x + "]: " + splits[x].getLength());
int count = 0; | InputRecordsSplit custom_reader = new InputRecordsSplit(job, splits[x]); |
jpatanooga/KnittingBoar | src/test/java/com/cloudera/knittingboar/conf/cmdline/TestDataConverterDriver.java | // Path: src/test/java/com/cloudera/knittingboar/utils/DataUtils.java
// public class DataUtils {
//
// private static File twentyNewsGroups;
// private static final String TWENTY_NEWS_GROUP_LOCAL_DIR = "knittingboar-20news";
// private static final String TWENTY_NEWS_GROUP_TAR_URL = "http://people.csail.mit.edu/jrennie/20Newsgroups/20news-bydate.tar.gz";
// private static final String TWENTY_NEWS_GROUP_TAR_FILE_NAME = "20news-bydate.tar.gz";
//
// public static String get20NewsgroupsLocalDataLocation() {
//
// File tmpDir = new File("/tmp");
// if(!tmpDir.isDirectory()) {
// tmpDir = new File(System.getProperty("java.io.tmpdir"));
// }
// File baseDir = new File(tmpDir, TWENTY_NEWS_GROUP_LOCAL_DIR);
//
//
// return baseDir.toString();
//
// }
//
// public static synchronized File getTwentyNewsGroupDir() throws IOException {
// if(twentyNewsGroups != null) {
// return twentyNewsGroups;
// }
// // mac gives unique tmp each run and we want to store this persist
// // this data across restarts
// File tmpDir = new File("/tmp");
// if(!tmpDir.isDirectory()) {
// tmpDir = new File(System.getProperty("java.io.tmpdir"));
// }
// File baseDir = new File(tmpDir, TWENTY_NEWS_GROUP_LOCAL_DIR);
// if(!(baseDir.isDirectory() || baseDir.mkdir())) {
// throw new IOException("Could not mkdir " + baseDir);
// }
// File tarFile = new File(baseDir, TWENTY_NEWS_GROUP_TAR_FILE_NAME);
//
// if(!tarFile.isFile()) {
// FileUtils.copyURLToFile(new URL(TWENTY_NEWS_GROUP_TAR_URL), tarFile);
// }
//
// Process p = Runtime.getRuntime().exec(String.format("tar -C %s -xvf %s",
// baseDir.getAbsolutePath(), tarFile.getAbsolutePath()));
// BufferedReader stdError = new BufferedReader(new
// InputStreamReader(p.getErrorStream()));
// System.out.println("Here is the standard error of the command (if any):\n");
// String s;
// while ((s = stdError.readLine()) != null) {
// System.out.println(s);
// }
// stdError.close();
// twentyNewsGroups = baseDir;
// return twentyNewsGroups;
// }
//
//
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.io.FileUtils;
import junit.framework.TestCase;
import com.cloudera.knittingboar.utils.DataUtils; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.knittingboar.conf.cmdline;
public class TestDataConverterDriver extends TestCase {
public void testBasics() throws Exception { | // Path: src/test/java/com/cloudera/knittingboar/utils/DataUtils.java
// public class DataUtils {
//
// private static File twentyNewsGroups;
// private static final String TWENTY_NEWS_GROUP_LOCAL_DIR = "knittingboar-20news";
// private static final String TWENTY_NEWS_GROUP_TAR_URL = "http://people.csail.mit.edu/jrennie/20Newsgroups/20news-bydate.tar.gz";
// private static final String TWENTY_NEWS_GROUP_TAR_FILE_NAME = "20news-bydate.tar.gz";
//
// public static String get20NewsgroupsLocalDataLocation() {
//
// File tmpDir = new File("/tmp");
// if(!tmpDir.isDirectory()) {
// tmpDir = new File(System.getProperty("java.io.tmpdir"));
// }
// File baseDir = new File(tmpDir, TWENTY_NEWS_GROUP_LOCAL_DIR);
//
//
// return baseDir.toString();
//
// }
//
// public static synchronized File getTwentyNewsGroupDir() throws IOException {
// if(twentyNewsGroups != null) {
// return twentyNewsGroups;
// }
// // mac gives unique tmp each run and we want to store this persist
// // this data across restarts
// File tmpDir = new File("/tmp");
// if(!tmpDir.isDirectory()) {
// tmpDir = new File(System.getProperty("java.io.tmpdir"));
// }
// File baseDir = new File(tmpDir, TWENTY_NEWS_GROUP_LOCAL_DIR);
// if(!(baseDir.isDirectory() || baseDir.mkdir())) {
// throw new IOException("Could not mkdir " + baseDir);
// }
// File tarFile = new File(baseDir, TWENTY_NEWS_GROUP_TAR_FILE_NAME);
//
// if(!tarFile.isFile()) {
// FileUtils.copyURLToFile(new URL(TWENTY_NEWS_GROUP_TAR_URL), tarFile);
// }
//
// Process p = Runtime.getRuntime().exec(String.format("tar -C %s -xvf %s",
// baseDir.getAbsolutePath(), tarFile.getAbsolutePath()));
// BufferedReader stdError = new BufferedReader(new
// InputStreamReader(p.getErrorStream()));
// System.out.println("Here is the standard error of the command (if any):\n");
// String s;
// while ((s = stdError.readLine()) != null) {
// System.out.println(s);
// }
// stdError.close();
// twentyNewsGroups = baseDir;
// return twentyNewsGroups;
// }
//
//
//
// }
// Path: src/test/java/com/cloudera/knittingboar/conf/cmdline/TestDataConverterDriver.java
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.io.FileUtils;
import junit.framework.TestCase;
import com.cloudera.knittingboar.utils.DataUtils;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cloudera.knittingboar.conf.cmdline;
public class TestDataConverterDriver extends TestCase {
public void testBasics() throws Exception { | File twentyNewsGroupDataDir = DataUtils.getTwentyNewsGroupDir(); |
jiangpeng79/antrace | app/src/main/java/com/jiangpeng/android/antrace/Utils.java | // Path: app/src/main/java/com/jiangpeng/android/antrace/Objects/path.java
// public class path {
// public int area; /* area of the bitmap path */
// public int sign; /* '+' or '-', depending on orientation */
// public curve curve; /* this path's vector data */
//
// public path next; /* linked list structure */
//
// public path childlist; /* tree structure */
// public path sibling; /* tree structure */
//
// public privpath priv; /* private state */
//
// public path()
// {
// }
// }
| import com.jiangpeng.android.antrace.Objects.path;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.view.WindowManager; | package com.jiangpeng.android.antrace;
public class Utils {
public static native void threshold(Bitmap input, int t, Bitmap output);
public static native void grayScale(Bitmap input, Bitmap output); | // Path: app/src/main/java/com/jiangpeng/android/antrace/Objects/path.java
// public class path {
// public int area; /* area of the bitmap path */
// public int sign; /* '+' or '-', depending on orientation */
// public curve curve; /* this path's vector data */
//
// public path next; /* linked list structure */
//
// public path childlist; /* tree structure */
// public path sibling; /* tree structure */
//
// public privpath priv; /* private state */
//
// public path()
// {
// }
// }
// Path: app/src/main/java/com/jiangpeng/android/antrace/Utils.java
import com.jiangpeng.android.antrace.Objects.path;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.view.WindowManager;
package com.jiangpeng.android.antrace;
public class Utils {
public static native void threshold(Bitmap input, int t, Bitmap output);
public static native void grayScale(Bitmap input, Bitmap output); | public static native path traceImage(Bitmap input); |
jiangpeng79/antrace | app/src/main/java/com/jiangpeng/android/antrace/Objects/ImageInteraction.java | // Path: app/src/main/java/com/jiangpeng/android/antrace/Utils.java
// public class Utils {
// public static native void threshold(Bitmap input, int t, Bitmap output);
// public static native void grayScale(Bitmap input, Bitmap output);
// public static native path traceImage(Bitmap input);
// public static native void unsharpMask(Bitmap input, Bitmap output);
// public static native boolean saveSVG(String filename, int w, int h);
// public static native boolean saveDXF(String filename, int w, int h);
// public static native boolean savePDF(String filename, int w, int h);
// public static native void clearState();
//
// private static android.content.pm.PackageInfo getPackageInfo(Context context)
// {
// android.content.pm.PackageInfo pi = null;
// try
// {
// String name = context.getPackageName();
// PackageManager pm = context.getPackageManager();
//
// pi = pm.getPackageInfo(name, 0);
// } catch (Exception err)
// {
// return null;
// }
// return pi;
// }
//
// public static String getCurrentVersionName(Context context)
// {
// android.content.pm.PackageInfo pi = getPackageInfo(context);
// return pi == null ? "0.0" : pi.versionName;
// }
//
// public static DisplayMetrics getDisplayMetrics(Context context)
// {
// DisplayMetrics metrics = new DisplayMetrics();
// WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(metrics);
//
// return metrics;
// }
//
// public static int getDPI(Context context)
// {
// DisplayMetrics metrics = getDisplayMetrics(context);
// return metrics.densityDpi;
// }
//
// }
| import com.jiangpeng.android.antrace.Utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType; | protected static final int NONE = 0;
protected static final int DRAG = 1;
protected static final int ZOOM = 2;
protected static final int ZOOM_SELECTION = 4;
protected static final int DRAG_SELECTION = 5;
protected Matrix m_imageToScreen = new Matrix();
protected Matrix m_screenToImage = new Matrix();
protected Bitmap m_bitmap = null;
protected Paint m_paint = new Paint();
protected static float HitRadius = 40f;
protected static final float MinSize = 80f;
protected int m_mode = NONE;
protected HitTestResult m_hitTest = HitTestResult.None;
// Remember some things for zooming
protected PointF m_start = new PointF();
protected PointF m_last = new PointF();
protected ImageView m_imageView = null;
protected boolean m_isCropping = false;
public abstract void draw(Canvas c);
public abstract boolean onTouch(View v, MotionEvent rawEvent);
public abstract void startCrop();
public abstract Bitmap getCroppedBitmap();
public ImageInteraction(ImageView view)
{
m_imageView = view; | // Path: app/src/main/java/com/jiangpeng/android/antrace/Utils.java
// public class Utils {
// public static native void threshold(Bitmap input, int t, Bitmap output);
// public static native void grayScale(Bitmap input, Bitmap output);
// public static native path traceImage(Bitmap input);
// public static native void unsharpMask(Bitmap input, Bitmap output);
// public static native boolean saveSVG(String filename, int w, int h);
// public static native boolean saveDXF(String filename, int w, int h);
// public static native boolean savePDF(String filename, int w, int h);
// public static native void clearState();
//
// private static android.content.pm.PackageInfo getPackageInfo(Context context)
// {
// android.content.pm.PackageInfo pi = null;
// try
// {
// String name = context.getPackageName();
// PackageManager pm = context.getPackageManager();
//
// pi = pm.getPackageInfo(name, 0);
// } catch (Exception err)
// {
// return null;
// }
// return pi;
// }
//
// public static String getCurrentVersionName(Context context)
// {
// android.content.pm.PackageInfo pi = getPackageInfo(context);
// return pi == null ? "0.0" : pi.versionName;
// }
//
// public static DisplayMetrics getDisplayMetrics(Context context)
// {
// DisplayMetrics metrics = new DisplayMetrics();
// WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
// wm.getDefaultDisplay().getMetrics(metrics);
//
// return metrics;
// }
//
// public static int getDPI(Context context)
// {
// DisplayMetrics metrics = getDisplayMetrics(context);
// return metrics.densityDpi;
// }
//
// }
// Path: app/src/main/java/com/jiangpeng/android/antrace/Objects/ImageInteraction.java
import com.jiangpeng.android.antrace.Utils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
protected static final int NONE = 0;
protected static final int DRAG = 1;
protected static final int ZOOM = 2;
protected static final int ZOOM_SELECTION = 4;
protected static final int DRAG_SELECTION = 5;
protected Matrix m_imageToScreen = new Matrix();
protected Matrix m_screenToImage = new Matrix();
protected Bitmap m_bitmap = null;
protected Paint m_paint = new Paint();
protected static float HitRadius = 40f;
protected static final float MinSize = 80f;
protected int m_mode = NONE;
protected HitTestResult m_hitTest = HitTestResult.None;
// Remember some things for zooming
protected PointF m_start = new PointF();
protected PointF m_last = new PointF();
protected ImageView m_imageView = null;
protected boolean m_isCropping = false;
public abstract void draw(Canvas c);
public abstract boolean onTouch(View v, MotionEvent rawEvent);
public abstract void startCrop();
public abstract Bitmap getCroppedBitmap();
public ImageInteraction(ImageView view)
{
m_imageView = view; | HitRadius = Utils.getDPI(view.getContext()) / 7; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/Application.java | // Path: voicesmith/src/de/jurihock/voicesmith/activities/HomeActivity.java
// public final class HomeActivity extends GDListActivity
// {
// public HomeActivity()
// {
// super(ActionBar.Type.Normal);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
//
// // Change the action bar icon
// ImageButton actionBarButton = (ImageButton) getActionBar()
// .findViewById(R.id.gd_action_bar_home_item);
// actionBarButton.setImageResource(R.drawable.action_bar_icon);
// actionBarButton.setClickable(false);
//
// // Init menu items
// ItemAdapter items = new ItemAdapter(this);
// {
// items.add(newMenuItem(
// R.string.DafxActivity,
// DafxActivity.class));
//
// items.add(newMenuItem(
// R.string.AafActivity,
// AafActivity.class));
//
// items.add(newMenuItem(
// R.string.PreferenceActivity,
// PreferenceActivity.class));
//
// items.add(new SeparatorItem("Help"));
//
// items.add(newMenuItem(
// R.string.SupportActivity,
// SupportActivity.class));
//
// items.add(newMenuItem(
// R.string.ContributionActivity,
// ContributionActivity.class));
//
// items.add(newMenuItem(
// R.string.AboutActivity,
// AboutActivity.class));
// }
// setListAdapter(items);
//
// new ChangeLog(this).show();
// }
//
// @Override
// protected void onResume()
// {
// super.onResume();
//
// Context serviceContext = this.getApplicationContext();
// Class<?> serviceClass;
// Intent serviceIntent;
//
// // Stop the DafxService if it's running
// serviceClass = DafxService.class;
// serviceIntent = new Intent(serviceContext, serviceClass);
// if (new Utils(serviceContext).isServiceRunning(serviceClass))
// {
// new Utils(this).log("Stopping DafxService.");
// stopService(serviceIntent);
// }
//
// // Stop the AafService if it's running
// serviceClass = AafService.class;
// serviceIntent = new Intent(serviceContext, serviceClass);
// if (new Utils(serviceContext).isServiceRunning(serviceClass))
// {
// new Utils(this).log("Stopping AafService.");
// stopService(serviceIntent);
// }
// }
//
// private Item newMenuItem(int activityName, Class<?> activityClass)
// {
// TextItem item = new TextItem(getString(activityName));
// {
// item.setTag(activityClass);
// }
//
// return item;
// }
//
// @Override
// protected void onListItemClick(ListView listView, View view, int position, long id)
// {
// Item item = (Item) listView.getAdapter().getItem(position);
// Intent intent = new Intent(this, (Class<?>) item.getTag());
// startActivity(intent);
// }
// }
| import greendroid.app.GDApplication;
import de.jurihock.voicesmith.activities.HomeActivity; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith;
public final class Application extends GDApplication
{
@Override
public void onCreate()
{
super.onCreate();
Utils.loadNativeLibrary();
}
@Override
public Class<?> getHomeActivityClass()
{ | // Path: voicesmith/src/de/jurihock/voicesmith/activities/HomeActivity.java
// public final class HomeActivity extends GDListActivity
// {
// public HomeActivity()
// {
// super(ActionBar.Type.Normal);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState)
// {
// super.onCreate(savedInstanceState);
//
// // Change the action bar icon
// ImageButton actionBarButton = (ImageButton) getActionBar()
// .findViewById(R.id.gd_action_bar_home_item);
// actionBarButton.setImageResource(R.drawable.action_bar_icon);
// actionBarButton.setClickable(false);
//
// // Init menu items
// ItemAdapter items = new ItemAdapter(this);
// {
// items.add(newMenuItem(
// R.string.DafxActivity,
// DafxActivity.class));
//
// items.add(newMenuItem(
// R.string.AafActivity,
// AafActivity.class));
//
// items.add(newMenuItem(
// R.string.PreferenceActivity,
// PreferenceActivity.class));
//
// items.add(new SeparatorItem("Help"));
//
// items.add(newMenuItem(
// R.string.SupportActivity,
// SupportActivity.class));
//
// items.add(newMenuItem(
// R.string.ContributionActivity,
// ContributionActivity.class));
//
// items.add(newMenuItem(
// R.string.AboutActivity,
// AboutActivity.class));
// }
// setListAdapter(items);
//
// new ChangeLog(this).show();
// }
//
// @Override
// protected void onResume()
// {
// super.onResume();
//
// Context serviceContext = this.getApplicationContext();
// Class<?> serviceClass;
// Intent serviceIntent;
//
// // Stop the DafxService if it's running
// serviceClass = DafxService.class;
// serviceIntent = new Intent(serviceContext, serviceClass);
// if (new Utils(serviceContext).isServiceRunning(serviceClass))
// {
// new Utils(this).log("Stopping DafxService.");
// stopService(serviceIntent);
// }
//
// // Stop the AafService if it's running
// serviceClass = AafService.class;
// serviceIntent = new Intent(serviceContext, serviceClass);
// if (new Utils(serviceContext).isServiceRunning(serviceClass))
// {
// new Utils(this).log("Stopping AafService.");
// stopService(serviceIntent);
// }
// }
//
// private Item newMenuItem(int activityName, Class<?> activityClass)
// {
// TextItem item = new TextItem(getString(activityName));
// {
// item.setTag(activityClass);
// }
//
// return item;
// }
//
// @Override
// protected void onListItemClick(ListView listView, View view, int position, long id)
// {
// Item item = (Item) listView.getAdapter().getItem(position);
// Intent intent = new Intent(this, (Class<?>) item.getTag());
// startActivity(intent);
// }
// }
// Path: voicesmith/src/de/jurihock/voicesmith/Application.java
import greendroid.app.GDApplication;
import de.jurihock.voicesmith.activities.HomeActivity;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith;
public final class Application extends GDApplication
{
@Override
public void onCreate()
{
super.onCreate();
Utils.loadNativeLibrary();
}
@Override
public Class<?> getHomeActivityClass()
{ | return HomeActivity.class; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/Preferences.java | // Path: voicesmith/src/de/jurihock/voicesmith/audio/HeadsetMode.java
// public enum HeadsetMode
// {
// WIRED_HEADPHONES,
// WIRED_HEADSET,
// BLUETOOTH_HEADSET
// }
//
// Path: voicesmith/src/de/jurihock/voicesmith/threads/AudioThread.java
// public abstract class AudioThread implements Runnable, Disposable
// {
// protected final Context context;
// protected final AudioDevice input, output;
//
// private Thread thread = null;
//
// public AudioThread(Context context, AudioDevice input, AudioDevice output)
// {
// this.context = context;
// this.input = input;
// this.output = output;
// }
//
// public void configure(String value)
// {
// // ReentrantLock lock = new ReentrantLock(true);
// // lock.lock();
// // try { ... } finally { lock.unlock(); }
// }
//
// public void dispose()
// {
// stop();
//
// new Utils(context).log("Disposing an audio thread.");
// }
//
// public boolean isRunning()
// {
// return (thread != null)
// && (thread.getState() != Thread.State.TERMINATED);
// }
//
// public void start()
// {
// if (isRunning()) return;
//
// thread = new Thread(this);
// thread.start();
// }
//
// public void stop()
// {
// if (!isRunning()) return;
//
// thread.interrupt();
//
// try
// {
// thread.join();
// }
// catch (InterruptedException exception)
// {
// new Utils(context).log(exception);
// }
// finally
// {
// thread = null;
// }
// }
//
// public void run()
// {
// android.os.Process.setThreadPriority(
// android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
//
// output.start();
// input.start();
//
// doProcessing();
//
// input.stop();
// output.stop();
// }
//
// protected abstract void doProcessing();
//
// public static AudioThread create(Context context, AudioDevice input, AudioDevice output, DAFX dafx)
// {
// switch (dafx)
// {
// case Robotize:
// return new RobotizeThread(context, input, output);
// case Transpose:
// return new TransposeThread(context, input, output);
// case Detune:
// return new DetuneThread(context, input, output);
// case Hoarseness:
// return new HoarsenessThread(context, input, output);
// default:
// throw new IllegalArgumentException("Illegal DAFX argument!");
// }
// }
//
// public static AudioThread create(Context context, AudioDevice input, AudioDevice output, AAF aaf)
// {
// switch (aaf)
// {
// case FAF:
// return new TransposeThread(context, input, output);
// case DAF:
// return new DelayThread(context, input, output);
// case UnprocessedFeedback:
// return new LowDelayThread(context, input, output);
// default:
// throw new IllegalArgumentException("Illegal AAF argument!");
// }
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.preference.PreferenceManager;
import de.jurihock.voicesmith.audio.HeadsetMode;
import de.jurihock.voicesmith.threads.AudioThread; | }
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener)
{
preferences.unregisterOnSharedPreferenceChangeListener(listener);
}
public void reset()
{
preferences.edit().clear().commit();
// There are no needs to show the Change Log again after reset
this.setChangeLogShowed(true);
}
public boolean isChangeLogShowed()
{
return preferences.getBoolean("ChangeLog", false);
}
public boolean setChangeLogShowed(boolean value)
{
return preferences.edit().putBoolean("ChangeLog", value).commit();
}
public boolean isForceVolumeLevelOn()
{
return preferences.getBoolean("ForceVolumeLevel", true);
}
| // Path: voicesmith/src/de/jurihock/voicesmith/audio/HeadsetMode.java
// public enum HeadsetMode
// {
// WIRED_HEADPHONES,
// WIRED_HEADSET,
// BLUETOOTH_HEADSET
// }
//
// Path: voicesmith/src/de/jurihock/voicesmith/threads/AudioThread.java
// public abstract class AudioThread implements Runnable, Disposable
// {
// protected final Context context;
// protected final AudioDevice input, output;
//
// private Thread thread = null;
//
// public AudioThread(Context context, AudioDevice input, AudioDevice output)
// {
// this.context = context;
// this.input = input;
// this.output = output;
// }
//
// public void configure(String value)
// {
// // ReentrantLock lock = new ReentrantLock(true);
// // lock.lock();
// // try { ... } finally { lock.unlock(); }
// }
//
// public void dispose()
// {
// stop();
//
// new Utils(context).log("Disposing an audio thread.");
// }
//
// public boolean isRunning()
// {
// return (thread != null)
// && (thread.getState() != Thread.State.TERMINATED);
// }
//
// public void start()
// {
// if (isRunning()) return;
//
// thread = new Thread(this);
// thread.start();
// }
//
// public void stop()
// {
// if (!isRunning()) return;
//
// thread.interrupt();
//
// try
// {
// thread.join();
// }
// catch (InterruptedException exception)
// {
// new Utils(context).log(exception);
// }
// finally
// {
// thread = null;
// }
// }
//
// public void run()
// {
// android.os.Process.setThreadPriority(
// android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
//
// output.start();
// input.start();
//
// doProcessing();
//
// input.stop();
// output.stop();
// }
//
// protected abstract void doProcessing();
//
// public static AudioThread create(Context context, AudioDevice input, AudioDevice output, DAFX dafx)
// {
// switch (dafx)
// {
// case Robotize:
// return new RobotizeThread(context, input, output);
// case Transpose:
// return new TransposeThread(context, input, output);
// case Detune:
// return new DetuneThread(context, input, output);
// case Hoarseness:
// return new HoarsenessThread(context, input, output);
// default:
// throw new IllegalArgumentException("Illegal DAFX argument!");
// }
// }
//
// public static AudioThread create(Context context, AudioDevice input, AudioDevice output, AAF aaf)
// {
// switch (aaf)
// {
// case FAF:
// return new TransposeThread(context, input, output);
// case DAF:
// return new DelayThread(context, input, output);
// case UnprocessedFeedback:
// return new LowDelayThread(context, input, output);
// default:
// throw new IllegalArgumentException("Illegal AAF argument!");
// }
// }
// }
// Path: voicesmith/src/de/jurihock/voicesmith/Preferences.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.preference.PreferenceManager;
import de.jurihock.voicesmith.audio.HeadsetMode;
import de.jurihock.voicesmith.threads.AudioThread;
}
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener)
{
preferences.unregisterOnSharedPreferenceChangeListener(listener);
}
public void reset()
{
preferences.edit().clear().commit();
// There are no needs to show the Change Log again after reset
this.setChangeLogShowed(true);
}
public boolean isChangeLogShowed()
{
return preferences.getBoolean("ChangeLog", false);
}
public boolean setChangeLogShowed(boolean value)
{
return preferences.edit().putBoolean("ChangeLog", value).commit();
}
public boolean isForceVolumeLevelOn()
{
return preferences.getBoolean("ForceVolumeLevel", true);
}
| public int getVolumeLevel(HeadsetMode mode) |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/io/oscillators/CosineWave.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
| import static de.jurihock.voicesmith.dsp.Math.cos;
import android.content.Context; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.io.oscillators;
public final class CosineWave extends PhaseAccumulator
{
public CosineWave(Context context, int frequency)
{
super(context, frequency);
}
public CosineWave(Context context, int sampleRate, int frequency)
{
super(context, sampleRate, frequency);
}
public int read(float[] buffer, int offset, int count)
{
if (count == 0) return 0;
for (int i = 0; i < count; i++)
{ | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
// Path: voicesmith/src/de/jurihock/voicesmith/io/oscillators/CosineWave.java
import static de.jurihock.voicesmith.dsp.Math.cos;
import android.content.Context;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.io.oscillators;
public final class CosineWave extends PhaseAccumulator
{
public CosineWave(Context context, int frequency)
{
super(context, frequency);
}
public CosineWave(Context context, int sampleRate, int frequency)
{
super(context, sampleRate, frequency);
}
public int read(float[] buffer, int offset, int count)
{
if (count == 0) return 0;
for (int i = 0; i < count; i++)
{ | buffer[i + offset] = cos(getNextPhase()); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/io/pcm/DelayedPcmInDevice.java | // Path: voicesmith/src/de/jurihock/voicesmith/audio/HeadsetMode.java
// public enum HeadsetMode
// {
// WIRED_HEADPHONES,
// WIRED_HEADSET,
// BLUETOOTH_HEADSET
// }
| import android.content.Context;
import de.jurihock.voicesmith.audio.HeadsetMode;
import java.io.IOException;
import java.util.Arrays; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.io.pcm;
public final class DelayedPcmInDevice extends PcmInDevice
{
private double delayTime = 0;
private int delaySamples = 0;
private int remainingZeros = 0;
| // Path: voicesmith/src/de/jurihock/voicesmith/audio/HeadsetMode.java
// public enum HeadsetMode
// {
// WIRED_HEADPHONES,
// WIRED_HEADSET,
// BLUETOOTH_HEADSET
// }
// Path: voicesmith/src/de/jurihock/voicesmith/io/pcm/DelayedPcmInDevice.java
import android.content.Context;
import de.jurihock.voicesmith.audio.HeadsetMode;
import java.io.IOException;
import java.util.Arrays;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.io.pcm;
public final class DelayedPcmInDevice extends PcmInDevice
{
private double delayTime = 0;
private int delaySamples = 0;
private int remainingZeros = 0;
| public DelayedPcmInDevice(Context context, HeadsetMode headsetMode) |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/widgets/AafPicker.java | // Path: voicesmith/src/de/jurihock/voicesmith/AAF.java
// public enum AAF
// {
// /**
// * Frequency-shifted Auditory Feedback.
// * */
// FAF,
//
// /**
// * Delayed Auditory Feedback.
// * */
// DAF,
//
// /**
// * Unprocessed Auditory Feedback (raw signal pumping from input directly to output).
// * Comparable with DAF but min. possible delay possible.
// * */
// UnprocessedFeedback;
//
// private static final AAF[] aafValues = AAF.values();
//
// public static int count()
// {
// return aafValues.length;
// }
//
// public static AAF valueOf(int aafIndex)
// {
// return aafValues[aafIndex];
// }
// }
| import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import de.jurihock.voicesmith.AAF;
import de.jurihock.voicesmith.R; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.widgets;
public final class AafPicker extends RadioGroup implements
OnClickListener
{ | // Path: voicesmith/src/de/jurihock/voicesmith/AAF.java
// public enum AAF
// {
// /**
// * Frequency-shifted Auditory Feedback.
// * */
// FAF,
//
// /**
// * Delayed Auditory Feedback.
// * */
// DAF,
//
// /**
// * Unprocessed Auditory Feedback (raw signal pumping from input directly to output).
// * Comparable with DAF but min. possible delay possible.
// * */
// UnprocessedFeedback;
//
// private static final AAF[] aafValues = AAF.values();
//
// public static int count()
// {
// return aafValues.length;
// }
//
// public static AAF valueOf(int aafIndex)
// {
// return aafValues[aafIndex];
// }
// }
// Path: voicesmith/src/de/jurihock/voicesmith/widgets/AafPicker.java
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import de.jurihock.voicesmith.AAF;
import de.jurihock.voicesmith.R;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.widgets;
public final class AafPicker extends RadioGroup implements
OnClickListener
{ | private AAF aaf; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2; | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2; | float re, im, abs, phase; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase | phase = random(-PI, PI); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase | phase = random(-PI, PI); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase
phase = random(-PI, PI);
// Compute destination Re and Im parts | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase
phase = random(-PI, PI);
// Compute destination Re and Im parts | frame[2 * i] = real(abs, phase); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase
phase = random(-PI, PI);
// Compute destination Re and Im parts
frame[2 * i] = real(abs, phase); | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float random(float min, float max);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/HoarsenessProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.random;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class HoarsenessProcessor
{
public static void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, phase;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Compute random phase
phase = random(-PI, PI);
// Compute destination Re and Im parts
frame[2 * i] = real(abs, phase); | frame[2 * i + 1] = imag(abs, phase); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/io/oscillators/PhaseAccumulator.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/io/AudioDevice.java
// public abstract class AudioDevice implements Disposable
// {
// protected final Context context;
//
// public Context getContext()
// {
// return context;
// }
//
// private int sampleRate;
//
// public int getSampleRate()
// {
// return sampleRate;
// }
//
// protected void setSampleRate(int sampleRate)
// {
// this.sampleRate = sampleRate;
// }
//
// public AudioDevice(Context context)
// {
// this(context, new Preferences(context).getSampleRate());
// }
//
// public AudioDevice(Context context, int sampleRate)
// {
// this.context = context;
// this.sampleRate = sampleRate;
// new Utils(context).log("Current sample rate is %s Hz.", sampleRate);
// }
//
// public int read(short[] buffer, int offset, int count)
// {
// return -1;
// }
//
// public final boolean read(short[] buffer)
// {
// if (buffer == null) return false;
// if (buffer.length == 0) return false;
//
// int count = 0;
//
// do
// {
// int result = read(buffer, count, buffer.length - count);
// if (result < 0) return false; // error on reading data
// count += result;
// }
// while (count < buffer.length);
//
// return true;
// }
//
// public int write(short[] buffer, int offset, int count)
// {
// return -1;
// }
//
// public final boolean write(short[] buffer)
// {
// if (buffer == null) return false;
// if (buffer.length == 0) return false;
//
// int count = 0;
//
// do
// {
// int result = write(buffer, count, buffer.length - count);
// if (result < 0) return false; // error on writing data
// count += result;
// }
// while (count < buffer.length);
//
// return true;
// }
//
// public void flush()
// {
// }
//
// public void start()
// {
// }
//
// public void stop()
// {
// }
//
// public void dispose()
// {
// }
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import android.content.Context;
import de.jurihock.voicesmith.io.AudioDevice; |
public PhaseAccumulator(Context context, int sampleRate, int waveFrequency)
{
super(context, sampleRate);
this.setWaveFrequency(waveFrequency);
}
private int waveFrequency;
public int getWaveFrequency()
{
return waveFrequency;
}
private void setWaveFrequency(int waveFrequency)
{
this.waveFrequency = waveFrequency;
phaseDeviation = getWaveFrequency() / getSampleRate();
phaseDivisor = -phaseDeviation;
}
protected float getNextPhase()
{
phaseDivisor += phaseDeviation;
while(phaseDivisor >= 1)
phaseDivisor -= 1;
| // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/io/AudioDevice.java
// public abstract class AudioDevice implements Disposable
// {
// protected final Context context;
//
// public Context getContext()
// {
// return context;
// }
//
// private int sampleRate;
//
// public int getSampleRate()
// {
// return sampleRate;
// }
//
// protected void setSampleRate(int sampleRate)
// {
// this.sampleRate = sampleRate;
// }
//
// public AudioDevice(Context context)
// {
// this(context, new Preferences(context).getSampleRate());
// }
//
// public AudioDevice(Context context, int sampleRate)
// {
// this.context = context;
// this.sampleRate = sampleRate;
// new Utils(context).log("Current sample rate is %s Hz.", sampleRate);
// }
//
// public int read(short[] buffer, int offset, int count)
// {
// return -1;
// }
//
// public final boolean read(short[] buffer)
// {
// if (buffer == null) return false;
// if (buffer.length == 0) return false;
//
// int count = 0;
//
// do
// {
// int result = read(buffer, count, buffer.length - count);
// if (result < 0) return false; // error on reading data
// count += result;
// }
// while (count < buffer.length);
//
// return true;
// }
//
// public int write(short[] buffer, int offset, int count)
// {
// return -1;
// }
//
// public final boolean write(short[] buffer)
// {
// if (buffer == null) return false;
// if (buffer.length == 0) return false;
//
// int count = 0;
//
// do
// {
// int result = write(buffer, count, buffer.length - count);
// if (result < 0) return false; // error on writing data
// count += result;
// }
// while (count < buffer.length);
//
// return true;
// }
//
// public void flush()
// {
// }
//
// public void start()
// {
// }
//
// public void stop()
// {
// }
//
// public void dispose()
// {
// }
// }
// Path: voicesmith/src/de/jurihock/voicesmith/io/oscillators/PhaseAccumulator.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import android.content.Context;
import de.jurihock.voicesmith.io.AudioDevice;
public PhaseAccumulator(Context context, int sampleRate, int waveFrequency)
{
super(context, sampleRate);
this.setWaveFrequency(waveFrequency);
}
private int waveFrequency;
public int getWaveFrequency()
{
return waveFrequency;
}
private void setWaveFrequency(int waveFrequency)
{
this.waveFrequency = waveFrequency;
phaseDeviation = getWaveFrequency() / getSampleRate();
phaseDivisor = -phaseDeviation;
}
protected float getNextPhase()
{
phaseDivisor += phaseDeviation;
while(phaseDivisor >= 1)
phaseDivisor -= 1;
| return 2 * PI * phaseDivisor; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{ | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{ | omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize! |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) hopSize;
}
}
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2; | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) hopSize;
}
}
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2; | float re, im, abs, nextPhase, phaseDelta; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) hopSize;
}
}
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) hopSize;
}
}
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value | nextPhase = arg(re, im); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) hopSize;
}
}
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value
nextPhase = arg(re, im);
// Compute phase delta | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
public final class SeparationProcessor
{
private final int fftSize;
private final float[] omega;
private final float[] prevPhase1;
private final float[] prevPhase2;
public SeparationProcessor(int frameSize, int hopSize)
{
fftSize = frameSize / 2;
omega = new float[fftSize];
prevPhase1 = new float[fftSize];
prevPhase2 = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omega[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) hopSize;
}
}
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value
nextPhase = arg(re, im);
// Compute phase delta | phaseDelta = princarg(nextPhase - 2F * prevPhase1[i] + prevPhase2[i]); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real; | public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value
nextPhase = arg(re, im);
// Compute phase delta
phaseDelta = princarg(nextPhase - 2F * prevPhase1[i] + prevPhase2[i]);
// Disable some frequency components
if(Math.abs(phaseDelta) > 0.05F * omega[i])
{
abs = 0;
nextPhase = 0;
}
// Save phase values
prevPhase2[i] = prevPhase1[i];
prevPhase1[i] = nextPhase;
// Compute destination Re and Im parts | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real;
public void processFrame(float[] frame)
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value
nextPhase = arg(re, im);
// Compute phase delta
phaseDelta = princarg(nextPhase - 2F * prevPhase1[i] + prevPhase2[i]);
// Disable some frequency components
if(Math.abs(phaseDelta) > 0.05F * omega[i])
{
abs = 0;
nextPhase = 0;
}
// Save phase values
prevPhase2[i] = prevPhase1[i];
prevPhase1[i] = nextPhase;
// Compute destination Re and Im parts | frame[2 * i] = real(abs, nextPhase); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real; | {
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value
nextPhase = arg(re, im);
// Compute phase delta
phaseDelta = princarg(nextPhase - 2F * prevPhase1[i] + prevPhase2[i]);
// Disable some frequency components
if(Math.abs(phaseDelta) > 0.05F * omega[i])
{
abs = 0;
nextPhase = 0;
}
// Save phase values
prevPhase2[i] = prevPhase1[i];
prevPhase1[i] = nextPhase;
// Compute destination Re and Im parts
frame[2 * i] = real(abs, nextPhase); | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float abs(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float arg(float real, float imag);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float imag(float abs, float arg);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float real(float abs, float arg);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/SeparationProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.abs;
import static de.jurihock.voicesmith.dsp.Math.arg;
import static de.jurihock.voicesmith.dsp.Math.imag;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.real;
{
final int fftSize = frame.length / 2;
float re, im, abs, nextPhase, phaseDelta;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
abs = abs(re, im);
// Invert phase value
nextPhase = arg(re, im);
// Compute phase delta
phaseDelta = princarg(nextPhase - 2F * prevPhase1[i] + prevPhase2[i]);
// Disable some frequency components
if(Math.abs(phaseDelta) > 0.05F * omega[i])
{
abs = 0;
nextPhase = 0;
}
// Save phase values
prevPhase2[i] = prevPhase1[i];
prevPhase1[i] = nextPhase;
// Compute destination Re and Im parts
frame[2 * i] = real(abs, nextPhase); | frame[2 * i + 1] = imag(abs, nextPhase); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/Window.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.sqrt; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp;
public final class Window
{
private final int frameSize;
private final int hopSize;
private final boolean isPeriodic;
private final boolean isWeighted;
/**
* @param isPeriodic
* Compute first N coefficients for the N+1 window.
* */
public Window(int frameSize, boolean isPeriodic)
{
this(frameSize, frameSize, isPeriodic, false);
}
/**
* @param isPeriodic
* Compute first N coefficients for the N+1 window.
* @param isWeighted
* Weight window according to the Weighted Overlap Add (WOLA)
* routine.
* */
public Window(int frameSize, int hopSize, boolean isPeriodic, boolean isWeighted)
{
this.frameSize = frameSize;
this.hopSize = hopSize;
this.isPeriodic = isPeriodic;
this.isWeighted = isWeighted;
}
private void weight(float[] window)
{
float weighting = 0;
for (int n = 0; n < frameSize; n++)
weighting += window[n] * window[n];
| // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Window.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp;
public final class Window
{
private final int frameSize;
private final int hopSize;
private final boolean isPeriodic;
private final boolean isWeighted;
/**
* @param isPeriodic
* Compute first N coefficients for the N+1 window.
* */
public Window(int frameSize, boolean isPeriodic)
{
this(frameSize, frameSize, isPeriodic, false);
}
/**
* @param isPeriodic
* Compute first N coefficients for the N+1 window.
* @param isWeighted
* Weight window according to the Weighted Overlap Add (WOLA)
* routine.
* */
public Window(int frameSize, int hopSize, boolean isPeriodic, boolean isWeighted)
{
this.frameSize = frameSize;
this.hopSize = hopSize;
this.isPeriodic = isPeriodic;
this.isWeighted = isWeighted;
}
private void weight(float[] window)
{
float weighting = 0;
for (int n = 0; n < frameSize; n++)
weighting += window[n] * window[n];
| weighting = 1F / sqrt(weighting / hopSize); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/Window.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.sqrt; | * routine.
* */
public Window(int frameSize, int hopSize, boolean isPeriodic, boolean isWeighted)
{
this.frameSize = frameSize;
this.hopSize = hopSize;
this.isPeriodic = isPeriodic;
this.isWeighted = isWeighted;
}
private void weight(float[] window)
{
float weighting = 0;
for (int n = 0; n < frameSize; n++)
weighting += window[n] * window[n];
weighting = 1F / sqrt(weighting / hopSize);
for (int n = 0; n < frameSize; n++)
window[n] *= weighting;
}
public float[] hann()
{
final float[] window = new float[frameSize];
final int N = (isPeriodic) ? frameSize + 1 : frameSize;
for (int n = 0; n < frameSize; n++)
{ | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Window.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
* routine.
* */
public Window(int frameSize, int hopSize, boolean isPeriodic, boolean isWeighted)
{
this.frameSize = frameSize;
this.hopSize = hopSize;
this.isPeriodic = isPeriodic;
this.isWeighted = isWeighted;
}
private void weight(float[] window)
{
float weighting = 0;
for (int n = 0; n < frameSize; n++)
weighting += window[n] * window[n];
weighting = 1F / sqrt(weighting / hopSize);
for (int n = 0; n < frameSize; n++)
window[n] *= weighting;
}
public float[] hann()
{
final float[] window = new float[frameSize];
final int N = (isPeriodic) ? frameSize + 1 : frameSize;
for (int n = 0; n < frameSize; n++)
{ | window[n] = 0.5F * (1F - cos(2F * PI * n / (N - 1F))); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/Window.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.sqrt; | * routine.
* */
public Window(int frameSize, int hopSize, boolean isPeriodic, boolean isWeighted)
{
this.frameSize = frameSize;
this.hopSize = hopSize;
this.isPeriodic = isPeriodic;
this.isWeighted = isWeighted;
}
private void weight(float[] window)
{
float weighting = 0;
for (int n = 0; n < frameSize; n++)
weighting += window[n] * window[n];
weighting = 1F / sqrt(weighting / hopSize);
for (int n = 0; n < frameSize; n++)
window[n] *= weighting;
}
public float[] hann()
{
final float[] window = new float[frameSize];
final int N = (isPeriodic) ? frameSize + 1 : frameSize;
for (int n = 0; n < frameSize; n++)
{ | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Window.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
* routine.
* */
public Window(int frameSize, int hopSize, boolean isPeriodic, boolean isWeighted)
{
this.frameSize = frameSize;
this.hopSize = hopSize;
this.isPeriodic = isPeriodic;
this.isWeighted = isWeighted;
}
private void weight(float[] window)
{
float weighting = 0;
for (int n = 0; n < frameSize; n++)
weighting += window[n] * window[n];
weighting = 1F / sqrt(weighting / hopSize);
for (int n = 0; n < frameSize; n++)
window[n] *= weighting;
}
public float[] hann()
{
final float[] window = new float[frameSize];
final int N = (isPeriodic) ? frameSize + 1 : frameSize;
for (int n = 0; n < frameSize; n++)
{ | window[n] = 0.5F * (1F - cos(2F * PI * n / (N - 1F))); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/widgets/DafxPicker.java | // Path: voicesmith/src/de/jurihock/voicesmith/DAFX.java
// public enum DAFX
// {
// Robotize,
// Transpose,
// Detune,
// Hoarseness;
//
// private static final DAFX[] dafxValues = DAFX.values();
//
// public static int count()
// {
// return dafxValues.length;
// }
//
// public static DAFX valueOf(int dafxIndex)
// {
// return dafxValues[dafxIndex];
// }
// }
| import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import de.jurihock.voicesmith.DAFX;
import de.jurihock.voicesmith.R; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.widgets;
public final class DafxPicker extends RadioGroup implements
OnClickListener
{ | // Path: voicesmith/src/de/jurihock/voicesmith/DAFX.java
// public enum DAFX
// {
// Robotize,
// Transpose,
// Detune,
// Hoarseness;
//
// private static final DAFX[] dafxValues = DAFX.values();
//
// public static int count()
// {
// return dafxValues.length;
// }
//
// public static DAFX valueOf(int dafxIndex)
// {
// return dafxValues[dafxIndex];
// }
// }
// Path: voicesmith/src/de/jurihock/voicesmith/widgets/DafxPicker.java
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import de.jurihock.voicesmith.DAFX;
import de.jurihock.voicesmith.R;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.widgets;
public final class DafxPicker extends RadioGroup implements
OnClickListener
{ | private DAFX dafx; |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/ResampleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float floor(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.floor;
import de.jurihock.voicesmith.Disposable; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
/**
* Replaced by the NativeResampleProcessor.
* */
@Deprecated
public final class ResampleProcessor implements Disposable
{
private final int[] ix;
private final int[] ix1;
private final float[] dx;
private final float[] dx1;
public ResampleProcessor(int frameSizeIn, int frameSizeOut)
{
ix = new int[frameSizeOut];
ix1 = new int[frameSizeOut];
dx = new float[frameSizeOut];
dx1 = new float[frameSizeOut];
for (int i = 0; i < frameSizeOut; i++)
{
float x = 1 + i * (float) frameSizeIn / (float) frameSizeOut;
| // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float floor(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/ResampleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.floor;
import de.jurihock.voicesmith.Disposable;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
/**
* Replaced by the NativeResampleProcessor.
* */
@Deprecated
public final class ResampleProcessor implements Disposable
{
private final int[] ix;
private final int[] ix1;
private final float[] dx;
private final float[] dx1;
public ResampleProcessor(int frameSizeIn, int frameSizeOut)
{
ix = new int[frameSizeOut];
ix1 = new int[frameSizeOut];
dx = new float[frameSizeOut];
dx1 = new float[frameSizeOut];
for (int i = 0; i < frameSizeOut; i++)
{
float x = 1 + i * (float) frameSizeIn / (float) frameSizeOut;
| ix[i] = (int) floor(x); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
/**
* Replaced by the NativeTimescaleProcessor.
* */
@Deprecated
public final class TimescaleProcessor implements Disposable
{
private final int fftSize;
private final float timescaleRatio;
private final float[] omegaA;
private final float[] omegaS;
private final float[] prevPhaseA;
private final float[] prevPhaseS;
public TimescaleProcessor(int frameSize, int analysisHopSize, int synthesisHopSize)
{
fftSize = frameSize / 2;
timescaleRatio = (float) synthesisHopSize / (float) analysisHopSize;
omegaA = new float[fftSize];
omegaS = new float[fftSize];
prevPhaseA = new float[fftSize];
prevPhaseS = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{ | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable;
/*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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
* 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 General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.jurihock.voicesmith.dsp.processors;
/**
* Replaced by the NativeTimescaleProcessor.
* */
@Deprecated
public final class TimescaleProcessor implements Disposable
{
private final int fftSize;
private final float timescaleRatio;
private final float[] omegaA;
private final float[] omegaS;
private final float[] prevPhaseA;
private final float[] prevPhaseS;
public TimescaleProcessor(int frameSize, int analysisHopSize, int synthesisHopSize)
{
fftSize = frameSize / 2;
timescaleRatio = (float) synthesisHopSize / (float) analysisHopSize;
omegaA = new float[fftSize];
omegaS = new float[fftSize];
prevPhaseA = new float[fftSize];
prevPhaseS = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{ | omegaA[i] = 2 * PI * (i / (float) frameSize) // not fftSize! |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable; | omegaS = new float[fftSize];
prevPhaseA = new float[fftSize];
prevPhaseS = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omegaA[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) analysisHopSize;
omegaS[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) synthesisHopSize;
}
}
public void processFrame(float[] frame)
{
if (timescaleRatio == 1)
return;
float re, im, abs;
float nextPhaseA, nextPhaseS;
float phaseDeltaA, phaseDeltaS;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable;
omegaS = new float[fftSize];
prevPhaseA = new float[fftSize];
prevPhaseS = new float[fftSize];
for (int i = 0; i < fftSize; i++)
{
omegaA[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) analysisHopSize;
omegaS[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) synthesisHopSize;
}
}
public void processFrame(float[] frame)
{
if (timescaleRatio == 1)
return;
float re, im, abs;
float nextPhaseA, nextPhaseS;
float phaseDeltaA, phaseDeltaS;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase | nextPhaseA = atan2(im, re); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable; | {
omegaA[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) analysisHopSize;
omegaS[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) synthesisHopSize;
}
}
public void processFrame(float[] frame)
{
if (timescaleRatio == 1)
return;
float re, im, abs;
float nextPhaseA, nextPhaseS;
float phaseDeltaA, phaseDeltaS;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable;
{
omegaA[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) analysisHopSize;
omegaS[i] = 2 * PI * (i / (float) frameSize) // not fftSize!
* (float) synthesisHopSize;
}
}
public void processFrame(float[] frame)
{
if (timescaleRatio == 1)
return;
float re, im, abs;
float nextPhaseA, nextPhaseS;
float phaseDeltaA, phaseDeltaS;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas | phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i])); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable; |
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas
phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i]));
phaseDeltaS = phaseDeltaA * timescaleRatio;
// Compute destination phase
nextPhaseS = princarg((prevPhaseS[i] + omegaS[i]) + phaseDeltaS);
// Save computed phase values
prevPhaseA[i] = nextPhaseA;
prevPhaseS[i] = nextPhaseS;
}
else
{
// Compute destination phase
nextPhaseS = princarg(nextPhaseA * 2);
}
// Compute destination Re and Im parts | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas
phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i]));
phaseDeltaS = phaseDeltaA * timescaleRatio;
// Compute destination phase
nextPhaseS = princarg((prevPhaseS[i] + omegaS[i]) + phaseDeltaS);
// Save computed phase values
prevPhaseA[i] = nextPhaseA;
prevPhaseS[i] = nextPhaseS;
}
else
{
// Compute destination phase
nextPhaseS = princarg(nextPhaseA * 2);
}
// Compute destination Re and Im parts | abs = sqrt(re * re + im * im); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable; | for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas
phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i]));
phaseDeltaS = phaseDeltaA * timescaleRatio;
// Compute destination phase
nextPhaseS = princarg((prevPhaseS[i] + omegaS[i]) + phaseDeltaS);
// Save computed phase values
prevPhaseA[i] = nextPhaseA;
prevPhaseS[i] = nextPhaseS;
}
else
{
// Compute destination phase
nextPhaseS = princarg(nextPhaseA * 2);
}
// Compute destination Re and Im parts
abs = sqrt(re * re + im * im); | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable;
for (int i = 1; i < fftSize; i++)
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas
phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i]));
phaseDeltaS = phaseDeltaA * timescaleRatio;
// Compute destination phase
nextPhaseS = princarg((prevPhaseS[i] + omegaS[i]) + phaseDeltaS);
// Save computed phase values
prevPhaseA[i] = nextPhaseA;
prevPhaseS[i] = nextPhaseS;
}
else
{
// Compute destination phase
nextPhaseS = princarg(nextPhaseA * 2);
}
// Compute destination Re and Im parts
abs = sqrt(re * re + im * im); | re = abs * cos(nextPhaseS); |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
| import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable; | {
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas
phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i]));
phaseDeltaS = phaseDeltaA * timescaleRatio;
// Compute destination phase
nextPhaseS = princarg((prevPhaseS[i] + omegaS[i]) + phaseDeltaS);
// Save computed phase values
prevPhaseA[i] = nextPhaseA;
prevPhaseS[i] = nextPhaseS;
}
else
{
// Compute destination phase
nextPhaseS = princarg(nextPhaseA * 2);
}
// Compute destination Re and Im parts
abs = sqrt(re * re + im * im);
re = abs * cos(nextPhaseS); | // Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static final float PI = (float) java.lang.Math.PI;
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float atan2(float y, float x);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float cos(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float princarg(float phase);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sin(float angle);
//
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/Math.java
// public static native float sqrt(float value);
//
// Path: voicesmith/src/de/jurihock/voicesmith/Disposable.java
// public interface Disposable
// {
// void dispose();
// }
// Path: voicesmith/src/de/jurihock/voicesmith/dsp/processors/TimescaleProcessor.java
import static de.jurihock.voicesmith.dsp.Math.PI;
import static de.jurihock.voicesmith.dsp.Math.atan2;
import static de.jurihock.voicesmith.dsp.Math.cos;
import static de.jurihock.voicesmith.dsp.Math.princarg;
import static de.jurihock.voicesmith.dsp.Math.sin;
import static de.jurihock.voicesmith.dsp.Math.sqrt;
import de.jurihock.voicesmith.Disposable;
{
// Get source Re and Im parts
re = frame[2 * i];
im = frame[2 * i + 1];
// Compute source phase
nextPhaseA = atan2(im, re);
if (timescaleRatio < 2)
{
// Compute phase deltas
phaseDeltaA = princarg(nextPhaseA - (prevPhaseA[i] + omegaA[i]));
phaseDeltaS = phaseDeltaA * timescaleRatio;
// Compute destination phase
nextPhaseS = princarg((prevPhaseS[i] + omegaS[i]) + phaseDeltaS);
// Save computed phase values
prevPhaseA[i] = nextPhaseA;
prevPhaseS[i] = nextPhaseS;
}
else
{
// Compute destination phase
nextPhaseS = princarg(nextPhaseA * 2);
}
// Compute destination Re and Im parts
abs = sqrt(re * re + im * im);
re = abs * cos(nextPhaseS); | im = abs * sin(nextPhaseS); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/methodreflector/GeneratedClassLoader.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
| import eu.mikroskeem.shuriken.common.Ensure;
import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; | package eu.mikroskeem.shuriken.instrumentation.methodreflector;
/**
* @author Mark Vainomaa
*/
final class GeneratedClassLoader extends ClassLoader {
@Contract("null, null -> fail")
Class<?> defineClass(String name, byte[] data) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/methodreflector/GeneratedClassLoader.java
import eu.mikroskeem.shuriken.common.Ensure;
import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
package eu.mikroskeem.shuriken.instrumentation.methodreflector;
/**
* @author Mark Vainomaa
*/
final class GeneratedClassLoader extends ClassLoader {
@Contract("null, null -> fail")
Class<?> defineClass(String name, byte[] data) { | name = Ensure.notNull(name, "Null name").replace('/', '.'); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/methodreflector/GeneratedClassLoader.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
| import eu.mikroskeem.shuriken.common.Ensure;
import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull; | package eu.mikroskeem.shuriken.instrumentation.methodreflector;
/**
* @author Mark Vainomaa
*/
final class GeneratedClassLoader extends ClassLoader {
@Contract("null, null -> fail")
Class<?> defineClass(String name, byte[] data) {
name = Ensure.notNull(name, "Null name").replace('/', '.');
synchronized(getClassLoadingLock(name)) {
if (hasClass(name)) throw new IllegalStateException(name + " already defined");
Class<?> c = this.define(name, Ensure.notNull(data, "Null data"));
Ensure.ensureCondition(c.getName().equals(name), "class name " + c.getName() + " != requested name " + name);
return c;
}
}
GeneratedClassLoader(ClassLoader parent) {
super(parent);
}
@NotNull
private Class<?> define(String name, byte[] data) {
synchronized (getClassLoadingLock(name)) {
Ensure.ensureCondition(!hasClass(name), "Already has class: " + name);
Class<?> c;
try {
c = defineClass(name, data, 0, data.length);
} catch (ClassFormatError e) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/methodreflector/GeneratedClassLoader.java
import eu.mikroskeem.shuriken.common.Ensure;
import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
package eu.mikroskeem.shuriken.instrumentation.methodreflector;
/**
* @author Mark Vainomaa
*/
final class GeneratedClassLoader extends ClassLoader {
@Contract("null, null -> fail")
Class<?> defineClass(String name, byte[] data) {
name = Ensure.notNull(name, "Null name").replace('/', '.');
synchronized(getClassLoadingLock(name)) {
if (hasClass(name)) throw new IllegalStateException(name + " already defined");
Class<?> c = this.define(name, Ensure.notNull(data, "Null data"));
Ensure.ensureCondition(c.getName().equals(name), "class name " + c.getName() + " != requested name " + name);
return c;
}
}
GeneratedClassLoader(ClassLoader parent) {
super(parent);
}
@NotNull
private Class<?> define(String name, byte[] data) {
synchronized (getClassLoadingLock(name)) {
Ensure.ensureCondition(!hasClass(name), "Already has class: " + name);
Class<?> c;
try {
c = defineClass(name, data, 0, data.length);
} catch (ClassFormatError e) { | SneakyThrow.throwException(e); |
mikroskeem/Shuriken | common/src/main/java/eu/mikroskeem/shuriken/common/function/UncheckedFunction.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import java.util.function.Function; | package eu.mikroskeem.shuriken.common.function;
/**
* @author Mark Vainomaa
*/
@FunctionalInterface
public interface UncheckedFunction<T, R, E extends Throwable> extends Function<T, R> {
@Override | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/function/UncheckedFunction.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import java.util.function.Function;
package eu.mikroskeem.shuriken.common.function;
/**
* @author Mark Vainomaa
*/
@FunctionalInterface
public interface UncheckedFunction<T, R, E extends Throwable> extends Function<T, R> {
@Override | default R apply(T t) { try { return actualApply(t); } catch (Throwable e) { SneakyThrow.throwException(e); return null; } } |
mikroskeem/Shuriken | instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/testagent/TestAgent2.java | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
| import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.GeneratorAdapter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain; | package eu.mikroskeem.test.shuriken.instrumentation.testagent;
/**
* @author Mark Vainomaa
*/
public class TestAgent2 implements ClassFileTransformer {
private final static String TARGET_CL = "eu/mikroskeem/test/shuriken/instrumentation/testclasses/TestTransformable2";
private final static int TARGET_A = Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER;
private final static String TARGET_M = "a"; | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
// Path: instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/testagent/TestAgent2.java
import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.GeneratorAdapter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
package eu.mikroskeem.test.shuriken.instrumentation.testagent;
/**
* @author Mark Vainomaa
*/
public class TestAgent2 implements ClassFileTransformer {
private final static String TARGET_CL = "eu/mikroskeem/test/shuriken/instrumentation/testclasses/TestTransformable2";
private final static int TARGET_A = Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER;
private final static String TARGET_M = "a"; | private final static String TARGET_S = new Descriptor().returns(String.class).build(); |
mikroskeem/Shuriken | common/src/main/java/eu/mikroskeem/shuriken/common/function/UncheckedBiFunction.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import java.util.function.BiFunction; | package eu.mikroskeem.shuriken.common.function;
/**
* @author Mark Vainomaa
*/
@FunctionalInterface
public interface UncheckedBiFunction<A, B, R, E extends Throwable> extends BiFunction<A, B, R> {
@Override | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/function/UncheckedBiFunction.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import java.util.function.BiFunction;
package eu.mikroskeem.shuriken.common.function;
/**
* @author Mark Vainomaa
*/
@FunctionalInterface
public interface UncheckedBiFunction<A, B, R, E extends Throwable> extends BiFunction<A, B, R> {
@Override | default R apply(A a, B b) { try { return actualApply(a, b); } catch (Throwable e) { SneakyThrow.throwException(e); return null; } } |
mikroskeem/Shuriken | classloader/src/main/java/eu/mikroskeem/shuriken/classloader/ShurikenClassLoader.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.meteogroup.jbrotli.io.BrotliInputStream;
import org.meteogroup.jbrotli.libloader.BrotliLibraryLoader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map; | package eu.mikroskeem.shuriken.classloader;
/**
* Shuriken compressed class loader
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ShurikenClassLoader extends URLClassLoader {
private final Map<String, Class<?>> classes = new HashMap<>();
public ShurikenClassLoader(URL[] urls) {
super(urls);
}
public ShurikenClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return classes.computeIfAbsent(name, k -> {
String path = name.replace('.', '/').concat(".class.br");
InputStream compressedClass = super.getResourceAsStream(path);
if(compressedClass != null) {
/* Decompress */ | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
// Path: classloader/src/main/java/eu/mikroskeem/shuriken/classloader/ShurikenClassLoader.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.meteogroup.jbrotli.io.BrotliInputStream;
import org.meteogroup.jbrotli.libloader.BrotliLibraryLoader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
package eu.mikroskeem.shuriken.classloader;
/**
* Shuriken compressed class loader
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ShurikenClassLoader extends URLClassLoader {
private final Map<String, Class<?>> classes = new HashMap<>();
public ShurikenClassLoader(URL[] urls) {
super(urls);
}
public ShurikenClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return classes.computeIfAbsent(name, k -> {
String path = name.replace('.', '/').concat(".class.br");
InputStream compressedClass = super.getResourceAsStream(path);
if(compressedClass != null) {
/* Decompress */ | byte[] decompressed = ByteArrays.fromInputStream(new BrotliInputStream(compressedClass)); |
mikroskeem/Shuriken | classloader/src/main/java/eu/mikroskeem/shuriken/classloader/ShurikenClassLoader.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.meteogroup.jbrotli.io.BrotliInputStream;
import org.meteogroup.jbrotli.libloader.BrotliLibraryLoader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map; | package eu.mikroskeem.shuriken.classloader;
/**
* Shuriken compressed class loader
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ShurikenClassLoader extends URLClassLoader {
private final Map<String, Class<?>> classes = new HashMap<>();
public ShurikenClassLoader(URL[] urls) {
super(urls);
}
public ShurikenClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return classes.computeIfAbsent(name, k -> {
String path = name.replace('.', '/').concat(".class.br");
InputStream compressedClass = super.getResourceAsStream(path);
if(compressedClass != null) {
/* Decompress */
byte[] decompressed = ByteArrays.fromInputStream(new BrotliInputStream(compressedClass));
String packageName = name.substring(0, name.lastIndexOf('.'));
if(getPackage(packageName) == null)
definePackage(packageName, null, null, null, null, null, null, null);
return super.defineClass(name, decompressed, 0, decompressed.length);
} else {
/* Try loading usual class */
try {
return super.findClass(name);
}
catch (ClassNotFoundException ignored) {}
} | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
// Path: classloader/src/main/java/eu/mikroskeem/shuriken/classloader/ShurikenClassLoader.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.meteogroup.jbrotli.io.BrotliInputStream;
import org.meteogroup.jbrotli.libloader.BrotliLibraryLoader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
package eu.mikroskeem.shuriken.classloader;
/**
* Shuriken compressed class loader
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ShurikenClassLoader extends URLClassLoader {
private final Map<String, Class<?>> classes = new HashMap<>();
public ShurikenClassLoader(URL[] urls) {
super(urls);
}
public ShurikenClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
return classes.computeIfAbsent(name, k -> {
String path = name.replace('.', '/').concat(".class.br");
InputStream compressedClass = super.getResourceAsStream(path);
if(compressedClass != null) {
/* Decompress */
byte[] decompressed = ByteArrays.fromInputStream(new BrotliInputStream(compressedClass));
String packageName = name.substring(0, name.lastIndexOf('.'));
if(getPackage(packageName) == null)
definePackage(packageName, null, null, null, null, null, null, null);
return super.defineClass(name, decompressed, 0, decompressed.length);
} else {
/* Try loading usual class */
try {
return super.findClass(name);
}
catch (ClassNotFoundException ignored) {}
} | SneakyThrow.throwException(new ClassNotFoundException()); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
| import eu.mikroskeem.shuriken.common.Ensure;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.*; | package eu.mikroskeem.shuriken.instrumentation;
public final class ClassTools {
/**
* Unqualify class name <br>
* In other words, <pre>foo.bar.baz</pre> -> <pre>foo/bar/baz</pre>
*
* @param className Class name
* @return Unqualified class name
*/
@NotNull
public static String unqualifyName(String className) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
import eu.mikroskeem.shuriken.common.Ensure;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.*;
package eu.mikroskeem.shuriken.instrumentation;
public final class ClassTools {
/**
* Unqualify class name <br>
* In other words, <pre>foo.bar.baz</pre> -> <pre>foo/bar/baz</pre>
*
* @param className Class name
* @return Unqualified class name
*/
@NotNull
public static String unqualifyName(String className) { | return Ensure.notNull(className, "Class name shouldn't be null!").replace(".", "/"); |
mikroskeem/Shuriken | classloader/src/test/java/eu/mikroskeem/test/shuriken/classloader/Utils.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/data/Pair.java
// public class Pair<K, V> {
// private final K key;
// private final V value;
//
// /**
// * Construct a new pair
// *
// * @param key Pair key
// * @param value Pair value
// */
// public Pair(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Gets pair key
// *
// * @return Pair key
// */
// public K getKey() {
// return this.key;
// }
//
// /**
// * Gets pair value
// *
// * @return Pair value
// */
// public V getValue() {
// return this.value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Pair)) return false;
// Pair other = (Pair) o;
// return key == null ? other.getKey() == null : key.equals(other.getKey()) &&
// value == null ? other.getValue() == null : value.equals(other.getValue());
// }
//
// @Override
// public int hashCode() {
// int result = 1;
// result = result * 59 + (key == null ? 43 : key.hashCode());
// result = result * 59 + (value == null ? 43 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "eu.mikroskeem.shuriken.common.data.Pair(key=" + this.getKey() + ", value=" + this.getValue() + ")";
// }
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import eu.mikroskeem.shuriken.common.data.Pair;
import org.meteogroup.jbrotli.BrotliStreamCompressor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; | package eu.mikroskeem.test.shuriken.classloader;
/**
* @author Mark Vainomaa
*/
public class Utils {
public static Path generateTestJar(Pair<String, byte[]>... files) {
Path jarFile;
try {
jarFile = Files.createTempFile("testjar", ".jar");
try(ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(jarFile))) {
Map<String, List<Pair<String, byte[]>>> filesMap = new HashMap<>();
for (Pair<String, byte[]> file : files) {
filesMap.compute(file.getKey(), (k, data) -> {
List<Pair<String, byte[]>> fileData = data != null ? data : new ArrayList<>();
fileData.add(new Pair<>(file.getKey(), compress(file.getValue())));
return fileData;
});
}
filesMap.forEach((path, data) -> {
putPath(Paths.get(path).getParent().toString(), zos);
data.forEach(file -> putFile(file.getKey(), file.getValue(), zos));
});
zos.closeEntry();
zos.finish();
}
} catch (Throwable e) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/data/Pair.java
// public class Pair<K, V> {
// private final K key;
// private final V value;
//
// /**
// * Construct a new pair
// *
// * @param key Pair key
// * @param value Pair value
// */
// public Pair(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Gets pair key
// *
// * @return Pair key
// */
// public K getKey() {
// return this.key;
// }
//
// /**
// * Gets pair value
// *
// * @return Pair value
// */
// public V getValue() {
// return this.value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Pair)) return false;
// Pair other = (Pair) o;
// return key == null ? other.getKey() == null : key.equals(other.getKey()) &&
// value == null ? other.getValue() == null : value.equals(other.getValue());
// }
//
// @Override
// public int hashCode() {
// int result = 1;
// result = result * 59 + (key == null ? 43 : key.hashCode());
// result = result * 59 + (value == null ? 43 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "eu.mikroskeem.shuriken.common.data.Pair(key=" + this.getKey() + ", value=" + this.getValue() + ")";
// }
// }
// Path: classloader/src/test/java/eu/mikroskeem/test/shuriken/classloader/Utils.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import eu.mikroskeem.shuriken.common.data.Pair;
import org.meteogroup.jbrotli.BrotliStreamCompressor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
package eu.mikroskeem.test.shuriken.classloader;
/**
* @author Mark Vainomaa
*/
public class Utils {
public static Path generateTestJar(Pair<String, byte[]>... files) {
Path jarFile;
try {
jarFile = Files.createTempFile("testjar", ".jar");
try(ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(jarFile))) {
Map<String, List<Pair<String, byte[]>>> filesMap = new HashMap<>();
for (Pair<String, byte[]> file : files) {
filesMap.compute(file.getKey(), (k, data) -> {
List<Pair<String, byte[]>> fileData = data != null ? data : new ArrayList<>();
fileData.add(new Pair<>(file.getKey(), compress(file.getValue())));
return fileData;
});
}
filesMap.forEach((path, data) -> {
putPath(Paths.get(path).getParent().toString(), zos);
data.forEach(file -> putFile(file.getKey(), file.getValue(), zos));
});
zos.closeEntry();
zos.finish();
}
} catch (Throwable e) { | SneakyThrow.throwException(e); |
mikroskeem/Shuriken | common/src/main/java/eu/mikroskeem/shuriken/common/function/UncheckedConsumer.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import java.util.function.Consumer; | package eu.mikroskeem.shuriken.common.function;
/**
* @author Mark Vainomaa
*/
@FunctionalInterface
public interface UncheckedConsumer<T, E extends Throwable> extends Consumer<T> {
@Override | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/function/UncheckedConsumer.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import java.util.function.Consumer;
package eu.mikroskeem.shuriken.common.function;
/**
* @author Mark Vainomaa
*/
@FunctionalInterface
public interface UncheckedConsumer<T, E extends Throwable> extends Consumer<T> {
@Override | default void accept(T t) { try { actualAccept(t); } catch (Throwable e) { SneakyThrow.throwException(e); } } |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/BytecodeManipulation.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/collections/CollectionUtilities.java
// @Nullable
// public static <T> T firstOrNull(@NotNull Iterator<T> iterator) {
// return iterator.hasNext() ? iterator.next() : null;
// }
| import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static eu.mikroskeem.shuriken.common.collections.CollectionUtilities.firstOrNull; | package eu.mikroskeem.shuriken.instrumentation.bytecode;
/**
* "Safer" bytecode manipulation utilities
*
* @author Mark Vainomaa
*/
public final class BytecodeManipulation {
/**
* Tries to find an instructions from instruction list
*
* @param instructions Instructions list
* @param instructionType Instruction type to find
* @param predicate Instruction test predicate
* @param <T> Instruction type
* @return Found instructions or empty list, if didn't find anything
*/
@NotNull
public static <T extends AbstractInsnNode> List<T> findInstructions(@NotNull InsnList instructions,
@NotNull Class<T> instructionType,
@NotNull Predicate<T> predicate) {
return Arrays.stream(instructions.toArray())
.filter(i -> i.getClass() == instructionType)
.map(instructionType::cast)
.filter(predicate)
.collect(Collectors.toList());
}
/**
* Tries to find an instruction from instruction list
*
* @param instructions Instruction list
* @param instructionType Instruction type
* @param predicate Instruction test predicate
* @param <T> Instruction type
* @return First target instruction, or null if not found
*/
@Nullable
public static <T extends AbstractInsnNode> T findInstruction(@NotNull InsnList instructions,
@NotNull Class<T> instructionType,
@NotNull Predicate<T> predicate) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/collections/CollectionUtilities.java
// @Nullable
// public static <T> T firstOrNull(@NotNull Iterator<T> iterator) {
// return iterator.hasNext() ? iterator.next() : null;
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/BytecodeManipulation.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static eu.mikroskeem.shuriken.common.collections.CollectionUtilities.firstOrNull;
package eu.mikroskeem.shuriken.instrumentation.bytecode;
/**
* "Safer" bytecode manipulation utilities
*
* @author Mark Vainomaa
*/
public final class BytecodeManipulation {
/**
* Tries to find an instructions from instruction list
*
* @param instructions Instructions list
* @param instructionType Instruction type to find
* @param predicate Instruction test predicate
* @param <T> Instruction type
* @return Found instructions or empty list, if didn't find anything
*/
@NotNull
public static <T extends AbstractInsnNode> List<T> findInstructions(@NotNull InsnList instructions,
@NotNull Class<T> instructionType,
@NotNull Predicate<T> predicate) {
return Arrays.stream(instructions.toArray())
.filter(i -> i.getClass() == instructionType)
.map(instructionType::cast)
.filter(predicate)
.collect(Collectors.toList());
}
/**
* Tries to find an instruction from instruction list
*
* @param instructions Instruction list
* @param instructionType Instruction type
* @param predicate Instruction test predicate
* @param <T> Instruction type
* @return First target instruction, or null if not found
*/
@Nullable
public static <T extends AbstractInsnNode> T findInstruction(@NotNull InsnList instructions,
@NotNull Class<T> instructionType,
@NotNull Predicate<T> predicate) { | return firstOrNull(findInstructions(instructions, instructionType, predicate)); |
mikroskeem/Shuriken | injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
| import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; | package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception { | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java
import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception { | Injector injector = ShurikenInjector.createInjector(binder -> { |
mikroskeem/Shuriken | injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
| import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; | package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception { | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java
import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception { | Injector injector = ShurikenInjector.createInjector(binder -> { |
mikroskeem/Shuriken | injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
| import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; | package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception {
Injector injector = ShurikenInjector.createInjector(binder -> { | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java
import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception {
Injector injector = ShurikenInjector.createInjector(binder -> { | binder.bind(InterfacesTestClass.a.class).to(InterfacesTestClass.A.class); |
mikroskeem/Shuriken | injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java | // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
| import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; | package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception {
Injector injector = ShurikenInjector.createInjector(binder -> {
binder.bind(InterfacesTestClass.a.class).to(InterfacesTestClass.A.class);
binder.bind(InterfacesTestClass.b.class).to(InterfacesTestClass.C.class);
});
| // Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Injector.java
// public interface Injector {
// /**
// * Instantiates object via no-args constructor
// *
// * @param clazz Class to instatiate
// * @param <T> Class type
// * @return Instatiated class with injected fields
// */
// <T> T getInstance(Class<T> clazz);
//
// /**
// * Injects existing fields annotated
// * with {@link javax.inject.Inject}
// *
// * @param instance Instance to inject
// * @param <T> Instance type
// * @return Injected instance (for chaining)
// */
// <T> T injectMembers(T instance);
// }
//
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/ShurikenInjector.java
// public class ShurikenInjector implements Injector {
// private final Binder binder;
// private ShurikenInjector(Binder binder) {
// this.binder = binder;
// }
//
// /**
// * Create injector out of {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation. <br>
// * You can either use Java 8 lambdas or implement interface directly
// * <pre>
// * ShurikenInjector.createInjector(binder -> {
// * binder.bind(InterfaceA.class).to(ImplementationB.class);
// * });
// * </pre>
// *
// * @param builder {@link eu.mikroskeem.shuriken.injector.Binder.Builder} implementation
// * @return {@link Injector} instance, in this case {@link ShurikenInjector}
// */
// public static Injector createInjector(Binder.Builder builder) {
// Binder binder = new Binder();
// Ensure.notNull(builder, "Builder shouldn't be null!").configure(binder);
// return new ShurikenInjector(binder);
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T getInstance(Class<T> clazz) {
// return injectMembers(Reflect.wrapClass(clazz).construct().getClassInstance());
// }
//
// /**
// * {@inheritDoc}
// */
// @Override
// public <T> T injectMembers(T instance) {
// Reflect.wrapInstance(instance).getFields().forEach(this::injectField);
// return instance;
// }
//
// /* Get binding for class */
// @SuppressWarnings("unchecked")
// private <T> Binder.Target<T> getTarget(Class<T> clazz) {
// return (Binder.Target<T>)binder.getBindings().get(clazz);
// }
//
// /* Inject field */
// private <T> void injectField(FieldWrapper<T> field) {
// if(field.getAnnotation(Inject.class).isPresent()) {
// Binder.Target<T> target;
// Ensure.ensureCondition(
// (target = getTarget(field.getType())) != null,
// "There are no registered bindings for class: " + field.getType()
// );
// field.write(target.getInstance());
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/InterfacesTestClass.java
// public class InterfacesTestClass {
// public interface a {}
// public interface b {}
//
// public static class A implements a {
// @Override
// public String toString() {
// return "a implementer A";
// }
// }
// public static class B implements a {
// @Override
// public String toString() {
// return "a implementer B";
// }
// }
// public static class C implements b {
// @Override
// public String toString() {
// return "b implementer C";
// }
// }
// public static class D implements b {
// @Override
// public String toString() {
// return "b implementer D";
// }
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassOne.java
// public class TestClassOne {
// @Inject @Named("name one") private Object a;
// @Inject @Named("name two") private String b;
//
// public Object getA() {
// return a;
// }
//
// public String getB() {
// return b;
// }
// }
//
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/testclasses/TestClassTwo.java
// public class TestClassTwo {
// @Inject private InterfacesTestClass.a a;
// @Inject private InterfacesTestClass.b b;
//
// public InterfacesTestClass.a getA() {
// return a;
// }
//
// public InterfacesTestClass.b getB() {
// return b;
// }
// }
// Path: injector/src/test/java/eu/mikroskeem/test/shuriken/injector/InjectorTester.java
import eu.mikroskeem.shuriken.injector.Injector;
import eu.mikroskeem.shuriken.injector.ShurikenInjector;
import eu.mikroskeem.test.shuriken.injector.testclasses.InterfacesTestClass;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassOne;
import eu.mikroskeem.test.shuriken.injector.testclasses.TestClassTwo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
package eu.mikroskeem.test.shuriken.injector;
/**
* @author Mark Vainomaa
*/
public class InjectorTester {
@Test
public void testBindingInjecting() throws Exception {
Injector injector = ShurikenInjector.createInjector(binder -> {
binder.bind(InterfacesTestClass.a.class).to(InterfacesTestClass.A.class);
binder.bind(InterfacesTestClass.b.class).to(InterfacesTestClass.C.class);
});
| TestClassTwo t1 = injector.getInstance(TestClassTwo.class); |
mikroskeem/Shuriken | injector/src/main/java/eu/mikroskeem/shuriken/injector/Named.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
| import eu.mikroskeem.shuriken.common.Ensure;
import java.lang.annotation.Annotation; | package eu.mikroskeem.shuriken.injector;
/**
* Implementation of {@link javax.inject.Named} used to define
* named annotations easily
*
* @author Mark Vainomaa
*/
public class Named implements javax.inject.Named {
private final String value;
Named(String value) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
// Path: injector/src/main/java/eu/mikroskeem/shuriken/injector/Named.java
import eu.mikroskeem.shuriken.common.Ensure;
import java.lang.annotation.Annotation;
package eu.mikroskeem.shuriken.injector;
/**
* Implementation of {@link javax.inject.Named} used to define
* named annotations easily
*
* @author Mark Vainomaa
*/
public class Named implements javax.inject.Named {
private final String value;
Named(String value) { | this.value = Ensure.notNull(value, "Value shouldn't be null!"); |
mikroskeem/Shuriken | common/src/test/java/eu/mikroskeem/test/shuriken/common/EnsureTester.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/wrappers/TypeWrapper.java
// @NotNull
// @Contract("null -> fail")
// public static TypeWrapper of(Object value) {
// return new TypeWrapper(value);
// }
| import eu.mikroskeem.shuriken.common.Ensure;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper.of; | package eu.mikroskeem.test.shuriken.common;
public class EnsureTester {
@Test
public void testTrueCondition() throws Exception { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/wrappers/TypeWrapper.java
// @NotNull
// @Contract("null -> fail")
// public static TypeWrapper of(Object value) {
// return new TypeWrapper(value);
// }
// Path: common/src/test/java/eu/mikroskeem/test/shuriken/common/EnsureTester.java
import eu.mikroskeem.shuriken.common.Ensure;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper.of;
package eu.mikroskeem.test.shuriken.common;
public class EnsureTester {
@Test
public void testTrueCondition() throws Exception { | Ensure.ensureCondition(true, UnsupportedOperationException.class, of("This shouldn't happen")); |
mikroskeem/Shuriken | common/src/test/java/eu/mikroskeem/test/shuriken/common/EnsureTester.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/wrappers/TypeWrapper.java
// @NotNull
// @Contract("null -> fail")
// public static TypeWrapper of(Object value) {
// return new TypeWrapper(value);
// }
| import eu.mikroskeem.shuriken.common.Ensure;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper.of; | package eu.mikroskeem.test.shuriken.common;
public class EnsureTester {
@Test
public void testTrueCondition() throws Exception { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// public class Ensure {
// /**
// * Ensure that condition is true
// *
// * @param condition Condition
// * @param exception Exception what will be thrown, if condition isn't true
// * @param args Exception arguments
// */
// @Contract("false, _, _ -> fail")
// public static void ensureCondition(boolean condition, Class<? extends Exception> exception, TypeWrapper... args) {
// if(!condition) throwException(Reflect.construct(Reflect.wrapClass(exception), args).getClassInstance());
// }
//
// /**
// * Throws {@link IllegalStateException} if condition is not true
// *
// * @param condition Condition to assert
// * @param text Message in {@link IllegalStateException}
// */
// @Contract("false, _ -> fail")
// public static void ensureCondition(boolean condition, String text) {
// if(!condition) throw new IllegalStateException(text);
// }
//
// /**
// * Check if reference is not null
// *
// * @param ref Object reference
// * @param errorMessage NullPointerException message
// * @param <T> Reference type
// * @return Passed reference
// */
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
//
// /**
// * Ensure that {@link Optional} value is present
// *
// * @param optional Optional to check
// * @param errorMessage NullPointerException message
// * @param <T> Value type wrapped inside {@link Optional}
// * @return Optional value
// */
// @SuppressWarnings({"ConstantConditions", "OptionalUsedAsFieldOrParameterType"})
// @NotNull
// @Contract("null, _ -> fail")
// public static <T> T ensurePresent(Optional<T> optional, @Nullable String errorMessage) {
// ensureCondition(
// notNull(optional, "Optional parameter shouldn't be null!").isPresent(),
// NullPointerException.class,
// of(""+errorMessage)
// );
// return optional.get();
// }
// }
//
// Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/wrappers/TypeWrapper.java
// @NotNull
// @Contract("null -> fail")
// public static TypeWrapper of(Object value) {
// return new TypeWrapper(value);
// }
// Path: common/src/test/java/eu/mikroskeem/test/shuriken/common/EnsureTester.java
import eu.mikroskeem.shuriken.common.Ensure;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Optional;
import static eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper.of;
package eu.mikroskeem.test.shuriken.common;
public class EnsureTester {
@Test
public void testTrueCondition() throws Exception { | Ensure.ensureCondition(true, UnsupportedOperationException.class, of("This shouldn't happen")); |
mikroskeem/Shuriken | classloader/src/test/java/eu/mikroskeem/test/shuriken/classloader/GenerateTestClass.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/data/Pair.java
// public class Pair<K, V> {
// private final K key;
// private final V value;
//
// /**
// * Construct a new pair
// *
// * @param key Pair key
// * @param value Pair value
// */
// public Pair(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Gets pair key
// *
// * @return Pair key
// */
// public K getKey() {
// return this.key;
// }
//
// /**
// * Gets pair value
// *
// * @return Pair value
// */
// public V getValue() {
// return this.value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Pair)) return false;
// Pair other = (Pair) o;
// return key == null ? other.getKey() == null : key.equals(other.getKey()) &&
// value == null ? other.getValue() == null : value.equals(other.getValue());
// }
//
// @Override
// public int hashCode() {
// int result = 1;
// result = result * 59 + (key == null ? 43 : key.hashCode());
// result = result * 59 + (value == null ? 43 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "eu.mikroskeem.shuriken.common.data.Pair(key=" + this.getKey() + ", value=" + this.getValue() + ")";
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
// public final class ClassTools {
// /**
// * Unqualify class name <br>
// * In other words, <pre>foo.bar.baz</pre> -> <pre>foo/bar/baz</pre>
// *
// * @param className Class name
// * @return Unqualified class name
// */
// @NotNull
// public static String unqualifyName(String className) {
// return Ensure.notNull(className, "Class name shouldn't be null!").replace(".", "/");
// }
//
// /**
// * Unqualify class name
// *
// * @see #unqualifyName(String)
// * @param clazz Class
// * @return Unqualified class name
// */
// @NotNull
// public static String unqualifyName(Class<?> clazz) {
// return unqualifyName(Ensure.notNull(clazz, "Class shouldn't be null!").getName());
// }
//
// /**
// * Generate simple <pre>super()</pre> calling constructor
// *
// * @param classVisitor ClassVisitor instance
// * @param superClass Super class name (use {@link Object} for non-extending classes
// * (or explictly extending Object, which is redundant anyway)
// */
// public static void generateSimpleSuperConstructor(@NotNull ClassVisitor classVisitor, @NotNull String superClass) {
// MethodVisitor mv = Ensure.notNull(classVisitor, "ClassWriter shouldn't be null!")
// .visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
// mv.visitCode();
// mv.visitVarInsn(ALOAD, 0);
// mv.visitMethodInsn(INVOKESPECIAL, unqualifyName(superClass), "<init>", "()V", false);
// mv.visitInsn(RETURN);
// mv.visitMaxs(1, 0);
// mv.visitEnd();
// }
//
// /**
// * Generate simple <pre>super()</pre> calling constructor
// *
// * @param classVisitor ClassWriter instance
// * @param superClass Super class object (use {@link Object} for non-extending classes
// * (or explictly extending Object, which is redundant anyway)
// */
// public static void generateSimpleSuperConstructor(@NotNull ClassVisitor classVisitor, @NotNull Class<?> superClass) {
// generateSimpleSuperConstructor(classVisitor, Ensure.notNull(superClass, "Class shouldn't be null").getName());
// }
//
// /**
// * Formats class resource path from class name
// *
// * @param className Class name
// * @return Resource path
// */
// @NotNull
// public static String getClassResourcePath(@NotNull String className) {
// return className.replace('.', '/').concat(".class");
// }
//
// /**
// * Formats class resource path from class object
// *
// * @param clazz Class
// * @return Resource path
// */
// @NotNull
// public static String getClassResourcePath(@NotNull Class<?> clazz) {
// return getClassResourcePath(clazz.getName());
// }
// }
| import eu.mikroskeem.shuriken.common.data.Pair;
import eu.mikroskeem.shuriken.instrumentation.ClassTools;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_SUPER; | package eu.mikroskeem.test.shuriken.classloader;
/**
* Generate test class
*
* @author Mark Vainomaa
*/
public class GenerateTestClass {
public static Pair<String, byte[]> generate(){
String className = "eu/mikroskeem/test/shuriken/classloader/classes/TestClass1";
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
cw.visit(52, ACC_PUBLIC + ACC_SUPER, className, null, Type.getInternalName(Object.class), null); | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/data/Pair.java
// public class Pair<K, V> {
// private final K key;
// private final V value;
//
// /**
// * Construct a new pair
// *
// * @param key Pair key
// * @param value Pair value
// */
// public Pair(K key, V value) {
// this.key = key;
// this.value = value;
// }
//
// /**
// * Gets pair key
// *
// * @return Pair key
// */
// public K getKey() {
// return this.key;
// }
//
// /**
// * Gets pair value
// *
// * @return Pair value
// */
// public V getValue() {
// return this.value;
// }
//
// @Override
// public boolean equals(Object o) {
// if (o == this) return true;
// if (!(o instanceof Pair)) return false;
// Pair other = (Pair) o;
// return key == null ? other.getKey() == null : key.equals(other.getKey()) &&
// value == null ? other.getValue() == null : value.equals(other.getValue());
// }
//
// @Override
// public int hashCode() {
// int result = 1;
// result = result * 59 + (key == null ? 43 : key.hashCode());
// result = result * 59 + (value == null ? 43 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "eu.mikroskeem.shuriken.common.data.Pair(key=" + this.getKey() + ", value=" + this.getValue() + ")";
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
// public final class ClassTools {
// /**
// * Unqualify class name <br>
// * In other words, <pre>foo.bar.baz</pre> -> <pre>foo/bar/baz</pre>
// *
// * @param className Class name
// * @return Unqualified class name
// */
// @NotNull
// public static String unqualifyName(String className) {
// return Ensure.notNull(className, "Class name shouldn't be null!").replace(".", "/");
// }
//
// /**
// * Unqualify class name
// *
// * @see #unqualifyName(String)
// * @param clazz Class
// * @return Unqualified class name
// */
// @NotNull
// public static String unqualifyName(Class<?> clazz) {
// return unqualifyName(Ensure.notNull(clazz, "Class shouldn't be null!").getName());
// }
//
// /**
// * Generate simple <pre>super()</pre> calling constructor
// *
// * @param classVisitor ClassVisitor instance
// * @param superClass Super class name (use {@link Object} for non-extending classes
// * (or explictly extending Object, which is redundant anyway)
// */
// public static void generateSimpleSuperConstructor(@NotNull ClassVisitor classVisitor, @NotNull String superClass) {
// MethodVisitor mv = Ensure.notNull(classVisitor, "ClassWriter shouldn't be null!")
// .visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
// mv.visitCode();
// mv.visitVarInsn(ALOAD, 0);
// mv.visitMethodInsn(INVOKESPECIAL, unqualifyName(superClass), "<init>", "()V", false);
// mv.visitInsn(RETURN);
// mv.visitMaxs(1, 0);
// mv.visitEnd();
// }
//
// /**
// * Generate simple <pre>super()</pre> calling constructor
// *
// * @param classVisitor ClassWriter instance
// * @param superClass Super class object (use {@link Object} for non-extending classes
// * (or explictly extending Object, which is redundant anyway)
// */
// public static void generateSimpleSuperConstructor(@NotNull ClassVisitor classVisitor, @NotNull Class<?> superClass) {
// generateSimpleSuperConstructor(classVisitor, Ensure.notNull(superClass, "Class shouldn't be null").getName());
// }
//
// /**
// * Formats class resource path from class name
// *
// * @param className Class name
// * @return Resource path
// */
// @NotNull
// public static String getClassResourcePath(@NotNull String className) {
// return className.replace('.', '/').concat(".class");
// }
//
// /**
// * Formats class resource path from class object
// *
// * @param clazz Class
// * @return Resource path
// */
// @NotNull
// public static String getClassResourcePath(@NotNull Class<?> clazz) {
// return getClassResourcePath(clazz.getName());
// }
// }
// Path: classloader/src/test/java/eu/mikroskeem/test/shuriken/classloader/GenerateTestClass.java
import eu.mikroskeem.shuriken.common.data.Pair;
import eu.mikroskeem.shuriken.instrumentation.ClassTools;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
import static org.objectweb.asm.Opcodes.ACC_SUPER;
package eu.mikroskeem.test.shuriken.classloader;
/**
* Generate test class
*
* @author Mark Vainomaa
*/
public class GenerateTestClass {
public static Pair<String, byte[]> generate(){
String className = "eu/mikroskeem/test/shuriken/classloader/classes/TestClass1";
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
cw.visit(52, ACC_PUBLIC + ACC_SUPER, className, null, Type.getInternalName(Object.class), null); | ClassTools.generateSimpleSuperConstructor(cw, Object.class); |
mikroskeem/Shuriken | common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static eu.mikroskeem.shuriken.common.Ensure.notNull; | package eu.mikroskeem.shuriken.common.streams;
/**
* Bytearray tools
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ByteArrays {
/**
* Convert an {@link InputStream} to byte array
*
* @param inputStream Source {@link InputStream}
* @return byte array or null, if reading failed
*/
@Nullable
@Contract("null -> fail; !null -> !null")
public static byte[] fromInputStream(InputStream inputStream) { | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static eu.mikroskeem.shuriken.common.Ensure.notNull;
package eu.mikroskeem.shuriken.common.streams;
/**
* Bytearray tools
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ByteArrays {
/**
* Convert an {@link InputStream} to byte array
*
* @param inputStream Source {@link InputStream}
* @return byte array or null, if reading failed
*/
@Nullable
@Contract("null -> fail; !null -> !null")
public static byte[] fromInputStream(InputStream inputStream) { | notNull(inputStream, "Input stream must not be null!"); |
mikroskeem/Shuriken | common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
| import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static eu.mikroskeem.shuriken.common.Ensure.notNull; | package eu.mikroskeem.shuriken.common.streams;
/**
* Bytearray tools
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ByteArrays {
/**
* Convert an {@link InputStream} to byte array
*
* @param inputStream Source {@link InputStream}
* @return byte array or null, if reading failed
*/
@Nullable
@Contract("null -> fail; !null -> !null")
public static byte[] fromInputStream(InputStream inputStream) {
notNull(inputStream, "Input stream must not be null!");
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int length;
while ((length =inputStream.read(buffer)) != -1)
output.write(buffer, 0, length);
return output.toByteArray();
} catch (IOException e){ | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/SneakyThrow.java
// public class SneakyThrow {
// /**
// * Good old SneakyThrows! Throws checked exceptions everywhere you want
// *
// * @param t Throwable
// */
// @Contract("_ -> fail")
// public static void throwException(Throwable t) {
// throw SneakyThrow.<RuntimeException>_throwException(t);
// }
//
// @Contract("_ -> fail")
// @SuppressWarnings("unchecked")
// private static <T extends Throwable> T _throwException(Throwable t) throws T {
// throw (T) Ensure.notNull(t, "Throwable should not be null");
// }
// }
//
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/Ensure.java
// @Contract("null, _ -> fail; !null, _ -> !null")
// public static <T> T notNull(T ref, @Nullable String errorMessage) {
// ensureCondition(ref != null, NullPointerException.class, of(""+errorMessage));
// return ref;
// }
// Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
import eu.mikroskeem.shuriken.common.SneakyThrow;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import static eu.mikroskeem.shuriken.common.Ensure.notNull;
package eu.mikroskeem.shuriken.common.streams;
/**
* Bytearray tools
*
* @author Mark Vainomaa
* @version 0.0.1
*/
public class ByteArrays {
/**
* Convert an {@link InputStream} to byte array
*
* @param inputStream Source {@link InputStream}
* @return byte array or null, if reading failed
*/
@Nullable
@Contract("null -> fail; !null -> !null")
public static byte[] fromInputStream(InputStream inputStream) {
notNull(inputStream, "Input stream must not be null!");
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int length;
while ((length =inputStream.read(buffer)) != -1)
output.write(buffer, 0, length);
return output.toByteArray();
} catch (IOException e){ | SneakyThrow.throwException(e); |
mikroskeem/Shuriken | instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/DescriptorTester.java | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
| import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; | package eu.mikroskeem.test.shuriken.instrumentation;
public class DescriptorTester {
@Test
public void testDescriptorGenerator(){ | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
// Path: instrumentation/src/test/java/eu/mikroskeem/test/shuriken/instrumentation/DescriptorTester.java
import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
package eu.mikroskeem.test.shuriken.instrumentation;
public class DescriptorTester {
@Test
public void testDescriptorGenerator(){ | String desc = new Descriptor() |
mikroskeem/Shuriken | reflect/src/main/java/eu/mikroskeem/shuriken/reflect/Reflect.java | // Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/wrappers/TypeWrapper.java
// public class TypeWrapper {
// private final Class<?> type;
// private final Object value;
//
// private TypeWrapper(Class<?> type, Object value) {
// this.type = type;
// this.value = value;
// }
//
// private TypeWrapper(Object value) {
// this.type = value.getClass();
// this.value = value;
// }
//
// public Class<?> getType() {
// return type;
// }
//
// public Object getValue() {
// return value;
// }
//
// @NotNull
// @Contract("null -> fail")
// public static TypeWrapper of(Object value) {
// return new TypeWrapper(value);
// }
//
// @NotNull
// @Contract("!null, _ -> !null; null, _ -> fail")
// public static TypeWrapper of(Class<?> type, Object value) {
// if(type == null) throw new IllegalStateException("Type must not be null");
// return new TypeWrapper(type, value);
// }
//
// @Override
// public String toString() {
// return String.format("TypeWrapper{type=%s, value=%s}", type, value);
// }
// }
| import eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;
import java.util.WeakHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream; | }
/**
* Get {@link Class} by name (like <pre>eu.mikroskeem.reflect.Reflect</pre>)
* <br>
* Throws {@link ClassNotFoundException} if class wasn't found
*
* @param name Class name
* @return Class object
* @param classLoader Classloader where class should be looked
*/
@NotNull
@Contract("null, null -> fail")
public static ClassWrapper<?> getClassThrows(String name, ClassLoader classLoader) {
return getClass(name, classLoader).orElseGet(() -> {
Reflect.Utils.throwException(new ClassNotFoundException(name));
return null;
});
}
/**
* Construct class with arguments
*
* @param classWrapper Class
* @param args Class (wrapped) arguments
* @param <T> Type
* @return Instance of class
* @see Constructor#newInstance(Object...) for exceptions
*/
@Contract("null, _ -> fail") | // Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/wrappers/TypeWrapper.java
// public class TypeWrapper {
// private final Class<?> type;
// private final Object value;
//
// private TypeWrapper(Class<?> type, Object value) {
// this.type = type;
// this.value = value;
// }
//
// private TypeWrapper(Object value) {
// this.type = value.getClass();
// this.value = value;
// }
//
// public Class<?> getType() {
// return type;
// }
//
// public Object getValue() {
// return value;
// }
//
// @NotNull
// @Contract("null -> fail")
// public static TypeWrapper of(Object value) {
// return new TypeWrapper(value);
// }
//
// @NotNull
// @Contract("!null, _ -> !null; null, _ -> fail")
// public static TypeWrapper of(Class<?> type, Object value) {
// if(type == null) throw new IllegalStateException("Type must not be null");
// return new TypeWrapper(type, value);
// }
//
// @Override
// public String toString() {
// return String.format("TypeWrapper{type=%s, value=%s}", type, value);
// }
// }
// Path: reflect/src/main/java/eu/mikroskeem/shuriken/reflect/Reflect.java
import eu.mikroskeem.shuriken.reflect.wrappers.TypeWrapper;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Optional;
import java.util.WeakHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
}
/**
* Get {@link Class} by name (like <pre>eu.mikroskeem.reflect.Reflect</pre>)
* <br>
* Throws {@link ClassNotFoundException} if class wasn't found
*
* @param name Class name
* @return Class object
* @param classLoader Classloader where class should be looked
*/
@NotNull
@Contract("null, null -> fail")
public static ClassWrapper<?> getClassThrows(String name, ClassLoader classLoader) {
return getClass(name, classLoader).orElseGet(() -> {
Reflect.Utils.throwException(new ClassNotFoundException(name));
return null;
});
}
/**
* Construct class with arguments
*
* @param classWrapper Class
* @param args Class (wrapped) arguments
* @param <T> Type
* @return Instance of class
* @see Constructor#newInstance(Object...) for exceptions
*/
@Contract("null, _ -> fail") | public static <T> ClassWrapper<T> construct(ClassWrapper<T> classWrapper, TypeWrapper... args) { |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentClassValidator.java | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @Nullable
// public static MethodNode findMethodWithAccessAtleast(@NotNull List<MethodNode> methodNodes, int access, @NotNull String name, @NotNull String desc) {
// return findMethod(methodNodes, m -> (m.access & access) != 0 && name.equals(m.name) && desc.equals(m.desc));
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @NotNull
// public static ClassNode readClass(@NotNull byte[] classData, int flags) {
// ClassReader classReader = new ClassReader(classData);
// ClassNode classNode = new ClassNode();
// classReader.accept(classNode, flags);
// return classNode;
// }
| import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.instrument.Instrumentation;
import java.util.List;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.findMethodWithAccessAtleast;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.readClass; | package eu.mikroskeem.shuriken.instrumentation.runtime;
/**
* @author Mark Vainomaa
*/
final class AgentClassValidator {
private final static Type STRING = Type.getType(String.class);
private final static Type INSTRUMENTATION = Type.getType(Instrumentation.class);
| // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @Nullable
// public static MethodNode findMethodWithAccessAtleast(@NotNull List<MethodNode> methodNodes, int access, @NotNull String name, @NotNull String desc) {
// return findMethod(methodNodes, m -> (m.access & access) != 0 && name.equals(m.name) && desc.equals(m.desc));
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @NotNull
// public static ClassNode readClass(@NotNull byte[] classData, int flags) {
// ClassReader classReader = new ClassReader(classData);
// ClassNode classNode = new ClassNode();
// classReader.accept(classNode, flags);
// return classNode;
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentClassValidator.java
import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.instrument.Instrumentation;
import java.util.List;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.findMethodWithAccessAtleast;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.readClass;
package eu.mikroskeem.shuriken.instrumentation.runtime;
/**
* @author Mark Vainomaa
*/
final class AgentClassValidator {
private final static Type STRING = Type.getType(String.class);
private final static Type INSTRUMENTATION = Type.getType(Instrumentation.class);
| private final static String SIGNATURE = new Descriptor().accepts(STRING, INSTRUMENTATION).build(); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentClassValidator.java | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @Nullable
// public static MethodNode findMethodWithAccessAtleast(@NotNull List<MethodNode> methodNodes, int access, @NotNull String name, @NotNull String desc) {
// return findMethod(methodNodes, m -> (m.access & access) != 0 && name.equals(m.name) && desc.equals(m.desc));
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @NotNull
// public static ClassNode readClass(@NotNull byte[] classData, int flags) {
// ClassReader classReader = new ClassReader(classData);
// ClassNode classNode = new ClassNode();
// classReader.accept(classNode, flags);
// return classNode;
// }
| import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.instrument.Instrumentation;
import java.util.List;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.findMethodWithAccessAtleast;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.readClass; | package eu.mikroskeem.shuriken.instrumentation.runtime;
/**
* @author Mark Vainomaa
*/
final class AgentClassValidator {
private final static Type STRING = Type.getType(String.class);
private final static Type INSTRUMENTATION = Type.getType(Instrumentation.class);
private final static String SIGNATURE = new Descriptor().accepts(STRING, INSTRUMENTATION).build();
static void validateMainClass(@NotNull AgentJarOutputStream outputStream) { | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @Nullable
// public static MethodNode findMethodWithAccessAtleast(@NotNull List<MethodNode> methodNodes, int access, @NotNull String name, @NotNull String desc) {
// return findMethod(methodNodes, m -> (m.access & access) != 0 && name.equals(m.name) && desc.equals(m.desc));
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @NotNull
// public static ClassNode readClass(@NotNull byte[] classData, int flags) {
// ClassReader classReader = new ClassReader(classData);
// ClassNode classNode = new ClassNode();
// classReader.accept(classNode, flags);
// return classNode;
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentClassValidator.java
import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.instrument.Instrumentation;
import java.util.List;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.findMethodWithAccessAtleast;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.readClass;
package eu.mikroskeem.shuriken.instrumentation.runtime;
/**
* @author Mark Vainomaa
*/
final class AgentClassValidator {
private final static Type STRING = Type.getType(String.class);
private final static Type INSTRUMENTATION = Type.getType(Instrumentation.class);
private final static String SIGNATURE = new Descriptor().accepts(STRING, INSTRUMENTATION).build();
static void validateMainClass(@NotNull AgentJarOutputStream outputStream) { | ClassNode classNode = readClass(outputStream.currentEntryData.toByteArray()); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentClassValidator.java | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @Nullable
// public static MethodNode findMethodWithAccessAtleast(@NotNull List<MethodNode> methodNodes, int access, @NotNull String name, @NotNull String desc) {
// return findMethod(methodNodes, m -> (m.access & access) != 0 && name.equals(m.name) && desc.equals(m.desc));
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @NotNull
// public static ClassNode readClass(@NotNull byte[] classData, int flags) {
// ClassReader classReader = new ClassReader(classData);
// ClassNode classNode = new ClassNode();
// classReader.accept(classNode, flags);
// return classNode;
// }
| import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.instrument.Instrumentation;
import java.util.List;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.findMethodWithAccessAtleast;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.readClass; | package eu.mikroskeem.shuriken.instrumentation.runtime;
/**
* @author Mark Vainomaa
*/
final class AgentClassValidator {
private final static Type STRING = Type.getType(String.class);
private final static Type INSTRUMENTATION = Type.getType(Instrumentation.class);
private final static String SIGNATURE = new Descriptor().accepts(STRING, INSTRUMENTATION).build();
static void validateMainClass(@NotNull AgentJarOutputStream outputStream) {
ClassNode classNode = readClass(outputStream.currentEntryData.toByteArray());
@SuppressWarnings("unchecked")
List<MethodNode> methods = (List<MethodNode>) classNode.methods;
// Try to find agentmain(String, Instrumentation) | // Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/Descriptor.java
// public final class Descriptor {
// /** Default method descriptor */
// public final static String DEFAULT = "()V";
//
// private String accepts = "";
// private String returns = "V";
// private final String finalString = "(%s)%s";
//
// /**
// * Get new descriptor builder instance
// *
// * @return {@link Descriptor} instance
// * @deprecated Use constructor instead
// */
// @Deprecated
// @Contract(" -> !null")
// public static Descriptor newDescriptor() {
// return new Descriptor();
// }
//
// /**
// * Build method accepts part
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.accepts = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Class<?>... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor accepts(@NotNull Type... arguments) {
// return accepts(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull String... arguments) {
// StringBuilder builder = new StringBuilder();
// for (String argument : arguments) builder.append(argument);
// this.returns = builder.toString();
// return this;
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Class<?>... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Build method returns part (default is primitive {@link Void})
// *
// * @param arguments Types what method accepts
// * @return this {@link Descriptor} instance
// */
// @NotNull
// public Descriptor returns(@NotNull Type... arguments) {
// return returns(Stream.of(arguments).map(Type::getDescriptor).toArray(String[]::new));
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @NotNull
// public String build() {
// return String.format(finalString, accepts, returns);
// }
//
// /**
// * Builds descriptor
// *
// * @return Descriptor string
// */
// @Override
// public String toString() {
// return build();
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @Nullable
// public static MethodNode findMethodWithAccessAtleast(@NotNull List<MethodNode> methodNodes, int access, @NotNull String name, @NotNull String desc) {
// return findMethod(methodNodes, m -> (m.access & access) != 0 && name.equals(m.name) && desc.equals(m.desc));
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/bytecode/ClassManipulation.java
// @NotNull
// public static ClassNode readClass(@NotNull byte[] classData, int flags) {
// ClassReader classReader = new ClassReader(classData);
// ClassNode classNode = new ClassNode();
// classReader.accept(classNode, flags);
// return classNode;
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentClassValidator.java
import eu.mikroskeem.shuriken.instrumentation.Descriptor;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import java.lang.instrument.Instrumentation;
import java.util.List;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.findMethodWithAccessAtleast;
import static eu.mikroskeem.shuriken.instrumentation.bytecode.ClassManipulation.readClass;
package eu.mikroskeem.shuriken.instrumentation.runtime;
/**
* @author Mark Vainomaa
*/
final class AgentClassValidator {
private final static Type STRING = Type.getType(String.class);
private final static Type INSTRUMENTATION = Type.getType(Instrumentation.class);
private final static String SIGNATURE = new Descriptor().accepts(STRING, INSTRUMENTATION).build();
static void validateMainClass(@NotNull AgentJarOutputStream outputStream) {
ClassNode classNode = readClass(outputStream.currentEntryData.toByteArray());
@SuppressWarnings("unchecked")
List<MethodNode> methods = (List<MethodNode>) classNode.methods;
// Try to find agentmain(String, Instrumentation) | MethodNode agentMain = findMethodWithAccessAtleast(methods, Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, "agentmain", SIGNATURE); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentJarOutputStream.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
// @NotNull
// public static String getClassResourcePath(@NotNull String className) {
// return className.replace('.', '/').concat(".class");
// }
| import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static eu.mikroskeem.shuriken.instrumentation.ClassTools.getClassResourcePath; | super.write(b, len, off);
}
@Override
public void write(byte[] b) throws IOException {
currentEntryData.write(b);
super.write(b);
}
@Override
public void closeEntry() throws IOException {
// Validate agent class
if(currentEntry.getName().equals(mainClassName)) {
AgentClassValidator.validateMainClass(this);
mainClassAdded = true;
}
currentEntry = null;
currentEntryData = null;
super.closeEntry();
}
/**
* Constructs new AgentJarOutputStream
*
* @param out Delegate output stream
* @param man {@link Manifest} to supply with jar
* @param mainClassName Main agent class name
*/
public AgentJarOutputStream(@NotNull OutputStream out, @NotNull Manifest man, @NotNull String mainClassName) throws IOException {
super(out); | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
// @NotNull
// public static String getClassResourcePath(@NotNull String className) {
// return className.replace('.', '/').concat(".class");
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentJarOutputStream.java
import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static eu.mikroskeem.shuriken.instrumentation.ClassTools.getClassResourcePath;
super.write(b, len, off);
}
@Override
public void write(byte[] b) throws IOException {
currentEntryData.write(b);
super.write(b);
}
@Override
public void closeEntry() throws IOException {
// Validate agent class
if(currentEntry.getName().equals(mainClassName)) {
AgentClassValidator.validateMainClass(this);
mainClassAdded = true;
}
currentEntry = null;
currentEntryData = null;
super.closeEntry();
}
/**
* Constructs new AgentJarOutputStream
*
* @param out Delegate output stream
* @param man {@link Manifest} to supply with jar
* @param mainClassName Main agent class name
*/
public AgentJarOutputStream(@NotNull OutputStream out, @NotNull Manifest man, @NotNull String mainClassName) throws IOException {
super(out); | this.mainClassName = getClassResourcePath(mainClassName); |
mikroskeem/Shuriken | instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentJarOutputStream.java | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
// @NotNull
// public static String getClassResourcePath(@NotNull String className) {
// return className.replace('.', '/').concat(".class");
// }
| import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static eu.mikroskeem.shuriken.instrumentation.ClassTools.getClassResourcePath; | this.mainClassName = getClassResourcePath(mainClassName);
// This is done in JarOutputStream constructor as well
ByteArrayOutputStream manifest; man.write(manifest = new ByteArrayOutputStream());
addEntry(JarFile.MANIFEST_NAME, manifest.toByteArray());
}
/**
* Adds new entry into jar
*
* @param entryPath Entry path
* @param data Entry data
*/
public void addEntry(@NotNull String entryPath, @NotNull byte[] data) throws IOException {
putNextEntry(new JarEntry(entryPath));
write(data);
closeEntry();
}
/**
* Adds class to jar
*
* @param clazz Target {@link Class}
*/
public void addClassToJar(@NotNull Class<?> clazz) throws IOException {
String clz = getClassResourcePath(clazz);
InputStream classStream;
if((classStream = clazz.getClassLoader().getResourceAsStream(clz)) == null) {
throw new IOException("Could not open resource: " + clz);
} | // Path: common/src/main/java/eu/mikroskeem/shuriken/common/streams/ByteArrays.java
// public class ByteArrays {
// /**
// * Convert an {@link InputStream} to byte array
// *
// * @param inputStream Source {@link InputStream}
// * @return byte array or null, if reading failed
// */
// @Nullable
// @Contract("null -> fail; !null -> !null")
// public static byte[] fromInputStream(InputStream inputStream) {
// notNull(inputStream, "Input stream must not be null!");
// ByteArrayOutputStream output = new ByteArrayOutputStream();
// try {
// byte[] buffer = new byte[1024];
// int length;
// while ((length =inputStream.read(buffer)) != -1)
// output.write(buffer, 0, length);
// return output.toByteArray();
// } catch (IOException e){
// SneakyThrow.throwException(e);
// return null;
// } finally {
// try {
// inputStream.close();
// output.close();
// }
// catch (IOException ignored){}
// }
// }
// }
//
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/ClassTools.java
// @NotNull
// public static String getClassResourcePath(@NotNull String className) {
// return className.replace('.', '/').concat(".class");
// }
// Path: instrumentation/src/main/java/eu/mikroskeem/shuriken/instrumentation/runtime/AgentJarOutputStream.java
import eu.mikroskeem.shuriken.common.streams.ByteArrays;
import org.jetbrains.annotations.NotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static eu.mikroskeem.shuriken.instrumentation.ClassTools.getClassResourcePath;
this.mainClassName = getClassResourcePath(mainClassName);
// This is done in JarOutputStream constructor as well
ByteArrayOutputStream manifest; man.write(manifest = new ByteArrayOutputStream());
addEntry(JarFile.MANIFEST_NAME, manifest.toByteArray());
}
/**
* Adds new entry into jar
*
* @param entryPath Entry path
* @param data Entry data
*/
public void addEntry(@NotNull String entryPath, @NotNull byte[] data) throws IOException {
putNextEntry(new JarEntry(entryPath));
write(data);
closeEntry();
}
/**
* Adds class to jar
*
* @param clazz Target {@link Class}
*/
public void addClassToJar(@NotNull Class<?> clazz) throws IOException {
String clz = getClassResourcePath(clazz);
InputStream classStream;
if((classStream = clazz.getClassLoader().getResourceAsStream(clz)) == null) {
throw new IOException("Could not open resource: " + clz);
} | addEntry(clz, ByteArrays.fromInputStream(classStream)); |
OpenSourcePhysics/tracker | src/org/opensourcephysics/cabrillo/tracker/CircleFitter.java | // Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class DataPoint extends TPoint {
//
// /**
// * Constructs a DataPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public DataPoint(double x, double y) {
// super(x, y);
// setStepEditTrigger(true);
// }
//
// /**
// * Overrides TPoint setXY method.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// if (getTrack().locked) return;
//
// if (circleFitter.isFixed()) {
// int row = 0;
// for (int j=0; j<dataPoints[0].length; j++) {
// if (this==dataPoints[0][j]) {
// row = j;
// break;
// }
// }
// CircleFitterStep keyStep = (CircleFitterStep)circleFitter.steps.getStep(0);
// while (keyStep.dataPoints[0].length<=row) {
// keyStep.addDataPoint(keyStep.new DataPoint(0, 0), false);
// }
// keyStep.dataPoints[0][row].setLocation(x, y); // set property of step 0
// if (doRefresh) keyStep.refreshCircle();
// if (doRefresh) circleFitter.refreshStep(CircleFitterStep.this); // sets properties of this step
// }
// else {
// setLocation(x, y);
// if (!this.isAttached())
// circleFitter.keyFrames.add(n);
// if (doRefresh) refreshCircle();
// }
// if (doRefresh) circleFitter.refreshFields(n);
//
// circleFitter.dataValid = false;
// if (doRefresh) circleFitter.firePropertyChange("data", null, circleFitter); //$NON-NLS-1$
// if (circleFitter.trackerPanel != null) {
// circleFitter.trackerPanel.changed = true;
// }
// }
//
// @Override
// public void setScreenPosition(int x, int y, VideoPanel vidPanel, InputEvent e) {
// if (this.isAttached()) return; // don't drag or nudge when attached to another point
// setScreenPosition(x, y, vidPanel);
// }
//
// @Override
// public String toString() {
// return "DataPoint "+n+": "+super.toString(); //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// public Step getAttachedStep() {
// TTrack track = getTrack();
// if (this.attachedTo!=null && track.trackerPanel!=null) {
// ArrayList<PointMass> masses = track.trackerPanel.getDrawables(PointMass.class);
// for (PointMass next: masses) {
// Step step = next.getStep(attachedTo, track.trackerPanel);
// if (step!=null) return step;
// }
// }
// return null;
// }
//
// }
//
// Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class CenterPoint extends TPoint {
//
// /**
// * Constructs a CenterPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public CenterPoint(double x, double y) {
// super(x, y);
// }
//
// /**
// * Overrides TPoint setXY method to prevent user dragging/nudging.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// return;
// }
//
// }
| import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import javax.swing.*;
import javax.swing.border.Border;
import org.opensourcephysics.display.*;
import org.opensourcephysics.media.core.*;
import org.opensourcephysics.tools.FontSizer;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.DataPoint;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.CenterPoint;
import org.opensourcephysics.controls.*; | CircleFitterStep step = new CircleFitterStep(this, 0);
step.setFootprint(getFootprint());
steps = new StepArray(step); // autofills
keyFrames.add(0);
fixedItem = new JCheckBoxMenuItem(TrackerRes.getString("TapeMeasure.MenuItem.Fixed")); //$NON-NLS-1$
fixedItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
setFixed(fixedItem.isSelected());
}
});
// create attachment dialog item
attachmentItem = new JMenuItem(TrackerRes.getString("MeasuringTool.MenuItem.Attach")); //$NON-NLS-1$
attachmentItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AttachmentDialog control = trackerPanel.getAttachmentDialog(CircleFitter.this);
control.setVisible(true);
}
});
clickToMarkLabel = new JLabel();
clickToMarkLabel.setForeground(Color.red.darker());
// create actions, listeners, labels and fields for data points
final Action dataPointAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (trackerPanel==null) return;
if (e!=null && e.getSource()==xDataField && xDataField.getBackground()!=Color.yellow) return;
if (e!=null && e.getSource()==yDataField && yDataField.getBackground()!=Color.yellow) return;
TPoint p = trackerPanel.getSelectedPoint(); | // Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class DataPoint extends TPoint {
//
// /**
// * Constructs a DataPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public DataPoint(double x, double y) {
// super(x, y);
// setStepEditTrigger(true);
// }
//
// /**
// * Overrides TPoint setXY method.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// if (getTrack().locked) return;
//
// if (circleFitter.isFixed()) {
// int row = 0;
// for (int j=0; j<dataPoints[0].length; j++) {
// if (this==dataPoints[0][j]) {
// row = j;
// break;
// }
// }
// CircleFitterStep keyStep = (CircleFitterStep)circleFitter.steps.getStep(0);
// while (keyStep.dataPoints[0].length<=row) {
// keyStep.addDataPoint(keyStep.new DataPoint(0, 0), false);
// }
// keyStep.dataPoints[0][row].setLocation(x, y); // set property of step 0
// if (doRefresh) keyStep.refreshCircle();
// if (doRefresh) circleFitter.refreshStep(CircleFitterStep.this); // sets properties of this step
// }
// else {
// setLocation(x, y);
// if (!this.isAttached())
// circleFitter.keyFrames.add(n);
// if (doRefresh) refreshCircle();
// }
// if (doRefresh) circleFitter.refreshFields(n);
//
// circleFitter.dataValid = false;
// if (doRefresh) circleFitter.firePropertyChange("data", null, circleFitter); //$NON-NLS-1$
// if (circleFitter.trackerPanel != null) {
// circleFitter.trackerPanel.changed = true;
// }
// }
//
// @Override
// public void setScreenPosition(int x, int y, VideoPanel vidPanel, InputEvent e) {
// if (this.isAttached()) return; // don't drag or nudge when attached to another point
// setScreenPosition(x, y, vidPanel);
// }
//
// @Override
// public String toString() {
// return "DataPoint "+n+": "+super.toString(); //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// public Step getAttachedStep() {
// TTrack track = getTrack();
// if (this.attachedTo!=null && track.trackerPanel!=null) {
// ArrayList<PointMass> masses = track.trackerPanel.getDrawables(PointMass.class);
// for (PointMass next: masses) {
// Step step = next.getStep(attachedTo, track.trackerPanel);
// if (step!=null) return step;
// }
// }
// return null;
// }
//
// }
//
// Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class CenterPoint extends TPoint {
//
// /**
// * Constructs a CenterPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public CenterPoint(double x, double y) {
// super(x, y);
// }
//
// /**
// * Overrides TPoint setXY method to prevent user dragging/nudging.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// return;
// }
//
// }
// Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitter.java
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import javax.swing.*;
import javax.swing.border.Border;
import org.opensourcephysics.display.*;
import org.opensourcephysics.media.core.*;
import org.opensourcephysics.tools.FontSizer;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.DataPoint;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.CenterPoint;
import org.opensourcephysics.controls.*;
CircleFitterStep step = new CircleFitterStep(this, 0);
step.setFootprint(getFootprint());
steps = new StepArray(step); // autofills
keyFrames.add(0);
fixedItem = new JCheckBoxMenuItem(TrackerRes.getString("TapeMeasure.MenuItem.Fixed")); //$NON-NLS-1$
fixedItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
setFixed(fixedItem.isSelected());
}
});
// create attachment dialog item
attachmentItem = new JMenuItem(TrackerRes.getString("MeasuringTool.MenuItem.Attach")); //$NON-NLS-1$
attachmentItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AttachmentDialog control = trackerPanel.getAttachmentDialog(CircleFitter.this);
control.setVisible(true);
}
});
clickToMarkLabel = new JLabel();
clickToMarkLabel.setForeground(Color.red.darker());
// create actions, listeners, labels and fields for data points
final Action dataPointAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (trackerPanel==null) return;
if (e!=null && e.getSource()==xDataField && xDataField.getBackground()!=Color.yellow) return;
if (e!=null && e.getSource()==yDataField && yDataField.getBackground()!=Color.yellow) return;
TPoint p = trackerPanel.getSelectedPoint(); | if (!(p instanceof DataPoint)) return; |
OpenSourcePhysics/tracker | src/org/opensourcephysics/cabrillo/tracker/CircleFitter.java | // Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class DataPoint extends TPoint {
//
// /**
// * Constructs a DataPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public DataPoint(double x, double y) {
// super(x, y);
// setStepEditTrigger(true);
// }
//
// /**
// * Overrides TPoint setXY method.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// if (getTrack().locked) return;
//
// if (circleFitter.isFixed()) {
// int row = 0;
// for (int j=0; j<dataPoints[0].length; j++) {
// if (this==dataPoints[0][j]) {
// row = j;
// break;
// }
// }
// CircleFitterStep keyStep = (CircleFitterStep)circleFitter.steps.getStep(0);
// while (keyStep.dataPoints[0].length<=row) {
// keyStep.addDataPoint(keyStep.new DataPoint(0, 0), false);
// }
// keyStep.dataPoints[0][row].setLocation(x, y); // set property of step 0
// if (doRefresh) keyStep.refreshCircle();
// if (doRefresh) circleFitter.refreshStep(CircleFitterStep.this); // sets properties of this step
// }
// else {
// setLocation(x, y);
// if (!this.isAttached())
// circleFitter.keyFrames.add(n);
// if (doRefresh) refreshCircle();
// }
// if (doRefresh) circleFitter.refreshFields(n);
//
// circleFitter.dataValid = false;
// if (doRefresh) circleFitter.firePropertyChange("data", null, circleFitter); //$NON-NLS-1$
// if (circleFitter.trackerPanel != null) {
// circleFitter.trackerPanel.changed = true;
// }
// }
//
// @Override
// public void setScreenPosition(int x, int y, VideoPanel vidPanel, InputEvent e) {
// if (this.isAttached()) return; // don't drag or nudge when attached to another point
// setScreenPosition(x, y, vidPanel);
// }
//
// @Override
// public String toString() {
// return "DataPoint "+n+": "+super.toString(); //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// public Step getAttachedStep() {
// TTrack track = getTrack();
// if (this.attachedTo!=null && track.trackerPanel!=null) {
// ArrayList<PointMass> masses = track.trackerPanel.getDrawables(PointMass.class);
// for (PointMass next: masses) {
// Step step = next.getStep(attachedTo, track.trackerPanel);
// if (step!=null) return step;
// }
// }
// return null;
// }
//
// }
//
// Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class CenterPoint extends TPoint {
//
// /**
// * Constructs a CenterPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public CenterPoint(double x, double y) {
// super(x, y);
// }
//
// /**
// * Overrides TPoint setXY method to prevent user dragging/nudging.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// return;
// }
//
// }
| import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import javax.swing.*;
import javax.swing.border.Border;
import org.opensourcephysics.display.*;
import org.opensourcephysics.media.core.*;
import org.opensourcephysics.tools.FontSizer;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.DataPoint;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.CenterPoint;
import org.opensourcephysics.controls.*; | list.add(yDataPointSeparator);
// count valid points
ArrayList<DataPoint> pts = step.getValidDataPoints();
int dataCount=pts.size();
if (dataCount<3) {
clickToMarkLabel.setText(TrackerRes.getString("CircleFitter.Label.MarkPoint")); //$NON-NLS-1$
list.add(clickToMarkLabel);
}
return list;
}
@Override
public Interactive findInteractive(
DrawingPanel panel, int xpix, int ypix) {
if (!(panel instanceof TrackerPanel) || !isVisible())
return null;
TrackerPanel trackerPanel = (TrackerPanel)panel;
int n = trackerPanel.getFrameNumber();
if (trackerPanel.getPlayer().getVideoClip().includesFrame(n)) {
CircleFitterStep step = (CircleFitterStep)steps.getStep(n);
Interactive ia = step.findInteractive(trackerPanel, xpix, ypix);
if (ia == null) {
partName = TrackerRes.getString("TTrack.Selected.Hint"); //$NON-NLS-1$
hint = TrackerRes.getString("CircleFitter.Hint.Mark3"); //$NON-NLS-1$
return null;
}
if (ia instanceof DataPoint) {
partName = TrackerRes.getString("CircleFitter.DataPoint.Name"); //$NON-NLS-1$
hint = TrackerRes.getString("CircleFitter.DataPoint.Hint"); //$NON-NLS-1$
} | // Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class DataPoint extends TPoint {
//
// /**
// * Constructs a DataPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public DataPoint(double x, double y) {
// super(x, y);
// setStepEditTrigger(true);
// }
//
// /**
// * Overrides TPoint setXY method.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// if (getTrack().locked) return;
//
// if (circleFitter.isFixed()) {
// int row = 0;
// for (int j=0; j<dataPoints[0].length; j++) {
// if (this==dataPoints[0][j]) {
// row = j;
// break;
// }
// }
// CircleFitterStep keyStep = (CircleFitterStep)circleFitter.steps.getStep(0);
// while (keyStep.dataPoints[0].length<=row) {
// keyStep.addDataPoint(keyStep.new DataPoint(0, 0), false);
// }
// keyStep.dataPoints[0][row].setLocation(x, y); // set property of step 0
// if (doRefresh) keyStep.refreshCircle();
// if (doRefresh) circleFitter.refreshStep(CircleFitterStep.this); // sets properties of this step
// }
// else {
// setLocation(x, y);
// if (!this.isAttached())
// circleFitter.keyFrames.add(n);
// if (doRefresh) refreshCircle();
// }
// if (doRefresh) circleFitter.refreshFields(n);
//
// circleFitter.dataValid = false;
// if (doRefresh) circleFitter.firePropertyChange("data", null, circleFitter); //$NON-NLS-1$
// if (circleFitter.trackerPanel != null) {
// circleFitter.trackerPanel.changed = true;
// }
// }
//
// @Override
// public void setScreenPosition(int x, int y, VideoPanel vidPanel, InputEvent e) {
// if (this.isAttached()) return; // don't drag or nudge when attached to another point
// setScreenPosition(x, y, vidPanel);
// }
//
// @Override
// public String toString() {
// return "DataPoint "+n+": "+super.toString(); //$NON-NLS-1$ //$NON-NLS-2$
// }
//
// public Step getAttachedStep() {
// TTrack track = getTrack();
// if (this.attachedTo!=null && track.trackerPanel!=null) {
// ArrayList<PointMass> masses = track.trackerPanel.getDrawables(PointMass.class);
// for (PointMass next: masses) {
// Step step = next.getStep(attachedTo, track.trackerPanel);
// if (step!=null) return step;
// }
// }
// return null;
// }
//
// }
//
// Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitterStep.java
// class CenterPoint extends TPoint {
//
// /**
// * Constructs a CenterPoint with specified image coordinates.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public CenterPoint(double x, double y) {
// super(x, y);
// }
//
// /**
// * Overrides TPoint setXY method to prevent user dragging/nudging.
// *
// * @param x the x coordinate
// * @param y the y coordinate
// */
// public void setXY(double x, double y) {
// return;
// }
//
// }
// Path: src/org/opensourcephysics/cabrillo/tracker/CircleFitter.java
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import javax.swing.*;
import javax.swing.border.Border;
import org.opensourcephysics.display.*;
import org.opensourcephysics.media.core.*;
import org.opensourcephysics.tools.FontSizer;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.DataPoint;
import org.opensourcephysics.cabrillo.tracker.CircleFitterStep.CenterPoint;
import org.opensourcephysics.controls.*;
list.add(yDataPointSeparator);
// count valid points
ArrayList<DataPoint> pts = step.getValidDataPoints();
int dataCount=pts.size();
if (dataCount<3) {
clickToMarkLabel.setText(TrackerRes.getString("CircleFitter.Label.MarkPoint")); //$NON-NLS-1$
list.add(clickToMarkLabel);
}
return list;
}
@Override
public Interactive findInteractive(
DrawingPanel panel, int xpix, int ypix) {
if (!(panel instanceof TrackerPanel) || !isVisible())
return null;
TrackerPanel trackerPanel = (TrackerPanel)panel;
int n = trackerPanel.getFrameNumber();
if (trackerPanel.getPlayer().getVideoClip().includesFrame(n)) {
CircleFitterStep step = (CircleFitterStep)steps.getStep(n);
Interactive ia = step.findInteractive(trackerPanel, xpix, ypix);
if (ia == null) {
partName = TrackerRes.getString("TTrack.Selected.Hint"); //$NON-NLS-1$
hint = TrackerRes.getString("CircleFitter.Hint.Mark3"); //$NON-NLS-1$
return null;
}
if (ia instanceof DataPoint) {
partName = TrackerRes.getString("CircleFitter.DataPoint.Name"); //$NON-NLS-1$
hint = TrackerRes.getString("CircleFitter.DataPoint.Hint"); //$NON-NLS-1$
} | else if (ia instanceof CenterPoint) { |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/Credentials.java
// public class Credentials {
//
// private long clientId;
// private String username;
// private String passoword;
// private String key;
//
// @Nullable
// private String restClientId;
// @Nullable
// private String restClientSecret;
// @Nullable
// private String restClientApiKey;
// @Nullable
// private String restRedirectUri;
//
// public Credentials(long clientId, String username, String passowrd, String key) {
// this(clientId, username, passowrd, key, null, null, null, null);
// }
//
// public Credentials(long clientId, String username, String passowrd, String key, @Nullable String restClientId, @Nullable String restClientSecret, @Nullable String restClientApiKey, @Nullable String restRedirectUri) {
// this.clientId = clientId;
// this.username = username;
// this.passoword = passowrd;
// this.key = key;
// this.restClientId = restClientId;
// this.restClientSecret = restClientSecret;
// this.restClientApiKey = restClientApiKey;
// this.restRedirectUri = restRedirectUri;
// }
//
// public long getClientId() {
// return clientId;
// }
// String getUsername() {
// return username;
// }
// String getPassoword() {
// return passoword;
// }
// public String getKey() {
// return key;
// }
// @Nullable
// public String getRestClientId() {
// return restClientId;
// }
// @Nullable
// public String getRestClientSecret() {
// return restClientSecret;
// }
// @Nullable
// public String getRestClientApiKey() {
// return restClientApiKey;
// }
// @Nullable
// public String getRestRedirectUri() {
// return restRedirectUri;
// }
//
// @Override
// public String toString() {
// return "Credentials{" +
// "clientId='" + clientId + "\', " +
// "username='" + username + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Credentials that = (Credentials) o;
//
// if (clientId != that.clientId) return false;
// if (!username.equals(that.username)) return false;
// if (!passoword.equals(that.passoword)) return false;
// if (!key.equals(that.key)) return false;
// if (restClientId != null ? !restClientId.equals(that.restClientId) : that.restClientId != null) return false;
// if (restClientSecret != null ? !restClientSecret.equals(that.restClientSecret) : that.restClientSecret != null) return false;
// if (restClientApiKey != null ? !restClientApiKey.equals(that.restClientApiKey) : that.restClientApiKey != null) return false;
// return restRedirectUri != null ? restRedirectUri.equals(that.restRedirectUri) : that.restRedirectUri == null;
// }
//
// @Override
// public int hashCode() {
// int result = (int) (clientId ^ (clientId >>> 32));
// result = 31 * result + username.hashCode();
// result = 31 * result + passoword.hashCode();
// result = 31 * result + key.hashCode();
// result = 31 * result + (restClientId != null ? restClientId.hashCode() : 0);
// result = 31 * result + (restClientSecret != null ? restClientSecret.hashCode() : 0);
// result = 31 * result + (restClientApiKey != null ? restClientApiKey.hashCode() : 0);
// result = 31 * result + (restRedirectUri != null ? restRedirectUri.hashCode() : 0);
// return result;
// }
//
// }
| import com.apwglobal.nice.login.Credentials;
import pl.allegro.webapi.ServicePort; | package com.apwglobal.nice.service;
public class AbstractService {
protected ServicePort allegro; | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/Credentials.java
// public class Credentials {
//
// private long clientId;
// private String username;
// private String passoword;
// private String key;
//
// @Nullable
// private String restClientId;
// @Nullable
// private String restClientSecret;
// @Nullable
// private String restClientApiKey;
// @Nullable
// private String restRedirectUri;
//
// public Credentials(long clientId, String username, String passowrd, String key) {
// this(clientId, username, passowrd, key, null, null, null, null);
// }
//
// public Credentials(long clientId, String username, String passowrd, String key, @Nullable String restClientId, @Nullable String restClientSecret, @Nullable String restClientApiKey, @Nullable String restRedirectUri) {
// this.clientId = clientId;
// this.username = username;
// this.passoword = passowrd;
// this.key = key;
// this.restClientId = restClientId;
// this.restClientSecret = restClientSecret;
// this.restClientApiKey = restClientApiKey;
// this.restRedirectUri = restRedirectUri;
// }
//
// public long getClientId() {
// return clientId;
// }
// String getUsername() {
// return username;
// }
// String getPassoword() {
// return passoword;
// }
// public String getKey() {
// return key;
// }
// @Nullable
// public String getRestClientId() {
// return restClientId;
// }
// @Nullable
// public String getRestClientSecret() {
// return restClientSecret;
// }
// @Nullable
// public String getRestClientApiKey() {
// return restClientApiKey;
// }
// @Nullable
// public String getRestRedirectUri() {
// return restRedirectUri;
// }
//
// @Override
// public String toString() {
// return "Credentials{" +
// "clientId='" + clientId + "\', " +
// "username='" + username + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Credentials that = (Credentials) o;
//
// if (clientId != that.clientId) return false;
// if (!username.equals(that.username)) return false;
// if (!passoword.equals(that.passoword)) return false;
// if (!key.equals(that.key)) return false;
// if (restClientId != null ? !restClientId.equals(that.restClientId) : that.restClientId != null) return false;
// if (restClientSecret != null ? !restClientSecret.equals(that.restClientSecret) : that.restClientSecret != null) return false;
// if (restClientApiKey != null ? !restClientApiKey.equals(that.restClientApiKey) : that.restClientApiKey != null) return false;
// return restRedirectUri != null ? restRedirectUri.equals(that.restRedirectUri) : that.restRedirectUri == null;
// }
//
// @Override
// public int hashCode() {
// int result = (int) (clientId ^ (clientId >>> 32));
// result = 31 * result + username.hashCode();
// result = 31 * result + passoword.hashCode();
// result = 31 * result + key.hashCode();
// result = 31 * result + (restClientId != null ? restClientId.hashCode() : 0);
// result = 31 * result + (restClientSecret != null ? restClientSecret.hashCode() : 0);
// result = 31 * result + (restClientApiKey != null ? restClientApiKey.hashCode() : 0);
// result = 31 * result + (restRedirectUri != null ? restRedirectUri.hashCode() : 0);
// return result;
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
import com.apwglobal.nice.login.Credentials;
import pl.allegro.webapi.ServicePort;
package com.apwglobal.nice.service;
public class AbstractService {
protected ServicePort allegro; | protected Credentials cred; |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/system/SystemService.java | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/Credentials.java
// public class Credentials {
//
// private long clientId;
// private String username;
// private String passoword;
// private String key;
//
// @Nullable
// private String restClientId;
// @Nullable
// private String restClientSecret;
// @Nullable
// private String restClientApiKey;
// @Nullable
// private String restRedirectUri;
//
// public Credentials(long clientId, String username, String passowrd, String key) {
// this(clientId, username, passowrd, key, null, null, null, null);
// }
//
// public Credentials(long clientId, String username, String passowrd, String key, @Nullable String restClientId, @Nullable String restClientSecret, @Nullable String restClientApiKey, @Nullable String restRedirectUri) {
// this.clientId = clientId;
// this.username = username;
// this.passoword = passowrd;
// this.key = key;
// this.restClientId = restClientId;
// this.restClientSecret = restClientSecret;
// this.restClientApiKey = restClientApiKey;
// this.restRedirectUri = restRedirectUri;
// }
//
// public long getClientId() {
// return clientId;
// }
// String getUsername() {
// return username;
// }
// String getPassoword() {
// return passoword;
// }
// public String getKey() {
// return key;
// }
// @Nullable
// public String getRestClientId() {
// return restClientId;
// }
// @Nullable
// public String getRestClientSecret() {
// return restClientSecret;
// }
// @Nullable
// public String getRestClientApiKey() {
// return restClientApiKey;
// }
// @Nullable
// public String getRestRedirectUri() {
// return restRedirectUri;
// }
//
// @Override
// public String toString() {
// return "Credentials{" +
// "clientId='" + clientId + "\', " +
// "username='" + username + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Credentials that = (Credentials) o;
//
// if (clientId != that.clientId) return false;
// if (!username.equals(that.username)) return false;
// if (!passoword.equals(that.passoword)) return false;
// if (!key.equals(that.key)) return false;
// if (restClientId != null ? !restClientId.equals(that.restClientId) : that.restClientId != null) return false;
// if (restClientSecret != null ? !restClientSecret.equals(that.restClientSecret) : that.restClientSecret != null) return false;
// if (restClientApiKey != null ? !restClientApiKey.equals(that.restClientApiKey) : that.restClientApiKey != null) return false;
// return restRedirectUri != null ? restRedirectUri.equals(that.restRedirectUri) : that.restRedirectUri == null;
// }
//
// @Override
// public int hashCode() {
// int result = (int) (clientId ^ (clientId >>> 32));
// result = 31 * result + username.hashCode();
// result = 31 * result + passoword.hashCode();
// result = 31 * result + key.hashCode();
// result = 31 * result + (restClientId != null ? restClientId.hashCode() : 0);
// result = 31 * result + (restClientSecret != null ? restClientSecret.hashCode() : 0);
// result = 31 * result + (restClientApiKey != null ? restClientApiKey.hashCode() : 0);
// result = 31 * result + (restRedirectUri != null ? restRedirectUri.hashCode() : 0);
// return result;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
| import com.apwglobal.nice.login.Credentials;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.Configuration;
import pl.allegro.webapi.DoQueryAllSysStatusRequest;
import pl.allegro.webapi.ServicePort;
import pl.allegro.webapi.SysStatusType;
import static com.apwglobal.nice.exception.AllegroExecutor.execute; | package com.apwglobal.nice.system;
public class SystemService extends AbstractService {
public SystemService(ServicePort allegro, Credentials cred, Configuration conf) {
super(allegro, cred, conf);
}
/**
* http://allegro.pl/webapi/documentation.php/show/id,62#method-output
*/
public SysStatusType getStatus() {
DoQueryAllSysStatusRequest request = new DoQueryAllSysStatusRequest(conf.getCountryId(), cred.getKey()); | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/Credentials.java
// public class Credentials {
//
// private long clientId;
// private String username;
// private String passoword;
// private String key;
//
// @Nullable
// private String restClientId;
// @Nullable
// private String restClientSecret;
// @Nullable
// private String restClientApiKey;
// @Nullable
// private String restRedirectUri;
//
// public Credentials(long clientId, String username, String passowrd, String key) {
// this(clientId, username, passowrd, key, null, null, null, null);
// }
//
// public Credentials(long clientId, String username, String passowrd, String key, @Nullable String restClientId, @Nullable String restClientSecret, @Nullable String restClientApiKey, @Nullable String restRedirectUri) {
// this.clientId = clientId;
// this.username = username;
// this.passoword = passowrd;
// this.key = key;
// this.restClientId = restClientId;
// this.restClientSecret = restClientSecret;
// this.restClientApiKey = restClientApiKey;
// this.restRedirectUri = restRedirectUri;
// }
//
// public long getClientId() {
// return clientId;
// }
// String getUsername() {
// return username;
// }
// String getPassoword() {
// return passoword;
// }
// public String getKey() {
// return key;
// }
// @Nullable
// public String getRestClientId() {
// return restClientId;
// }
// @Nullable
// public String getRestClientSecret() {
// return restClientSecret;
// }
// @Nullable
// public String getRestClientApiKey() {
// return restClientApiKey;
// }
// @Nullable
// public String getRestRedirectUri() {
// return restRedirectUri;
// }
//
// @Override
// public String toString() {
// return "Credentials{" +
// "clientId='" + clientId + "\', " +
// "username='" + username + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Credentials that = (Credentials) o;
//
// if (clientId != that.clientId) return false;
// if (!username.equals(that.username)) return false;
// if (!passoword.equals(that.passoword)) return false;
// if (!key.equals(that.key)) return false;
// if (restClientId != null ? !restClientId.equals(that.restClientId) : that.restClientId != null) return false;
// if (restClientSecret != null ? !restClientSecret.equals(that.restClientSecret) : that.restClientSecret != null) return false;
// if (restClientApiKey != null ? !restClientApiKey.equals(that.restClientApiKey) : that.restClientApiKey != null) return false;
// return restRedirectUri != null ? restRedirectUri.equals(that.restRedirectUri) : that.restRedirectUri == null;
// }
//
// @Override
// public int hashCode() {
// int result = (int) (clientId ^ (clientId >>> 32));
// result = 31 * result + username.hashCode();
// result = 31 * result + passoword.hashCode();
// result = 31 * result + key.hashCode();
// result = 31 * result + (restClientId != null ? restClientId.hashCode() : 0);
// result = 31 * result + (restClientSecret != null ? restClientSecret.hashCode() : 0);
// result = 31 * result + (restClientApiKey != null ? restClientApiKey.hashCode() : 0);
// result = 31 * result + (restRedirectUri != null ? restRedirectUri.hashCode() : 0);
// return result;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/system/SystemService.java
import com.apwglobal.nice.login.Credentials;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.Configuration;
import pl.allegro.webapi.DoQueryAllSysStatusRequest;
import pl.allegro.webapi.ServicePort;
import pl.allegro.webapi.SysStatusType;
import static com.apwglobal.nice.exception.AllegroExecutor.execute;
package com.apwglobal.nice.system;
public class SystemService extends AbstractService {
public SystemService(ServicePort allegro, Credentials cred, Configuration conf) {
super(allegro, cred, conf);
}
/**
* http://allegro.pl/webapi/documentation.php/show/id,62#method-output
*/
public SysStatusType getStatus() {
DoQueryAllSysStatusRequest request = new DoQueryAllSysStatusRequest(conf.getCountryId(), cred.getKey()); | return execute(() -> allegro.doQueryAllSysStatus(request) |
awronski/allegro-nice-api | allegro-nice-api/src/test/java/com/apwglobal/nice/service/AllegroNiceApiTest.java | // Path: allegro-nice-api/src/test/java/com/apwglobal/nice/login/AbstractLoggedServiceBaseTest.java
// public class AbstractLoggedServiceBaseTest extends AbstractServiceBaseTest {
//
// protected static IAllegroNiceApi api;
//
// @BeforeClass
// public static void abstractLoggedServiceSetup() {
// api = new AllegroNiceApi.Builder()
// .conf(conf)
// .cred(cred)
// .test(test)
// .build();
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
| import com.apwglobal.nice.domain.*;
import com.apwglobal.nice.login.AbstractLoggedServiceBaseTest;
import com.apwglobal.nice.rest.RestApiSession;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import rx.Observable;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*; | package com.apwglobal.nice.service;
public class AllegroNiceApiTest extends AbstractLoggedServiceBaseTest {
@Test
public void shouldResturnRestApiSession() { | // Path: allegro-nice-api/src/test/java/com/apwglobal/nice/login/AbstractLoggedServiceBaseTest.java
// public class AbstractLoggedServiceBaseTest extends AbstractServiceBaseTest {
//
// protected static IAllegroNiceApi api;
//
// @BeforeClass
// public static void abstractLoggedServiceSetup() {
// api = new AllegroNiceApi.Builder()
// .conf(conf)
// .cred(cred)
// .test(test)
// .build();
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
// Path: allegro-nice-api/src/test/java/com/apwglobal/nice/service/AllegroNiceApiTest.java
import com.apwglobal.nice.domain.*;
import com.apwglobal.nice.login.AbstractLoggedServiceBaseTest;
import com.apwglobal.nice.rest.RestApiSession;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import rx.Observable;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.*;
package com.apwglobal.nice.service;
public class AllegroNiceApiTest extends AbstractLoggedServiceBaseTest {
@Test
public void shouldResturnRestApiSession() { | RestApiSession restApiSession = api.restLogin(code).getRestApiSession(); |
awronski/allegro-nice-api | allegro-nice-api/src/test/java/com/apwglobal/nice/login/AbstractServiceBaseTest.java | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
| import com.apwglobal.nice.service.Configuration;
import org.junit.BeforeClass;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; | package com.apwglobal.nice.login;
public abstract class AbstractServiceBaseTest {
protected static Credentials cred; | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
// Path: allegro-nice-api/src/test/java/com/apwglobal/nice/login/AbstractServiceBaseTest.java
import com.apwglobal.nice.service.Configuration;
import org.junit.BeforeClass;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
package com.apwglobal.nice.login;
public abstract class AbstractServiceBaseTest {
protected static Credentials cred; | protected static Configuration conf; |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
| import com.apwglobal.nice.exception.RestApiException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.apwglobal.nice.util;
public class ClientExecuteUtil {
private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
@NotNull
public static String execute(@NotNull HttpRequestBase httpRequest) {
CloseableHttpClient client = HttpClients.createDefault();
try (CloseableHttpResponse res = client.execute(httpRequest)) {
HttpEntity entity = res.getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
logger.error(e.getMessage(), e); | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
import com.apwglobal.nice.exception.RestApiException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.apwglobal.nice.util;
public class ClientExecuteUtil {
private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
@NotNull
public static String execute(@NotNull HttpRequestBase httpRequest) {
CloseableHttpClient client = HttpClients.createDefault();
try (CloseableHttpResponse res = client.execute(httpRequest)) {
HttpEntity entity = res.getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
logger.error(e.getMessage(), e); | throw new RestApiException(e.getMessage(), e); |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/service/IAllegroNiceApi.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
| import com.apwglobal.nice.domain.*;
import com.apwglobal.nice.rest.RestApiSession;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pl.allegro.webapi.ItemPostBuyDataStruct;
import pl.allegro.webapi.SysStatusType;
import rx.Observable;
import java.util.List;
import java.util.Map;
import java.util.Optional; | package com.apwglobal.nice.service;
public interface IAllegroNiceApi {
//rest
IAllegroNiceApi restLogin(@NotNull String code); | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/IAllegroNiceApi.java
import com.apwglobal.nice.domain.*;
import com.apwglobal.nice.rest.RestApiSession;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import pl.allegro.webapi.ItemPostBuyDataStruct;
import pl.allegro.webapi.SysStatusType;
import rx.Observable;
import java.util.List;
import java.util.Map;
import java.util.Optional;
package com.apwglobal.nice.service;
public interface IAllegroNiceApi {
//rest
IAllegroNiceApi restLogin(@NotNull String code); | @Nullable RestApiSession getRestApiSession(); |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/conv/FormFieldConv.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/FieldType.java
// public class FieldType {
//
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public FieldType() { }
//
// private FieldType(Builder builder) {
// type = builder.type;
// valueType = builder.valueType;
// defValue = builder.defValue;
// optsValues = builder.optsValues;
// optValuesDesc = builder.optValuesDesc;
// }
//
// public Type getType() {
// return type;
// }
// public Type getValueType() {
// return valueType;
// }
// public List<String> getOptsValues() {
// return optsValues;
// }
// public List<String> getOptValuesDesc() {
// return optValuesDesc;
// }
// public String getDefValue() {
// return optsValues.isEmpty() ? Integer.toString(defValue) : optsValues.get(defValue);
// }
//
// public enum Type {
//
// STRING(1),
// INTEGER(2),
// FLOAT(3),
// COMBOBOX(4),
// RADIOBUTTON(5),
// CHECKBOX(6),
// IMAGE(7),
// TEXT(8),
// UNIX_DATE(9),
// DATE(13);
//
// private int type;
// Type(int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static final Map<Integer, Type> VALUES;
// static {
// VALUES = Collections.unmodifiableMap(
// Arrays.stream(Type.values())
// .collect(Collectors.toMap((Type v) -> v.type, v -> v))
// );
// }
//
// }
//
// public static final class Builder {
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public Builder() {
// }
//
// public Builder type(int type) {
// this.type = Type.VALUES.get(type);
// return this;
// }
//
// public Builder valueType(int valueType) {
// this.valueType = Type.VALUES.get(valueType);
// return this;
// }
//
// public Builder defValue(int defValue) {
// this.defValue = defValue;
// return this;
// }
//
// public Builder optsValues(String optsValues) {
// if (optsValues.isEmpty()) {
// this.optsValues = Collections.emptyList();
// } else {
// this.optsValues = Arrays.asList(optsValues.split("\\|"));
// }
// return this;
// }
//
// public Builder optValuesDesc(String optValuesDesc) {
// if (optValuesDesc.isEmpty()) {
// this.optValuesDesc = Collections.emptyList();
// } else {
// this.optValuesDesc = Arrays.asList(optValuesDesc.split("\\|"));
// }
// return this;
// }
//
// public FieldType build() {
// return new FieldType(this);
// }
// }
//
// @Override
// public String toString() {
// return "FieldType{" +
// "type=" + type +
// ", valueType=" + valueType +
// ", defValue=" + defValue +
// ", optsValues='" + optsValues + '\'' +
// ", optValuesDesc='" + optValuesDesc + '\'' +
// '}';
// }
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/FormField.java
// public class FormField {
//
// private int id;
// private String title;
// private boolean required;
// private FieldType type;
// private String desc;
//
// public FormField() { }
//
// private FormField(Builder builder) {
// id = builder.id;
// title = builder.title;
// required = builder.required;
// type = builder.type;
// desc = builder.desc;
// }
//
// public int getId() {
// return id;
// }
// public String getTitle() {
// return title;
// }
// public boolean isRequired() {
// return required;
// }
// public FieldType getType() {
// return type;
// }
// public String getDesc() {
// return desc;
// }
//
// public static final class Builder {
// private int id;
// private String title;
// private boolean required;
// private FieldType type;
// private String desc;
//
// public Builder() {
// }
//
// public Builder id(int id) {
// this.id = id;
// return this;
// }
//
// public Builder title(String title) {
// this.title = title;
// return this;
// }
//
// public Builder required(int required) {
// this.required = required == 1;
// return this;
// }
//
// public Builder type(FieldType type) {
// this.type = type;
// return this;
// }
//
// public Builder desc(String desc) {
// this.desc = desc;
// return this;
// }
//
// public FormField build() {
// return new FormField(this);
// }
// }
//
// @Override
// public String toString() {
// return "FormField{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", required=" + required +
// '}';
// }
// }
| import com.apwglobal.nice.domain.FieldType;
import com.apwglobal.nice.domain.FormField;
import pl.allegro.webapi.SellFormType; | package com.apwglobal.nice.conv;
public class FormFieldConv {
public static FormField convert(SellFormType t) {
return new FormField.Builder()
.id(t.getSellFormId())
.required(t.getSellFormOpt())
.title(t.getSellFormTitle())
.desc(t.getSellFormFieldDesc()) | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/FieldType.java
// public class FieldType {
//
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public FieldType() { }
//
// private FieldType(Builder builder) {
// type = builder.type;
// valueType = builder.valueType;
// defValue = builder.defValue;
// optsValues = builder.optsValues;
// optValuesDesc = builder.optValuesDesc;
// }
//
// public Type getType() {
// return type;
// }
// public Type getValueType() {
// return valueType;
// }
// public List<String> getOptsValues() {
// return optsValues;
// }
// public List<String> getOptValuesDesc() {
// return optValuesDesc;
// }
// public String getDefValue() {
// return optsValues.isEmpty() ? Integer.toString(defValue) : optsValues.get(defValue);
// }
//
// public enum Type {
//
// STRING(1),
// INTEGER(2),
// FLOAT(3),
// COMBOBOX(4),
// RADIOBUTTON(5),
// CHECKBOX(6),
// IMAGE(7),
// TEXT(8),
// UNIX_DATE(9),
// DATE(13);
//
// private int type;
// Type(int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static final Map<Integer, Type> VALUES;
// static {
// VALUES = Collections.unmodifiableMap(
// Arrays.stream(Type.values())
// .collect(Collectors.toMap((Type v) -> v.type, v -> v))
// );
// }
//
// }
//
// public static final class Builder {
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public Builder() {
// }
//
// public Builder type(int type) {
// this.type = Type.VALUES.get(type);
// return this;
// }
//
// public Builder valueType(int valueType) {
// this.valueType = Type.VALUES.get(valueType);
// return this;
// }
//
// public Builder defValue(int defValue) {
// this.defValue = defValue;
// return this;
// }
//
// public Builder optsValues(String optsValues) {
// if (optsValues.isEmpty()) {
// this.optsValues = Collections.emptyList();
// } else {
// this.optsValues = Arrays.asList(optsValues.split("\\|"));
// }
// return this;
// }
//
// public Builder optValuesDesc(String optValuesDesc) {
// if (optValuesDesc.isEmpty()) {
// this.optValuesDesc = Collections.emptyList();
// } else {
// this.optValuesDesc = Arrays.asList(optValuesDesc.split("\\|"));
// }
// return this;
// }
//
// public FieldType build() {
// return new FieldType(this);
// }
// }
//
// @Override
// public String toString() {
// return "FieldType{" +
// "type=" + type +
// ", valueType=" + valueType +
// ", defValue=" + defValue +
// ", optsValues='" + optsValues + '\'' +
// ", optValuesDesc='" + optValuesDesc + '\'' +
// '}';
// }
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/FormField.java
// public class FormField {
//
// private int id;
// private String title;
// private boolean required;
// private FieldType type;
// private String desc;
//
// public FormField() { }
//
// private FormField(Builder builder) {
// id = builder.id;
// title = builder.title;
// required = builder.required;
// type = builder.type;
// desc = builder.desc;
// }
//
// public int getId() {
// return id;
// }
// public String getTitle() {
// return title;
// }
// public boolean isRequired() {
// return required;
// }
// public FieldType getType() {
// return type;
// }
// public String getDesc() {
// return desc;
// }
//
// public static final class Builder {
// private int id;
// private String title;
// private boolean required;
// private FieldType type;
// private String desc;
//
// public Builder() {
// }
//
// public Builder id(int id) {
// this.id = id;
// return this;
// }
//
// public Builder title(String title) {
// this.title = title;
// return this;
// }
//
// public Builder required(int required) {
// this.required = required == 1;
// return this;
// }
//
// public Builder type(FieldType type) {
// this.type = type;
// return this;
// }
//
// public Builder desc(String desc) {
// this.desc = desc;
// return this;
// }
//
// public FormField build() {
// return new FormField(this);
// }
// }
//
// @Override
// public String toString() {
// return "FormField{" +
// "id=" + id +
// ", title='" + title + '\'' +
// ", required=" + required +
// '}';
// }
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/conv/FormFieldConv.java
import com.apwglobal.nice.domain.FieldType;
import com.apwglobal.nice.domain.FormField;
import pl.allegro.webapi.SellFormType;
package com.apwglobal.nice.conv;
public class FormFieldConv {
public static FormField convert(SellFormType t) {
return new FormField.Builder()
.id(t.getSellFormId())
.required(t.getSellFormOpt())
.title(t.getSellFormTitle())
.desc(t.getSellFormFieldDesc()) | .type(new FieldType.Builder() |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/conv/AuctionFieldConv.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/AuctionField.java
// public class AuctionField<T> {
//
// private int id;
// private FieldType.Type type;
// private T value;
//
// public AuctionField() { }
//
// public AuctionField(int id, FieldType.Type type, T value) {
// this.id = id;
// this.type = type;
// this.value = value;
// }
//
// public AuctionField(FieldId id, FieldType.Type type, T value) {
// this.id = id.getId();
// this.type = type;
// this.value = value;
// }
//
// public int getId() {
// return id;
// }
// public FieldType.Type getType() {
// return type;
// }
// public T getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return "AuctionField{" +
// "id=" + id +
// ", type=" + type +
// ", value=" + value +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/FieldType.java
// public class FieldType {
//
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public FieldType() { }
//
// private FieldType(Builder builder) {
// type = builder.type;
// valueType = builder.valueType;
// defValue = builder.defValue;
// optsValues = builder.optsValues;
// optValuesDesc = builder.optValuesDesc;
// }
//
// public Type getType() {
// return type;
// }
// public Type getValueType() {
// return valueType;
// }
// public List<String> getOptsValues() {
// return optsValues;
// }
// public List<String> getOptValuesDesc() {
// return optValuesDesc;
// }
// public String getDefValue() {
// return optsValues.isEmpty() ? Integer.toString(defValue) : optsValues.get(defValue);
// }
//
// public enum Type {
//
// STRING(1),
// INTEGER(2),
// FLOAT(3),
// COMBOBOX(4),
// RADIOBUTTON(5),
// CHECKBOX(6),
// IMAGE(7),
// TEXT(8),
// UNIX_DATE(9),
// DATE(13);
//
// private int type;
// Type(int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static final Map<Integer, Type> VALUES;
// static {
// VALUES = Collections.unmodifiableMap(
// Arrays.stream(Type.values())
// .collect(Collectors.toMap((Type v) -> v.type, v -> v))
// );
// }
//
// }
//
// public static final class Builder {
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public Builder() {
// }
//
// public Builder type(int type) {
// this.type = Type.VALUES.get(type);
// return this;
// }
//
// public Builder valueType(int valueType) {
// this.valueType = Type.VALUES.get(valueType);
// return this;
// }
//
// public Builder defValue(int defValue) {
// this.defValue = defValue;
// return this;
// }
//
// public Builder optsValues(String optsValues) {
// if (optsValues.isEmpty()) {
// this.optsValues = Collections.emptyList();
// } else {
// this.optsValues = Arrays.asList(optsValues.split("\\|"));
// }
// return this;
// }
//
// public Builder optValuesDesc(String optValuesDesc) {
// if (optValuesDesc.isEmpty()) {
// this.optValuesDesc = Collections.emptyList();
// } else {
// this.optValuesDesc = Arrays.asList(optValuesDesc.split("\\|"));
// }
// return this;
// }
//
// public FieldType build() {
// return new FieldType(this);
// }
// }
//
// @Override
// public String toString() {
// return "FieldType{" +
// "type=" + type +
// ", valueType=" + valueType +
// ", defValue=" + defValue +
// ", optsValues='" + optsValues + '\'' +
// ", optValuesDesc='" + optValuesDesc + '\'' +
// '}';
// }
// }
| import com.apwglobal.bd.BD;
import com.apwglobal.nice.domain.AuctionField;
import com.apwglobal.nice.domain.FieldType;
import pl.allegro.webapi.ArrayOfFieldsvalue;
import pl.allegro.webapi.FieldsValue;
import java.util.List;
import static java.util.stream.Collectors.toList; | fv.setFvalueInt((Integer) f.getValue());
break;
case FLOAT:
if (f.getValue() instanceof Float) {
fv.setFvalueFloat((Float) f.getValue());
} else {
fv.setFvalueFloat(new BD((Double) f.getValue()).floatValue());
}
break;
case IMAGE:
fv.setFvalueImage(((String) f.getValue()).getBytes());
break;
case UNIX_DATE:
fv.setFvalueDatetime((Float) f.getValue());
break;
case DATE:
fv.setFvalueDate((String) f.getValue());
break;
}
return fv;
}
public static AuctionField convert(FieldsValue f) {
AuctionField<?> af;
if (!f.getFvalueString().isEmpty()) { | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/AuctionField.java
// public class AuctionField<T> {
//
// private int id;
// private FieldType.Type type;
// private T value;
//
// public AuctionField() { }
//
// public AuctionField(int id, FieldType.Type type, T value) {
// this.id = id;
// this.type = type;
// this.value = value;
// }
//
// public AuctionField(FieldId id, FieldType.Type type, T value) {
// this.id = id.getId();
// this.type = type;
// this.value = value;
// }
//
// public int getId() {
// return id;
// }
// public FieldType.Type getType() {
// return type;
// }
// public T getValue() {
// return value;
// }
//
// @Override
// public String toString() {
// return "AuctionField{" +
// "id=" + id +
// ", type=" + type +
// ", value=" + value +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/FieldType.java
// public class FieldType {
//
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public FieldType() { }
//
// private FieldType(Builder builder) {
// type = builder.type;
// valueType = builder.valueType;
// defValue = builder.defValue;
// optsValues = builder.optsValues;
// optValuesDesc = builder.optValuesDesc;
// }
//
// public Type getType() {
// return type;
// }
// public Type getValueType() {
// return valueType;
// }
// public List<String> getOptsValues() {
// return optsValues;
// }
// public List<String> getOptValuesDesc() {
// return optValuesDesc;
// }
// public String getDefValue() {
// return optsValues.isEmpty() ? Integer.toString(defValue) : optsValues.get(defValue);
// }
//
// public enum Type {
//
// STRING(1),
// INTEGER(2),
// FLOAT(3),
// COMBOBOX(4),
// RADIOBUTTON(5),
// CHECKBOX(6),
// IMAGE(7),
// TEXT(8),
// UNIX_DATE(9),
// DATE(13);
//
// private int type;
// Type(int type) {
// this.type = type;
// }
//
// public int getType() {
// return type;
// }
//
// public static final Map<Integer, Type> VALUES;
// static {
// VALUES = Collections.unmodifiableMap(
// Arrays.stream(Type.values())
// .collect(Collectors.toMap((Type v) -> v.type, v -> v))
// );
// }
//
// }
//
// public static final class Builder {
// private Type type;
// private Type valueType;
// private int defValue;
// private List<String> optsValues;
// private List<String> optValuesDesc;
//
// public Builder() {
// }
//
// public Builder type(int type) {
// this.type = Type.VALUES.get(type);
// return this;
// }
//
// public Builder valueType(int valueType) {
// this.valueType = Type.VALUES.get(valueType);
// return this;
// }
//
// public Builder defValue(int defValue) {
// this.defValue = defValue;
// return this;
// }
//
// public Builder optsValues(String optsValues) {
// if (optsValues.isEmpty()) {
// this.optsValues = Collections.emptyList();
// } else {
// this.optsValues = Arrays.asList(optsValues.split("\\|"));
// }
// return this;
// }
//
// public Builder optValuesDesc(String optValuesDesc) {
// if (optValuesDesc.isEmpty()) {
// this.optValuesDesc = Collections.emptyList();
// } else {
// this.optValuesDesc = Arrays.asList(optValuesDesc.split("\\|"));
// }
// return this;
// }
//
// public FieldType build() {
// return new FieldType(this);
// }
// }
//
// @Override
// public String toString() {
// return "FieldType{" +
// "type=" + type +
// ", valueType=" + valueType +
// ", defValue=" + defValue +
// ", optsValues='" + optsValues + '\'' +
// ", optValuesDesc='" + optValuesDesc + '\'' +
// '}';
// }
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/conv/AuctionFieldConv.java
import com.apwglobal.bd.BD;
import com.apwglobal.nice.domain.AuctionField;
import com.apwglobal.nice.domain.FieldType;
import pl.allegro.webapi.ArrayOfFieldsvalue;
import pl.allegro.webapi.FieldsValue;
import java.util.List;
import static java.util.stream.Collectors.toList;
fv.setFvalueInt((Integer) f.getValue());
break;
case FLOAT:
if (f.getValue() instanceof Float) {
fv.setFvalueFloat((Float) f.getValue());
} else {
fv.setFvalueFloat(new BD((Double) f.getValue()).floatValue());
}
break;
case IMAGE:
fv.setFvalueImage(((String) f.getValue()).getBytes());
break;
case UNIX_DATE:
fv.setFvalueDatetime((Float) f.getValue());
break;
case DATE:
fv.setFvalueDate((String) f.getValue());
break;
}
return fv;
}
public static AuctionField convert(FieldsValue f) {
AuctionField<?> af;
if (!f.getFvalueString().isEmpty()) { | af = new AuctionField<>(f.getFid(), FieldType.Type.STRING, f.getFvalueString()); |
awronski/allegro-nice-api | allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/IncomingPayment.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/util/UnixDate.java
// public class UnixDate {
//
// public static Date toDate(long unixTimestamp) {
// return new Date(unixTimestamp * 1000);
// }
//
// public static long toUnixTimestamp(Date date) {
// return date.getTime() / 1000;
// }
//
// }
| import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;
import java.util.Date;
import java.util.Optional; |
public Builder() {
}
public Builder transactionId(long transactionId) {
this.transactionId = transactionId;
return this;
}
public Builder buyerId(long buyerId) {
this.buyerId = buyerId;
return this;
}
public Builder sellerId(long sellerId) {
this.sellerId = sellerId;
return this;
}
public Builder status(String status) {
this.status = IncomingPaymentStatus.VALUES.get(status);
return this;
}
public Builder amount(double amount) {
this.amount = new BD(amount).doubleValue(2);
return this;
}
public Builder receiveDate(long receiveDate) { | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/util/UnixDate.java
// public class UnixDate {
//
// public static Date toDate(long unixTimestamp) {
// return new Date(unixTimestamp * 1000);
// }
//
// public static long toUnixTimestamp(Date date) {
// return date.getTime() / 1000;
// }
//
// }
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/IncomingPayment.java
import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;
import java.util.Date;
import java.util.Optional;
public Builder() {
}
public Builder transactionId(long transactionId) {
this.transactionId = transactionId;
return this;
}
public Builder buyerId(long buyerId) {
this.buyerId = buyerId;
return this;
}
public Builder sellerId(long sellerId) {
this.sellerId = sellerId;
return this;
}
public Builder status(String status) {
this.status = IncomingPaymentStatus.VALUES.get(status);
return this;
}
public Builder amount(double amount) {
this.amount = new BD(amount).doubleValue(2);
return this;
}
public Builder receiveDate(long receiveDate) { | this.receiveDate = UnixDate.toDate(receiveDate); |
awronski/allegro-nice-api | allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/Journal.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/util/UnixDate.java
// public class UnixDate {
//
// public static Date toDate(long unixTimestamp) {
// return new Date(unixTimestamp * 1000);
// }
//
// public static long toUnixTimestamp(Date date) {
// return date.getTime() / 1000;
// }
//
// }
| import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;
import java.util.Date;
import java.util.Optional; | return sellerId;
}
public static final class Builder {
private long rowId;
private long itemId;
private JournalType changeType;
private Date changeDate;
private Optional<Double> currentPrice;
private long sellerId;
public Builder() {
}
public Builder rowId(long rowId) {
this.rowId = rowId;
return this;
}
public Builder itemId(long itemId) {
this.itemId = itemId;
return this;
}
public Builder changeType(String changeType) {
this.changeType = JournalType.VALUES.get(changeType);
return this;
}
public Builder changeDate(long unitTimestamp) { | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/util/UnixDate.java
// public class UnixDate {
//
// public static Date toDate(long unixTimestamp) {
// return new Date(unixTimestamp * 1000);
// }
//
// public static long toUnixTimestamp(Date date) {
// return date.getTime() / 1000;
// }
//
// }
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/Journal.java
import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;
import java.util.Date;
import java.util.Optional;
return sellerId;
}
public static final class Builder {
private long rowId;
private long itemId;
private JournalType changeType;
private Date changeDate;
private Optional<Double> currentPrice;
private long sellerId;
public Builder() {
}
public Builder rowId(long rowId) {
this.rowId = rowId;
return this;
}
public Builder itemId(long itemId) {
this.itemId = itemId;
return this;
}
public Builder changeType(String changeType) {
this.changeType = JournalType.VALUES.get(changeType);
return this;
}
public Builder changeDate(long unitTimestamp) { | this.changeDate = UnixDate.toDate(unitTimestamp); |
awronski/allegro-nice-api | allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/Auction.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/util/UnixDate.java
// public class UnixDate {
//
// public static Date toDate(long unixTimestamp) {
// return new Date(unixTimestamp * 1000);
// }
//
// public static long toUnixTimestamp(Date date) {
// return date.getTime() / 1000;
// }
//
// }
| import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;
import java.util.Date;
import java.util.List;
import java.util.Optional; | this.id = id;
return this;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder thumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
return this;
}
public Builder startQuantity(int startQuantity) {
this.startQuantity = startQuantity;
return this;
}
public Builder soldQuantity(int soldQuantity) {
this.soldQuantity = soldQuantity;
return this;
}
public Builder quantityType(int quantityType) {
this.quantityType = ItemQuantityType.VALUES.get(quantityType);
return this;
}
public Builder startTime(long startTime) { | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/util/UnixDate.java
// public class UnixDate {
//
// public static Date toDate(long unixTimestamp) {
// return new Date(unixTimestamp * 1000);
// }
//
// public static long toUnixTimestamp(Date date) {
// return date.getTime() / 1000;
// }
//
// }
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/Auction.java
import com.apwglobal.bd.BD;
import com.apwglobal.nice.util.UnixDate;
import java.util.Date;
import java.util.List;
import java.util.Optional;
this.id = id;
return this;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder thumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
return this;
}
public Builder startQuantity(int startQuantity) {
this.startQuantity = startQuantity;
return this;
}
public Builder soldQuantity(int soldQuantity) {
this.soldQuantity = soldQuantity;
return this;
}
public Builder quantityType(int quantityType) {
this.quantityType = ItemQuantityType.VALUES.get(quantityType);
return this;
}
public Builder startTime(long startTime) { | this.startTime = UnixDate.toDate(startTime); |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/conv/ItemConv.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/Item.java
// public class Item {
//
// private long auctionId;
// private long formDealId;
// private long sellerId;
// private long transactionId;
// private String title;
//
// private double price;
// private int quantity;
// private double amount;
//
// public Item() { }
//
// private Item(Builder builder) {
// auctionId = builder.auctionId;
// formDealId = builder.formDealId;
// sellerId = builder.sellerId;
// transactionId = builder.transactionId;
// title = builder.title;
// price = builder.price;
// quantity = builder.quantity;
// amount = builder.amount;
// }
//
// public long getAuctionId() {
// return auctionId;
// }
// public long getFormDealId() {
// return formDealId;
// }
// public String getTitle() {
// return title;
// }
// public double getPrice() {
// return price;
// }
// public int getQuantity() {
// return quantity;
// }
// public double getAmount() {
// return amount;
// }
// public long getTransactionId() {
// return transactionId;
// }
// public long getSellerId() {
// return sellerId;
// }
//
// public static final class Builder {
// private long auctionId;
// private long formDealId;
// private long sellerId;
// private long transactionId;
// private String title;
// private double price;
// private int quantity;
// private double amount;
//
// public Builder() {
// }
//
// public Builder auctionId(long auctionId) {
// this.auctionId = auctionId;
// return this;
// }
//
// public Builder formDealId(long formDealId) {
// this.formDealId = formDealId;
// return this;
// }
//
// public Builder sellerId(long sellerId) {
// this.sellerId = sellerId;
// return this;
// }
//
// public Builder transactionId(long transactionId) {
// this.transactionId = transactionId;
// return this;
// }
//
// public Builder title(String title) {
// this.title = title;
// return this;
// }
//
// public Builder price(float price) {
// this.price = new BD(price).doubleValue();
// return this;
// }
//
// public Builder quantity(int quantity) {
// this.quantity = quantity;
// return this;
// }
//
// public Builder amount(float amount) {
// this.amount = new BD(amount).doubleValue();
// return this;
// }
//
// public Item build() {
// return new Item(this);
// }
// }
//
// @Override
// public String toString() {
// return "Item{" +
// "auctionId=" + auctionId +
// ", formDealId=" + formDealId +
// ", sellerId='" + sellerId + '\'' +
// ", transactionId='" + transactionId + '\'' +
// ", title='" + title + '\'' +
// ", price=" + price +
// ", quantity=" + quantity +
// ", amount=" + amount +
// '}';
// }
//
// }
| import com.apwglobal.bd.BD;
import com.apwglobal.nice.domain.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.allegro.webapi.ArrayOfPostbuyformitemdealsstruct;
import pl.allegro.webapi.PostBuyFormItemDealsStruct;
import pl.allegro.webapi.PostBuyFormItemStruct;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList; | package com.apwglobal.nice.conv;
public class ItemConv {
private final static Logger logger = LoggerFactory.getLogger(ItemConv.class);
| // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/Item.java
// public class Item {
//
// private long auctionId;
// private long formDealId;
// private long sellerId;
// private long transactionId;
// private String title;
//
// private double price;
// private int quantity;
// private double amount;
//
// public Item() { }
//
// private Item(Builder builder) {
// auctionId = builder.auctionId;
// formDealId = builder.formDealId;
// sellerId = builder.sellerId;
// transactionId = builder.transactionId;
// title = builder.title;
// price = builder.price;
// quantity = builder.quantity;
// amount = builder.amount;
// }
//
// public long getAuctionId() {
// return auctionId;
// }
// public long getFormDealId() {
// return formDealId;
// }
// public String getTitle() {
// return title;
// }
// public double getPrice() {
// return price;
// }
// public int getQuantity() {
// return quantity;
// }
// public double getAmount() {
// return amount;
// }
// public long getTransactionId() {
// return transactionId;
// }
// public long getSellerId() {
// return sellerId;
// }
//
// public static final class Builder {
// private long auctionId;
// private long formDealId;
// private long sellerId;
// private long transactionId;
// private String title;
// private double price;
// private int quantity;
// private double amount;
//
// public Builder() {
// }
//
// public Builder auctionId(long auctionId) {
// this.auctionId = auctionId;
// return this;
// }
//
// public Builder formDealId(long formDealId) {
// this.formDealId = formDealId;
// return this;
// }
//
// public Builder sellerId(long sellerId) {
// this.sellerId = sellerId;
// return this;
// }
//
// public Builder transactionId(long transactionId) {
// this.transactionId = transactionId;
// return this;
// }
//
// public Builder title(String title) {
// this.title = title;
// return this;
// }
//
// public Builder price(float price) {
// this.price = new BD(price).doubleValue();
// return this;
// }
//
// public Builder quantity(int quantity) {
// this.quantity = quantity;
// return this;
// }
//
// public Builder amount(float amount) {
// this.amount = new BD(amount).doubleValue();
// return this;
// }
//
// public Item build() {
// return new Item(this);
// }
// }
//
// @Override
// public String toString() {
// return "Item{" +
// "auctionId=" + auctionId +
// ", formDealId=" + formDealId +
// ", sellerId='" + sellerId + '\'' +
// ", transactionId='" + transactionId + '\'' +
// ", title='" + title + '\'' +
// ", price=" + price +
// ", quantity=" + quantity +
// ", amount=" + amount +
// '}';
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/conv/ItemConv.java
import com.apwglobal.bd.BD;
import com.apwglobal.nice.domain.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.allegro.webapi.ArrayOfPostbuyformitemdealsstruct;
import pl.allegro.webapi.PostBuyFormItemDealsStruct;
import pl.allegro.webapi.PostBuyFormItemStruct;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
package com.apwglobal.nice.conv;
public class ItemConv {
private final static Logger logger = LoggerFactory.getLogger(ItemConv.class);
| public static List<Item> convert(PostBuyFormItemStruct s, long transactionId, long sellerId) { |
awronski/allegro-nice-api | allegro-nice-domain/src/main/java/com/apwglobal/nice/command/SearchJournal.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/JournalType.java
// public enum JournalType {
// START("start"),
// END("end"),
// BID("bid"),
// NOW("now"),
// CHANGE("change"),
// CANCEL("cancel_bid");
//
// private String type;
// JournalType(String type) {
// this.type = type;
// }
//
// public static final Map<String, JournalType> VALUES;
// static {
// VALUES = Collections.unmodifiableMap(
// Arrays.stream(JournalType.values())
// .collect(Collectors.toMap((JournalType v) -> v.type, v -> v))
// );
// }
// }
| import com.apwglobal.nice.domain.JournalType;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.Optional; | package com.apwglobal.nice.command;
public class SearchJournal {
private Optional<Integer> limit = Optional.empty();
private Optional<Long> rowId = Optional.empty();
private Optional<Long> itemId = Optional.empty(); | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/domain/JournalType.java
// public enum JournalType {
// START("start"),
// END("end"),
// BID("bid"),
// NOW("now"),
// CHANGE("change"),
// CANCEL("cancel_bid");
//
// private String type;
// JournalType(String type) {
// this.type = type;
// }
//
// public static final Map<String, JournalType> VALUES;
// static {
// VALUES = Collections.unmodifiableMap(
// Arrays.stream(JournalType.values())
// .collect(Collectors.toMap((JournalType v) -> v.type, v -> v))
// );
// }
// }
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/command/SearchJournal.java
import com.apwglobal.nice.domain.JournalType;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.Optional;
package com.apwglobal.nice.command;
public class SearchJournal {
private Optional<Integer> limit = Optional.empty();
private Optional<Long> rowId = Optional.empty();
private Optional<Long> itemId = Optional.empty(); | private Optional<JournalType> changeType = Optional.empty(); |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/login/RestLoginService.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiErrorResult.java
// public class RestApiErrorResult {
//
// @SerializedName("error")
// private String error;
//
// @SerializedName("error_description")
// private String errorDescription;
//
// public String getError() {
// return error;
// }
//
// public String getErrorDescription() {
// return errorDescription;
// }
//
// @Override
// public String toString() {
// return "RestApiErrorResult{" +
// "error='" + error + '\'' +
// ", errorDescription='" + errorDescription + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
// public class ClientExecuteUtil {
//
// private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
//
// @NotNull
// public static String execute(@NotNull HttpRequestBase httpRequest) {
// CloseableHttpClient client = HttpClients.createDefault();
//
// try (CloseableHttpResponse res = client.execute(httpRequest)) {
// HttpEntity entity = res.getEntity();
// return EntityUtils.toString(entity, "UTF-8");
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RestApiException(e.getMessage(), e);
// }
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/RestCommandBuilder.java
// public class RestCommandBuilder {
//
// private static final String SCHEMA = "https";
// private static final String HOST = "allegroapi.io";
//
// private String schema = SCHEMA;
// private String host = HOST;
// private String path;
// private Map<String, String> params = new HashMap<>();
// private Map<String, String> headers = new HashMap<>();
// private String entity;
//
// public RestCommandBuilder schema(String val) {
// schema = val;
// return this;
// }
//
// public RestCommandBuilder host(String val) {
// host = val;
// return this;
// }
//
// public RestCommandBuilder path(String val) {
// path = val;
// return this;
// }
//
// public RestCommandBuilder addParam(String key, String val) {
// params.put(key, val);
// return this;
// }
//
// public RestCommandBuilder addHeader(String key, String val) {
// headers.put(key, val);
// return this;
// }
//
// public RestCommandBuilder entity(String val) {
// entity = val;
// return this;
// }
//
// public HttpGet buildGet() {
// URI uri = buildUri();
// HttpGet post = new HttpGet(uri);
// headers.forEach(post::setHeader);
//
// return post;
// }
//
// public HttpPost buildPost() {
// URI uri = buildUri();
// HttpPost post = new HttpPost(uri);
// headers.forEach(post::setHeader);
// setEntity(post);
//
// return post;
// }
//
// public HttpPut buildPut() {
// URI uri = buildUri();
// HttpPut put = new HttpPut(uri);
// headers.forEach(put::setHeader);
// setEntity(put);
// return put;
// }
//
// private void setEntity(HttpEntityEnclosingRequestBase put) {
// if (this.entity == null) {
// return;
// }
//
// try {
// put.setEntity(new StringEntity(entity));
// } catch (UnsupportedEncodingException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// private URI buildUri() {
// URIBuilder uriBuilder = new URIBuilder().setScheme(schema).setHost(host).setPath(path);
// params.forEach(uriBuilder::setParameter);
//
// try {
// return uriBuilder.build();
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException(e.getMessage(), e);
// }
// }
//
// }
| import com.apwglobal.nice.exception.RestApiException;
import com.apwglobal.nice.rest.RestApiErrorResult;
import com.apwglobal.nice.rest.RestApiSession;
import com.apwglobal.nice.util.ClientExecuteUtil;
import com.apwglobal.nice.util.RestCommandBuilder;
import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.jetbrains.annotations.NotNull;
import static java.util.Base64.getEncoder; | package com.apwglobal.nice.login;
public class RestLoginService {
private static final String PATH = "/auth/oauth/token";
public static final String LOGIN_HOST = "ssl.allegro.pl";
private final Credentials credentials;
public RestLoginService(@NotNull Credentials cred) {
this.credentials = cred;
}
| // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiErrorResult.java
// public class RestApiErrorResult {
//
// @SerializedName("error")
// private String error;
//
// @SerializedName("error_description")
// private String errorDescription;
//
// public String getError() {
// return error;
// }
//
// public String getErrorDescription() {
// return errorDescription;
// }
//
// @Override
// public String toString() {
// return "RestApiErrorResult{" +
// "error='" + error + '\'' +
// ", errorDescription='" + errorDescription + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
// public class ClientExecuteUtil {
//
// private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
//
// @NotNull
// public static String execute(@NotNull HttpRequestBase httpRequest) {
// CloseableHttpClient client = HttpClients.createDefault();
//
// try (CloseableHttpResponse res = client.execute(httpRequest)) {
// HttpEntity entity = res.getEntity();
// return EntityUtils.toString(entity, "UTF-8");
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RestApiException(e.getMessage(), e);
// }
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/RestCommandBuilder.java
// public class RestCommandBuilder {
//
// private static final String SCHEMA = "https";
// private static final String HOST = "allegroapi.io";
//
// private String schema = SCHEMA;
// private String host = HOST;
// private String path;
// private Map<String, String> params = new HashMap<>();
// private Map<String, String> headers = new HashMap<>();
// private String entity;
//
// public RestCommandBuilder schema(String val) {
// schema = val;
// return this;
// }
//
// public RestCommandBuilder host(String val) {
// host = val;
// return this;
// }
//
// public RestCommandBuilder path(String val) {
// path = val;
// return this;
// }
//
// public RestCommandBuilder addParam(String key, String val) {
// params.put(key, val);
// return this;
// }
//
// public RestCommandBuilder addHeader(String key, String val) {
// headers.put(key, val);
// return this;
// }
//
// public RestCommandBuilder entity(String val) {
// entity = val;
// return this;
// }
//
// public HttpGet buildGet() {
// URI uri = buildUri();
// HttpGet post = new HttpGet(uri);
// headers.forEach(post::setHeader);
//
// return post;
// }
//
// public HttpPost buildPost() {
// URI uri = buildUri();
// HttpPost post = new HttpPost(uri);
// headers.forEach(post::setHeader);
// setEntity(post);
//
// return post;
// }
//
// public HttpPut buildPut() {
// URI uri = buildUri();
// HttpPut put = new HttpPut(uri);
// headers.forEach(put::setHeader);
// setEntity(put);
// return put;
// }
//
// private void setEntity(HttpEntityEnclosingRequestBase put) {
// if (this.entity == null) {
// return;
// }
//
// try {
// put.setEntity(new StringEntity(entity));
// } catch (UnsupportedEncodingException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// private URI buildUri() {
// URIBuilder uriBuilder = new URIBuilder().setScheme(schema).setHost(host).setPath(path);
// params.forEach(uriBuilder::setParameter);
//
// try {
// return uriBuilder.build();
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException(e.getMessage(), e);
// }
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/RestLoginService.java
import com.apwglobal.nice.exception.RestApiException;
import com.apwglobal.nice.rest.RestApiErrorResult;
import com.apwglobal.nice.rest.RestApiSession;
import com.apwglobal.nice.util.ClientExecuteUtil;
import com.apwglobal.nice.util.RestCommandBuilder;
import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.jetbrains.annotations.NotNull;
import static java.util.Base64.getEncoder;
package com.apwglobal.nice.login;
public class RestLoginService {
private static final String PATH = "/auth/oauth/token";
public static final String LOGIN_HOST = "ssl.allegro.pl";
private final Credentials credentials;
public RestLoginService(@NotNull Credentials cred) {
this.credentials = cred;
}
| public RestApiSession login(@NotNull String code) throws RestApiException { |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/login/RestLoginService.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiErrorResult.java
// public class RestApiErrorResult {
//
// @SerializedName("error")
// private String error;
//
// @SerializedName("error_description")
// private String errorDescription;
//
// public String getError() {
// return error;
// }
//
// public String getErrorDescription() {
// return errorDescription;
// }
//
// @Override
// public String toString() {
// return "RestApiErrorResult{" +
// "error='" + error + '\'' +
// ", errorDescription='" + errorDescription + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
// public class ClientExecuteUtil {
//
// private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
//
// @NotNull
// public static String execute(@NotNull HttpRequestBase httpRequest) {
// CloseableHttpClient client = HttpClients.createDefault();
//
// try (CloseableHttpResponse res = client.execute(httpRequest)) {
// HttpEntity entity = res.getEntity();
// return EntityUtils.toString(entity, "UTF-8");
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RestApiException(e.getMessage(), e);
// }
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/RestCommandBuilder.java
// public class RestCommandBuilder {
//
// private static final String SCHEMA = "https";
// private static final String HOST = "allegroapi.io";
//
// private String schema = SCHEMA;
// private String host = HOST;
// private String path;
// private Map<String, String> params = new HashMap<>();
// private Map<String, String> headers = new HashMap<>();
// private String entity;
//
// public RestCommandBuilder schema(String val) {
// schema = val;
// return this;
// }
//
// public RestCommandBuilder host(String val) {
// host = val;
// return this;
// }
//
// public RestCommandBuilder path(String val) {
// path = val;
// return this;
// }
//
// public RestCommandBuilder addParam(String key, String val) {
// params.put(key, val);
// return this;
// }
//
// public RestCommandBuilder addHeader(String key, String val) {
// headers.put(key, val);
// return this;
// }
//
// public RestCommandBuilder entity(String val) {
// entity = val;
// return this;
// }
//
// public HttpGet buildGet() {
// URI uri = buildUri();
// HttpGet post = new HttpGet(uri);
// headers.forEach(post::setHeader);
//
// return post;
// }
//
// public HttpPost buildPost() {
// URI uri = buildUri();
// HttpPost post = new HttpPost(uri);
// headers.forEach(post::setHeader);
// setEntity(post);
//
// return post;
// }
//
// public HttpPut buildPut() {
// URI uri = buildUri();
// HttpPut put = new HttpPut(uri);
// headers.forEach(put::setHeader);
// setEntity(put);
// return put;
// }
//
// private void setEntity(HttpEntityEnclosingRequestBase put) {
// if (this.entity == null) {
// return;
// }
//
// try {
// put.setEntity(new StringEntity(entity));
// } catch (UnsupportedEncodingException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// private URI buildUri() {
// URIBuilder uriBuilder = new URIBuilder().setScheme(schema).setHost(host).setPath(path);
// params.forEach(uriBuilder::setParameter);
//
// try {
// return uriBuilder.build();
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException(e.getMessage(), e);
// }
// }
//
// }
| import com.apwglobal.nice.exception.RestApiException;
import com.apwglobal.nice.rest.RestApiErrorResult;
import com.apwglobal.nice.rest.RestApiSession;
import com.apwglobal.nice.util.ClientExecuteUtil;
import com.apwglobal.nice.util.RestCommandBuilder;
import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.jetbrains.annotations.NotNull;
import static java.util.Base64.getEncoder; | package com.apwglobal.nice.login;
public class RestLoginService {
private static final String PATH = "/auth/oauth/token";
public static final String LOGIN_HOST = "ssl.allegro.pl";
private final Credentials credentials;
public RestLoginService(@NotNull Credentials cred) {
this.credentials = cred;
}
| // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiErrorResult.java
// public class RestApiErrorResult {
//
// @SerializedName("error")
// private String error;
//
// @SerializedName("error_description")
// private String errorDescription;
//
// public String getError() {
// return error;
// }
//
// public String getErrorDescription() {
// return errorDescription;
// }
//
// @Override
// public String toString() {
// return "RestApiErrorResult{" +
// "error='" + error + '\'' +
// ", errorDescription='" + errorDescription + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
// public class ClientExecuteUtil {
//
// private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
//
// @NotNull
// public static String execute(@NotNull HttpRequestBase httpRequest) {
// CloseableHttpClient client = HttpClients.createDefault();
//
// try (CloseableHttpResponse res = client.execute(httpRequest)) {
// HttpEntity entity = res.getEntity();
// return EntityUtils.toString(entity, "UTF-8");
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RestApiException(e.getMessage(), e);
// }
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/RestCommandBuilder.java
// public class RestCommandBuilder {
//
// private static final String SCHEMA = "https";
// private static final String HOST = "allegroapi.io";
//
// private String schema = SCHEMA;
// private String host = HOST;
// private String path;
// private Map<String, String> params = new HashMap<>();
// private Map<String, String> headers = new HashMap<>();
// private String entity;
//
// public RestCommandBuilder schema(String val) {
// schema = val;
// return this;
// }
//
// public RestCommandBuilder host(String val) {
// host = val;
// return this;
// }
//
// public RestCommandBuilder path(String val) {
// path = val;
// return this;
// }
//
// public RestCommandBuilder addParam(String key, String val) {
// params.put(key, val);
// return this;
// }
//
// public RestCommandBuilder addHeader(String key, String val) {
// headers.put(key, val);
// return this;
// }
//
// public RestCommandBuilder entity(String val) {
// entity = val;
// return this;
// }
//
// public HttpGet buildGet() {
// URI uri = buildUri();
// HttpGet post = new HttpGet(uri);
// headers.forEach(post::setHeader);
//
// return post;
// }
//
// public HttpPost buildPost() {
// URI uri = buildUri();
// HttpPost post = new HttpPost(uri);
// headers.forEach(post::setHeader);
// setEntity(post);
//
// return post;
// }
//
// public HttpPut buildPut() {
// URI uri = buildUri();
// HttpPut put = new HttpPut(uri);
// headers.forEach(put::setHeader);
// setEntity(put);
// return put;
// }
//
// private void setEntity(HttpEntityEnclosingRequestBase put) {
// if (this.entity == null) {
// return;
// }
//
// try {
// put.setEntity(new StringEntity(entity));
// } catch (UnsupportedEncodingException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// private URI buildUri() {
// URIBuilder uriBuilder = new URIBuilder().setScheme(schema).setHost(host).setPath(path);
// params.forEach(uriBuilder::setParameter);
//
// try {
// return uriBuilder.build();
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException(e.getMessage(), e);
// }
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/RestLoginService.java
import com.apwglobal.nice.exception.RestApiException;
import com.apwglobal.nice.rest.RestApiErrorResult;
import com.apwglobal.nice.rest.RestApiSession;
import com.apwglobal.nice.util.ClientExecuteUtil;
import com.apwglobal.nice.util.RestCommandBuilder;
import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.jetbrains.annotations.NotNull;
import static java.util.Base64.getEncoder;
package com.apwglobal.nice.login;
public class RestLoginService {
private static final String PATH = "/auth/oauth/token";
public static final String LOGIN_HOST = "ssl.allegro.pl";
private final Credentials credentials;
public RestLoginService(@NotNull Credentials cred) {
this.credentials = cred;
}
| public RestApiSession login(@NotNull String code) throws RestApiException { |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/login/RestLoginService.java | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiErrorResult.java
// public class RestApiErrorResult {
//
// @SerializedName("error")
// private String error;
//
// @SerializedName("error_description")
// private String errorDescription;
//
// public String getError() {
// return error;
// }
//
// public String getErrorDescription() {
// return errorDescription;
// }
//
// @Override
// public String toString() {
// return "RestApiErrorResult{" +
// "error='" + error + '\'' +
// ", errorDescription='" + errorDescription + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
// public class ClientExecuteUtil {
//
// private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
//
// @NotNull
// public static String execute(@NotNull HttpRequestBase httpRequest) {
// CloseableHttpClient client = HttpClients.createDefault();
//
// try (CloseableHttpResponse res = client.execute(httpRequest)) {
// HttpEntity entity = res.getEntity();
// return EntityUtils.toString(entity, "UTF-8");
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RestApiException(e.getMessage(), e);
// }
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/RestCommandBuilder.java
// public class RestCommandBuilder {
//
// private static final String SCHEMA = "https";
// private static final String HOST = "allegroapi.io";
//
// private String schema = SCHEMA;
// private String host = HOST;
// private String path;
// private Map<String, String> params = new HashMap<>();
// private Map<String, String> headers = new HashMap<>();
// private String entity;
//
// public RestCommandBuilder schema(String val) {
// schema = val;
// return this;
// }
//
// public RestCommandBuilder host(String val) {
// host = val;
// return this;
// }
//
// public RestCommandBuilder path(String val) {
// path = val;
// return this;
// }
//
// public RestCommandBuilder addParam(String key, String val) {
// params.put(key, val);
// return this;
// }
//
// public RestCommandBuilder addHeader(String key, String val) {
// headers.put(key, val);
// return this;
// }
//
// public RestCommandBuilder entity(String val) {
// entity = val;
// return this;
// }
//
// public HttpGet buildGet() {
// URI uri = buildUri();
// HttpGet post = new HttpGet(uri);
// headers.forEach(post::setHeader);
//
// return post;
// }
//
// public HttpPost buildPost() {
// URI uri = buildUri();
// HttpPost post = new HttpPost(uri);
// headers.forEach(post::setHeader);
// setEntity(post);
//
// return post;
// }
//
// public HttpPut buildPut() {
// URI uri = buildUri();
// HttpPut put = new HttpPut(uri);
// headers.forEach(put::setHeader);
// setEntity(put);
// return put;
// }
//
// private void setEntity(HttpEntityEnclosingRequestBase put) {
// if (this.entity == null) {
// return;
// }
//
// try {
// put.setEntity(new StringEntity(entity));
// } catch (UnsupportedEncodingException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// private URI buildUri() {
// URIBuilder uriBuilder = new URIBuilder().setScheme(schema).setHost(host).setPath(path);
// params.forEach(uriBuilder::setParameter);
//
// try {
// return uriBuilder.build();
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException(e.getMessage(), e);
// }
// }
//
// }
| import com.apwglobal.nice.exception.RestApiException;
import com.apwglobal.nice.rest.RestApiErrorResult;
import com.apwglobal.nice.rest.RestApiSession;
import com.apwglobal.nice.util.ClientExecuteUtil;
import com.apwglobal.nice.util.RestCommandBuilder;
import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.jetbrains.annotations.NotNull;
import static java.util.Base64.getEncoder; | package com.apwglobal.nice.login;
public class RestLoginService {
private static final String PATH = "/auth/oauth/token";
public static final String LOGIN_HOST = "ssl.allegro.pl";
private final Credentials credentials;
public RestLoginService(@NotNull Credentials cred) {
this.credentials = cred;
}
public RestApiSession login(@NotNull String code) throws RestApiException { | // Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/exception/RestApiException.java
// public class RestApiException extends AllegroException {
//
// public RestApiException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RestApiException(String message) {
// super(message);
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiErrorResult.java
// public class RestApiErrorResult {
//
// @SerializedName("error")
// private String error;
//
// @SerializedName("error_description")
// private String errorDescription;
//
// public String getError() {
// return error;
// }
//
// public String getErrorDescription() {
// return errorDescription;
// }
//
// @Override
// public String toString() {
// return "RestApiErrorResult{" +
// "error='" + error + '\'' +
// ", errorDescription='" + errorDescription + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-domain/src/main/java/com/apwglobal/nice/rest/RestApiSession.java
// public class RestApiSession {
//
// @SerializedName("access_token")
// private String accessToken;
// @SerializedName("refresh_token")
// private String refreshRoken;
//
//
// public String getAccessToken() {
// return accessToken;
// }
// public String getRefreshRoken() {
// return refreshRoken;
// }
//
// @Override
// public String toString() {
// return "RestApiSession{" +
// "accessToken='" + accessToken + '\'' +
// ", refreshRoken='" + refreshRoken + '\'' +
// '}';
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/ClientExecuteUtil.java
// public class ClientExecuteUtil {
//
// private final static Logger logger = LoggerFactory.getLogger(ClientExecuteUtil.class);
//
// @NotNull
// public static String execute(@NotNull HttpRequestBase httpRequest) {
// CloseableHttpClient client = HttpClients.createDefault();
//
// try (CloseableHttpResponse res = client.execute(httpRequest)) {
// HttpEntity entity = res.getEntity();
// return EntityUtils.toString(entity, "UTF-8");
// } catch (Exception e) {
// logger.error(e.getMessage(), e);
// throw new RestApiException(e.getMessage(), e);
// }
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/RestCommandBuilder.java
// public class RestCommandBuilder {
//
// private static final String SCHEMA = "https";
// private static final String HOST = "allegroapi.io";
//
// private String schema = SCHEMA;
// private String host = HOST;
// private String path;
// private Map<String, String> params = new HashMap<>();
// private Map<String, String> headers = new HashMap<>();
// private String entity;
//
// public RestCommandBuilder schema(String val) {
// schema = val;
// return this;
// }
//
// public RestCommandBuilder host(String val) {
// host = val;
// return this;
// }
//
// public RestCommandBuilder path(String val) {
// path = val;
// return this;
// }
//
// public RestCommandBuilder addParam(String key, String val) {
// params.put(key, val);
// return this;
// }
//
// public RestCommandBuilder addHeader(String key, String val) {
// headers.put(key, val);
// return this;
// }
//
// public RestCommandBuilder entity(String val) {
// entity = val;
// return this;
// }
//
// public HttpGet buildGet() {
// URI uri = buildUri();
// HttpGet post = new HttpGet(uri);
// headers.forEach(post::setHeader);
//
// return post;
// }
//
// public HttpPost buildPost() {
// URI uri = buildUri();
// HttpPost post = new HttpPost(uri);
// headers.forEach(post::setHeader);
// setEntity(post);
//
// return post;
// }
//
// public HttpPut buildPut() {
// URI uri = buildUri();
// HttpPut put = new HttpPut(uri);
// headers.forEach(put::setHeader);
// setEntity(put);
// return put;
// }
//
// private void setEntity(HttpEntityEnclosingRequestBase put) {
// if (this.entity == null) {
// return;
// }
//
// try {
// put.setEntity(new StringEntity(entity));
// } catch (UnsupportedEncodingException e) {
// throw new IllegalArgumentException(e);
// }
// }
//
// private URI buildUri() {
// URIBuilder uriBuilder = new URIBuilder().setScheme(schema).setHost(host).setPath(path);
// params.forEach(uriBuilder::setParameter);
//
// try {
// return uriBuilder.build();
// } catch (URISyntaxException e) {
// throw new IllegalArgumentException(e.getMessage(), e);
// }
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/RestLoginService.java
import com.apwglobal.nice.exception.RestApiException;
import com.apwglobal.nice.rest.RestApiErrorResult;
import com.apwglobal.nice.rest.RestApiSession;
import com.apwglobal.nice.util.ClientExecuteUtil;
import com.apwglobal.nice.util.RestCommandBuilder;
import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.jetbrains.annotations.NotNull;
import static java.util.Base64.getEncoder;
package com.apwglobal.nice.login;
public class RestLoginService {
private static final String PATH = "/auth/oauth/token";
public static final String LOGIN_HOST = "ssl.allegro.pl";
private final Credentials credentials;
public RestLoginService(@NotNull Credentials cred) {
this.credentials = cred;
}
public RestApiSession login(@NotNull String code) throws RestApiException { | String response = ClientExecuteUtil.execute(createLognHttpPost(code)); |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/client/ClientService.java | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public class AllegroExecutor {
//
// private static final AllegroExceptionConventer aec = new AllegroExceptionConventer();
//
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/Credentials.java
// public class Credentials {
//
// private long clientId;
// private String username;
// private String passoword;
// private String key;
//
// @Nullable
// private String restClientId;
// @Nullable
// private String restClientSecret;
// @Nullable
// private String restClientApiKey;
// @Nullable
// private String restRedirectUri;
//
// public Credentials(long clientId, String username, String passowrd, String key) {
// this(clientId, username, passowrd, key, null, null, null, null);
// }
//
// public Credentials(long clientId, String username, String passowrd, String key, @Nullable String restClientId, @Nullable String restClientSecret, @Nullable String restClientApiKey, @Nullable String restRedirectUri) {
// this.clientId = clientId;
// this.username = username;
// this.passoword = passowrd;
// this.key = key;
// this.restClientId = restClientId;
// this.restClientSecret = restClientSecret;
// this.restClientApiKey = restClientApiKey;
// this.restRedirectUri = restRedirectUri;
// }
//
// public long getClientId() {
// return clientId;
// }
// String getUsername() {
// return username;
// }
// String getPassoword() {
// return passoword;
// }
// public String getKey() {
// return key;
// }
// @Nullable
// public String getRestClientId() {
// return restClientId;
// }
// @Nullable
// public String getRestClientSecret() {
// return restClientSecret;
// }
// @Nullable
// public String getRestClientApiKey() {
// return restClientApiKey;
// }
// @Nullable
// public String getRestRedirectUri() {
// return restRedirectUri;
// }
//
// @Override
// public String toString() {
// return "Credentials{" +
// "clientId='" + clientId + "\', " +
// "username='" + username + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Credentials that = (Credentials) o;
//
// if (clientId != that.clientId) return false;
// if (!username.equals(that.username)) return false;
// if (!passoword.equals(that.passoword)) return false;
// if (!key.equals(that.key)) return false;
// if (restClientId != null ? !restClientId.equals(that.restClientId) : that.restClientId != null) return false;
// if (restClientSecret != null ? !restClientSecret.equals(that.restClientSecret) : that.restClientSecret != null) return false;
// if (restClientApiKey != null ? !restClientApiKey.equals(that.restClientApiKey) : that.restClientApiKey != null) return false;
// return restRedirectUri != null ? restRedirectUri.equals(that.restRedirectUri) : that.restRedirectUri == null;
// }
//
// @Override
// public int hashCode() {
// int result = (int) (clientId ^ (clientId >>> 32));
// result = 31 * result + username.hashCode();
// result = 31 * result + passoword.hashCode();
// result = 31 * result + key.hashCode();
// result = 31 * result + (restClientId != null ? restClientId.hashCode() : 0);
// result = 31 * result + (restClientSecret != null ? restClientSecret.hashCode() : 0);
// result = 31 * result + (restClientApiKey != null ? restClientApiKey.hashCode() : 0);
// result = 31 * result + (restRedirectUri != null ? restRedirectUri.hashCode() : 0);
// return result;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
| import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.login.Credentials;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.Configuration;
import pl.allegro.webapi.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.singletonList; | package com.apwglobal.nice.client;
public class ClientService extends AbstractService {
public ClientService(ServicePort allegro, Credentials cred, Configuration conf) {
super(allegro, cred, conf);
}
public List<ItemPostBuyDataStruct> getClientsDate(String session, long itemId) {
DoGetPostBuyDataRequest request = new DoGetPostBuyDataRequest();
request.setSessionHandle(session);
request.setItemsArray(new ArrayOfLong(singletonList(itemId))); | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public class AllegroExecutor {
//
// private static final AllegroExceptionConventer aec = new AllegroExceptionConventer();
//
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/Credentials.java
// public class Credentials {
//
// private long clientId;
// private String username;
// private String passoword;
// private String key;
//
// @Nullable
// private String restClientId;
// @Nullable
// private String restClientSecret;
// @Nullable
// private String restClientApiKey;
// @Nullable
// private String restRedirectUri;
//
// public Credentials(long clientId, String username, String passowrd, String key) {
// this(clientId, username, passowrd, key, null, null, null, null);
// }
//
// public Credentials(long clientId, String username, String passowrd, String key, @Nullable String restClientId, @Nullable String restClientSecret, @Nullable String restClientApiKey, @Nullable String restRedirectUri) {
// this.clientId = clientId;
// this.username = username;
// this.passoword = passowrd;
// this.key = key;
// this.restClientId = restClientId;
// this.restClientSecret = restClientSecret;
// this.restClientApiKey = restClientApiKey;
// this.restRedirectUri = restRedirectUri;
// }
//
// public long getClientId() {
// return clientId;
// }
// String getUsername() {
// return username;
// }
// String getPassoword() {
// return passoword;
// }
// public String getKey() {
// return key;
// }
// @Nullable
// public String getRestClientId() {
// return restClientId;
// }
// @Nullable
// public String getRestClientSecret() {
// return restClientSecret;
// }
// @Nullable
// public String getRestClientApiKey() {
// return restClientApiKey;
// }
// @Nullable
// public String getRestRedirectUri() {
// return restRedirectUri;
// }
//
// @Override
// public String toString() {
// return "Credentials{" +
// "clientId='" + clientId + "\', " +
// "username='" + username + '\'' +
// '}';
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Credentials that = (Credentials) o;
//
// if (clientId != that.clientId) return false;
// if (!username.equals(that.username)) return false;
// if (!passoword.equals(that.passoword)) return false;
// if (!key.equals(that.key)) return false;
// if (restClientId != null ? !restClientId.equals(that.restClientId) : that.restClientId != null) return false;
// if (restClientSecret != null ? !restClientSecret.equals(that.restClientSecret) : that.restClientSecret != null) return false;
// if (restClientApiKey != null ? !restClientApiKey.equals(that.restClientApiKey) : that.restClientApiKey != null) return false;
// return restRedirectUri != null ? restRedirectUri.equals(that.restRedirectUri) : that.restRedirectUri == null;
// }
//
// @Override
// public int hashCode() {
// int result = (int) (clientId ^ (clientId >>> 32));
// result = 31 * result + username.hashCode();
// result = 31 * result + passoword.hashCode();
// result = 31 * result + key.hashCode();
// result = 31 * result + (restClientId != null ? restClientId.hashCode() : 0);
// result = 31 * result + (restClientSecret != null ? restClientSecret.hashCode() : 0);
// result = 31 * result + (restClientApiKey != null ? restClientApiKey.hashCode() : 0);
// result = 31 * result + (restRedirectUri != null ? restRedirectUri.hashCode() : 0);
// return result;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/client/ClientService.java
import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.login.Credentials;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.Configuration;
import pl.allegro.webapi.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.singletonList;
package com.apwglobal.nice.client;
public class ClientService extends AbstractService {
public ClientService(ServicePort allegro, Credentials cred, Configuration conf) {
super(allegro, cred, conf);
}
public List<ItemPostBuyDataStruct> getClientsDate(String session, long itemId) {
DoGetPostBuyDataRequest request = new DoGetPostBuyDataRequest();
request.setSessionHandle(session);
request.setItemsArray(new ArrayOfLong(singletonList(itemId))); | DoGetPostBuyDataResponse response = AllegroExecutor.execute(() -> allegro.doGetPostBuyData(request)); |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/login/LoginService.java | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public class AllegroExecutor {
//
// private static final AllegroExceptionConventer aec = new AllegroExceptionConventer();
//
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AllegroSession.java
// public class AllegroSession {
//
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// private AllegroSession(Builder builder) {
// sessionId = builder.sessionId;
// userId = builder.userId;
// }
//
// public String getSessionId() {
// if (sessionId == null) {
// throw new IllegalStateException("Session was not initalized. You need to use .login() first");
// }
// return sessionId;
// }
// public long getUserId() {
// return userId;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public static final class Builder {
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// public Builder() {
// }
//
// public Builder sessionId(String sessionId) {
// this.sessionId = sessionId;
// return this;
// }
//
// public Builder userId(long userId) {
// this.userId = userId;
// return this;
// }
//
// public Builder lastLoginDate(Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// return this;
// }
//
// public AllegroSession build() {
// return new AllegroSession(this);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/VersionUtil.java
// public class VersionUtil {
//
// public static long getVersion(ServicePort allegro, int countryId, String key) {
// DoQueryAllSysStatusRequest request = new DoQueryAllSysStatusRequest(countryId, key);
// return allegro.doQueryAllSysStatus(request)
// .getSysCountryStatus()
// .getItem()
// .stream()
// .filter(type -> type.getCountryId() == countryId)
// .findAny()
// .get()
// .getVerKey();
// }
//
// }
| import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.AllegroSession;
import com.apwglobal.nice.service.Configuration;
import com.apwglobal.nice.util.VersionUtil;
import pl.allegro.webapi.DoLoginEncRequest;
import pl.allegro.webapi.DoLoginEncResponse;
import pl.allegro.webapi.ServicePort;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date; | package com.apwglobal.nice.login;
public class LoginService extends AbstractService {
private static final String SHA_256 = "SHA-256";
| // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public class AllegroExecutor {
//
// private static final AllegroExceptionConventer aec = new AllegroExceptionConventer();
//
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AllegroSession.java
// public class AllegroSession {
//
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// private AllegroSession(Builder builder) {
// sessionId = builder.sessionId;
// userId = builder.userId;
// }
//
// public String getSessionId() {
// if (sessionId == null) {
// throw new IllegalStateException("Session was not initalized. You need to use .login() first");
// }
// return sessionId;
// }
// public long getUserId() {
// return userId;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public static final class Builder {
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// public Builder() {
// }
//
// public Builder sessionId(String sessionId) {
// this.sessionId = sessionId;
// return this;
// }
//
// public Builder userId(long userId) {
// this.userId = userId;
// return this;
// }
//
// public Builder lastLoginDate(Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// return this;
// }
//
// public AllegroSession build() {
// return new AllegroSession(this);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/VersionUtil.java
// public class VersionUtil {
//
// public static long getVersion(ServicePort allegro, int countryId, String key) {
// DoQueryAllSysStatusRequest request = new DoQueryAllSysStatusRequest(countryId, key);
// return allegro.doQueryAllSysStatus(request)
// .getSysCountryStatus()
// .getItem()
// .stream()
// .filter(type -> type.getCountryId() == countryId)
// .findAny()
// .get()
// .getVerKey();
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/LoginService.java
import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.AllegroSession;
import com.apwglobal.nice.service.Configuration;
import com.apwglobal.nice.util.VersionUtil;
import pl.allegro.webapi.DoLoginEncRequest;
import pl.allegro.webapi.DoLoginEncResponse;
import pl.allegro.webapi.ServicePort;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
package com.apwglobal.nice.login;
public class LoginService extends AbstractService {
private static final String SHA_256 = "SHA-256";
| public LoginService(ServicePort allegro, Credentials cred, Configuration conf) { |
awronski/allegro-nice-api | allegro-nice-api/src/main/java/com/apwglobal/nice/login/LoginService.java | // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public class AllegroExecutor {
//
// private static final AllegroExceptionConventer aec = new AllegroExceptionConventer();
//
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AllegroSession.java
// public class AllegroSession {
//
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// private AllegroSession(Builder builder) {
// sessionId = builder.sessionId;
// userId = builder.userId;
// }
//
// public String getSessionId() {
// if (sessionId == null) {
// throw new IllegalStateException("Session was not initalized. You need to use .login() first");
// }
// return sessionId;
// }
// public long getUserId() {
// return userId;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public static final class Builder {
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// public Builder() {
// }
//
// public Builder sessionId(String sessionId) {
// this.sessionId = sessionId;
// return this;
// }
//
// public Builder userId(long userId) {
// this.userId = userId;
// return this;
// }
//
// public Builder lastLoginDate(Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// return this;
// }
//
// public AllegroSession build() {
// return new AllegroSession(this);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/VersionUtil.java
// public class VersionUtil {
//
// public static long getVersion(ServicePort allegro, int countryId, String key) {
// DoQueryAllSysStatusRequest request = new DoQueryAllSysStatusRequest(countryId, key);
// return allegro.doQueryAllSysStatus(request)
// .getSysCountryStatus()
// .getItem()
// .stream()
// .filter(type -> type.getCountryId() == countryId)
// .findAny()
// .get()
// .getVerKey();
// }
//
// }
| import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.AllegroSession;
import com.apwglobal.nice.service.Configuration;
import com.apwglobal.nice.util.VersionUtil;
import pl.allegro.webapi.DoLoginEncRequest;
import pl.allegro.webapi.DoLoginEncResponse;
import pl.allegro.webapi.ServicePort;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date; | package com.apwglobal.nice.login;
public class LoginService extends AbstractService {
private static final String SHA_256 = "SHA-256";
public LoginService(ServicePort allegro, Credentials cred, Configuration conf) {
super(allegro, cred, conf);
}
| // Path: allegro-nice-api/src/main/java/com/apwglobal/nice/exception/AllegroExecutor.java
// public class AllegroExecutor {
//
// private static final AllegroExceptionConventer aec = new AllegroExceptionConventer();
//
// public static <T> T execute(Supplier<T> task) {
// try {
// return task.get();
// } catch (SOAPFaultException e) {
// throw aec.convertException(e.getFault().getFaultCode(), e);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AbstractService.java
// public class AbstractService {
//
// protected ServicePort allegro;
// protected Credentials cred;
// protected Configuration conf;
//
// public AbstractService() {
// }
//
// public AbstractService(ServicePort allegro, Credentials cred, Configuration conf) {
// this.allegro = allegro;
// this.cred = cred;
// this.conf = conf;
// }
//
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/AllegroSession.java
// public class AllegroSession {
//
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// private AllegroSession(Builder builder) {
// sessionId = builder.sessionId;
// userId = builder.userId;
// }
//
// public String getSessionId() {
// if (sessionId == null) {
// throw new IllegalStateException("Session was not initalized. You need to use .login() first");
// }
// return sessionId;
// }
// public long getUserId() {
// return userId;
// }
//
// public Date getLastLoginDate() {
// return lastLoginDate;
// }
//
// public static final class Builder {
// private String sessionId;
// private long userId;
// private Date lastLoginDate;
//
// public Builder() {
// }
//
// public Builder sessionId(String sessionId) {
// this.sessionId = sessionId;
// return this;
// }
//
// public Builder userId(long userId) {
// this.userId = userId;
// return this;
// }
//
// public Builder lastLoginDate(Date lastLoginDate) {
// this.lastLoginDate = lastLoginDate;
// return this;
// }
//
// public AllegroSession build() {
// return new AllegroSession(this);
// }
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/service/Configuration.java
// public class Configuration {
//
// private int countryId;
//
// public Configuration(int countryId) {
// this.countryId = countryId;
// }
//
// public int getCountryId() {
// return countryId;
// }
// }
//
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/util/VersionUtil.java
// public class VersionUtil {
//
// public static long getVersion(ServicePort allegro, int countryId, String key) {
// DoQueryAllSysStatusRequest request = new DoQueryAllSysStatusRequest(countryId, key);
// return allegro.doQueryAllSysStatus(request)
// .getSysCountryStatus()
// .getItem()
// .stream()
// .filter(type -> type.getCountryId() == countryId)
// .findAny()
// .get()
// .getVerKey();
// }
//
// }
// Path: allegro-nice-api/src/main/java/com/apwglobal/nice/login/LoginService.java
import com.apwglobal.nice.exception.AllegroExecutor;
import com.apwglobal.nice.service.AbstractService;
import com.apwglobal.nice.service.AllegroSession;
import com.apwglobal.nice.service.Configuration;
import com.apwglobal.nice.util.VersionUtil;
import pl.allegro.webapi.DoLoginEncRequest;
import pl.allegro.webapi.DoLoginEncResponse;
import pl.allegro.webapi.ServicePort;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
package com.apwglobal.nice.login;
public class LoginService extends AbstractService {
private static final String SHA_256 = "SHA-256";
public LoginService(ServicePort allegro, Credentials cred, Configuration conf) {
super(allegro, cred, conf);
}
| public AllegroSession login() { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.