answer stringlengths 17 10.2M |
|---|
package monto.service.javascript;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import monto.service.MontoService;
import monto.service.ZMQConfiguration;
import monto.service.ast.AST;
import monto.service.ast.ASTVisitor;
import monto.service.ast.ASTs;
import monto.service.ast.NonTerminal;
import monto.service.ast.Terminal;
import monto.service.completion.Completion;
import monto.service.completion.Completions;
import monto.service.product.ProductMessage;
import monto.service.product.Products;
import monto.service.region.IRegion;
import monto.service.registration.ProductDependency;
import monto.service.registration.SourceDependency;
import monto.service.request.Request;
import monto.service.source.SourceMessage;
import monto.service.types.Languages;
import monto.service.types.ParseException;
import monto.service.types.Selection;
public class JavaScriptCodeCompletion extends MontoService {
public JavaScriptCodeCompletion(ZMQConfiguration zmqConfig) {
super(zmqConfig,
JavaScriptServices.JAVASCRIPT_CODE_COMPLETION,
"Code Completion",
"A code completion service for JavaScript",
Languages.JAVASCRIPT,
Products.COMPLETIONS,
options(),
dependencies(
new SourceDependency(Languages.JAVASCRIPT),
new ProductDependency(JavaScriptServices.JAVASCRIPT_PARSER,Products.AST,Languages.JAVASCRIPT)
));
}
private List<Completion> allCompletions(String contents, AST root) {
AllCompletions completionVisitor = new AllCompletions(contents);
root.accept(completionVisitor);
return completionVisitor.getCompletions();
}
@Override
public ProductMessage onRequest(Request request) throws ParseException {
SourceMessage version = request.getSourceMessage()
.orElseThrow(() -> new IllegalArgumentException("No version message in request"));
ProductMessage ast = request.getProductMessage(Products.AST, Languages.JAVASCRIPT)
.orElseThrow(() -> new IllegalArgumentException("No AST message in request"));
if (version.getSelection().isPresent()) {
AST root = ASTs.decode(ast);
List<Completion> allcompletions = allCompletions(version.getContent(), root);
List<AST> selectedPath = selectedPath(root, version.getSelection().get());
Terminal terminalToBeCompleted = (Terminal) selectedPath.get(0);
String text = extract(version.getContent(),terminalToBeCompleted).toString();
if (terminalToBeCompleted.getEndOffset() >= version.getSelection().get().getStartOffset() && terminalToBeCompleted.getStartOffset() <= version.getSelection().get().getStartOffset()) {
int vStart = version.getSelection().get().getStartOffset();
int tStart = terminalToBeCompleted.getStartOffset();
text = text.substring(0, vStart - tStart);
}
String toBeCompleted = text;
List<Completion> relevant =
allcompletions
.stream()
.filter(comp -> comp.getReplacement().startsWith(toBeCompleted))
.map(comp -> new Completion(
comp.getDescription() + ": " + comp.getReplacement(),
comp.getReplacement().substring(toBeCompleted.length()),
version.getSelection().get().getStartOffset(),
comp.getIcon()))
.collect(Collectors.toList());
return productMessage(
version.getId(),
version.getSource(),
Products.COMPLETIONS,
Languages.JAVASCRIPT,
Completions.encode(relevant));
}
throw new IllegalArgumentException("Code completion needs selection");
}
private class AllCompletions implements ASTVisitor {
private List<Completion> completions = new ArrayList<>();
private String content;
public AllCompletions(String content) {
this.content = content;
}
@Override
public void visit(NonTerminal node) {
switch (node.getName()) {
case "Class":
structureDeclaration(node, "class", getResource("class.png"));
break;
case "Const":
structureDeclaration(node, "const", getResource("const.png"));
break;
case "variableDeclaration":
structureDeclaration(node, "var", getResource("variable.png"));
break;
case "functionDeclaration":
addFuncToConverted(node, "function", getResource("public.png"));
default:
node.getChildren().forEach(child -> child.accept(this));
}
}
private void addFuncToConverted(NonTerminal node, String name, URL icon) {
Object[] terminalChildren = node.getChildren()
.stream()
.filter(ast -> ast instanceof Terminal)
.toArray();
if (terminalChildren.length > 1) {
Terminal structureIdent = (Terminal) terminalChildren[1];
completions.add(new Completion(name, extract(content,structureIdent).toString(), icon));
}
node.getChildren().forEach(child -> child.accept(this));
}
@Override
public void visit(Terminal token) {
}
private void structureDeclaration(NonTerminal node, String name, URL icon) {
Terminal structureIdent = (Terminal) node
.getChildren()
.stream()
.filter(ast -> ast instanceof Terminal)
.reduce((previous, current) -> current).get();
completions.add(new Completion(name, extract(content,structureIdent).toString(), icon));
node.getChildren().forEach(child -> child.accept(this));
}
public List<Completion> getCompletions() {
return completions;
}
}
private static List<AST> selectedPath(AST root, Selection sel) {
SelectedPath finder = new SelectedPath(sel);
root.accept(finder);
return finder.getSelected();
}
private static class SelectedPath implements ASTVisitor {
private Selection selection;
private List<AST> selectedPath = new ArrayList<>();
public SelectedPath(Selection selection) {
this.selection = selection;
}
@Override
public void visit(NonTerminal node) {
node.getChildren()
.stream()
.forEach(child -> child.accept(this));
}
@Override
public void visit(Terminal token) {
if (rightBehind(selection, token))
selectedPath.add(token);
}
public List<AST> getSelected() {
return selectedPath;
}
private static boolean rightBehind(IRegion region1, IRegion region2) {
try {
return region1.getStartOffset() <= region2.getEndOffset() && region1.getStartOffset() >= region2.getStartOffset();
} catch (Exception e) {
return false;
}
}
}
private static String extract(String str, AST indent) {
return str.subSequence(indent.getStartOffset(), indent.getStartOffset()+indent.getLength()).toString();
}
} |
package net.lacolaco.smileessence.view;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import net.lacolaco.smileessence.R;
import net.lacolaco.smileessence.activity.MainActivity;
import net.lacolaco.smileessence.notification.Notificator;
import net.lacolaco.smileessence.view.adapter.CustomListAdapter;
public class CustomListFragment extends Fragment implements AbsListView.OnScrollListener,
PullToRefreshBase.OnRefreshListener2<ListView>
{
public static final String ADAPTER_INDEX = "fragmentIndex";
public static final int SCROLL_DURATION = 1500;
private int fragmentIndex;
protected PullToRefreshBase.Mode getRefreshMode()
{
return PullToRefreshBase.Mode.DISABLED;
}
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView)
{
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView)
{
}
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState)
{
Bundle args = getArguments();
fragmentIndex = args.getInt(ADAPTER_INDEX);
CustomListAdapter<?> adapter = getListAdapter(fragmentIndex);
adapter.setNotifiable(false);
if(absListView.getFirstVisiblePosition() == 0 && absListView.getChildAt(0) != null && absListView.getChildAt(0).getTop() == 0)
{
if(scrollState == SCROLL_STATE_IDLE)
{
updateListViewWithNotice(absListView, adapter, true);
}
}
}
@Override
public void onScroll(AbsListView absListView, int i, int i2, int i3)
{
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
int fragmentIndex = args.getInt(ADAPTER_INDEX);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View page = inflater.inflate(R.layout.fragment_list, container, false);
Bundle args = getArguments();
int fragmentIndex = args.getInt(ADAPTER_INDEX);
PullToRefreshListView listView = getListView(page);
ListAdapter adapter = getListAdapter(fragmentIndex);
listView.setAdapter(adapter);
listView.setOnScrollListener(this);
listView.setOnRefreshListener(this);
listView.setMode(getRefreshMode());
return page;
}
protected CustomListAdapter<?> getListAdapter(int fragmentIndex)
{
return ((MainActivity) getActivity()).getListAdapter(fragmentIndex);
}
protected PullToRefreshListView getListView(View page)
{
return (PullToRefreshListView) page.findViewById(R.id.fragment_list_listview);
}
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(ADAPTER_INDEX, fragmentIndex);
}
@Override
public void onViewStateRestored(Bundle savedInstanceState)
{
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState != null)
{
fragmentIndex = savedInstanceState.getInt(ADAPTER_INDEX);
}
}
protected void updateListViewWithNotice(AbsListView absListView, CustomListAdapter<?> adapter, boolean addedToTop)
{
int before = adapter.getCount();
adapter.notifyDataSetChanged(); // synchronized call (not adapter#updateForce())
int after = adapter.getCount();
int increments = after - before;
if(increments > 0)
{
adapter.setNotifiable(false);
notifyListUpdated(increments);
if(addedToTop)
{
absListView.setSelection(increments + 1);
absListView.smoothScrollToPositionFromTop(increments, 0);
absListView.setSelection(increments);
}
else
{
absListView.smoothScrollToPositionFromTop(before, 0);
}
if(increments == 1)
{
adapter.setNotifiable(true);
}
}
else
{
adapter.setNotifiable(true);
}
}
protected void notifyListUpdated(int increments)
{
Notificator.publish(getActivity(), getString(R.string.notice_timeline_new, increments));
}
} |
package org.adligo.tests4j_4jacoco.plugin;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
* this provides a way to load classes (mostly interfaces) in the default class loader
* so that they are the same in child class loaders.
*
* @author scott
*
*/
public class SharedClassList {
public static Set<String> WHITELIST = getSharedClassWhitelist();
private static Set<String> getSharedClassWhitelist() {
Set<String> toRet = new HashSet<String>();
toRet.add("org.adligo.tests4j.models.shared.AfterTrial");
toRet.add("org.adligo.tests4j.models.shared.BeforeTrial");
toRet.add("org.adligo.tests4j.models.shared.I_AbstractTrial");
toRet.add("org.adligo.tests4j.models.shared.IgnoreTest");
toRet.add("org.adligo.tests4j.models.shared.IgnoreTrial");
toRet.add("org.adligo.tests4j.models.shared.I_Trial");
toRet.add("org.adligo.tests4j.models.shared.I_TrialProcessorBindings");
toRet.add("org.adligo.tests4j.models.shared.I_MetaTrial");
toRet.add("org.adligo.tests4j.models.shared.PackageScope");
toRet.add("org.adligo.tests4j.models.shared.SourceFileScope");
toRet.add("org.adligo.tests4j.models.shared.Test");
toRet.add("org.adligo.tests4j.models.shared.TrialType");
toRet.add("org.adligo.tests4j.models.shared.UseCaseScope");
toRet.add("org.adligo.tests4j.models.shared.asserts.AssertType");
toRet.add("org.adligo.tests4j.models.shared.asserts.I_Asserts");
toRet.add("org.adligo.tests4j.models.shared.asserts.I_AssertType");
toRet.add("org.adligo.tests4j.models.shared.asserts.I_Thrower");
toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_LineTextCompareResult");
toRet.add("org.adligo.tests4j.models.shared.common.TrialTypeEnum");
toRet.add("org.adligo.tests4j.models.shared.common.I_Platform");
toRet.add("org.adligo.tests4j.models.shared.common.PlatformEnum");
toRet.add("org.adligo.tests4j.models.shared.coverage.I_CoverageUnits");
toRet.add("org.adligo.tests4j.models.shared.coverage.I_CoverageUnitsContainer");
toRet.add("org.adligo.tests4j.models.shared.coverage.I_LineCoverage");
toRet.add("org.adligo.tests4j.models.shared.coverage.I_LineCoverageSegment");
toRet.add("org.adligo.tests4j.models.shared.coverage.I_PackageCoverage");
toRet.add("org.adligo.tests4j.models.shared.coverage.I_SourceFileCoverage");
toRet.add("org.adligo.tests4j.models.shared.metadata.I_SourceInfo");
toRet.add("org.adligo.tests4j.models.shared.metadata.I_TestMetadata");
toRet.add("org.adligo.tests4j.models.shared.metadata.I_TrialMetadata");
toRet.add("org.adligo.tests4j.models.shared.metadata.I_TrialRunMetadata");
toRet.add("org.adligo.tests4j.models.shared.metadata.I_UseCase");
toRet.add("org.adligo.tests4j.models.shared.results.I_ApiTrialResult");
toRet.add("org.adligo.tests4j.models.shared.results.I_Duration");
toRet.add("org.adligo.tests4j.models.shared.results.I_SourceFileTrialResult");
toRet.add("org.adligo.tests4j.models.shared.results.I_TestFailure");
toRet.add("org.adligo.tests4j.models.shared.results.I_TestResult");
toRet.add("org.adligo.tests4j.models.shared.results.I_TrialFailure");
toRet.add("org.adligo.tests4j.models.shared.results.I_TrialResult");
toRet.add("org.adligo.tests4j.models.shared.results.I_TrialRunResult");
toRet.add("org.adligo.tests4j.models.shared.results.I_UseCaseTrialResult");
toRet.add("org.adligo.tests4j.models.shared.system.I_ThreadCount");
toRet.add("org.adligo.tests4j.models.shared.system.I_AssertListener");
toRet.add("org.adligo.tests4j.models.shared.system.I_CoveragePlugin");
toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Params");
toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_RemoteInfo");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.I_Tests4J_Constants");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.eclipse.I_EclipseErrors");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_AfterTrialErrors");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_AfterTrialTestErrors");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_AnnotationErrors");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_BeforeTrialErrors");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_TestMethodErrors");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.I_Tests4J_TrialDescriptionMessages");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.asserts.I_Tests4J_AssertionInputMessages");
toRet.add("org.adligo.tests4j.models.shared.system.i18n.trials.asserts.I_Tests4J_AssertionResultMessages");
toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_Probes");
return Collections.unmodifiableSet(toRet);
}
} |
package org.aikodi.chameleon.workspace;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.lang.ref.WeakReference;
import java.util.stream.Collectors;
import org.aikodi.chameleon.core.declaration.Declaration;
import org.aikodi.chameleon.core.document.Document;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.core.lookup.LookupException;
import org.aikodi.chameleon.core.namespace.DocumentLoaderNamespace;
import org.aikodi.chameleon.core.namespace.Namespace;
import org.aikodi.chameleon.core.namespacedeclaration.NamespaceDeclaration;
import org.aikodi.chameleon.exception.ChameleonProgrammerException;
import org.aikodi.rejuse.association.SingleAssociation;
import static java.util.stream.Collectors.toList;
/**
* A default implementation for document loaders.
*
* @author Marko van Dooren
*/
public abstract class DocumentLoaderImpl implements DocumentLoader {
protected void init(DocumentScanner scanner) {
setScanner(scanner);
}
protected void init(DocumentLoaderNamespace ns, DocumentScanner scanner) throws InputException {
init(scanner);
setNamespace(ns);
}
private void setScanner(DocumentScanner scanner) {
if(scanner == null) {
throw new ChameleonProgrammerException();
}
scanner.add(this);
}
@Override
public void setNamespace(DocumentLoaderNamespace ns) throws InputException {
ns.addDocumentLoader(this);
}
@Override
public DocumentLoaderNamespace namespace() {
return _namespace.getOtherEnd();
}
@Override
public SingleAssociation<DocumentLoader, DocumentLoaderNamespace> namespaceLink() {
return _namespace;
}
private SingleAssociation<DocumentLoader, DocumentLoaderNamespace> _namespace = new SingleAssociation<DocumentLoader, DocumentLoaderNamespace>(this);
/**
* Return a direct reference to the managed document. This may return null
* as this method does not load the document. If that is required, use
* {@link #document()} instead.
*
* @return the document that is managed by this document loader.
*/
protected Document rawDocument() {
return _document.getOtherEnd();
}
// /**
// * Loads ({@link #load()}) and returns the document managed by this document loader.
// *
// * @return the document managed by this document loader.
// * @throws InputException
// */
// public Document document() throws InputException {
// return load();
/**
* Set the document managed by this document loader.
*
* @param document The document that is managed by this document loader.
*/
protected void setDocument(Document document) {
if(document != null) {
_document.connectTo(document.loaderLink());
} else {
_document.connectTo(null);
}
}
/**
* @return True if and only if the document is loaded.
*/
public boolean isLoaded() {
return _document.getOtherEnd() != null;
}
@Override
public final synchronized Document load() throws InputException {
if(! isLoaded()) {
return refresh();
} else {
return rawDocument();
}
}
private long _totalLoadTime;
/**
* @{inheritDoc}
*/
@Override
public long loadTime() {
return _totalLoadTime;
}
private int _numberOfLoads;
@Override
public int numberOfLoads() {
return _numberOfLoads;
}
@Override
public final Document refresh() throws InputException {
long start = System.nanoTime();
doRefresh();
long stop = System.nanoTime();
_totalLoadTime += stop-start;
_numberOfLoads++;
Logger.trace("Loading (count {} in {} ms) {}",() -> numberOfLoads(), () -> ((double)stop-start)/1000000,() -> resourceName());
Document result = rawDocument();
result.activate();
notifyLoaded(result);
return result;
}
/**
* Return a name to describe the resource loaded by this document loader
* in log messages.
*
* @return A name to describe the loaded resource.
*/
protected abstract String resourceName();
/**
* Actually load the document. Invoke {@link #setDocument(Document)} to
* store the loaded document.
*
* @throws InputException The document could not be loaded.
*/
protected abstract void doRefresh() throws InputException;
@Override
public Project project() {
return scanner().project();
}
@Override
public View view() {
DocumentScanner scanner = scanner();
if(scanner != null) {
return scanner.view();
} else {
throw new IllegalArgumentException();
}
}
private SingleAssociation<DocumentLoaderImpl, Document> _document = new SingleAssociation<DocumentLoaderImpl, Document>(this);
@Override
public DocumentScanner scanner() {
return _scanner.getOtherEnd();
}
@Override
public SingleAssociation<DocumentLoader, DocumentScanner> scannerLink() {
return _scanner;
}
private SingleAssociation<DocumentLoader, DocumentScanner> _scanner = new SingleAssociation<DocumentLoader, DocumentScanner>(this);
@Override
public List<Declaration> targetDeclarations(String name) throws LookupException {
try {
load();
} catch (InputException e) {
e.printStackTrace();
throw new LookupException("Error opening file",e);
}
NamespaceDeclaration namespaceDeclaration = rawDocument().lexical().children(NamespaceDeclaration.class).get(0);
if(namespaceDeclaration != null) {
List<Element> children = namespaceDeclaration.lexical().children();
List<Declaration> result = children.stream().filter(Declaration.class::isInstance).map(Declaration.class::cast).filter(child -> child.name().equals(name)).collect(toList());
return result;
} else {
throw new LookupException("No target declarations are defined in document loader "+toString());
}
}
public List<String> refreshTargetDeclarationNames(Namespace ns) {
List<NamespaceDeclaration> cs = rawDocument().lexical().children(NamespaceDeclaration.class);
if(! cs.isEmpty()) {
NamespaceDeclaration namespaceDeclaration = cs.get(0);
if(namespaceDeclaration != null) {
List<Declaration> children = namespaceDeclaration.lexical().children(Declaration.class);
List<String> result = children.stream().map(child -> child.name()).collect(toList());
return result;
}
}
// Let's make it robust and return an empty collection if there is no content. This typically
// indicates the addition of a file of a language that doesn't support lazy loading to a namespace.
// Since we load the file anyway, we know that it doesn't contain namespace declarations. If that
// changes, the document must have changed, and any loaded namespace declarations will be activated.
//throw new InputException("No target declarations are defined in document loader "+toString());
return Collections.EMPTY_LIST;
}
@Override
public void flushCache() {
Document document = rawDocument();
if(document != null) {
document.flushCache();
}
}
public void addLoadListener(DocumentLoadingListener listener) {
if(_listeners == null) {
_listeners = new ArrayList<DocumentLoadingListener>();
}
_listeners.add(listener);
}
public void removeLoadListener(DocumentLoadingListener listener) {
if(_listeners != null) {
_listeners.remove(listener);
}
}
protected void notifyLoaded(Document document) {
if(_listeners != null) {
for(DocumentLoadingListener listener: _listeners) {
listener.notifyLoaded(document);
}
}
}
private List<DocumentLoadingListener> _listeners;
@Override
public void destroy() {
// This will break down the bidirectional association with the namespace
// the association end of the namespace will send an event to the namespace
// which will then remove this document loader from its caches.
_namespace.clear();
_scanner.clear();
Document doc = rawDocument();
if(doc != null) {
doc.disconnect();
}
_document.clear();
_listeners = null;
}
/**
* Compare this document loader with the given other document loader.
* A document loader that is bigger than another has a higher priority.
*
* FIXME: this is a bad design. A document scanner path (similar to classpath)
* or a proper module system is needed.
*/
@Override
public int compareTo(DocumentLoader other) {
if(other == null) {
// I know that I should throw an exception,
// but I want to make it robust.
return 1;
} else {
return scanner().compareTo(other.scanner());
}
}
} |
package org.concord.framework.otrunk.view;
import java.util.Vector;
import org.concord.framework.otrunk.OTrunk;
public interface OTMultiUserView
extends OTView
{
public void setUserList(OTrunk otrunk, Vector userList);
} |
// This file is part of JavaSMT,
// an API wrapper for a collection of SMT solvers:
package org.sosy_lab.java_smt.solvers.z3;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Table;
import com.google.common.primitives.Longs;
import com.microsoft.z3.Native;
import com.microsoft.z3.Z3Exception;
import com.microsoft.z3.enumerations.Z3_ast_kind;
import com.microsoft.z3.enumerations.Z3_decl_kind;
import com.microsoft.z3.enumerations.Z3_sort_kind;
import com.microsoft.z3.enumerations.Z3_symbol_kind;
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.common.ShutdownNotifier;
import org.sosy_lab.common.configuration.Configuration;
import org.sosy_lab.common.configuration.InvalidConfigurationException;
import org.sosy_lab.common.configuration.Option;
import org.sosy_lab.common.configuration.Options;
import org.sosy_lab.common.rationals.Rational;
import org.sosy_lab.common.time.Timer;
import org.sosy_lab.java_smt.api.ArrayFormula;
import org.sosy_lab.java_smt.api.BitvectorFormula;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.api.FloatingPointFormula;
import org.sosy_lab.java_smt.api.FloatingPointRoundingMode;
import org.sosy_lab.java_smt.api.Formula;
import org.sosy_lab.java_smt.api.FormulaType;
import org.sosy_lab.java_smt.api.FormulaType.ArrayFormulaType;
import org.sosy_lab.java_smt.api.FunctionDeclarationKind;
import org.sosy_lab.java_smt.api.QuantifiedFormulaManager.Quantifier;
import org.sosy_lab.java_smt.api.RegexFormula;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.api.StringFormula;
import org.sosy_lab.java_smt.api.visitors.FormulaVisitor;
import org.sosy_lab.java_smt.basicimpl.FormulaCreator;
import org.sosy_lab.java_smt.basicimpl.FunctionDeclarationImpl;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3ArrayFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3BitvectorFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3BooleanFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3FloatingPointFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3FloatingPointRoundingModeFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3IntegerFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3RationalFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3RegexFormula;
import org.sosy_lab.java_smt.solvers.z3.Z3Formula.Z3StringFormula;
@Options(prefix = "solver.z3")
class Z3FormulaCreator extends FormulaCreator<Long, Long, Long, Long> {
private static final ImmutableMap<Integer, Object> Z3_CONSTANTS =
ImmutableMap.<Integer, Object>builder()
.put(Z3_decl_kind.Z3_OP_TRUE.toInt(), true)
.put(Z3_decl_kind.Z3_OP_FALSE.toInt(), false)
.put(Z3_decl_kind.Z3_OP_FPA_PLUS_ZERO.toInt(), +0.0)
.put(Z3_decl_kind.Z3_OP_FPA_MINUS_ZERO.toInt(), -0.0)
.put(Z3_decl_kind.Z3_OP_FPA_PLUS_INF.toInt(), Double.POSITIVE_INFINITY)
.put(Z3_decl_kind.Z3_OP_FPA_MINUS_INF.toInt(), Double.NEGATIVE_INFINITY)
.put(Z3_decl_kind.Z3_OP_FPA_NAN.toInt(), Double.NaN)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN.toInt(),
FloatingPointRoundingMode.NEAREST_TIES_TO_EVEN)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY.toInt(),
FloatingPointRoundingMode.NEAREST_TIES_AWAY)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_POSITIVE.toInt(),
FloatingPointRoundingMode.TOWARD_POSITIVE)
.put(
Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_NEGATIVE.toInt(),
FloatingPointRoundingMode.TOWARD_NEGATIVE)
.put(Z3_decl_kind.Z3_OP_FPA_RM_TOWARD_ZERO.toInt(), FloatingPointRoundingMode.TOWARD_ZERO)
.build();
// Set of error messages that might occur if Z3 is interrupted.
private static final ImmutableSet<String> Z3_INTERRUPT_ERRORS =
ImmutableSet.of(
"canceled", // Z3::src/util/common_msgs.cpp
"Proof error!",
"interrupted", // Z3::src/solver/check_sat_result.cpp
"maximization suspended" // Z3::src/opt/opt_solver.cpp
);
@Option(secure = true, description = "Whether to use PhantomReferences for discarding Z3 AST")
private boolean usePhantomReferences = false;
/**
* We need to track all created symbols for parsing.
*
* <p>This map stores symbols (names) and their declaration (type information).
*/
private final Map<String, Long> symbolsToDeclarations = new LinkedHashMap<>();
private final Table<Long, Long, Long> allocatedArraySorts = HashBasedTable.create();
/** Automatic clean-up of Z3 ASTs. */
private final ReferenceQueue<Z3Formula> referenceQueue = new ReferenceQueue<>();
private final IdentityHashMap<PhantomReference<? extends Z3Formula>, Long> referenceMap =
new IdentityHashMap<>();
// todo: getters for statistic.
private final Timer cleanupTimer = new Timer();
protected final ShutdownNotifier shutdownNotifier;
@SuppressWarnings("ParameterNumber")
Z3FormulaCreator(
long pEnv,
long pBoolType,
long pIntegerType,
long pRealType,
long pStringType,
long pRegexType,
Configuration config,
ShutdownNotifier pShutdownNotifier)
throws InvalidConfigurationException {
super(pEnv, pBoolType, pIntegerType, pRealType, pStringType, pRegexType);
shutdownNotifier = pShutdownNotifier;
config.inject(this);
}
final Z3Exception handleZ3Exception(Z3Exception e) throws Z3Exception, InterruptedException {
if (Z3_INTERRUPT_ERRORS.contains(e.getMessage())) {
shutdownNotifier.shutdownIfNecessary();
}
throw e;
}
@Override
public Long makeVariable(Long type, String varName) {
long z3context = getEnv();
long symbol = Native.mkStringSymbol(z3context, varName);
long var = Native.mkConst(z3context, symbol, type);
symbolsToDeclarations.put(varName, Native.getAppDecl(z3context, var));
return var;
}
@Override
public Long extractInfo(Formula pT) {
if (pT instanceof Z3Formula) {
return ((Z3Formula) pT).getFormulaInfo();
}
throw new IllegalArgumentException(
"Cannot get the formula info of type " + pT.getClass().getSimpleName() + " in the Solver!");
}
@SuppressWarnings("unchecked")
@Override
public <T extends Formula> FormulaType<T> getFormulaType(T pFormula) {
Long term = extractInfo(pFormula);
return (FormulaType<T>) getFormulaType(term);
}
public FormulaType<?> getFormulaTypeFromSort(Long pSort) {
long z3context = getEnv();
Z3_sort_kind sortKind = Z3_sort_kind.fromInt(Native.getSortKind(z3context, pSort));
switch (sortKind) {
case Z3_BOOL_SORT:
return FormulaType.BooleanType;
case Z3_INT_SORT:
return FormulaType.IntegerType;
case Z3_REAL_SORT:
return FormulaType.RationalType;
case Z3_BV_SORT:
return FormulaType.getBitvectorTypeWithSize(Native.getBvSortSize(z3context, pSort));
case Z3_ARRAY_SORT:
long domainSort = Native.getArraySortDomain(z3context, pSort);
long rangeSort = Native.getArraySortRange(z3context, pSort);
return FormulaType.getArrayType(
getFormulaTypeFromSort(domainSort), getFormulaTypeFromSort(rangeSort));
case Z3_FLOATING_POINT_SORT:
return FormulaType.getFloatingPointType(
Native.fpaGetEbits(z3context, pSort), Native.fpaGetSbits(z3context, pSort) - 1);
case Z3_ROUNDING_MODE_SORT:
return FormulaType.FloatingPointRoundingModeType;
case Z3_RE_SORT:
return FormulaType.RegexType;
case Z3_DATATYPE_SORT:
case Z3_RELATION_SORT:
case Z3_FINITE_DOMAIN_SORT:
case Z3_SEQ_SORT:
case Z3_UNKNOWN_SORT:
case Z3_UNINTERPRETED_SORT:
if (Native.isStringSort(z3context, pSort)) {
return FormulaType.StringType;
} else {
// TODO: support for remaining sorts.
throw new IllegalArgumentException(
"Unknown formula type "
+ Native.sortToString(z3context, pSort)
+ " with sort "
+ sortKind);
}
default:
throw new UnsupportedOperationException("Unexpected state.");
}
}
@Override
public FormulaType<?> getFormulaType(Long pFormula) {
long sort = Native.getSort(getEnv(), pFormula);
return getFormulaTypeFromSort(sort);
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> FormulaType<TR> getArrayFormulaElementType(
ArrayFormula<TD, TR> pArray) {
return ((Z3ArrayFormula<TD, TR>) pArray).getElementType();
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> FormulaType<TD> getArrayFormulaIndexType(
ArrayFormula<TD, TR> pArray) {
return ((Z3ArrayFormula<TD, TR>) pArray).getIndexType();
}
@Override
@SuppressWarnings("MethodTypeParameterName")
protected <TD extends Formula, TR extends Formula> ArrayFormula<TD, TR> encapsulateArray(
Long pTerm, FormulaType<TD> pIndexType, FormulaType<TR> pElementType) {
assert getFormulaType(pTerm).equals(FormulaType.getArrayType(pIndexType, pElementType));
cleanupReferences();
return storePhantomReference(
new Z3ArrayFormula<>(getEnv(), pTerm, pIndexType, pElementType), pTerm);
}
private <T extends Z3Formula> T storePhantomReference(T out, Long pTerm) {
if (usePhantomReferences) {
PhantomReference<T> ref = new PhantomReference<>(out, referenceQueue);
referenceMap.put(ref, pTerm);
}
return out;
}
@SuppressWarnings("unchecked")
@Override
public <T extends Formula> T encapsulate(FormulaType<T> pType, Long pTerm) {
assert pType.equals(getFormulaType(pTerm))
|| (pType.equals(FormulaType.RationalType)
&& getFormulaType(pTerm).equals(FormulaType.IntegerType))
: String.format(
"Trying to encapsulate formula of type %s as %s", getFormulaType(pTerm), pType);
cleanupReferences();
if (pType.isBooleanType()) {
return (T) storePhantomReference(new Z3BooleanFormula(getEnv(), pTerm), pTerm);
} else if (pType.isIntegerType()) {
return (T) storePhantomReference(new Z3IntegerFormula(getEnv(), pTerm), pTerm);
} else if (pType.isRationalType()) {
return (T) storePhantomReference(new Z3RationalFormula(getEnv(), pTerm), pTerm);
} else if (pType.isStringType()) {
return (T) storePhantomReference(new Z3StringFormula(getEnv(), pTerm), pTerm);
} else if (pType.isRegexType()) {
return (T) storePhantomReference(new Z3RegexFormula(getEnv(), pTerm), pTerm);
} else if (pType.isBitvectorType()) {
return (T) storePhantomReference(new Z3BitvectorFormula(getEnv(), pTerm), pTerm);
} else if (pType.isFloatingPointType()) {
return (T) storePhantomReference(new Z3FloatingPointFormula(getEnv(), pTerm), pTerm);
} else if (pType.isFloatingPointRoundingModeType()) {
return (T)
storePhantomReference(new Z3FloatingPointRoundingModeFormula(getEnv(), pTerm), pTerm);
} else if (pType.isArrayType()) {
ArrayFormulaType<?, ?> arrFt = (ArrayFormulaType<?, ?>) pType;
return (T)
storePhantomReference(
new Z3ArrayFormula<>(getEnv(), pTerm, arrFt.getIndexType(), arrFt.getElementType()),
pTerm);
}
throw new IllegalArgumentException("Cannot create formulas of type " + pType + " in Z3");
}
@Override
public BooleanFormula encapsulateBoolean(Long pTerm) {
assert getFormulaType(pTerm).isBooleanType();
cleanupReferences();
return storePhantomReference(new Z3BooleanFormula(getEnv(), pTerm), pTerm);
}
@Override
public BitvectorFormula encapsulateBitvector(Long pTerm) {
assert getFormulaType(pTerm).isBitvectorType();
cleanupReferences();
return storePhantomReference(new Z3BitvectorFormula(getEnv(), pTerm), pTerm);
}
@Override
protected FloatingPointFormula encapsulateFloatingPoint(Long pTerm) {
assert getFormulaType(pTerm).isFloatingPointType();
cleanupReferences();
return storePhantomReference(new Z3FloatingPointFormula(getEnv(), pTerm), pTerm);
}
@Override
protected StringFormula encapsulateString(Long pTerm) {
assert getFormulaType(pTerm).isStringType()
: String.format(
"Term %s has unexpected type %s.",
Native.astToString(getEnv(), pTerm),
Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
cleanupReferences();
return storePhantomReference(new Z3StringFormula(getEnv(), pTerm), pTerm);
}
@Override
protected RegexFormula encapsulateRegex(Long pTerm) {
assert getFormulaType(pTerm).isRegexType()
: String.format(
"Term %s has unexpected type %s.",
Native.astToString(getEnv(), pTerm),
Native.sortToString(getEnv(), Native.getSort(getEnv(), pTerm)));
cleanupReferences();
return storePhantomReference(new Z3RegexFormula(getEnv(), pTerm), pTerm);
}
@Override
public Long getArrayType(Long pIndexType, Long pElementType) {
Long allocatedArraySort = allocatedArraySorts.get(pIndexType, pElementType);
if (allocatedArraySort == null) {
allocatedArraySort = Native.mkArraySort(getEnv(), pIndexType, pElementType);
Native.incRef(getEnv(), allocatedArraySort);
allocatedArraySorts.put(pIndexType, pElementType, allocatedArraySort);
}
return allocatedArraySort;
}
@Override
public Long getBitvectorType(int pBitwidth) {
checkArgument(pBitwidth > 0, "Cannot use bitvector type with size %s", pBitwidth);
long bvSort = Native.mkBvSort(getEnv(), pBitwidth);
Native.incRef(getEnv(), Native.sortToAst(getEnv(), bvSort));
return bvSort;
}
@Override
public Long getFloatingPointType(FormulaType.FloatingPointType type) {
long fpSort = Native.mkFpaSort(getEnv(), type.getExponentSize(), type.getMantissaSize() + 1);
Native.incRef(getEnv(), Native.sortToAst(getEnv(), fpSort));
return fpSort;
}
private void cleanupReferences() {
if (!usePhantomReferences) {
return;
}
cleanupTimer.start();
try {
Reference<? extends Z3Formula> ref;
while ((ref = referenceQueue.poll()) != null) {
long z3ast = referenceMap.remove(ref);
Native.decRef(environment, z3ast);
}
} finally {
cleanupTimer.stop();
}
}
private String getAppName(long f) {
long funcDecl = Native.getAppDecl(environment, f);
long symbol = Native.getDeclName(environment, funcDecl);
return symbolToString(symbol);
}
@Override
public <R> R visit(FormulaVisitor<R> visitor, final Formula formula, final Long f) {
switch (Z3_ast_kind.fromInt(Native.getAstKind(environment, f))) {
case Z3_NUMERAL_AST:
return visitor.visitConstant(formula, convertValue(f));
case Z3_APP_AST:
int arity = Native.getAppNumArgs(environment, f);
int declKind = Native.getDeclKind(environment, Native.getAppDecl(environment, f));
if (arity == 0) {
// constants
Object value = Z3_CONSTANTS.get(declKind);
if (value != null) {
return visitor.visitConstant(formula, value);
} else if (declKind == Z3_decl_kind.Z3_OP_FPA_NUM.toInt()
|| Native.getSortKind(environment, Native.getSort(environment, f))
== Z3_sort_kind.Z3_ROUNDING_MODE_SORT.toInt()) {
return visitor.visitConstant(formula, convertValue(f));
} else {
// Has to be a variable otherwise.
// TODO: assert that.
return visitor.visitFreeVariable(formula, getAppName(f));
}
}
ImmutableList.Builder<Formula> args = ImmutableList.builder();
ImmutableList.Builder<FormulaType<?>> argTypes = ImmutableList.builder();
for (int i = 0; i < arity; i++) {
long arg = Native.getAppArg(environment, f, i);
FormulaType<?> argumentType = getFormulaType(arg);
args.add(encapsulate(argumentType, arg));
argTypes.add(argumentType);
}
return visitor.visitFunction(
formula,
args.build(),
FunctionDeclarationImpl.of(
getAppName(f),
getDeclarationKind(f),
argTypes.build(),
getFormulaType(f),
Native.getAppDecl(environment, f)));
case Z3_VAR_AST:
int deBruijnIdx = Native.getIndexValue(environment, f);
return visitor.visitBoundVariable(formula, deBruijnIdx);
case Z3_QUANTIFIER_AST:
BooleanFormula body = encapsulateBoolean(Native.getQuantifierBody(environment, f));
Quantifier q =
Native.isQuantifierForall(environment, f) ? Quantifier.FORALL : Quantifier.EXISTS;
return visitor.visitQuantifier((BooleanFormula) formula, q, getBoundVars(f), body);
case Z3_SORT_AST:
case Z3_FUNC_DECL_AST:
case Z3_UNKNOWN_AST:
default:
throw new UnsupportedOperationException(
"Input should be a formula AST, " + "got unexpected type instead");
}
}
protected String symbolToString(long symbol) {
switch (Z3_symbol_kind.fromInt(Native.getSymbolKind(environment, symbol))) {
case Z3_STRING_SYMBOL:
return Native.getSymbolString(environment, symbol);
case Z3_INT_SYMBOL:
// Bound variable.
return "#" + Native.getSymbolInt(environment, symbol);
default:
throw new UnsupportedOperationException("Unexpected state");
}
}
private List<Formula> getBoundVars(long f) {
int numBound = Native.getQuantifierNumBound(environment, f);
List<Formula> boundVars = new ArrayList<>(numBound);
for (int i = 0; i < numBound; i++) {
long varName = Native.getQuantifierBoundName(environment, f, i);
long varSort = Native.getQuantifierBoundSort(environment, f, i);
boundVars.add(
encapsulate(
getFormulaTypeFromSort(varSort), Native.mkConst(environment, varName, varSort)));
}
return boundVars;
}
private FunctionDeclarationKind getDeclarationKind(long f) {
assert Native.getArity(environment, Native.getAppDecl(environment, f)) > 0
: "Variables should be handled in other branch.";
if (getAppName(f).equals("div0")) {
return FunctionDeclarationKind.OTHER;
}
Z3_decl_kind decl =
Z3_decl_kind.fromInt(Native.getDeclKind(environment, Native.getAppDecl(environment, f)));
switch (decl) {
case Z3_OP_AND:
return FunctionDeclarationKind.AND;
case Z3_OP_NOT:
return FunctionDeclarationKind.NOT;
case Z3_OP_OR:
return FunctionDeclarationKind.OR;
case Z3_OP_IFF:
return FunctionDeclarationKind.IFF;
case Z3_OP_ITE:
return FunctionDeclarationKind.ITE;
case Z3_OP_XOR:
return FunctionDeclarationKind.XOR;
case Z3_OP_DISTINCT:
return FunctionDeclarationKind.DISTINCT;
case Z3_OP_IMPLIES:
return FunctionDeclarationKind.IMPLIES;
case Z3_OP_SUB:
return FunctionDeclarationKind.SUB;
case Z3_OP_ADD:
return FunctionDeclarationKind.ADD;
case Z3_OP_DIV:
return FunctionDeclarationKind.DIV;
case Z3_OP_MUL:
return FunctionDeclarationKind.MUL;
case Z3_OP_MOD:
return FunctionDeclarationKind.MODULO;
case Z3_OP_TO_INT:
return FunctionDeclarationKind.FLOOR;
case Z3_OP_TO_REAL:
return FunctionDeclarationKind.TO_REAL;
case Z3_OP_UNINTERPRETED:
return FunctionDeclarationKind.UF;
case Z3_OP_LT:
return FunctionDeclarationKind.LT;
case Z3_OP_LE:
return FunctionDeclarationKind.LTE;
case Z3_OP_GT:
return FunctionDeclarationKind.GT;
case Z3_OP_GE:
return FunctionDeclarationKind.GTE;
case Z3_OP_EQ:
return FunctionDeclarationKind.EQ;
case Z3_OP_STORE:
return FunctionDeclarationKind.STORE;
case Z3_OP_SELECT:
return FunctionDeclarationKind.SELECT;
case Z3_OP_TRUE:
case Z3_OP_FALSE:
case Z3_OP_ANUM:
case Z3_OP_AGNUM:
throw new UnsupportedOperationException("Unexpected state: constants not expected");
case Z3_OP_OEQ:
throw new UnsupportedOperationException("Unexpected state: not a proof");
case Z3_OP_UMINUS:
return FunctionDeclarationKind.UMINUS;
case Z3_OP_IDIV:
// TODO: different handling for integer division?
return FunctionDeclarationKind.DIV;
case Z3_OP_EXTRACT:
return FunctionDeclarationKind.BV_EXTRACT;
case Z3_OP_CONCAT:
return FunctionDeclarationKind.BV_CONCAT;
case Z3_OP_BNOT:
return FunctionDeclarationKind.BV_NOT;
case Z3_OP_BNEG:
return FunctionDeclarationKind.BV_NEG;
case Z3_OP_BAND:
return FunctionDeclarationKind.BV_AND;
case Z3_OP_BOR:
return FunctionDeclarationKind.BV_OR;
case Z3_OP_BXOR:
return FunctionDeclarationKind.BV_XOR;
case Z3_OP_ULT:
return FunctionDeclarationKind.BV_ULT;
case Z3_OP_SLT:
return FunctionDeclarationKind.BV_SLT;
case Z3_OP_ULEQ:
return FunctionDeclarationKind.BV_ULE;
case Z3_OP_SLEQ:
return FunctionDeclarationKind.BV_SLE;
case Z3_OP_UGT:
return FunctionDeclarationKind.BV_UGT;
case Z3_OP_SGT:
return FunctionDeclarationKind.BV_SGT;
case Z3_OP_UGEQ:
return FunctionDeclarationKind.BV_UGE;
case Z3_OP_SGEQ:
return FunctionDeclarationKind.BV_SGE;
case Z3_OP_BADD:
return FunctionDeclarationKind.BV_ADD;
case Z3_OP_BSUB:
return FunctionDeclarationKind.BV_SUB;
case Z3_OP_BMUL:
return FunctionDeclarationKind.BV_MUL;
case Z3_OP_BUDIV:
return FunctionDeclarationKind.BV_UDIV;
case Z3_OP_BSDIV:
return FunctionDeclarationKind.BV_SDIV;
case Z3_OP_BUREM:
return FunctionDeclarationKind.BV_UREM;
case Z3_OP_BSREM:
return FunctionDeclarationKind.BV_SREM;
case Z3_OP_BSHL:
return FunctionDeclarationKind.BV_SHL;
case Z3_OP_BLSHR:
return FunctionDeclarationKind.BV_LSHR;
case Z3_OP_BASHR:
return FunctionDeclarationKind.BV_ASHR;
case Z3_OP_SIGN_EXT:
return FunctionDeclarationKind.BV_SIGN_EXTENSION;
case Z3_OP_ZERO_EXT:
return FunctionDeclarationKind.BV_ZERO_EXTENSION;
case Z3_OP_FPA_NEG:
return FunctionDeclarationKind.FP_NEG;
case Z3_OP_FPA_ABS:
return FunctionDeclarationKind.FP_ABS;
case Z3_OP_FPA_MAX:
return FunctionDeclarationKind.FP_MAX;
case Z3_OP_FPA_MIN:
return FunctionDeclarationKind.FP_MIN;
case Z3_OP_FPA_SQRT:
return FunctionDeclarationKind.FP_SQRT;
case Z3_OP_FPA_SUB:
return FunctionDeclarationKind.FP_SUB;
case Z3_OP_FPA_ADD:
return FunctionDeclarationKind.FP_ADD;
case Z3_OP_FPA_DIV:
return FunctionDeclarationKind.FP_DIV;
case Z3_OP_FPA_MUL:
return FunctionDeclarationKind.FP_MUL;
case Z3_OP_FPA_LT:
return FunctionDeclarationKind.FP_LT;
case Z3_OP_FPA_LE:
return FunctionDeclarationKind.FP_LE;
case Z3_OP_FPA_GE:
return FunctionDeclarationKind.FP_GE;
case Z3_OP_FPA_GT:
return FunctionDeclarationKind.FP_GT;
case Z3_OP_FPA_EQ:
return FunctionDeclarationKind.FP_EQ;
case Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN:
return FunctionDeclarationKind.FP_ROUND_EVEN;
case Z3_OP_FPA_RM_NEAREST_TIES_TO_AWAY:
return FunctionDeclarationKind.FP_ROUND_AWAY;
case Z3_OP_FPA_RM_TOWARD_POSITIVE:
return FunctionDeclarationKind.FP_ROUND_POSITIVE;
case Z3_OP_FPA_RM_TOWARD_NEGATIVE:
return FunctionDeclarationKind.FP_ROUND_NEGATIVE;
case Z3_OP_FPA_RM_TOWARD_ZERO:
return FunctionDeclarationKind.FP_ROUND_ZERO;
case Z3_OP_FPA_ROUND_TO_INTEGRAL:
return FunctionDeclarationKind.FP_ROUND_TO_INTEGRAL;
case Z3_OP_FPA_TO_FP_UNSIGNED:
return FunctionDeclarationKind.BV_UCASTTO_FP;
case Z3_OP_FPA_TO_SBV:
return FunctionDeclarationKind.FP_CASTTO_SBV;
case Z3_OP_FPA_TO_IEEE_BV:
return FunctionDeclarationKind.FP_AS_IEEEBV;
case Z3_OP_FPA_TO_FP:
Z3_sort_kind sortKind =
Z3_sort_kind.fromInt(
Native.getSortKind(
environment, Native.getSort(environment, Native.getAppArg(environment, f, 1))));
if (Z3_sort_kind.Z3_BV_SORT == sortKind) {
return FunctionDeclarationKind.BV_SCASTTO_FP;
} else {
return FunctionDeclarationKind.FP_CASTTO_FP;
}
case Z3_OP_FPA_IS_NAN:
return FunctionDeclarationKind.FP_IS_NAN;
case Z3_OP_FPA_IS_INF:
return FunctionDeclarationKind.FP_IS_INF;
case Z3_OP_FPA_IS_ZERO:
return FunctionDeclarationKind.FP_IS_ZERO;
case Z3_OP_FPA_IS_NEGATIVE:
return FunctionDeclarationKind.FP_IS_NEGATIVE;
case Z3_OP_FPA_IS_SUBNORMAL:
return FunctionDeclarationKind.FP_IS_SUBNORMAL;
case Z3_OP_FPA_IS_NORMAL:
return FunctionDeclarationKind.FP_IS_NORMAL;
case Z3_OP_SEQ_CONCAT:
return FunctionDeclarationKind.STR_CONCAT;
case Z3_OP_SEQ_PREFIX:
return FunctionDeclarationKind.STR_PREFIX;
case Z3_OP_SEQ_SUFFIX:
return FunctionDeclarationKind.STR_SUFFIX;
case Z3_OP_SEQ_CONTAINS:
return FunctionDeclarationKind.STR_CONTAINS;
case Z3_OP_SEQ_EXTRACT:
return FunctionDeclarationKind.STR_SUBSTRING;
case Z3_OP_SEQ_REPLACE:
return FunctionDeclarationKind.STR_REPLACE;
case Z3_OP_SEQ_AT:
return FunctionDeclarationKind.STR_CHAR_AT;
case Z3_OP_SEQ_LENGTH:
return FunctionDeclarationKind.STR_LENGTH;
case Z3_OP_SEQ_INDEX:
return FunctionDeclarationKind.STR_INDEX_OF;
case Z3_OP_SEQ_TO_RE:
return FunctionDeclarationKind.STR_TO_RE;
case Z3_OP_SEQ_IN_RE:
return FunctionDeclarationKind.STR_IN_RE;
case Z3_OP_STR_TO_INT:
return FunctionDeclarationKind.STR_TO_INT;
case Z3_OP_INT_TO_STR:
return FunctionDeclarationKind.INT_TO_STR;
case Z3_OP_STRING_LT:
return FunctionDeclarationKind.STR_LT;
case Z3_OP_STRING_LE:
return FunctionDeclarationKind.STR_LE;
case Z3_OP_RE_PLUS:
return FunctionDeclarationKind.RE_PLUS;
case Z3_OP_RE_STAR:
return FunctionDeclarationKind.RE_STAR;
case Z3_OP_RE_OPTION:
return FunctionDeclarationKind.RE_OPTIONAL;
case Z3_OP_RE_CONCAT:
return FunctionDeclarationKind.RE_CONCAT;
case Z3_OP_RE_UNION:
return FunctionDeclarationKind.RE_UNION;
case Z3_OP_RE_RANGE:
return FunctionDeclarationKind.RE_RANGE;
case Z3_OP_RE_INTERSECT:
return FunctionDeclarationKind.RE_INTERSECT;
case Z3_OP_RE_COMPLEMENT:
return FunctionDeclarationKind.RE_COMPLEMENT;
default:
return FunctionDeclarationKind.OTHER;
}
}
/**
* @param value Z3_ast
* @return Whether the value is a constant and can be passed to {@link #convertValue(Long)}.
*/
public boolean isConstant(long value) {
return Native.isNumeralAst(environment, value)
|| Native.isAlgebraicNumber(environment, value)
|| Native.isString(environment, value)
|| isOP(environment, value, Z3_decl_kind.Z3_OP_TRUE.toInt())
|| isOP(environment, value, Z3_decl_kind.Z3_OP_FALSE.toInt());
}
/**
* @param value Z3_ast representing a constant value.
* @return {@link BigInteger} or {@link Double} or {@link Rational} or {@link Boolean} or {@link
* FloatingPointRoundingMode}.
*/
@Override
public Object convertValue(Long value) {
if (!isConstant(value)) {
return null;
}
Native.incRef(environment, value);
Object constantValue =
Z3_CONSTANTS.get(Native.getDeclKind(environment, Native.getAppDecl(environment, value)));
if (constantValue != null) {
return constantValue;
}
try {
FormulaType<?> type = getFormulaType(value);
if (type.isBooleanType()) {
return isOP(environment, value, Z3_decl_kind.Z3_OP_TRUE.toInt());
} else if (type.isIntegerType()) {
return new BigInteger(Native.getNumeralString(environment, value));
} else if (type.isRationalType()) {
return Rational.ofString(Native.getNumeralString(environment, value));
} else if (type.isStringType()) {
return Native.getString(environment, value);
} else if (type.isBitvectorType()) {
return new BigInteger(Native.getNumeralString(environment, value));
} else if (type.isFloatingPointType()) {
// Converting to Rational first.
return convertValue(Native.simplify(environment, Native.mkFpaToReal(environment, value)));
} else {
// Explicitly crash on unknown type.
throw new IllegalArgumentException("Unexpected type encountered: " + type);
}
} finally {
Native.decRef(environment, value);
}
}
@Override
public Long declareUFImpl(String pName, Long returnType, List<Long> pArgTypes) {
long symbol = Native.mkStringSymbol(environment, pName);
long[] sorts = Longs.toArray(pArgTypes);
long func = Native.mkFuncDecl(environment, symbol, sorts.length, sorts, returnType);
Native.incRef(environment, func);
symbolsToDeclarations.put(pName, func);
return func;
}
@Override
public Long callFunctionImpl(Long declaration, List<Long> args) {
return Native.mkApp(environment, declaration, args.size(), Longs.toArray(args));
}
@Override
protected Long getBooleanVarDeclarationImpl(Long pLong) {
return Native.getAppDecl(getEnv(), pLong);
}
/** returns, if the function of the expression is the given operation. */
static boolean isOP(long z3context, long expr, int op) {
if (!Native.isApp(z3context, expr)) {
return false;
}
long decl = Native.getAppDecl(z3context, expr);
return Native.getDeclKind(z3context, decl) == op;
}
/**
* Apply multiple tactics in sequence.
*
* @throws InterruptedException thrown by JNI code in case of termination request
* @throws SolverException thrown by JNI code in case of error
*/
public long applyTactics(long z3context, final Long pF, String... pTactics)
throws InterruptedException, SolverException {
long overallResult = pF;
for (String tactic : pTactics) {
overallResult = applyTactic(z3context, overallResult, tactic);
}
return overallResult;
}
/**
* Apply tactic on a Z3_ast object, convert the result back to Z3_ast.
*
* @param z3context Z3_context
* @param tactic Z3 Tactic Name
* @param pF Z3_ast
* @return Z3_ast
* @throws InterruptedException If execution gets interrupted.
*/
public long applyTactic(long z3context, long pF, String tactic) throws InterruptedException {
long tacticObject = Native.mkTactic(z3context, tactic);
Native.tacticIncRef(z3context, tacticObject);
long goal = Native.mkGoal(z3context, true, false, false);
Native.goalIncRef(z3context, goal);
Native.goalAssert(z3context, goal, pF);
long result;
try {
result = Native.tacticApply(z3context, tacticObject, goal);
} catch (Z3Exception exp) {
throw handleZ3Exception(exp);
}
try {
return applyResultToAST(z3context, result);
} finally {
Native.goalDecRef(z3context, goal);
Native.tacticDecRef(z3context, tacticObject);
}
}
private long applyResultToAST(long z3context, long applyResult) {
int subgoalsCount = Native.applyResultGetNumSubgoals(z3context, applyResult);
long[] goalFormulas = new long[subgoalsCount];
for (int i = 0; i < subgoalsCount; i++) {
long subgoal = Native.applyResultGetSubgoal(z3context, applyResult, i);
goalFormulas[i] = goalToAST(z3context, subgoal);
}
return goalFormulas.length == 1
? goalFormulas[0]
: Native.mkOr(z3context, goalFormulas.length, goalFormulas);
}
private long goalToAST(long z3context, long goal) {
int subgoalFormulasCount = Native.goalSize(z3context, goal);
long[] subgoalFormulas = new long[subgoalFormulasCount];
for (int k = 0; k < subgoalFormulasCount; k++) {
subgoalFormulas[k] = Native.goalFormula(z3context, goal, k);
}
return subgoalFormulas.length == 1
? subgoalFormulas[0]
: Native.mkAnd(z3context, subgoalFormulas.length, subgoalFormulas);
}
/** Closing the context. */
public void forceClose() {
cleanupReferences();
// Force clean all ASTs, even those which were not GC'd yet.
// Is a no-op if phantom reference handling is not enabled.
for (long ast : referenceMap.values()) {
Native.decRef(getEnv(), ast);
}
}
/**
* get a previously created application declaration, or <code>NULL</code> if the symbol is
* unknown.
*/
@Nullable Long getKnownDeclaration(String symbolName) {
return symbolsToDeclarations.get(symbolName);
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.usfirst.frc3946.UltimateAscent.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
* @author OpalStone
*/
public class Climb extends CommandGroup {
public Climb() {
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// addSequential (new ExtendClimbingPiston());
//MoveClimbingMotor
addSequential (new RetractClimbingPiston());
addSequential (new MoveClimbingMotor());
addSequential (new PartiallyExtendPiston());
//#9 move horizontal hooks until level
addSequential (new LevelDuringClimb());
addParallel (new ExtendClimbingPiston());
addSequential (new LevelDuringClimb());
addSequential (new MoveClimbingMotorBackwards());
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
}
} |
package org.objectweb.proactive.core.mop;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Active;
import org.objectweb.proactive.api.ProActiveObject;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.body.MetaObjectFactory;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.util.log.Loggers;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
/**
* A place where static methods go
*/
public abstract class MOP {
/**
* The name of the interface that caracterizes all stub classes
*/
protected static String STUB_OBJECT_INTERFACE_NAME = "org.objectweb.proactive.core.mop.StubObject";
protected static Class<?> STUB_OBJECT_INTERFACE;
static Logger logger = ProActiveLogger.getLogger(Loggers.MOP);
/**
* The root interface of all metabehaviors
*/
//protected static String ROOT_INTERFACE_NAME = "org.objectweb.proactive.core.mop.Reflect";
//protected static Class ROOT_INTERFACE;
/**
* Class array representing no parameters
*/
protected static final Class<?>[] EMPTY_CLASS_ARRAY = new Class<?>[0];
/**
* Empty object array
*/
public static final Object[] EMPTY_OBJECT_ARRAY = new Object[0];
/**
* Class<?> array representing (Constructor Call, Object[])
*/
protected static Class<?>[] PROXY_CONSTRUCTOR_PARAMETERS_TYPES_ARRAY = new Class<?>[2];
/**
* A Hashtable to cache (reified class, stub class constructor) couples.
*/
protected static java.util.Hashtable<GenericStubKey, Constructor> stubTable = new java.util.Hashtable<GenericStubKey, Constructor>();
/**
* A Hashtable to cache (proxy class, proxy class constructor) couples
*/
protected static java.util.Hashtable<String, Constructor> proxyTable = new java.util.Hashtable<String, Constructor>();
/**
* A Hashtable to cache (Class<?> name, proxy class name) couples
* this is meant for class-based reification
*/
protected static java.util.Hashtable secondProxyTable = new java.util.Hashtable();
protected static MOPClassLoader singleton = MOPClassLoader.getMOPClassLoader(); //MOPClassLoader.createMOPClassLoader();
/**
* As this class is center to the API, its static initializer is
* a good place to initialize general stuff.
*/
protected static HashMap<String, Class<?>> loadedClass = new HashMap<String, Class<?>>();
static {
PROXY_CONSTRUCTOR_PARAMETERS_TYPES_ARRAY = new Class<?>[] {
org.objectweb.proactive.core.mop.ConstructorCall.class,
EMPTY_OBJECT_ARRAY.getClass()
};
try {
STUB_OBJECT_INTERFACE = forName(STUB_OBJECT_INTERFACE_NAME);
} catch (ClassNotFoundException e) {
throw new CannotFindClassException(STUB_OBJECT_INTERFACE_NAME);
}
//try {
// ROOT_INTERFACE = forName(ROOT_INTERFACE_NAME);
//} catch (ClassNotFoundException e) {
// throw new CannotFindClassException(ROOT_INTERFACE_NAME);
}
/**
* Loads a class using standard classloader or a hashtable
* @param s the name of the class to fetch
* @return the Class<?> object representing class s
*/
public static Class<?> forName(String s)
throws java.lang.ClassNotFoundException {
try {
return Class.forName(s);
} catch (ClassNotFoundException e) {
// System.out.println(
// "MOP forName failed for class " + s + ", looking in table");
Class<?> cl = loadedClass.get(s);
// System.out.println("MOP forName failed, result is " +
if (cl == null) {
throw e;
} else {
return cl;
}
}
}
/**
* Creates an instance of an object
* @param nameOfClass The class to instantiate
* @param genericParameters the types of the generic parameters for the class (if any, otherwise this parameter may be null)
* @param constructorParameters Array of the constructor's parameters [wrapper]
* @param nameOfProxy The name of its proxy class
* @param proxyParameters The array holding the proxy parameter
*/
public static Object newInstance(String nameOfClass,
Class<?>[] genericParameters, Object[] constructorParameters,
String nameOfProxy, Object[] proxyParameters)
throws ClassNotFoundException, ClassNotReifiableException,
InvalidProxyClassException, ConstructionOfProxyObjectFailedException,
ConstructionOfReifiedObjectFailedException {
try {
return newInstance(nameOfClass, nameOfClass, genericParameters,
constructorParameters, nameOfProxy, proxyParameters);
} catch (ReifiedCastException e) {
throw new InternalException(e);
}
}
public static Object newInstance(Class<?> clazz,
Object[] constructorParameters, String nameOfProxy,
Object[] proxyParameters)
throws ClassNotFoundException, ClassNotReifiableException,
InvalidProxyClassException, ConstructionOfProxyObjectFailedException,
ConstructionOfReifiedObjectFailedException {
try {
return newInstance(clazz, clazz.getName(), null,
constructorParameters, nameOfProxy, proxyParameters);
} catch (ReifiedCastException e) {
throw new InternalException(e);
}
}
/**
* Creates an instance of an object
* @param nameOfStubClass The name of the Stub class corresponding to the object
* @param nameOfClass The class to instantiate
* @param genericParameters the types of the generic parameters for the class (if any, otherwise this parameter may be null)
* @param constructorParameters Array of the constructor's parameters [wrapper]
* @param nameOfProxy The name of its proxy class
* @param proxyParameters The array holding the proxy parameter
*/
public static Object newInstance(String nameOfStubClass,
String nameOfClass, Class<?>[] genericParameters,
Object[] constructorParameters, String nameOfProxy,
Object[] proxyParameters)
throws ClassNotFoundException, ClassNotReifiableException,
ReifiedCastException, InvalidProxyClassException,
ConstructionOfProxyObjectFailedException,
ConstructionOfReifiedObjectFailedException {
// For convenience, allows 'null' to be equivalent to an empty array
if (constructorParameters == null) {
constructorParameters = EMPTY_OBJECT_ARRAY;
}
if (proxyParameters == null) {
proxyParameters = EMPTY_OBJECT_ARRAY;
}
// Throws a ClassNotFoundException
Class<?> targetClass = forName(nameOfClass);
// Class<?> stubClass = null;
// try {
// targetClass = forName(nameOfStubClass);
// } catch (ClassNotFoundException e) {
// //if (targetClass.getClassLoader() != null) {
// // targetClass = targetClass.getClassLoader().loadClass(nameOfClass);
// //} else {
// // System.out.println("TargetClass " + targetClass + " has null classloader");
// MOP.forName(nameOfClass);// addClassToCache(nameOfStubClass, targetClass);
// Instanciates the stub object
StubObject stub = createStubObject(nameOfStubClass, targetClass,
genericParameters);
// build the constructor call for the target object to create
ConstructorCall reifiedCall = buildTargetObjectConstructorCall(targetClass,
constructorParameters);
// Instanciates the proxy object
Proxy proxy = createProxyObject(nameOfProxy, proxyParameters,
reifiedCall);
// Connects the proxy to the stub
stub.setProxy(proxy);
return stub;
}
public static Object newInstance(Class<?> stubClass, String nameOfClass,
Class<?>[] genericParameters, Object[] constructorParameters,
String nameOfProxy, Object[] proxyParameters)
throws ClassNotFoundException, ClassNotReifiableException,
ReifiedCastException, InvalidProxyClassException,
ConstructionOfProxyObjectFailedException,
ConstructionOfReifiedObjectFailedException {
// For convenience, allows 'null' to be equivalent to an empty array
if (constructorParameters == null) {
constructorParameters = EMPTY_OBJECT_ARRAY;
}
if (proxyParameters == null) {
proxyParameters = EMPTY_OBJECT_ARRAY;
}
// Throws a ClassNotFoundException
Class<?> targetClass = null; // forName(nameOfClass);
// Class<?> stubClass = null;
try {
targetClass = forName(nameOfClass);
} catch (ClassNotFoundException e) {
if (stubClass.getClassLoader() != null) {
targetClass = stubClass.getClassLoader().loadClass(nameOfClass);
} else {
logger.info("TargetClass " + targetClass +
" has null classloader");
}
// MOP.forName(nameOfClass);// addClassToCache(nameOfStubClass, targetClass);
}
// Instanciates the stub object
StubObject stub = createStubObject(stubClass.getName(), targetClass,
genericParameters);
// build the constructor call for the target object to create
ConstructorCall reifiedCall = buildTargetObjectConstructorCall(targetClass,
constructorParameters);
// Instanciates the proxy object
Proxy proxy = createProxyObject(nameOfProxy, proxyParameters,
reifiedCall);
// Connects the proxy to the stub
stub.setProxy(proxy);
return stub;
}
/**
* Creates an instance of an object
* @param nameOfClass The class to instanciate
* @param constructorParameters Array of the constructor's parameters [wrapper]
* @param proxyParameters The array holding the proxy parameter
*/
// public static Object newInstance(String nameOfClass,
// Object[] constructorParameters, Object[] proxyParameters)
// throws ClassNotFoundException, ClassNotReifiableException,
// CannotGuessProxyNameException, InvalidProxyClassException,
// ConstructionOfProxyObjectFailedException,
// ConstructionOfReifiedObjectFailedException {
// String nameOfProxy = guessProxyName(forName(nameOfClass));
// return newInstance(nameOfClass, constructorParameters, nameOfProxy,
// proxyParameters);
/**
* Reifies an object
*
* @param proxyParameters
* Array holding the proxy parameters
* @param target
* the object to reify
*/
// public static Object turnReified(Object[] proxyParameters, Object target)
// throws ClassNotReifiableException, CannotGuessProxyNameException,
// InvalidProxyClassException,
// ConstructionOfProxyObjectFailedException {
// try {
// return turnReified(guessProxyName(target.getClass()),
// proxyParameters, target);
// } catch (ClassNotFoundException e) {
// throw new CannotGuessProxyNameException();
/**
* Reifies an object
* @param nameOfProxyClass the name of the object's proxy
* @param proxyParameters Array holding the proxy parameters
* @param target the object to reify
* @param genericParameters * @param genericParameters the types of the generic parameters for the class (if any, otherwise this parameter may be null)
*/
public static Object turnReified(String nameOfProxyClass,
Object[] proxyParameters, Object target, Class<?>[] genericParameters)
throws ClassNotFoundException, ClassNotReifiableException,
InvalidProxyClassException, ConstructionOfProxyObjectFailedException {
try {
return turnReified(target.getClass().getName(), nameOfProxyClass,
proxyParameters, target, genericParameters);
// return turnReifiedFAb(target.getClass(), nameOfProxyClass, proxyParameters, target);
} catch (ReifiedCastException e) {
throw new InternalException(e);
}
}
/**
* Reifies an object
* @param proxyParameters Array holding the proxy parameters
* @param nameOfStubClass The name of the object's stub class
* @param target the object to reify
*/
// public static Object turnReified(Object[] proxyParameters,
// String nameOfStubClass, Object target)
// throws ClassNotFoundException, ReifiedCastException,
// ClassNotReifiableException, CannotGuessProxyNameException,
// InvalidProxyClassException,
// ConstructionOfProxyObjectFailedException {
// String nameOfProxy = guessProxyName(target.getClass());
// return turnReified(nameOfStubClass, nameOfProxy, proxyParameters,
// target);
/**
* Reifies an object
*
* @param nameOfProxyClass
* the name of the object's proxy
* @param nameOfStubClass
* The name of the object's stub class
* @param proxyParameters
* Array holding the proxy parameters
* @param target
* the object to reify
*/
public static Object turnReified(String nameOfStubClass,
String nameOfProxyClass, Object[] proxyParameters, Object target,
Class<?>[] genericParameters)
throws ClassNotFoundException, ReifiedCastException,
ClassNotReifiableException, InvalidProxyClassException,
ConstructionOfProxyObjectFailedException {
// For convenience, allows 'null' to be equivalent to an empty array
// System.out.println("MOP.turnReified");
if (proxyParameters == null) {
proxyParameters = EMPTY_OBJECT_ARRAY;
}
// Throws a ClassNotFoundException
Class<?> targetClass = target.getClass();
// Instanciates the stub object
StubObject stub = createStubObject(nameOfStubClass, targetClass,
genericParameters);
// First, build the FakeConstructorCall object to pass to the constructor
// of the proxy Object
// FakeConstructorCall fakes a ConstructorCall object by returning
// an already-existing object as the result of its execution
ConstructorCall reifiedCall = new FakeConstructorCall(target);
// Instanciates the proxy object
Proxy proxy = createProxyObject(nameOfProxyClass, proxyParameters,
reifiedCall);
// Connects the proxy to the stub
stub.setProxy(proxy);
return stub;
}
// public static Object turnReifiedFAb(Class<?> targetClass, String nameOfProxyClass, Object[] proxyParameters, Object target)
// throws ClassNotFoundException, ReifiedCastException, ClassNotReifiableException, InvalidProxyClassException, ConstructionOfProxyObjectFailedException {
// For convenience, allows 'null' to be equivalent to an empty array
// System.out.println("MOP.turnReified");
// System.out.println("turnReifiedFAb");
// if (proxyParameters == null)
// proxyParameters = EMPTY_OBJECT_ARRAY;
// Throws a ClassNotFoundException
// Class<?> targetClass = target.getClass();
// Instanciates the stub object
// StubObject stub = createStubObjectFAb(targetClass);
// First, build the FakeConstructorCall object to pass to the constructor
// of the proxy Object
// FakeConstructorCall fakes a ConstructorCall object by returning
// an already-existing object as the result of its execution
// ConstructorCall reifiedCall = new FakeConstructorCall(target);
// Instanciates the proxy object
// Proxy proxy = createProxyObject(nameOfProxyClass, proxyParameters, reifiedCall);
// Connects the proxy to the stub
// stub.setProxy(proxy);
// return stub;
/**
* Checks if a stub class can be created for the class <code>cl</code>.
*
* A class cannot be reified if at least one of the following conditions are
* met : <UL>
* <LI>This <code>Class<?></code> objects represents a primitive type
* (except void)
* <LI>The class is <code>final</code>
* <LI>There is an ambiguity in constructors signatures
* <LI>There is no noargs constructor
* </UL>
*
* @author Julien Vayssi?re, INRIA
* @param cl Class<?> to be checked
* @return <code>true</code> is the class exists and can be reified,
* <code>false</code> otherwise.
*/
static void checkClassIsReifiable(String className)
throws ClassNotReifiableException, ClassNotFoundException {
checkClassIsReifiable(forName(className));
}
public static void checkClassIsReifiable(Class<?> cl)
throws ClassNotReifiableException {
int mods = cl.getModifiers();
if (cl.isInterface()) {
// Interfaces are always reifiable, although some of the methods
// they contain may not be reifiable
return;
} else {
// normal case, this is a class
if (cl.isPrimitive()) {
throw new ClassNotReifiableException(
"Cannot reify primitive types: " + cl.getName());
} else if (Modifier.isFinal(mods)) {
throw new ClassNotReifiableException(
"Cannot reify final classes: " + cl.getName());
} else if (!(checkNoArgsConstructor(cl))) {
throw new ClassNotReifiableException("Class " + cl.getName() +
" needs to have an empty noarg constructor.");
} else {
return;
}
}
}
/**
* Checks if class <code>c</code> has a noargs constructor
*/
protected static boolean checkNoArgsConstructor(Class<?> cl) {
try {
cl.getConstructor(EMPTY_CLASS_ARRAY);
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* Checks if an object is a stub object
*
* Being a stub object is equivalent to implementing the StubObject
* interface
*
* @param o the object to check
* @return <code>true</code> if it is a stub object, <code>false</code>
* otherwise */
public static boolean isReifiedObject(Object o) {
if (o != null) {
return (STUB_OBJECT_INTERFACE.isAssignableFrom(o.getClass()));
} else {
return false;
}
}
/**
* Creates a stub class for the specified class
* @param nameOfBaseClass The name of the class
* @return A class object representing the class, or NULL if failed
*/
private static Class<?> createStubClass(String nameOfBaseClass,
Class<?>[] genericParameters) {
try {
//return Class.forName(Utils.convertClassNameToStubClassName(nameOfClass), true, singleton);
return singleton.loadClass(Utils.convertClassNameToStubClassName(
nameOfBaseClass, genericParameters));
} catch (ClassNotFoundException e) {
throw new GenerationOfStubClassFailedException(
"Cannot create the Stub class : " +
Utils.convertClassNameToStubClassName(nameOfBaseClass,
genericParameters) + "\nThe class \"" + nameOfBaseClass +
"\" must have a public access ");
}
}
private static Class<?> createStubClass(String nameOfClass,
Class<?>[] genericParameters, ClassLoader cl) {
try {
//return Class.forName(Utils.convertClassNameToStubClassName(nameOfClass), true, singleton);
return singleton.loadClass(Utils.convertClassNameToStubClassName(
nameOfClass, genericParameters), genericParameters, cl);
} catch (ClassNotFoundException e) {
throw new GenerationOfStubClassFailedException(
"Cannot load Stub class : " +
Utils.convertClassNameToStubClassName(nameOfClass,
genericParameters));
}
}
/**
* Finds the Stub Constructor for a specified class
* @param nameOfClass the name of the class
* @return The Constructor object.
* @throws ClassNotFoundException if the class cannot be located
*/
static Constructor findStubConstructor(String nameOfClass,
Class<?>[] genericParameters) throws ClassNotFoundException {
return findStubConstructor(forName(nameOfClass), genericParameters);
}
/**
* Finds the Stub Constructor for a specified class
* @param targetClass the representation of the class
* @return The Constructor object.
*/
private static Constructor findStubConstructor(Class<?> targetClass,
Class<?>[] genericParameters) {
Constructor stubConstructor;
String nameOfClass = targetClass.getName();
// Is it cached in Hashtable ?
stubConstructor = (Constructor) stubTable.get(new GenericStubKey(
nameOfClass, genericParameters));
//System.out.println("xxxxxx targetClass is " + targetClass);
// On cache miss, finds the constructor
if (stubConstructor == null) {
Class<?> stubClass;
try {
stubClass = forName(Utils.convertClassNameToStubClassName(
nameOfClass, genericParameters));
} catch (ClassNotFoundException e) {
// No stub class can be found, let's create it from scratch
stubClass = createStubClass(nameOfClass, genericParameters,
targetClass.getClassLoader());
// stubClass = createStubClass(nameOfClass,
// targetClass.getClassLoader());
}
// Verifies that the stub has a noargs constructor and caches it
try {
stubConstructor = stubClass.getConstructor(EMPTY_CLASS_ARRAY);
stubTable.put(new GenericStubKey(nameOfClass, genericParameters),
stubConstructor);
} catch (NoSuchMethodException e) {
throw new GenerationOfStubClassFailedException(
"Stub for class " + nameOfClass +
"has no noargs constructor. This is a bug in ProActive.");
}
}
return stubConstructor;
}
/**
* Finds the Constructor of the proxy for a specified class
* @param proxyClass The represenation of the proxy
* @return the Constructor
* @throws InvalidProxyClassException If the class is not a valid Proxy
*/
private static Constructor findProxyConstructor(Class<?> proxyClass)
throws InvalidProxyClassException {
Constructor proxyConstructor;
// Localizes the proxy class constructor
proxyConstructor = proxyTable.get(proxyClass.getName());
//System.out.println("MOP: The class of the proxy is " + proxyClass.getName());
// Cache miss
if (proxyConstructor == null) {
try {
proxyConstructor = proxyClass.getConstructor(PROXY_CONSTRUCTOR_PARAMETERS_TYPES_ARRAY);
proxyTable.put(proxyClass.getName(), proxyConstructor);
} catch (NoSuchMethodException e) {
throw new InvalidProxyClassException(
"No constructor matching (ConstructorCall, Object[]) found in proxy class " +
proxyClass.getName());
}
}
return proxyConstructor;
}
private static StubObject instantiateStubObject(Constructor stubConstructor)
throws ConstructionOfStubObjectFailedException {
try {
Object o = stubConstructor.newInstance(EMPTY_OBJECT_ARRAY);
return (StubObject) o;
} catch (InstantiationException e) {
throw new ConstructionOfStubObjectFailedException("Constructor " +
stubConstructor + " belongs to an abstract class.");
} catch (IllegalArgumentException e) {
throw new ConstructionOfStubObjectFailedException(
"Wrapping problem with constructor " + stubConstructor);
} catch (IllegalAccessException e) {
throw new ConstructionOfStubObjectFailedException(
"Access denied to constructor " + stubConstructor);
} catch (InvocationTargetException e) {
throw new ConstructionOfStubObjectFailedException("The constructor of the stub has thrown an exception: ",
e.getTargetException());
}
}
public static StubObject createStubObject(String nameOfBaseClass,
Class<?> targetClass, Class<?>[] genericParameters)
throws ClassNotFoundException, ReifiedCastException,
ClassNotReifiableException {
//System.out.println("StubClass is " + nameOfBaseClass);
// BUG ID: #327
//this has been added to deal with downloaded classes
//if we cannot load the stub class using its name
//it is probably because it has been downloaded by another classloader
//thus we ask the classloader of the target class to load it
Class<?> baseClass = null;
try {
baseClass = forName(nameOfBaseClass);
} catch (ClassNotFoundException e) {
baseClass = targetClass.getClassLoader().loadClass(nameOfBaseClass);
MOP.addClassToCache(nameOfBaseClass, baseClass);
}
// Class<?> stubClass = forName(nameOfStubClass,targetClass.getClassLoader());
// Check that the type of the class is compatible with the type of the stub
if (!(baseClass.isAssignableFrom(targetClass))) {
throw new ReifiedCastException("Cannot convert " +
targetClass.getName() + "into " + baseClass.getName());
}
// Throws a ClassNotReifiableException exception if not reifiable
checkClassIsReifiable(baseClass);
// Finds the constructor of the stub class
// If the stub class has not yet been created,
// it is created within this call
Constructor stubConstructor = findStubConstructor(baseClass,
genericParameters);
// Instanciates the stub object
return instantiateStubObject(stubConstructor);
}
// BUG ID: #327
protected static void addClassToCache(String name, Class<?> cl) {
// System.out.println("MOP: puting " + nameOfStubClass +
// " in loadedClass");
// loadedClass.put(nameOfStubClass, stubClass);
// Field[] clArray = stubClass.getDeclaredFields();
// System.out.println("MOP: nuumber of declared classes " +
// clArray.length);
// for (int i = 0; i < clArray.length; i++) {
// Field ob1 = clArray[i];
// System.out.println("MOP: field " + ob1.getName());
// Class<?> cl = ob1.getType();
// System.out.println("MOP: key = " + cl.getName() + " value = " +
// loadedClass.put(cl.getName(), cl);
loadedClass.put(name, cl);
}
// Instanciates the proxy object
public static Proxy createProxyObject(String nameOfProxy,
Object[] proxyParameters, ConstructorCall reifiedCall)
throws ConstructionOfProxyObjectFailedException, ClassNotFoundException,
InvalidProxyClassException {
// Throws a ClassNotFoundException
Class<?> proxyClass = forName(nameOfProxy);
// Finds constructor of the proxy class
Constructor proxyConstructor = findProxyConstructor(proxyClass);
// Now calls the constructor of the proxy
Object[] params = new Object[] { reifiedCall, proxyParameters };
try {
return (Proxy) proxyConstructor.newInstance(params);
} catch (InstantiationException e) {
throw new ConstructionOfProxyObjectFailedException("Constructor " +
proxyConstructor + " belongs to an abstract class");
} catch (IllegalArgumentException e) {
throw new ConstructionOfProxyObjectFailedException(
"Wrapping problem with constructor " + proxyConstructor);
} catch (IllegalAccessException e) {
throw new ConstructionOfProxyObjectFailedException(
"Access denied to constructor " + proxyConstructor);
} catch (InvocationTargetException e) {
throw new ConstructionOfProxyObjectFailedException("The constructor of the proxy object has thrown an exception: ",
e.getTargetException());
}
}
public static ConstructorCall buildTargetObjectConstructorCall(
Class<?> targetClass, Object[] constructorParameters)
throws ConstructionOfReifiedObjectFailedException {
// First, build the ConstructorCall object to pass to the constructor
// of the proxy Object. It represents the construction of the reified
// object.
Constructor targetConstructor;
// Locates the right constructor (should use a cache here ?)
Class<?>[] targetConstructorArgs = new Class<?>[constructorParameters.length];
for (int i = 0; i < constructorParameters.length; i++) {
// System.out.println("MOP: constructorParameters[i] = " + constructorParameters[i]);
if (constructorParameters[i] != null) {
targetConstructorArgs[i] = constructorParameters[i].getClass();
} else {
targetConstructorArgs[i] = null;
}
// System.out.println("MOP: targetConstructorArgs[i] = " + targetConstructorArgs[i]);
}
//System.out.println("MOP: targetClass is " + targetClass);
// System.out.println("MOP: targetConstructorArgs = " + targetConstructorArgs);
// System.out.println("MOP: targetConstructorArgs.length = " + targetConstructorArgs.length);
try {
//MODIFIED 4/5/00
if (targetClass.isInterface()) {
//there is no point in looking for the constructor of an interface
// System.out.println("MOP: WARNING Interface detected");
targetConstructor = null;
} else {
targetConstructor = targetClass.getConstructor(targetConstructorArgs);
}
} catch (NoSuchMethodException e) {
// This may have failed because getConstructor does not allow subtypes
targetConstructor = findReifiedConstructor(targetClass,
targetConstructorArgs);
if (targetConstructor == null) {
throw new ConstructionOfReifiedObjectFailedException(
"Cannot locate this constructor in " + targetClass + " : " +
Arrays.asList(targetConstructorArgs));
}
}
return new ConstructorCallImpl(targetConstructor, constructorParameters);
}
/**
* Try to guess the name of the proxy for a specified class
* @param targetClass the source class
* @return the name of the proxy class
* @throws CannotGuessProxyNameException If the MOP cannot guess the name of the proxy
*/
// private static String guessProxyName(Class<?> targetClass)
// throws CannotGuessProxyNameException {
// int i;
// Class<?> cl;
// Class<?> myInterface = null;
// Class<?>[] interfaces;
// Field myField = null;
// // Checks the cache
// String nameOfProxy = (String) secondProxyTable.get(targetClass
// .getName());
// if (nameOfProxy == null) {
// Class<?> currentClass;
// // Checks if this class or any of its superclasses implements an
// // interface that is a subinterface of ROOT_INTERFACE
// currentClass = targetClass;
// // System.out.println("MOP: guessProxyName for targetClass " +
// // targetClass);
// while ((currentClass != null) && (myInterface == null)) {
// boolean multipleMatches = false;
// interfaces = currentClass.getInterfaces();
// for (i = 0; i < interfaces.length; i++) {
// if (ROOT_INTERFACE.isAssignableFrom(interfaces[i])) {
// if (multipleMatches == false) {
// myInterface = interfaces[i];
// multipleMatches = true;
// } else {
// // There are multiple interfaces in the current
// // class
// // that inherit from ROOT_INTERFACE.
// System.err
// .println("More than one interfaces declared in class "
// + currentClass.getName()
// + " inherit from "
// + ROOT_INTERFACE
// + ". Using " + myInterface);
// currentClass = currentClass.getSuperclass();
// if (myInterface == null) {
// throw new CannotGuessProxyNameException(
// "Class "
// + targetClass.getName()
// + " does not implement any interface that inherits from org.objectweb.proactive.core.mop.Reflect");
// // Now look for the PROXY_CLASS_NAME field in this interface
// try {
// myField = myInterface.getField("PROXY_CLASS_NAME");
// } catch (NoSuchFieldException e) {
// throw new CannotGuessProxyNameException(
// "No field PROXY_CLASS_NAME in interface " + myInterface);
// try {
// nameOfProxy = (String) myField.get(null);
// throw new CannotGuessProxyNameException(
// "Cannot access field PROXY_CLASS_NAME in interface "
// + myInterface);
// secondProxyTable.put(targetClass.getName(), nameOfProxy);
// return nameOfProxy;
/**
* Finds the reified constructor
* @param targetClass The class
* @param the effective arguments
* @return The constructor
* @throws ConstructionOfReifiedObjectFailedException
*/
private static Constructor<?> findReifiedConstructor(Class<?> targetClass,
Class<?>[] targetConstructorArgs)
throws ConstructionOfReifiedObjectFailedException {
boolean match;
TreeMap<HashSet<Constructor<?>>, HashSet<Constructor<?>>> matchingConstructors =
new TreeMap<HashSet<Constructor<?>>, HashSet<Constructor<?>>>(new ConstructorComparator(
targetConstructorArgs));
Constructor<?>[] publicConstructors = targetClass.getConstructors();
// For each public constructor of the reified class
for (int i = 0; i < publicConstructors.length; i++) {
Constructor<?> currentConstructor = publicConstructors[i];
Class<?>[] currentConstructorParameterTypes = currentConstructor.getParameterTypes();
match = true;
// Check if the parameters types of this constructor are
// assignable from the actual parameter types.
if (currentConstructorParameterTypes.length == targetConstructorArgs.length) {
for (int j = 0; j < currentConstructorParameterTypes.length;
j++) {
if (targetConstructorArgs[j] != null) {
if (!(currentConstructorParameterTypes[j].isAssignableFrom(
targetConstructorArgs[j]))) {
if (Utils.isWrapperClass(targetConstructorArgs[j])) {
// If the parameter is a wrapper class we try to find a constructor
// with the corresponding primitive type
Class<?> primitive = Utils.getPrimitiveType(targetConstructorArgs[j]);
if (!(currentConstructorParameterTypes[j].isAssignableFrom(
primitive))) {
match = false;
break;
}
} else {
match = false;
break;
}
}
} else if (currentConstructorParameterTypes[j].isPrimitive()) {
// we suppose that null is assignable to anything not primitive
match = false;
break;
}
}
} else {
match = false;
}
if (match == true) {
HashSet<Constructor<?>> newSet = new HashSet<Constructor<?>>();
newSet.add(currentConstructor);
if (matchingConstructors.containsKey(newSet)) {
HashSet<Constructor<?>> oldSet = matchingConstructors.remove(newSet);
oldSet.add(currentConstructor);
matchingConstructors.put(oldSet, oldSet);
}
matchingConstructors.put(newSet, newSet);
}
}
if (matchingConstructors.size() > 0) {
HashSet<Constructor<?>> bestConstructors = matchingConstructors.lastKey();
if (bestConstructors.size() > 1) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println(
"Choice of a constructor is ambiguous, possible choices are :");
for (Constructor c : bestConstructors) {
pw.println(c);
}
throw new ConstructionOfReifiedObjectFailedException(sw.toString());
}
if (bestConstructors.size() == 1) {
return bestConstructors.iterator().next();
}
}
return null;
}
/**
* Dynamic cast
* @param sourceObject The source object
* @param targetTypeName the destination class
* @return The resulting object
* @throws ReifiedCastException if the class cast is invalid
*/
private static Object castInto(Object sourceObject, String targetTypeName)
throws ReifiedCastException {
try {
Class<?> cl = forName(targetTypeName);
return castInto(sourceObject, cl, null);
} catch (ClassNotFoundException e) {
throw new ReifiedCastException("Cannot load class " +
targetTypeName);
// throw new ReifiedCastException ("Cannot cast "+sourceObject.getClass().getName()+" into "+targetTypeName);
}
}
/**
* Dynamic cast
* @param sourceObject The source object
* @param targetType the destination class
* @param genericParameters TODO
* @return The resulting object
* @throws ReifiedCastException if the class cast is invalid
*/
private static Object castInto(Object sourceObject, Class<?> targetType,
Class<?>[] genericParameters) throws ReifiedCastException {
// First, check if sourceObject is a reified object
if (!(isReifiedObject(sourceObject))) {
throw new ReifiedCastException(
"Cannot perform a reified cast on an object that is not reified");
}
// Gets a Class<?> object representing the type of sourceObject
Class<?> sourceType = sourceObject.getClass().getSuperclass();
// Check if types are compatible
// Here we assume that the 'type of the stub' (i.e, the type of the
// reified object) is its direct superclass
if (!((sourceType.isAssignableFrom(targetType)) ||
(targetType.isAssignableFrom(sourceType)))) {
throw new ReifiedCastException("Cannot cast " +
sourceObject.getClass().getName() + " into " +
targetType.getName());
}
// Let's create a stub object for the target type
Constructor stubConstructor = findStubConstructor(targetType,
genericParameters);
// Instanciates the stub object
StubObject stub = instantiateStubObject(stubConstructor);
// Connects the proxy of the old stub to the new stub
stub.setProxy(((StubObject) sourceObject).getProxy());
return stub;
}
public static Class<?> loadClass(String name) throws ClassNotFoundException {
//return singleton.loadClass(name);
return forName(name);
}
static class GenericStubKey {
String className;
Class<?>[] genericParameters;
public GenericStubKey(String className, Class<?>[] genericParameters) {
this.className = className;
this.genericParameters = genericParameters;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof GenericStubKey)) {
return false;
}
// className cannot be null
return (className.equals(((GenericStubKey) o).getClassName()) &&
(Arrays.equals(genericParameters,
((GenericStubKey) o).getGenericParameters())));
}
@Override
public int hashCode() {
return className.hashCode() +
Arrays.deepHashCode(genericParameters);
}
public String getClassName() {
return className;
}
public Class<?>[] getGenericParameters() {
return genericParameters;
}
}
public static Object createStubObject(String className, UniversalBody body)
throws MOPException {
return createStubObject(className, null, null, new Object[] { body });
}
public static Object createStubObject(String className,
Class<?>[] genericParameters, Object[] constructorParameters,
Node node, Active activity, MetaObjectFactory factory)
throws MOPException {
return createStubObject(className, genericParameters,
constructorParameters,
new Object[] { node, activity, factory, ProActiveObject.getJobId() });
}
private static Object createStubObject(String className,
Class<?>[] genericParameters, Object[] constructorParameters,
Object[] proxyParameters) throws MOPException {
try {
return newInstance(className, genericParameters,
constructorParameters, Constants.DEFAULT_BODY_PROXY_CLASS_NAME,
proxyParameters);
} catch (ClassNotFoundException e) {
throw new ConstructionOfProxyObjectFailedException(
"Class can't be found e=" + e);
}
}
public static Object createStubObject(Object target,
String nameOfTargetType, Class<?>[] genericParameters, Node node,
Active activity, MetaObjectFactory factory) throws MOPException {
return createStubObject(target,
new Object[] { node, activity, factory, ProActiveObject.getJobId() },
nameOfTargetType, genericParameters);
}
public static StubObject createStubObject(Object object,
Object[] proxyParameters, String nameOfTargetType,
Class<?>[] genericParameters) throws MOPException {
try {
return (StubObject) turnReified(nameOfTargetType,
Constants.DEFAULT_BODY_PROXY_CLASS_NAME, proxyParameters,
object, genericParameters);
} catch (ClassNotFoundException e) {
throw new ConstructionOfProxyObjectFailedException(
"Class can't be found e=" + e);
}
}
private static class ConstructorComparator implements Comparator<HashSet<Constructor<?>>> {
Class<?>[] parameterTypes;
public ConstructorComparator(Class<?>[] parameterTypes) {
this.parameterTypes = parameterTypes;
}
public int compare(HashSet<Constructor<?>> set1,
HashSet<Constructor<?>> set2) {
Integer result = null;
// This function compares each element of set to each element of set2
for (Constructor<?> c1 : set1) {
for (Constructor<?> c2 : set2) {
int test = compareConstructors(c1, c2);
if (test == 0) {
// if two elements are equals then the sets are considered equal
return 0;
}
if (result == null) {
result = test;
} else if ((test * result) < 0) {
// if two elements have contradictory orders then the sets are considered equal
return 0;
}
// Otherwise
}
}
return result;
}
private void exceptionInComparison(Class<?> c1, Class<?> c2) {
throw new IllegalArgumentException(c1 + " and " + c2 +
" are not comparable.");
}
public int compareConstructors(Constructor c1, Constructor c2) {
// Compare two constructors using the following principles
// if every parameters of c1 are assignable to the corresponding parameters in c2
// ==> then c1 is more pertinent than c2 (and resp)
// if there exist both one parameter of c1 assignable to the param in c2 and one parameter of c2 assigable to the param in c1,
// ==> then the constructors are equivalent (ambiguous)
Class<?>[] c1PT = c1.getParameterTypes();
Class<?>[] c2PT = c2.getParameterTypes();
Integer result = null;
for (int i = 0; i < c1PT.length; i++) {
int currentResult;
if (parameterTypes[i] == null) {
// if the specified parameter is null, we can't make any supposition
currentResult = 0;
} else if (c1PT[i].equals(c2PT[i])) {
// not decidable
currentResult = 0;
} else if (c1PT[i].isPrimitive() && c2PT[i].isPrimitive()) {
// c1 and c2 are not comparable, this should not happen
exceptionInComparison(c1PT[i], c2PT[i]);
currentResult = 0;
} else if (c1PT[i].isPrimitive()) {
Class<?> wrapper = Utils.getWrapperClass(c1PT[i]);
if (c2PT[i].isAssignableFrom(wrapper)) {
// c1 is more pertinent
currentResult = 1;
} else {
// c1 and c2 are not comparable, this should not happen
exceptionInComparison(c1PT[i], c2PT[i]);
currentResult = 0;
}
} else if (c2PT[i].isPrimitive()) {
Class<?> wrapper = Utils.getWrapperClass(c2PT[i]);
if (c1PT[i].isAssignableFrom(wrapper)) {
// c2 is more pertinent
currentResult = -1;
} else {
// c1 and c2 are not comparable, this should not happen
exceptionInComparison(c1PT[i], c2PT[i]);
currentResult = 0;
}
} else {
if (c1PT[i].isAssignableFrom(c2PT[i])) {
// c2 is more pertinent
currentResult = -1;
} else if (c2PT[i].isAssignableFrom(c1PT[i])) {
// c1 is more pertinent
currentResult = 1;
} else {
// c1 and c2 are not comparable, this should not happen
throw new IllegalArgumentException(c1PT[i] + " and " +
c2PT[i] + " are not comparable.");
}
}
if (result == null) {
if (currentResult != 0) {
result = currentResult;
}
} else if ((currentResult * result) < 0) {
// The only case when we know they are equivalent (ambiguous)
return 0;
}
}
if (result == null) {
result = 0;
}
return result;
}
}
} |
package io.qala.datagen;
public class Vocabulary {
/** Can be globally overwritten for your particular project. */
public static String SPECIAL_SYMBOLS = "!@
static char[] specialSymbols() {
return SPECIAL_SYMBOLS.toCharArray();
}
} |
package model;
import java.util.List;
import java.net.UnknownHostException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import controller.Controller.QueryType;
public class MongoQueryExecuter implements QueryInterpreter {
private Model model;
private static String lastQuery;
private static QueryType lastQueryType;
private final static String database = "mediacollection";
private final static String user = "clientapp";
private final static String pass = "qwerty";
private final static String host = "mongodb:
private final static String connection = "localhost:27017/";
private MongoCredential cr = null;
private MongoClient mc = null;
private DB db = null;
private DBCollection coll = null;
// URI styled
// host + user + ":" + pass + "@" + connection + database
public static void main(String args[]) throws UnknownHostException,
SQLException {
Model model = new Model("User42", "");
MongoQueryExecuter mqe = new MongoQueryExecuter(model);
mqe.addMedia("Lenny Hits", "1998", "Lennstyle", new Object[] { "Lenny P",
"Lenny K" }, 360, 1);
mqe.addMedia("Rosenrot", "2005", "Rammstyle", new Object[] { "Rammstein"}, 360, 1);
mqe.peek();
}
// TODO remove
public void peek()
{
Cursor fetchAll = coll.find();
// rough peek
while (fetchAll.hasNext()) {
System.out.println(fetchAll.next());
}
}
public MongoQueryExecuter(Model model) {
this.model = model;
try {
cr = MongoCredential.createMongoCRCredential("clientapp",
"mediacollection", "qwerty".toCharArray());
mc = new MongoClient(new ServerAddress(), Arrays.asList(cr));
db = mc.getDB("mediacollection");
//Set<String> colls = db.getCollectionNames();
//System.out.println(colls.toString());
coll = db.getCollection("Media");
mc.setWriteConcern(WriteConcern.JOURNALED);
/*
* BasicDBObject oneAlbum = new BasicDBObject("Title", "Imagine")
* .append("Creator", "John Lennon") .append("Genre",
* "Lennstyle").append("Year", "2006") .append("Duration", "120");
*
* List<BasicDBObject> reviews = new ArrayList<BasicDBObject>();
* reviews.add(new BasicDBObject("User", "Bar").append("Its good",
* "Excellent!").append("Review", "I liked this album."));
* oneAlbum.put("Review", reviews);
*
* List<BasicDBObject> rating = new ArrayList<BasicDBObject>();
* rating.add(new BasicDBObject("User", "Foo").append("Rating",
* "5")); rating.add(new BasicDBObject("User",
* "Bar").append("Rating", "5")); oneAlbum.put("Rating", rating);
*
* oneAlbum.put("AddedBy", "Bar"); oneAlbum.put("Mediatype",
* "Album");
*
* coll.insert(oneAlbum);
*/
// Cursor fetchAll = coll.find();
// rough peek
// while (fetchAll.hasNext()) {
// System.out.println(fetchAll.next());
// specified peek
} catch (Exception e) {
System.out.println("catch: " + e.toString());
}
}
@Override
public void disconnect() {
// TODO Auto-generated method stub
}
private synchronized void setLastQuery(String lastQuery, QueryType queryType) {
MongoQueryExecuter.lastQuery = lastQuery;
MongoQueryExecuter.lastQueryType = queryType;
}
private synchronized String getLastQuery() {
return MongoQueryExecuter.lastQuery;
}
private synchronized QueryType getLastQueryType() {
return MongoQueryExecuter.lastQueryType;
}
@Override
public ArrayList<Album> getAlbumsByTitle(String title) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAlbumsByGenre(String genre) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAllAlbums(ResultSet rsetAlbum)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAlbumsByAny(String title) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAlbumsByArtist(String artist)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAlbumsByRating(String rating)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAlbumsByYear(String year) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Album> getAlbumsByUser(String user) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMoviesByAny(String queryText)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMovieByUser(String user) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getAllMovies(ResultSet rsetMovie)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMovieByYear(String year) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMovieByTitle(String title) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMovieByRating(String rating) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMovieByDirector(String director)
throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Movie> getMovieByGenre(String genre) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void getReviewsByAny(String queryText) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void reviewMedia(Review review, int pk) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void rateAlbum(int rating, int media) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void verifyAccount(String user, String pass) throws SQLException {
// TODO check that user is longer than 4 chars, do not attempt to
// verify the account, it cannot be done securely.
}
@Override
public void addMedia(String name, String year, String genre,
Object[] objects, int duration, int mediaType) throws SQLException {
BasicDBObject oneDocument = new BasicDBObject("Title", name)
.append("Genre", genre).append("Year", year)
.append("Duration", duration);
oneDocument.put("AddedBy", model.getUser());
switch (mediaType) {
case 1:
oneDocument.put("Mediatype", "Album");
break;
case 2:
oneDocument.put("Mediatype", "Movie");
break;
}
List<BasicDBObject> creators = new ArrayList<BasicDBObject>();
for (int i = 0; i < objects.length; i++) {
creators.add(new BasicDBObject("Name", objects[i].toString()));
}
oneDocument.put("Creator", creators);
coll.insert(oneDocument);
Cursor fetchAll = coll.find();
}
} |
package joliex.wsdl;
import com.ibm.wsdl.PortTypeImpl;
import com.ibm.wsdl.ServiceImpl;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.wsdl.Binding;
import javax.wsdl.BindingFault;
import javax.wsdl.BindingInput;
import javax.wsdl.BindingOperation;
import javax.wsdl.BindingOutput;
import javax.wsdl.Definition;
import javax.wsdl.Fault;
import javax.wsdl.Input;
import javax.wsdl.Message;
import javax.wsdl.Operation;
import javax.wsdl.OperationType;
import javax.wsdl.Output;
import javax.wsdl.Part;
import javax.wsdl.Port;
import javax.wsdl.PortType;
import javax.wsdl.Service;
import javax.wsdl.Types;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensionRegistry;
import javax.wsdl.extensions.schema.Schema;
import javax.wsdl.extensions.soap.SOAPAddress;
import javax.wsdl.extensions.soap.SOAPBinding;
import javax.wsdl.extensions.soap.SOAPBody;
import javax.wsdl.extensions.soap.SOAPFault;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLWriter;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import jolie.lang.NativeType;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.types.TypeDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.lang.parse.util.ProgramInspector;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author Francesco Bullini and Claudio Guidi
*/
public class WSDLDocCreator
{
// Schema
private Document schemaDocument;
private Element schemaRootElement ;
private int MAX_CARD = 2147483647;
private String tns;
private String tns_schema;
private String tns_schema_prefix = "sch";
static ExtensionRegistry extensionRegistry;
private static WSDLFactory wsdlFactory;
private Definition localDef = null;
private WSDLWriter ww = null;
private Writer fw = null;
private List<String> rootTypes = new ArrayList<String>();
private ProgramInspector inspector;
private URI originalFile;
public WSDLDocCreator( ProgramInspector inspector, URI originalFile )
{
this.inspector=inspector;
this.originalFile=originalFile;
}
public Definition initWsdl( String serviceName, String filename )
{
try {
wsdlFactory = WSDLFactory.newInstance();
localDef = wsdlFactory.newDefinition();
extensionRegistry = wsdlFactory.newPopulatedExtensionRegistry();
if ( serviceName != null ) {
QName servDefQN = new QName( serviceName );
localDef.setQName( servDefQN );
}
localDef.addNamespace( NameSpacesEnum.WSDL.getNameSpacePrefix(), NameSpacesEnum.WSDL.getNameSpaceURI() );
localDef.addNamespace( NameSpacesEnum.SOAP.getNameSpacePrefix(), NameSpacesEnum.SOAP.getNameSpaceURI() );
localDef.addNamespace( "tns", tns );
localDef.addNamespace( NameSpacesEnum.XML_SCH.getNameSpacePrefix(), NameSpacesEnum.XML_SCH.getNameSpaceURI() );
localDef.setTargetNamespace( tns );
localDef.addNamespace( "xsd1", tns_schema );
fw = new FileWriter( filename );
} catch( IOException ex ) {
Logger.getLogger( WSDLDocCreator.class.getName() ).log( Level.SEVERE, null, ex );
} catch( WSDLException ex ) {
Logger.getLogger( WSDLDocCreator.class.getName() ).log( Level.SEVERE, null, ex );
}
return localDef;
}
public void ConvertDocument( String filename, String tns ) throws Jolie2WsdlException
{
boolean soap_port_flag = false;
System.out.println( "Starting conversion..." );
this.tns = tns + ".wsdl";
this.tns_schema = tns + ".xsd";
try {
initWsdl( null, filename );
schemaDocument = this.createDOMdocument();
schemaRootElement = this.createSchemaRootElement( schemaDocument );
// scans inputPorts
InputPortInfo[] inputPortList = inspector.getInputPorts( originalFile );
for( InputPortInfo inputPort : inputPortList ) {
if ( inputPort.protocolId().equals( "soap" ) ) {
soap_port_flag = true;
// portType creation
String portTypeName = inputPort.id();
PortType pt = createPortType(localDef, portTypeName);
// binding creation
Binding bd = createBindingSOAP(localDef, pt, portTypeName + "SOAPBinding" );
// service creation
String address = inputPort.location().toString().substring( 6 ); // exclude socket word
address = "http" + address;
createService(localDef, portTypeName + "Service", bd, address );
// scans interfaces
for ( InterfaceDefinition interfaceDefinition:inputPort.getInterfaceList() )
{
// scan operations
Map< String , OperationDeclaration > operationMap = interfaceDefinition.operationsMap();
for ( Entry< String , OperationDeclaration > operationEntry:operationMap.entrySet() ) {
if ( operationEntry.getValue() instanceof OneWayOperationDeclaration ) {
OneWayOperationDeclaration oneWayOperation = ( OneWayOperationDeclaration)operationEntry.getValue();
Operation wsdlOp = addOWOperation2PT( localDef, pt, oneWayOperation );
// adding operation binding
addOperationSOAPBinding( localDef, pt, wsdlOp, bd );
} else {
RequestResponseOperationDeclaration requestResponseOperation = ( RequestResponseOperationDeclaration ) operationEntry.getValue();
Operation wsdlOp = addRROperation2PT( localDef, pt, requestResponseOperation );
// adding operation binding
addOperationSOAPBinding( localDef, pt, wsdlOp, bd );
}
}
}
}
}
if ( soap_port_flag == false ) {
throw( new Jolie2WsdlException( "ERROR: jolie2wsdl only support soap port declarations in jolie files" ) );
}
setSchemaDocIntoWSDLTypes( schemaDocument );
WSDLWriter wsdl_writer = wsdlFactory.newWSDLWriter();
wsdl_writer.writeWSDL( localDef, fw );
}
catch( WSDLException ex ) {
System.err.println( ex.getMessage() );
Logger.getLogger( WSDLDocCreator.class.getName() ).log( Level.SEVERE, null, ex );
} catch( Exception ex ) {
System.err.println( ex.getMessage() );
Logger.getLogger( WSDLDocCreator.class.getName() ).log( Level.SEVERE, null, ex );
}
System.out.println( "Success: WSDL document generated!" );
}
private String getSchemaNativeType ( NativeType nType ) {
/*
* TO DO:
* wsdl_types ANY, RAW, VOID
*/
String prefix = "xs:";
String suffix = "";
if ( nType.equals( NativeType.STRING)) {
suffix = "string";
} else if ( nType.equals( NativeType.DOUBLE )) {
suffix = "double";
} else if ( nType.equals( NativeType.INT )) {
suffix = "int";
}
if ( suffix.isEmpty() ) {
return "";
} else {
return prefix+suffix;
}
}
private void addRootType( TypeDefinition type ) throws Exception
{
if ( type instanceof TypeDefinitionLink ) {
throw( new Exception("ERROR, type " + type.id() +":conversion not allowed when the types defined as operation messages are linked type!"));
}
if ( !rootTypes.contains( type.id()) ) {
schemaRootElement.appendChild( createTypeDefinition( ( TypeInlineDefinition ) type, false ));
}
rootTypes.add( type.id() );
}
private Element createTypeDefinition( TypeInlineDefinition type, boolean inMessage ) throws Exception
{
if ( type.nativeType() != NativeType.VOID ) {
throw( new Exception("ERROR, type " + type.id() +": conversion not allowed when the types defined as operation messages have native type different from void!" ));
}
Element newEl = schemaDocument.createElement( "xs:complexType" );
if ( inMessage == false ) {
String typename = type.id();
newEl.setAttribute( "name", typename );
}
Element sequence = schemaDocument.createElement("xs:sequence");
// adding subtypes
if ( type.hasSubTypes() ) {
Iterator it = type.subTypes().iterator();
while ( it.hasNext() ) {
TypeDefinition curType = ((Entry<String,TypeDefinition>) it.next()).getValue();
Element subEl = schemaDocument.createElement("xs:element");
subEl.setAttribute("name", curType.id() );
subEl.setAttribute( "minOccurs", new Integer( curType.cardinality().min()).toString() );
String maxOccurs = "unbounded";
if ( curType.cardinality().max() < MAX_CARD ) {
maxOccurs = new Integer( curType.cardinality().max() ).toString();
}
subEl.setAttribute( "maxOccurs", maxOccurs );
if ( curType instanceof TypeInlineDefinition ) {
if ( curType.hasSubTypes( ) ) {
if ( curType.nativeType() != NativeType.VOID ) {
throw( new Exception("ERROR, type " + curType.id() +": conversion not allowed when the types defined as operation messages have native type different from void!" ));
} else {
subEl.appendChild( createTypeDefinition( ( TypeInlineDefinition ) curType, true ));
}
} else {
subEl.setAttribute("type", getSchemaNativeType( curType.nativeType() ));
}
} else {
subEl.setAttribute("type", tns_schema_prefix + ":" + (( TypeDefinitionLink ) curType ).linkedTypeName());
addRootType( ((TypeDefinitionLink) curType ).linkedType() );
}
sequence.appendChild( subEl );
}
}
newEl.appendChild( sequence );
return newEl;
}
private void addMessageType( TypeDefinition rootType, String typename ) throws Exception
{
// when converting from Jolie type of messages must have root type = "void"
// no type link are allowed for conversion
// message types define elements
if ( !rootTypes.contains( rootType.id() )) {
Element newEl = schemaDocument.createElement("xs:element");
newEl.setAttribute("name", typename );
if ( rootType instanceof TypeInlineDefinition ) {
newEl.appendChild( createTypeDefinition( ( TypeInlineDefinition ) rootType, true ));
rootTypes.add( typename );
schemaRootElement.appendChild( newEl );
if ( rootType.nativeType() != NativeType.VOID ) {
throw( new Exception("ERROR, type " + rootType.id() +": conversion not allowed when the types defined as operation messages have native type different from void!"));
}
} else if ( rootType instanceof TypeDefinitionLink ) {
throw( new Exception("ERROR, type " + rootType.id() +":conversion not allowed when the types defined as operation messages are linked type!"));
// newEl.appendChild( lookForLinkedType( (TypeDefinitionLink ) rootType, typename ));
//schemaRootElement.appendChild( createTypeDefinitionLink( ( TypeDefinitionLink ) rootType, true, typename ));
}
}
}
private Message addRequestMessage( Definition localDef, OperationDeclaration op )
{
Message inputMessage = localDef.createMessage();
inputMessage.setUndefined( false );
Part inputPart = localDef.createPart();
inputPart.setName( "body" );
try {
// adding wsdl_types related to this message
if ( op instanceof OneWayOperationDeclaration ) {
OneWayOperationDeclaration op_ow = ( OneWayOperationDeclaration ) op;
// set the message name as the name of the jolie request message type
inputMessage.setQName( new QName( tns, op_ow.requestType().id() ) );
addMessageType( op_ow.requestType(), op_ow.id() );
} else {
RequestResponseOperationDeclaration op_rr = ( RequestResponseOperationDeclaration ) op;
// set the message name as the name of the jolie request message type
inputMessage.setQName( new QName( tns, op_rr.requestType().id() ) );
addMessageType( op_rr.requestType(), op_rr.id() );
}
// set the input part as the operation name
inputPart.setElementName( new QName( tns_schema, op.id() ) );
inputMessage.addPart( inputPart );
inputMessage.setUndefined( false );
localDef.addMessage( inputMessage );
} catch( Exception e ) {
e.printStackTrace();
}
return inputMessage;
}
private Message addResponseMessage( Definition localDef, OperationDeclaration op )
{
Message outputMessage = localDef.createMessage();
outputMessage.setUndefined( false );
Part outputPart = localDef.createPart();
outputPart.setName( "body" );
// adding wsdl_types related to this message
try {
RequestResponseOperationDeclaration op_rr = ( RequestResponseOperationDeclaration ) op;
String outputPartName = op_rr.id() + "Response";
// set the message name as the name of the jolie response message type
outputMessage.setQName( new QName( tns, op_rr.responseType().id()) );
addMessageType( op_rr.responseType(), outputPartName );
outputPart.setElementName( new QName( tns_schema, outputPartName ) );
outputMessage.addPart( outputPart );
outputMessage.setUndefined( false );
localDef.addMessage( outputMessage );
} catch( Exception e ) {
e.printStackTrace();
}
return outputMessage;
}
private Message addFaultMessage( Definition localDef, OperationDeclaration op, TypeDefinition tp, String faultName )
{
Message faultMessage = localDef.createMessage();
faultMessage.setUndefined( false );
// set the fault message name as the name of the fault jolie message type
faultMessage.setQName( new QName( tns, tp.id() ) );
Part faultPart = localDef.createPart();
faultPart.setName( "body" );
String faultPartName = tp.id();
try {
// adding wsdl_types related to this message
addMessageType( tp, faultPartName );
faultPart.setElementName( new QName( tns_schema, faultPartName ) );
faultMessage.addPart( faultPart );
faultMessage.setUndefined( false );
localDef.addMessage( faultMessage );
} catch( Exception e ) {
e.printStackTrace();
}
return faultMessage;
}
private PortType createPortType( Definition def, String portTypeName ) {
PortType pt = def.getPortType( new QName( portTypeName ) );
if ( pt == null ) {
pt = new PortTypeImpl();
}
pt.setUndefined( false );
QName pt_QN = new QName( tns, portTypeName );
pt.setQName( pt_QN );
def.addPortType( pt );
return pt;
}
private Operation addOWOperation2PT( Definition def, PortType pt, OneWayOperationDeclaration op )
{
Operation wsdlOp = def.createOperation();
wsdlOp.setName( op.id() );
wsdlOp.setStyle( OperationType.ONE_WAY );
wsdlOp.setUndefined( false );
Input in = def.createInput();
Message msg_req = addRequestMessage( localDef, op );
msg_req.setUndefined( false );
in.setMessage( msg_req );
wsdlOp.setInput( in );
wsdlOp.setUndefined( false );
pt.addOperation( wsdlOp );
return wsdlOp;
}
private Operation addRROperation2PT( Definition def, PortType pt, RequestResponseOperationDeclaration op )
{
Operation wsdlOp = def.createOperation();
wsdlOp.setName( op.id() );
wsdlOp.setStyle( OperationType.REQUEST_RESPONSE );
wsdlOp.setUndefined( false );
// creating input
Input in = def.createInput();
Message msg_req = addRequestMessage( localDef, op );
in.setMessage( msg_req );
wsdlOp.setInput( in );
// creating output
Output out = def.createOutput();
Message msg_resp = addResponseMessage( localDef, op );
out.setMessage( msg_resp );
wsdlOp.setOutput( out );
// creating faults
for( Entry<String, TypeDefinition> curFault : op.faults().entrySet() ) {
Fault fault = localDef.createFault();
fault.setName( curFault.getKey() );
Message flt_msg = addFaultMessage( localDef, op, curFault.getValue(), curFault.getKey() );
fault.setMessage( flt_msg );
wsdlOp.addFault( fault );
}
pt.addOperation( wsdlOp );
return wsdlOp;
}
private Binding createBindingSOAP( Definition def, PortType pt, String bindingName ) {
Binding bind = def.getBinding( new QName( bindingName ) );
if ( bind == null ) {
bind = def.createBinding();
bind.setQName( new QName( tns, bindingName ) );
}
bind.setPortType( pt );
bind.setUndefined( false );
try {
SOAPBinding soapBinding = (SOAPBinding) extensionRegistry.createExtension( Binding.class, new QName( NameSpacesEnum.SOAP.getNameSpaceURI(), "binding" ) );
soapBinding.setTransportURI( NameSpacesEnum.SOAPoverHTTP.getNameSpaceURI() );
soapBinding.setStyle( "document" );
bind.addExtensibilityElement( soapBinding );
} catch( WSDLException ex ) {
System.out.println( ( ex.getStackTrace() ));
}
def.addBinding( bind );
return bind;
}
private void addOperationSOAPBinding( Definition localDef, PortType portType, Operation wsdlOp, Binding bind )
{
try {
// creating operation binding
BindingOperation bindOp = localDef.createBindingOperation();
bindOp.setName( wsdlOp.getName() );
// adding soap extensibility elements
SOAPOperation soapOperation = (SOAPOperation) extensionRegistry.createExtension( BindingOperation.class, new QName( NameSpacesEnum.SOAP.getNameSpaceURI(), "operation" ) );
soapOperation.setStyle( "document" );
//NOTA-BENE: Come settare SOAPACTION? jolie usa SOAP1.1 o 1.2? COme usa la SoapAction?
soapOperation.setSoapActionURI( wsdlOp.getName() );
bindOp.addExtensibilityElement( soapOperation );
bindOp.setOperation( wsdlOp );
// adding input
BindingInput bindingInput = localDef.createBindingInput();
SOAPBody body = (SOAPBody) extensionRegistry.createExtension( BindingInput.class, new QName( NameSpacesEnum.SOAP.getNameSpaceURI(), "body" ) );
body.setUse( "literal" );
bindingInput.addExtensibilityElement( body );
bindOp.setBindingInput( bindingInput );
// adding output
BindingOutput bindingOutput = localDef.createBindingOutput();
bindingOutput.addExtensibilityElement( body );
bindOp.setBindingOutput( bindingOutput );
// adding fault
if ( !wsdlOp.getFaults().isEmpty() ) {
Iterator it = wsdlOp.getFaults().entrySet().iterator();
while ( it.hasNext() ) {
BindingFault bindingFault = localDef.createBindingFault();
SOAPFault soapFault = ( SOAPFault ) extensionRegistry.createExtension( BindingFault.class, new QName( NameSpacesEnum.SOAP.getNameSpaceURI(), "fault" ) );
soapFault.setUse("literal");
String faultName = ((Entry) it.next()).getKey().toString();
bindingFault.setName( faultName );
soapFault.setName( faultName );
bindingFault.addExtensibilityElement( soapFault );
bindOp.addBindingFault( bindingFault );
}
}
bind.addBindingOperation( bindOp );
} catch( WSDLException ex ) {
ex.printStackTrace();
}
}
public Service createService( Definition localdef, String serviceName, Binding bind, String mySOAPAddress )
{
Port p = localDef.createPort();
p.setName( serviceName + "Port" );
try {
SOAPAddress soapAddress = (SOAPAddress) extensionRegistry.createExtension( Port.class, new QName( NameSpacesEnum.SOAP.getNameSpaceURI(), "address" ) );
soapAddress.setLocationURI( mySOAPAddress );
p.addExtensibilityElement( soapAddress );
} catch( WSDLException ex ) {
ex.printStackTrace();
}
p.setBinding( bind );
Service s = new ServiceImpl();
QName serviceQName = new QName( serviceName );
s.setQName( serviceQName );
s.addPort( p );
localDef.addService( s );
return s;
}
private Document createDOMdocument()
{
Document document;
DocumentBuilder db = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware( true );
db = dbf.newDocumentBuilder();
} catch( Exception e ) {
e.printStackTrace();
}
document = db.newDocument();
return document;
}
private Element createSchemaRootElement( Document document )
{
Element rootElement = document.createElement("xs:schema");
rootElement.setAttribute( "xmlns:xs", NameSpacesEnum.XML_SCH.getNameSpaceURI() );
rootElement.setAttribute( "targetNamespace", tns_schema );
rootElement.setAttribute( "xmlns:" + tns_schema_prefix, tns_schema);
document.appendChild( rootElement );
return rootElement;
}
public void setSchemaDocIntoWSDLTypes( Document doc )
{
try {
Types wsdl_types = localDef.createTypes();
Schema typesExt = (Schema) extensionRegistry.createExtension( Types.class, new QName( NameSpacesEnum.XML_SCH.getNameSpaceURI(), "schema" ) );
typesExt.setElement( (Element) doc.getFirstChild() );
wsdl_types.addExtensibilityElement( typesExt );
localDef.setTypes( wsdl_types );
} catch( Exception ex ) {
System.err.println( ex.getMessage() );
}
}
} |
// InputModifiers.java
package imagej.ext;
/**
* A UI-independent representation of keyboard modifier key states.
*
* @author Curtis Rueden
*/
public class InputModifiers {
private final boolean altDown, altGrDown, ctrlDown, metaDown, shiftDown;
private final boolean leftButtonDown, middleButtonDown, rightButtonDown;
public InputModifiers(final boolean altDown,
final boolean altGrDown, final boolean ctrlDown, final boolean metaDown,
final boolean shiftDown, final boolean leftButtonDown,
final boolean middleButtonDown, final boolean rightButtonDown)
{
this.altDown = altDown;
this.altGrDown = altGrDown;
this.ctrlDown = ctrlDown;
this.metaDown = metaDown;
this.shiftDown = shiftDown;
this.leftButtonDown = leftButtonDown;
this.middleButtonDown = middleButtonDown;
this.rightButtonDown = rightButtonDown;
}
public boolean isAltDown() {
return altDown;
}
public boolean isAltGrDown() {
return altGrDown;
}
public boolean isCtrlDown() {
return ctrlDown;
}
public boolean isMetaDown() {
return metaDown;
}
public boolean isShiftDown() {
return shiftDown;
}
public boolean isLeftButtonDown() {
return leftButtonDown;
}
public boolean isMiddleButtonDown() {
return middleButtonDown;
}
public boolean isRightButtonDown() {
return rightButtonDown;
}
// -- Object methods --
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (altDown) sb.append(", Alt");
if (altGrDown) sb.append(", AltGr");
if (ctrlDown) sb.append(", Ctrl");
if (metaDown) sb.append(", Meta");
if (shiftDown) sb.append(", Shift");
if (leftButtonDown) sb.append(", Left Button");
if (middleButtonDown) sb.append(", Middle Button");
if (rightButtonDown) sb.append(", Right Button");
return sb.toString();
}
} |
package bisq.core.locale;
import bisq.core.app.BisqEnvironment;
import bisq.core.btc.BaseCurrencyNetwork;
import bisq.core.dao.governance.asset.AssetService;
import bisq.core.filter.FilterManager;
import bisq.asset.Asset;
import bisq.asset.AssetRegistry;
import bisq.asset.Coin;
import bisq.asset.Token;
import bisq.asset.coins.BSQ;
import bisq.common.app.DevEnv;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import lombok.extern.slf4j.Slf4j;
import static com.google.common.base.Preconditions.checkArgument;
@Slf4j
public class CurrencyUtil {
public static void setup() {
setBaseCurrencyCode(BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode());
}
private static final AssetRegistry assetRegistry = new AssetRegistry();
private static String baseCurrencyCode = "BTC";
private static List<FiatCurrency> allSortedFiatCurrencies;
private static List<CryptoCurrency> allSortedCryptoCurrencies;
public static void setBaseCurrencyCode(String baseCurrencyCode) {
CurrencyUtil.baseCurrencyCode = baseCurrencyCode;
}
public static List<FiatCurrency> getAllSortedFiatCurrencies() {
if (Objects.isNull(allSortedFiatCurrencies))
allSortedFiatCurrencies = createAllSortedFiatCurrenciesList();
return allSortedFiatCurrencies;
}
private static List<FiatCurrency> createAllSortedFiatCurrenciesList() {
return CountryUtil.getAllCountries().stream()
.map(country -> getCurrencyByCountryCode(country.code))
.distinct()
.sorted(TradeCurrency::compareTo)
.collect(Collectors.toList());
}
public static List<FiatCurrency> getMainFiatCurrencies() {
TradeCurrency defaultTradeCurrency = getDefaultTradeCurrency();
List<FiatCurrency> list = new ArrayList<>();
// Top traded currencies
list.add(new FiatCurrency("USD"));
list.add(new FiatCurrency("EUR"));
list.add(new FiatCurrency("GBP"));
list.add(new FiatCurrency("CAD"));
list.add(new FiatCurrency("AUD"));
list.add(new FiatCurrency("RUB"));
list.add(new FiatCurrency("INR"));
list.sort(TradeCurrency::compareTo);
FiatCurrency defaultFiatCurrency =
defaultTradeCurrency instanceof FiatCurrency ? (FiatCurrency) defaultTradeCurrency : null;
if (defaultFiatCurrency != null && list.contains(defaultFiatCurrency)) {
//noinspection SuspiciousMethodCalls
list.remove(defaultTradeCurrency);
list.add(0, defaultFiatCurrency);
}
return list;
}
public static List<CryptoCurrency> getAllSortedCryptoCurrencies() {
if (allSortedCryptoCurrencies == null)
allSortedCryptoCurrencies = createAllSortedCryptoCurrenciesList();
return allSortedCryptoCurrencies;
}
private static List<CryptoCurrency> createAllSortedCryptoCurrenciesList() {
return getSortedAssetStream()
.map(CurrencyUtil::assetToCryptoCurrency)
.collect(Collectors.toList());
}
public static Stream<Asset> getSortedAssetStream() {
return assetRegistry.stream()
.filter(CurrencyUtil::assetIsNotBaseCurrency)
.filter(asset -> isNotBsqOrBsqTradingActivated(asset, BisqEnvironment.getBaseCurrencyNetwork(), DevEnv.isDaoTradingActivated()))
.filter(asset -> assetMatchesNetworkIfMainnet(asset, BisqEnvironment.getBaseCurrencyNetwork()))
.sorted(Comparator.comparing(Asset::getName));
}
public static List<CryptoCurrency> getMainCryptoCurrencies() {
final List<CryptoCurrency> result = new ArrayList<>();
result.add(new CryptoCurrency("XRC", "Bitcoin Rhodium"));
if (DevEnv.isDaoTradingActivated())
result.add(new CryptoCurrency("BSQ", "BSQ"));
result.add(new CryptoCurrency("BEAM", "Beam"));
result.add(new CryptoCurrency("DASH", "Dash"));
result.add(new CryptoCurrency("DCR", "Decred"));
result.add(new CryptoCurrency("ETH", "Ether"));
result.add(new CryptoCurrency("GRIN", "Grin"));
result.add(new CryptoCurrency("LTC", "Litecoin"));
result.add(new CryptoCurrency("XMR", "Monero"));
result.add(new CryptoCurrency("NMC", "Namecoin"));
result.add(new CryptoCurrency("SF", "Siafund"));
result.add(new CryptoCurrency("ZEC", "Zcash"));
result.sort(TradeCurrency::compareTo);
return result;
}
public static List<CryptoCurrency> getRemovedCryptoCurrencies() {
final List<CryptoCurrency> currencies = new ArrayList<>();
currencies.add(new CryptoCurrency("BCH", "Bitcoin Cash"));
currencies.add(new CryptoCurrency("BCHC", "Bitcoin Clashic"));
currencies.add(new CryptoCurrency("ACH", "AchieveCoin"));
currencies.add(new CryptoCurrency("SC", "Siacoin"));
currencies.add(new CryptoCurrency("PPI", "PiedPiper Coin"));
currencies.add(new CryptoCurrency("PEPECASH", "Pepe Cash"));
currencies.add(new CryptoCurrency("GRC", "Gridcoin"));
currencies.add(new CryptoCurrency("LTZ", "LitecoinZ"));
currencies.add(new CryptoCurrency("ZOC", "01coin"));
currencies.add(new CryptoCurrency("BURST", "Burstcoin"));
currencies.add(new CryptoCurrency("STEEM", "Steem"));
currencies.add(new CryptoCurrency("DAC", "DACash"));
currencies.add(new CryptoCurrency("RDD", "ReddCoin"));
return currencies;
}
public static List<TradeCurrency> getAllAdvancedCashCurrencies() {
ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
new FiatCurrency("USD"),
new FiatCurrency("EUR"),
new FiatCurrency("GBP"),
new FiatCurrency("RUB"),
new FiatCurrency("UAH"),
new FiatCurrency("KZT"),
new FiatCurrency("BRL")
));
currencies.sort(Comparator.comparing(TradeCurrency::getCode));
return currencies;
}
public static List<TradeCurrency> getAllMoneyGramCurrencies() {
ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
new FiatCurrency("AED"),
new FiatCurrency("AUD"),
new FiatCurrency("BND"),
new FiatCurrency("CAD"),
new FiatCurrency("CHF"),
new FiatCurrency("CZK"),
new FiatCurrency("DKK"),
new FiatCurrency("EUR"),
new FiatCurrency("FJD"),
new FiatCurrency("GBP"),
new FiatCurrency("HKD"),
new FiatCurrency("HUF"),
new FiatCurrency("IDR"),
new FiatCurrency("ILS"),
new FiatCurrency("INR"),
new FiatCurrency("JPY"),
new FiatCurrency("KRW"),
new FiatCurrency("KWD"),
new FiatCurrency("LKR"),
new FiatCurrency("MAD"),
new FiatCurrency("MGA"),
new FiatCurrency("MXN"),
new FiatCurrency("MYR"),
new FiatCurrency("NOK"),
new FiatCurrency("NZD"),
new FiatCurrency("OMR"),
new FiatCurrency("PEN"),
new FiatCurrency("PGK"),
new FiatCurrency("PHP"),
new FiatCurrency("PKR"),
new FiatCurrency("PLN"),
new FiatCurrency("SAR"),
new FiatCurrency("SBD"),
new FiatCurrency("SCR"),
new FiatCurrency("SEK"),
new FiatCurrency("SGD"),
new FiatCurrency("THB"),
new FiatCurrency("TOP"),
new FiatCurrency("TRY"),
new FiatCurrency("TWD"),
new FiatCurrency("USD"),
new FiatCurrency("VND"),
new FiatCurrency("VUV"),
new FiatCurrency("WST"),
new FiatCurrency("XOF"),
new FiatCurrency("XPF"),
new FiatCurrency("ZAR")
));
currencies.sort(Comparator.comparing(TradeCurrency::getCode));
return currencies;
}
public static List<TradeCurrency> getAllUpholdCurrencies() {
ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
new FiatCurrency("USD"),
new FiatCurrency("EUR"),
new FiatCurrency("GBP"),
new FiatCurrency("CNY"),
new FiatCurrency("JPY"),
new FiatCurrency("CHF"),
new FiatCurrency("INR"),
new FiatCurrency("MXN"),
new FiatCurrency("AUD"),
new FiatCurrency("CAD"),
new FiatCurrency("HKD"),
new FiatCurrency("NZD"),
new FiatCurrency("SGD"),
new FiatCurrency("KES"),
new FiatCurrency("ILS"),
new FiatCurrency("DKK"),
new FiatCurrency("NOK"),
new FiatCurrency("SEK"),
new FiatCurrency("PLN"),
new FiatCurrency("ARS"),
new FiatCurrency("BRL"),
new FiatCurrency("AED"),
new FiatCurrency("PHP")
));
currencies.sort(Comparator.comparing(TradeCurrency::getCode));
return currencies;
}
//https://www.revolut.com/pa/faq#can-i-hold-multiple-currencies
public static List<TradeCurrency> getAllRevolutCurrencies() {
ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
new FiatCurrency("USD"),
new FiatCurrency("GBP"),
new FiatCurrency("EUR"),
new FiatCurrency("PLN"),
new FiatCurrency("CHF"),
new FiatCurrency("DKK"),
new FiatCurrency("NOK"),
new FiatCurrency("SEK"),
new FiatCurrency("RON"),
new FiatCurrency("SGD"),
new FiatCurrency("HKD"),
new FiatCurrency("AUD"),
new FiatCurrency("NZD"),
new FiatCurrency("TRY"),
new FiatCurrency("ILS"),
new FiatCurrency("AED"),
new FiatCurrency("CAD"),
new FiatCurrency("HUF"),
new FiatCurrency("INR"),
new FiatCurrency("JPY"),
new FiatCurrency("MAD"),
new FiatCurrency("QAR"),
new FiatCurrency("THB"),
new FiatCurrency("ZAR")
));
currencies.sort(Comparator.comparing(TradeCurrency::getCode));
return currencies;
}
public static boolean isFiatCurrency(String currencyCode) {
try {
return currencyCode != null
&& !currencyCode.isEmpty()
&& !isCryptoCurrency(currencyCode)
&& Currency.getInstance(currencyCode) != null;
} catch (Throwable t) {
return false;
}
}
public static Optional<FiatCurrency> getFiatCurrency(String currencyCode) {
return getAllSortedFiatCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny();
}
@SuppressWarnings("WeakerAccess")
/**
* We return true if it is BTC or any of our currencies available in the assetRegistry.
* For removed assets it would fail as they are not found but we don't want to conclude that they are fiat then.
* As the caller might not deal with the case that a currency can be neither a cryptoCurrency nor Fiat if not found
* we return true as well in case we have no fiat currency for the code.
*
* As we use a boolean result for isCryptoCurrency and isFiatCurrency we do not treat missing currencies correctly.
* To throw an exception might be an option but that will require quite a lot of code change, so we don't do that
* for the moment, but could be considered for the future. Another maybe better option is to introduce a enum which
* contains 3 entries (CryptoCurrency, Fiat, Undefined).
*/
public static boolean isCryptoCurrency(String currencyCode) {
// Some tests call that method with null values. Should be fixed in the tests but to not break them return false.
if (currencyCode == null)
return false;
// BTC is not part of our assetRegistry so treat it extra here. Other old base currencies (LTC, DOGE, DASH)
// are not supported anymore so we can ignore that case.
if (currencyCode.equals("BTC"))
return true;
// If we find the code in our assetRegistry we return true.
// It might be that an asset was removed from the assetsRegistry, we deal with such cases below by checking if
// it is a fiat currency
if (getCryptoCurrency(currencyCode).isPresent())
return true;
// In case the code is from a removed asset we cross check if there exist a fiat currency with that code,
// if we don't find a fiat currency we treat it as a crypto currency.
if (!getFiatCurrency(currencyCode).isPresent())
return true;
// If we would have found a fiat currency we return false
return false;
}
public static Optional<CryptoCurrency> getCryptoCurrency(String currencyCode) {
return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny();
}
public static Optional<TradeCurrency> getTradeCurrency(String currencyCode) {
Optional<FiatCurrency> fiatCurrencyOptional = getFiatCurrency(currencyCode);
if (isFiatCurrency(currencyCode) && fiatCurrencyOptional.isPresent())
return Optional.of(fiatCurrencyOptional.get());
Optional<CryptoCurrency> cryptoCurrencyOptional = getCryptoCurrency(currencyCode);
if (isCryptoCurrency(currencyCode) && cryptoCurrencyOptional.isPresent())
return Optional.of(cryptoCurrencyOptional.get());
return Optional.empty();
}
public static FiatCurrency getCurrencyByCountryCode(String countryCode) {
if (countryCode.equals("XK"))
return new FiatCurrency("EUR");
Currency currency = Currency.getInstance(new Locale(LanguageUtil.getDefaultLanguage(), countryCode));
return new FiatCurrency(currency.getCurrencyCode());
}
public static String getNameByCode(String currencyCode) {
if (isCryptoCurrency(currencyCode)) {
// We might not find the name in case we have a call for a removed asset.
// If BTC is the code (used in tests) we also want return Bitcoin as name.
final Optional<CryptoCurrency> removedCryptoCurrency = getRemovedCryptoCurrencies().stream()
.filter(cryptoCurrency -> cryptoCurrency.getCode().equals(currencyCode))
.findAny();
String btcOrRemovedAsset = "BTC".equals(currencyCode) ? "Bitcoin" :
removedCryptoCurrency.isPresent() ? removedCryptoCurrency.get().getName() : Res.get("shared.na");
return getCryptoCurrency(currencyCode).map(TradeCurrency::getName).orElse(btcOrRemovedAsset);
}
try {
return Currency.getInstance(currencyCode).getDisplayName();
} catch (Throwable t) {
log.debug("No currency name available {}", t.getMessage());
return currencyCode;
}
}
public static Optional<CryptoCurrency> findCryptoCurrencyByName(String currencyName) {
return getAllSortedCryptoCurrencies().stream()
.filter(e -> e.getName().equals(currencyName))
.findAny();
}
public static String getNameAndCode(String currencyCode) {
return getNameByCode(currencyCode) + " (" + currencyCode + ")";
}
public static TradeCurrency getDefaultTradeCurrency() {
return GlobalSettings.getDefaultTradeCurrency();
}
private static boolean assetIsNotBaseCurrency(Asset asset) {
return !assetMatchesCurrencyCode(asset, baseCurrencyCode);
}
// TODO We handle assets of other types (Token, ERC20) as matching the network which is not correct.
// We should add support for network property in those tokens as well.
public static boolean assetMatchesNetwork(Asset asset, BaseCurrencyNetwork baseCurrencyNetwork) {
return !(asset instanceof Coin) ||
((Coin) asset).getNetwork().name().equals(baseCurrencyNetwork.getNetwork());
}
// We only check for coins not other types of assets (TODO network check should be supported for all assets)
public static boolean assetMatchesNetworkIfMainnet(Asset asset, BaseCurrencyNetwork baseCurrencyNetwork) {
return !(asset instanceof Coin) ||
coinMatchesNetworkIfMainnet((Coin) asset, baseCurrencyNetwork);
}
// We want all coins available also in testnet or regtest for testing purpose
public static boolean coinMatchesNetworkIfMainnet(Coin coin, BaseCurrencyNetwork baseCurrencyNetwork) {
boolean matchesNetwork = assetMatchesNetwork(coin, baseCurrencyNetwork);
return !baseCurrencyNetwork.isMainnet() || matchesNetwork;
}
private static CryptoCurrency assetToCryptoCurrency(Asset asset) {
return new CryptoCurrency(asset.getTickerSymbol(), asset.getName(), asset instanceof Token);
}
private static boolean isNotBsqOrBsqTradingActivated(Asset asset, BaseCurrencyNetwork baseCurrencyNetwork, boolean daoTradingActivated) {
return !(asset instanceof BSQ) ||
daoTradingActivated && assetMatchesNetwork(asset, baseCurrencyNetwork);
}
public static boolean assetMatchesCurrencyCode(Asset asset, String currencyCode) {
return currencyCode.equals(asset.getTickerSymbol());
}
public static Optional<Asset> findAsset(AssetRegistry assetRegistry, String currencyCode,
BaseCurrencyNetwork baseCurrencyNetwork, boolean daoTradingActivated) {
List<Asset> assets = assetRegistry.stream()
.filter(asset -> assetMatchesCurrencyCode(asset, currencyCode)).collect(Collectors.toList());
// If we don't have the ticker symbol we throw an exception
if (!assets.stream().findFirst().isPresent())
return Optional.empty();
if (currencyCode.equals("BSQ") && baseCurrencyNetwork.isMainnet() && !daoTradingActivated)
return Optional.empty();
// We check for exact match with network, e.g. BTC$TESTNET
Optional<Asset> optionalAssetMatchesNetwork = assets.stream()
.filter(asset -> assetMatchesNetwork(asset, baseCurrencyNetwork))
.findFirst();
if (optionalAssetMatchesNetwork.isPresent())
return optionalAssetMatchesNetwork;
// In testnet or regtest we want to show all coins as well. Most coins have only Mainnet defined so we deliver
// that if no exact match was found in previous step
if (!baseCurrencyNetwork.isMainnet()) {
Optional<Asset> optionalAsset = assets.stream().findFirst();
checkArgument(optionalAsset.isPresent(), "optionalAsset must be present as we checked for " +
"not matching ticker symbols already above");
return optionalAsset;
}
// If we are in mainnet we need have a mainet asset defined.
throw new IllegalArgumentException("We are on mainnet and we could not find an asset with network type mainnet");
}
public static Optional<Asset> findAsset(String tickerSymbol) {
return assetRegistry.stream()
.filter(asset -> asset.getTickerSymbol().equals(tickerSymbol))
.findAny();
}
public static Optional<Asset> findAsset(String tickerSymbol, BaseCurrencyNetwork baseCurrencyNetwork) {
return assetRegistry.stream()
.filter(asset -> asset.getTickerSymbol().equals(tickerSymbol))
.filter(asset -> assetMatchesNetwork(asset, baseCurrencyNetwork))
.findAny();
}
// Excludes all assets which got removed by DAO voting
public static List<CryptoCurrency> getActiveSortedCryptoCurrencies(AssetService assetService, FilterManager filterManager) {
return getAllSortedCryptoCurrencies().stream()
.filter(e -> e.getCode().equals("BSQ") || assetService.isActive(e.getCode()))
.filter(e -> !filterManager.isCurrencyBanned(e.getCode()))
.collect(Collectors.toList());
}
} |
package com.github.nyrkovalex.seed;
import com.github.nyrkovalex.seed.Io.Entity;
import com.github.nyrkovalex.seed.Io.Err;
import com.github.nyrkovalex.seed.Io.File;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public final class Io {
private Io() {
// Module
}
/**
* Creates a filesystem abstraction that can be used as an external dependency for your classes
*
* @return {@link Fs} instance
*/
public static Fs fs() {
return IoFs.instance();
}
public interface Entity {
/**
* Check whether file with a given path exists
*
* @return true if file exists on a given path
*/
boolean exists();
/**
* Path current object is bound to
*
* @return target path
*/
String path();
/**
* Delets current {@link Fs.Entity}
*
* @throws Io.Err if something goes wrong
*/
void delete() throws Io.Err;
String name();
}
/**
* Easy to use file abstraction suitable for mocking
*/
public interface File extends Entity {
/**
* Creates a {@link BufferedReader} reading current file bytes
*
* @return {@link BufferedReader} for current file
* @throws IOException if something goes wrong
*/
BufferedReader reader() throws IOException;
/**
* Reads current file as an {@link BufferedReader} passed to the <code>handler</code> provided.
* Stream is being automatically closed after <code>hanlder</code> returns. Result of
* <code>handler</code> invocation is returned from this method as is.
*
* @param <T> type of a result to return
* @param handler function receiving file's {@link BufferedReader} and producing output of type
* <code>T</code>
* @return result of a <code>handler</code> function invocation
* @throws Io.Err if something goes wrong during I/O
*/
<T> T reader(Function<BufferedReader, T> handler) throws Io.Err;
/**
* Reads current file as an {@link InputStream}
*
* @return {@link InputStream} of a current file
* @throws Io.Err if something goes wrong
*/
InputStream stream() throws Io.Err;
/**
* Reads current file as an {@link InputStream} passed to the <code>handler</code> provided.
* Reader is being automatically closed after <code>hanlder</code> returns. Result of
* <code>handler</code> invocation is returned from this method as is.
*
* @param <T> type of a result to return
* @param handler function receiving file's {@link InputStream} and producing output of type
* <code>T</code>
* @return result of a <code>handler</code> function invocation
* @throws Io.Err if something goes wrong during I/O
*/
<T> T stream(Function<InputStream, T> handler) throws Io.Err;
/**
* Reads target file contents to a single String
*
* @return target file content as a single String
* @throws Io.Err if something goes wrong
*/
String string() throws Io.Err;
/**
* Writes bytes to a current file
*
* @param data bytes to write
* @throws Io.Err if something goes wrong
*/
void write(byte[] data) throws Io.Err;
/**
* Writes to current file using its {@link BufferedWriter} passed to the <code>handler</code>
* provided. Writer is being automatically closed after <code>hanlder</code> returns.
*
* @param handler function receiving file's {@link BufferedWriter}
* @throws Io.Err if something goes wrong during I/O
*/
void write(Consumer<BufferedWriter> handler) throws Io.Err;
void copyTo(File target) throws Io.Err;
}
public interface Dir extends Entity {
Stream<Entity> stream() throws Err;
}
/**
* Filesystem abstraction mostly for dependency injection and easy mocking
*/
public interface Fs {
/**
* Creates a {@link Io.File} instance on a given path
*
* @param first first part of a file path
* @param more other parts of a file path
* @return {@link Io.File} instance bound to a given path
* @throws Io.Err if this <code>path</code> corresponds to a directory
*/
File file(String first, String... more) throws Io.Err;
/**
* Creates a {@link Io.Dir} instance on a given path
*
* @param first first part of a dir path
* @param more other parts of a dir path
* @return {@link Io.Dir} object bound to a given path
* @throws Io.Err if <code>path</code> corresponds to a file
*/
Dir dir(String first, String... more) throws Io.Err;
/**
* Creates a directory in a system standard tmp location
*
* @return temporary {@link Io.Dir}
* @throws Io.Err if something goes wrong
*/
Dir tempDir() throws Io.Err;
}
/**
* This exception is thrown when something goes fubar during I/O. See its reason for details.
*/
public static class Err extends Exception {
Err(String message) {
super(message);
}
Err(Throwable cause) {
super(cause);
}
static Io.Err from(Exception ex) {
if (ex instanceof Io.Err) {
return (Io.Err) ex;
}
return new Io.Err(ex);
}
}
private static abstract class IoEntity implements Io.Entity {
protected final Path path;
IoEntity(String first, String... more) {
this(Paths.get(first, more));
}
IoEntity(Path path) {
this.path = path;
}
@Override
public String path() {
return path.toString();
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " at " + path;
}
@Override
public String name() {
return path.getFileName().toString();
}
}
private static class IoFile extends IoEntity implements Io.File {
IoFile(String first, String... more) throws Err {
super(first, more);
throwIfDirectory();
}
private void throwIfDirectory() throws Err {
if (Files.isDirectory(path)) {
throw new Io.Err(path() + " is a directory");
}
}
IoFile(Path path) throws Err {
super(path);
throwIfDirectory();
}
@Override
public void write(byte[] data) throws Io.Err {
Errors.rethrow(() -> Files.write(path, data), Err::from);
}
@Override
public void write(Consumer<BufferedWriter> handler) throws Io.Err {
Errors.rethrow(() -> {
try (final BufferedWriter writer = Files.newBufferedWriter(path)) {
handler.accept(writer);
}
}, Err::from);
}
@Override
public boolean exists() {
return Files.exists(path);
}
@Override
public String string() throws Io.Err {
return Errors.rethrow(() -> new String(Files.readAllBytes(path)), Err::from);
}
@Override
public BufferedReader reader() throws IOException {
return Files.newBufferedReader(path);
}
@Override
public <T> T reader(Function<BufferedReader, T> handler) throws Io.Err {
return Errors.rethrow(() -> {
try (final BufferedReader reader = reader()) {
return handler.apply(reader);
}
}, Err::from);
}
@Override
public InputStream stream() throws Io.Err {
return Errors.rethrow(() -> Files.newInputStream(path), Err::from);
}
@Override
public <T> T stream(Function<InputStream, T> handler) throws Io.Err {
return Errors.rethrow(() -> {
try (final InputStream stream = stream()) {
return handler.apply(stream);
}
}, Err::from);
}
@Override
public void delete() throws Err {
Errors.rethrow(() -> Files.delete(path), Err::from);
}
@Override
public void copyTo(File target) throws Err {
Errors.rethrow(() -> Files.copy(
this.path,
((IoEntity) target).path,
StandardCopyOption.REPLACE_EXISTING
), Err::from);
}
}
private static class IoDir extends IoEntity implements Io.Dir {
IoDir(String first, String... more) throws Err {
super(first, more);
throwIfFile();
}
IoDir(Path path) throws Err {
super(path);
throwIfFile();
}
private void throwIfFile() throws Err {
if (!Files.isDirectory(path)) {
throw new Io.Err(path() + " is a directory");
}
}
@Override
public boolean exists() {
return Files.exists(path) && Files.isDirectory(path);
}
@Override
public void delete() throws Io.Err {
for (Io.Entity e : stream().collect(Collectors.toList())) {
e.delete();
}
Errors.rethrow(() -> Files.delete(path), Err::from);
}
@Override
public Stream<Io.Entity> stream() throws Io.Err {
Errors.Catcher<Err> error = Errors.catcher(Io.Err.class);
Stream<Io.Entity> stream = Errors.rethrow(() -> Files
.list(path)
.map(f -> error.safeCall(() -> Files.isDirectory(f)
? new IoDir(f)
: new IoFile(f))), Err::from)
.filter(Optional::isPresent)
.map(Optional::get);
error.rethrow();
return stream;
}
}
private static class IoFs implements Io.Fs {
private static final IoFs INSTANCE = new IoFs();
public static IoFs instance() {
return INSTANCE;
}
private IoFs() {
}
@Override
public Io.File file(String first, String... more) throws Err {
return new IoFile(first, more);
}
@Override
public Io.Dir tempDir() throws Io.Err {
return Errors.rethrow(() -> new IoDir(Files.createTempDirectory("")), Err::from);
}
@Override
public Io.Dir dir(String first, String... more) throws Err {
return new IoDir(first, more);
}
}
} |
package nl.mpi.arbil;
import nl.mpi.arbil.templates.ArbilTemplateManager;
import nl.mpi.arbil.templates.ArbilTemplate;
import nl.mpi.arbil.importexport.ImportExportDialog;
import nl.mpi.arbil.data.ImdiTreeObject;
import java.awt.Component;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.tree.DefaultMutableTreeNode;
import nl.mpi.arbil.clarin.CmdiComponentBuilder;
import nl.mpi.arbil.data.ImdiLoader;
import nl.mpi.arbil.data.MetadataBuilder;
import nl.mpi.arbil.importexport.ArbilCsvImporter;
import nl.mpi.arbil.templates.ArbilTemplateManager.MenuItemData;
public class ContextMenu {
private JMenu addFromFavouritesMenu;
private JMenuItem addLocalDirectoryMenuItem;
private JCheckBoxMenuItem showHiddenFilesMenuItem;
private JMenuItem addDefaultLocationsMenuItem;
private JMenu addMenu;
private JMenuItem addRemoteCorpusMenuItem;
private JMenuItem addToFavouritesMenuItem;
private JMenuItem copyBranchMenuItem;
private JMenuItem searchRemoteBranchMenuItem;
private JMenuItem copyImdiUrlMenuItem;
private JMenuItem deleteMenuItem;
private JMenuItem exportMenuItem;
private JMenuItem importCsvMenuItem;
private JMenuItem importBranchMenuItem;
private JMenuItem reImportBranchMenuItem;
// private JMenu favouritesMenu;
private JMenu mergeWithFavouritesMenu;
private JMenuItem pasteMenuItem1;
private JMenuItem reloadSubnodesMenuItem;
private JMenuItem removeCachedCopyMenuItem;
private JMenuItem removeLocalDirectoryMenuItem;
private JMenuItem removeRemoteCorpusMenuItem;
private JMenuItem saveMenuItem;
private JMenuItem searchSubnodesMenuItem;
private JMenuItem sendToServerMenuItem;
private JPopupMenu treePopupMenu;
// private JSeparator treePopupMenuSeparator1;
// private JSeparator treePopupMenuSeparator2;
private JMenuItem validateMenuItem;
private JMenu historyMenu;
private JMenuItem viewChangesMenuItem;
private JMenuItem browseForResourceFileMenuItem;
private JMenuItem viewSelectedNodesMenuItem;
private JMenuItem viewXmlMenuItem;
private JMenuItem viewInBrrowserMenuItem;
private JMenuItem viewXmlMenuItemFormatted;
private JMenuItem openXmlMenuItemFormatted;
private JMenuItem exportHtmlMenuItemFormatted;
private JMenuItem overrideTypeCheckerDecision;
static private ContextMenu singleInstance = null;
// table menu items
private JMenuItem copySelectedRowsMenuItem;
private JMenuItem pasteIntoSelectedRowsMenuItem;
private JMenuItem viewSelectedRowsMenuItem;
private JMenuItem matchingRowsMenuItem;
private JMenuItem removeSelectedRowsMenuItem;
private JMenuItem hideSelectedColumnsMenuItem;
private JMenuItem searchReplaceMenuItem;
private JMenuItem deleteFieldMenuItem;
private JMenuItem revertFieldMenuItem;
private JMenuItem copyCellToColumnMenuItem;
// private JSeparator cellMenuDivider;
// private JSeparator cellTableDivider;
private JMenuItem matchingCellsMenuItem;
private JMenuItem openInLongFieldEditorMenuItem;
private JMenuItem clearCellColoursMenuItem;
private JMenuItem jumpToNodeInTreeMenuItem;
private JMenuItem showChildNodesMenuItem;
ImdiTreeObject[] selectedTreeNodes = null;
ImdiTreeObject leadSelectedTreeNode = null;
ImdiTable currentTable = null;
static synchronized public ContextMenu getSingleInstance() {
// TODO: this should really be removed and a new instance made each time
System.out.println("ContextMenu getSingleInstance");
if (singleInstance == null) {
singleInstance = new ContextMenu();
}
return singleInstance;
}
private ContextMenu() {
treePopupMenu = new JPopupMenu();
viewSelectedNodesMenuItem = new JMenuItem();
copyImdiUrlMenuItem = new JMenuItem();
pasteMenuItem1 = new JMenuItem();
copyBranchMenuItem = new JMenuItem();
searchRemoteBranchMenuItem = new JMenuItem();
searchSubnodesMenuItem = new JMenuItem();
reloadSubnodesMenuItem = new JMenuItem();
addMenu = new JMenu();
// favouritesMenu = new JMenu();
addToFavouritesMenuItem = new JMenuItem();
addFromFavouritesMenu = new JMenu();
mergeWithFavouritesMenu = new JMenu();
deleteMenuItem = new JMenuItem();
// treePopupMenuSeparator1 = new JSeparator();
viewXmlMenuItem = new JMenuItem();
viewXmlMenuItemFormatted = new JMenuItem();
openXmlMenuItemFormatted = new JMenuItem();
exportHtmlMenuItemFormatted = new JMenuItem();
overrideTypeCheckerDecision = new JMenuItem();
viewInBrrowserMenuItem = new JMenuItem();
browseForResourceFileMenuItem = new JMenuItem();
validateMenuItem = new JMenuItem();
historyMenu = new JMenu();
// treePopupMenuSeparator2 = new JSeparator();
addRemoteCorpusMenuItem = new JMenuItem();
addDefaultLocationsMenuItem = new JMenuItem();
removeRemoteCorpusMenuItem = new JMenuItem();
removeCachedCopyMenuItem = new JMenuItem();
addLocalDirectoryMenuItem = new JMenuItem();
showHiddenFilesMenuItem = new JCheckBoxMenuItem();
removeLocalDirectoryMenuItem = new JMenuItem();
saveMenuItem = new JMenuItem();
viewChangesMenuItem = new JMenuItem();
sendToServerMenuItem = new JMenuItem();
exportMenuItem = new JMenuItem();
importCsvMenuItem = new JMenuItem();
importBranchMenuItem = new JMenuItem();
reImportBranchMenuItem = new JMenuItem();
// table menu items
copySelectedRowsMenuItem = new JMenuItem();
pasteIntoSelectedRowsMenuItem = new JMenuItem();
viewSelectedRowsMenuItem = new JMenuItem();
matchingRowsMenuItem = new JMenuItem();
removeSelectedRowsMenuItem = new JMenuItem();
hideSelectedColumnsMenuItem = new JMenuItem();
searchReplaceMenuItem = new JMenuItem();
deleteFieldMenuItem = new JMenuItem();
revertFieldMenuItem = new JMenuItem();
copyCellToColumnMenuItem = new JMenuItem();
// cellMenuDivider = new JSeparator();
// cellTableDivider = new JSeparator();
matchingCellsMenuItem = new JMenuItem();
openInLongFieldEditorMenuItem = new JMenuItem();
clearCellColoursMenuItem = new JMenuItem();
jumpToNodeInTreeMenuItem = new JMenuItem();
showChildNodesMenuItem = new JMenuItem();
// table menu items
copySelectedRowsMenuItem.setText("Copy");
copySelectedRowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.copySelectedTableRowsToClipBoard();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(copySelectedRowsMenuItem);
pasteIntoSelectedRowsMenuItem.setText("Paste");
pasteIntoSelectedRowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.pasteIntoSelectedTableRowsFromClipBoard();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(pasteIntoSelectedRowsMenuItem);
treePopupMenu.add(new JSeparator());
// field menu items
openInLongFieldEditorMenuItem.setText("Open in Long Field Editor");
openInLongFieldEditorMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.startLongFieldEditorForSelectedFields();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(openInLongFieldEditorMenuItem);
hideSelectedColumnsMenuItem.setText("Hide Selected Columns");
hideSelectedColumnsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.hideSelectedColumnsFromTable();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(hideSelectedColumnsMenuItem);
showChildNodesMenuItem.setText("Show Child Nodes");
showChildNodesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.showRowChildData();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(showChildNodesMenuItem);
deleteFieldMenuItem.setText("Delete MultiField");
deleteFieldMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ImdiField[] selectedFields = currentTable.getSelectedFields();
if (selectedFields != null) {
// to delete these fields they must be separated into imdi tree objects and request delete for each one
// todo: the delete field action should also be available in the long field editor
Hashtable<ImdiTreeObject, ArrayList> selectedFieldHashtable = new Hashtable<ImdiTreeObject, ArrayList>();
for (ImdiField currentField : selectedFields) {
ArrayList currentList = selectedFieldHashtable.get(currentField.parentImdi);
if (currentList == null) {
currentList = new ArrayList();
selectedFieldHashtable.put(currentField.parentImdi, currentList);
}
currentList.add(currentField.getFullXmlPath());
}
for (ImdiTreeObject currentImdiObject : selectedFieldHashtable.keySet()) {
CmdiComponentBuilder componentBuilder = new CmdiComponentBuilder();
boolean result = componentBuilder.removeChildNodes(currentImdiObject, (String[]) selectedFieldHashtable.get(currentImdiObject).toArray(new String[]{}));
if (result) {
currentImdiObject.reloadNode();
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Error deleting fields, check the log file via the help menu for more information.", "Delete Field");
}
//currentImdiObject.deleteFromDomViaId((String[]) selectedFieldHashtable.get(currentImdiObject).toArray(new String[]{}));
// GuiHelper.linorgBugCatcher.logError(new Exception("deleteFromDomViaId"));
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(deleteFieldMenuItem);
revertFieldMenuItem.setText("Revert Selected Fields");
revertFieldMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ImdiField[] selectedFields = currentTable.getSelectedFields();
if (selectedFields != null) {
for (ImdiField currentField : selectedFields) {
currentField.revertChanges();
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(revertFieldMenuItem);
copyCellToColumnMenuItem.setText("Copy Cell to Whole Column"); // NOI18N
copyCellToColumnMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO: change this to copy to selected rows
if (!(currentTable.imdiTableModel.getValueAt(currentTable.getSelectedRow(), currentTable.getSelectedColumn()) instanceof ImdiField)) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Cannot copy this type of field", "Copy Cell to Whole Column");
} else if (0 == JOptionPane.showConfirmDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "About to replace all values in column \"" + currentTable.imdiTableModel.getColumnName(currentTable.getSelectedColumn()) + "\"\nwith the value \"" + currentTable.imdiTableModel.getValueAt(currentTable.getSelectedRow(), currentTable.getSelectedColumn()) + "\"\n(<multiple values> will not be affected)", "Copy cell to whole column", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE)) {
currentTable.imdiTableModel.copyCellToColumn(currentTable.getSelectedRow(), currentTable.getSelectedColumn());
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(copyCellToColumnMenuItem);
matchingCellsMenuItem.setText("Highlight Matching Cells");
matchingCellsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.imdiTableModel.highlightMatchingCells(currentTable.getSelectedRow(), currentTable.getSelectedColumn());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(matchingCellsMenuItem);
clearCellColoursMenuItem.setText("Clear Cell Highlight"); // NOI18N
clearCellColoursMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.imdiTableModel.clearCellColours();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(clearCellColoursMenuItem);
searchReplaceMenuItem.setText("Find/Replace");
searchReplaceMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
((LinorgSplitPanel) currentTable.getParent().getParent().getParent().getParent()).showSearchPane();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(searchReplaceMenuItem);
treePopupMenu.add(new JSeparator());
// row menu items
viewSelectedRowsMenuItem.setText("View Selected Rows");
viewSelectedRowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.viewSelectedTableRows();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(viewSelectedRowsMenuItem);
matchingRowsMenuItem.setText("Select Matching Rows"); // NOI18N
matchingRowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.highlightMatchingRows();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(matchingRowsMenuItem);
removeSelectedRowsMenuItem.setText("Remove Selected Rows");
removeSelectedRowsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
currentTable.removeSelectedRowsFromTable();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(removeSelectedRowsMenuItem);
jumpToNodeInTreeMenuItem.setText("Jump to in Tree"); // NOI18N
jumpToNodeInTreeMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
TreeHelper.getSingleInstance().jumpToSelectionInTree(false, currentTable.getImdiNodeForSelection());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(jumpToNodeInTreeMenuItem);
treePopupMenu.add(new JSeparator());
viewSelectedNodesMenuItem.setText("View Selected");
viewSelectedNodesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ArrayList<ImdiTreeObject> filteredNodes = new ArrayList<ImdiTreeObject>();
for (ImdiTreeObject currentItem : ((ImdiTree) treePopupMenu.getInvoker()).getSelectedNodes()) {
if (currentItem.isMetaDataNode() || currentItem.getFields().size() > 0) {
filteredNodes.add(currentItem);
} else {
try {
LinorgWindowManager.getSingleInstance().openUrlWindowOnce(currentItem.toString(), currentItem.getURI().toURL());
} catch (MalformedURLException murle) {
GuiHelper.linorgBugCatcher.logError(murle);
}
}
}
if (filteredNodes.size() > 0) {
LinorgWindowManager.getSingleInstance().openFloatingTableOnce(filteredNodes.toArray(new ImdiTreeObject[]{}), null);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(viewSelectedNodesMenuItem);
copyImdiUrlMenuItem.setText("Copy");
copyImdiUrlMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
if (selectedTreeNodes == null) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("No node selected", "Copy");
} else {
ImdiTree sourceTree = (ImdiTree) treePopupMenu.getInvoker();
sourceTree.copyNodeUrlToClipboard(selectedTreeNodes);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(copyImdiUrlMenuItem);
pasteMenuItem1.setText("Paste");
pasteMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
currentNode.pasteIntoNode();
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(pasteMenuItem1);
searchRemoteBranchMenuItem.setText("Search Remote Corpus");
searchRemoteBranchMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
searchRemoteSubnodesMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(searchRemoteBranchMenuItem);
copyBranchMenuItem.setText("Import to Local Corpus");
copyBranchMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
copyBranchMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(copyBranchMenuItem);
searchSubnodesMenuItem.setText("Search");
searchSubnodesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
searchSubnodesMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(searchSubnodesMenuItem);
reloadSubnodesMenuItem.setText("Reload");
reloadSubnodesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
// this reload will first clear the save is required flag then reload
currentNode.reloadNode();
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(reloadSubnodesMenuItem);
addMenu.setText("Add");
addMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
try {
initAddMenu(addMenu, leadSelectedTreeNode);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(addMenu);
// favouritesMenu.setText("Favourites");
addFromFavouritesMenu.setText("Add From Favourites");
addFromFavouritesMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
initAddFromFavouritesMenu();
}
});
treePopupMenu.add(addFromFavouritesMenu);
// favouritesMenu.add(addFromFavouritesMenu);
addToFavouritesMenuItem.setText("Set As Favourite");
addToFavouritesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
LinorgFavourites.getSingleInstance().toggleFavouritesList(((ImdiTree) treePopupMenu.getInvoker()).getSelectedNodes(), addToFavouritesMenuItem.getActionCommand().equals("true"));
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(addToFavouritesMenuItem);
mergeWithFavouritesMenu.setText("Merge With Favourite");
mergeWithFavouritesMenu.setActionCommand("Merge With Favouurite");
browseForResourceFileMenuItem.setText("Browse For Resource File");
browseForResourceFileMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
File[] selectedFiles = LinorgWindowManager.getSingleInstance().showFileSelectBox("Select Resource File", false, false, false);
if (selectedFiles != null && selectedFiles.length > 0) {
leadSelectedTreeNode.resourceUrlField.setFieldValue(selectedFiles[0].toURL().toExternalForm(), true, false);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(browseForResourceFileMenuItem);
// favouritesMenu.add(mergeWithFavouritesMenu);
deleteMenuItem.setText("Delete");
deleteMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
TreeHelper.getSingleInstance().deleteNode(treePopupMenu.getInvoker());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(deleteMenuItem);
treePopupMenu.add(new JSeparator());
overrideTypeCheckerDecision.setText("Override Type Checker Decision");
overrideTypeCheckerDecision.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
String titleString = "Override Type Checker Decision";
String messageString = "The type checker does not recognise the selected file/s, which means that they\nare not an archivable type. This action will override that decision and allow you\nto add the file/s to a session, as either media or written resources,\nhowever it might not be possible to import the result to the copus server.";
String[] optionStrings = {"WrittenResource", "MediaFile", "Cancel"};
int userSelection = JOptionPane.showOptionDialog(LinorgWindowManager.getSingleInstance().linorgFrame.getContentPane(), messageString, titleString, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, optionStrings, optionStrings[2]);
if (optionStrings[userSelection].equals("WrittenResource") || optionStrings[userSelection].equals("MediaFile")) {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
if (currentNode.mpiMimeType == null) {
currentNode.mpiMimeType = "Manual/" + optionStrings[userSelection];
currentNode.typeCheckerMessage = "Manually overridden (might not be compatible with the archive)";
currentNode.clearIcon();
}
}
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(overrideTypeCheckerDecision);
viewInBrrowserMenuItem.setText("Open in External Application");
todo: add custom applicaitons menu with dialogue to enter them: suffix, switches, applicaiton file
viewInBrrowserMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
openFileInBrowser(selectedTreeNodes);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(viewInBrrowserMenuItem);
viewXmlMenuItem.setText("View XML");
viewXmlMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
GuiHelper.getSingleInstance().openImdiXmlWindow(currentNode, false, false);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(viewXmlMenuItem);
viewXmlMenuItemFormatted.setText("View IMDI Formatted");
viewXmlMenuItemFormatted.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
GuiHelper.getSingleInstance().openImdiXmlWindow(currentNode, true, false);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(viewXmlMenuItemFormatted);
openXmlMenuItemFormatted.setText("Open IMDI Formatted");
openXmlMenuItemFormatted.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
GuiHelper.getSingleInstance().openImdiXmlWindow(currentNode, true, true);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(openXmlMenuItemFormatted);
exportHtmlMenuItemFormatted.setText("Export IMDI to HTML");
exportHtmlMenuItemFormatted.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
new ImdiToHtmlConverter().exportImdiToHtml(selectedTreeNodes);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(exportHtmlMenuItemFormatted);
validateMenuItem.setText("Check XML Conformance");
validateMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
validateMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(validateMenuItem);
historyMenu.setText("History");
historyMenu.addMenuListener(new javax.swing.event.MenuListener() {
public void menuCanceled(javax.swing.event.MenuEvent evt) {
}
public void menuDeselected(javax.swing.event.MenuEvent evt) {
}
public void menuSelected(javax.swing.event.MenuEvent evt) {
try {
initHistoryMenu();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(historyMenu);
treePopupMenu.add(new JSeparator());
addRemoteCorpusMenuItem.setText("Add Remote Location");
addRemoteCorpusMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
addRemoteCorpusMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(addRemoteCorpusMenuItem);
addDefaultLocationsMenuItem.setText("Add Default Remote Locations");
addDefaultLocationsMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
addDefaultLocationsMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(addDefaultLocationsMenuItem);
removeRemoteCorpusMenuItem.setText("Remove Remote Location");
removeRemoteCorpusMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject selectedNode : selectedTreeNodes) {
TreeHelper.getSingleInstance().removeLocation(selectedNode);
}
TreeHelper.getSingleInstance().applyRootLocations();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(removeRemoteCorpusMenuItem);
removeCachedCopyMenuItem.setText("Remove Cache Link");
removeCachedCopyMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
removeCachedCopyMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(removeCachedCopyMenuItem);
addLocalDirectoryMenuItem.setText("Add Working Directory");
addLocalDirectoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
addLocalDirectoryMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(addLocalDirectoryMenuItem);
showHiddenFilesMenuItem.setText("Show Hidden Files");
showHiddenFilesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
TreeHelper.getSingleInstance().setShowHiddenFilesInTree(showHiddenFilesMenuItem.getState());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(showHiddenFilesMenuItem);
removeLocalDirectoryMenuItem.setText("Remove Link to Directory");
removeLocalDirectoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject selectedNode : selectedTreeNodes) {
TreeHelper.getSingleInstance().removeLocation(selectedNode);
}
TreeHelper.getSingleInstance().applyRootLocations();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(removeLocalDirectoryMenuItem);
saveMenuItem.setText("Save Changes to Disk");
saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject selectedNode : selectedTreeNodes) {
System.out.println("userObject: " + selectedNode);
// reloading will first check if a save is required then save and reload
ImdiLoader.getSingleInstance().requestReload((ImdiTreeObject) selectedNode.getParentDomNode());
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(saveMenuItem);
viewChangesMenuItem.setText("View Changes");
viewChangesMenuItem.setEnabled(false);
viewChangesMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
// LinorgWindowManager.getSingleInstance().openDiffWindow(currentNode);
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(viewChangesMenuItem);
sendToServerMenuItem.setText("Send to Server");
sendToServerMenuItem.setEnabled(false);
sendToServerMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
sendToServerMenuItemActionPerformed(evt);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(sendToServerMenuItem);
exportMenuItem.setText("Export");
exportMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ImportExportDialog importExportDialog = new ImportExportDialog(TreeHelper.getSingleInstance().arbilTreePanel.remoteCorpusTree);
importExportDialog.selectExportDirectoryAndExport(((ImdiTree) treePopupMenu.getInvoker()).getSelectedNodes());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(exportMenuItem);
importCsvMenuItem.setText("Import CSV");
importCsvMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ArbilCsvImporter csvImporter = new ArbilCsvImporter(leadSelectedTreeNode);
csvImporter.doImport();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(importCsvMenuItem);
importBranchMenuItem.setText("Import Branch");
importBranchMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ImportExportDialog importExportDialog = new ImportExportDialog(TreeHelper.getSingleInstance().arbilTreePanel.localCorpusTree); // TODO: this may not always be to correct component and this code should be updated
importExportDialog.setDestinationNode(leadSelectedTreeNode);
importExportDialog.importImdiBranch();
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(importBranchMenuItem);
reImportBranchMenuItem.setText("Re-Import this Branch");
reImportBranchMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
URI remoteImdiFile = LinorgSessionStorage.getSingleInstance().getOriginatingUri(leadSelectedTreeNode.getURI());
if (remoteImdiFile != null) {
ImdiTreeObject originatingNode = ImdiLoader.getSingleInstance().getImdiObjectWithoutLoading(remoteImdiFile);
if (originatingNode.isLocal() && !originatingNode.getFile().exists()) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The origional file location cannot be found", "Re Import Branch");
} else if (originatingNode.isMetaDataNode()) {
ImportExportDialog importExportDialog = new ImportExportDialog(TreeHelper.getSingleInstance().arbilTreePanel.localCorpusTree); // TODO: this may not always be to correct component and this code should be updated
importExportDialog.setDestinationNode(leadSelectedTreeNode); // TODO: do not re add the location in this case
importExportDialog.copyToCache(new ImdiTreeObject[]{originatingNode});
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Could not determine the origional node type", "Re Import Branch");
}
} else {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Could not determine the origional location", "Re Import Branch");
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
treePopupMenu.add(reImportBranchMenuItem);
}
private void copyBranchMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (treePopupMenu.getInvoker() instanceof JTree) {
try {
ImportExportDialog importExportDialog = new ImportExportDialog(treePopupMenu.getInvoker());
importExportDialog.copyToCache(((ImdiTree) treePopupMenu.getInvoker()).getSelectedNodes());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
}
private void addLocalDirectoryMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
File[] selectedFiles = LinorgWindowManager.getSingleInstance().showFileSelectBox("Add Working Directory", true, true, false);
if (selectedFiles != null && selectedFiles.length > 0) {
for (File currentDirectory : selectedFiles) {
TreeHelper.getSingleInstance().addLocationGui(currentDirectory.toURI());
}
}
}
private void addRemoteCorpusMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
String addableLocation = (String) JOptionPane.showInputDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "Enter the URL", "Add Location", JOptionPane.PLAIN_MESSAGE);
if ((addableLocation != null) && (addableLocation.length() > 0)) {
TreeHelper.getSingleInstance().addLocationGui(ImdiTreeObject.conformStringToUrl(addableLocation));
}
}
private void addDefaultLocationsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
if (0 < TreeHelper.getSingleInstance().addDefaultCorpusLocations()) {
TreeHelper.getSingleInstance().applyRootLocations();
} else {
// alert the user when the node already exists and cannot be added again
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("The default locations already exists and will not be added again", "Add Default Locations");
}
}
private void removeCachedCopyMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
DefaultMutableTreeNode selectedTreeNode = null;
}
private void searchSubnodesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
LinorgWindowManager.getSingleInstance().openSearchTable(((ImdiTree) TreeHelper.getSingleInstance().arbilTreePanel.localCorpusTree).getSelectedNodes(), "Search");
}
private void searchRemoteSubnodesMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
LinorgWindowManager.getSingleInstance().openSearchTable(((ImdiTree) TreeHelper.getSingleInstance().arbilTreePanel.remoteCorpusTree).getSelectedNodes(), "Search Remote Corpus");
}
private void sendToServerMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
}
private void validateMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
for (ImdiTreeObject currentNode : selectedTreeNodes) {
// todo: offer to save node first
XsdChecker xsdChecker = new XsdChecker();
LinorgWindowManager.getSingleInstance().createWindow("XsdChecker", xsdChecker);
xsdChecker.checkXML(currentNode);
xsdChecker.setDividerLocation(0.5);
}
}
private void openFileInBrowser(ImdiTreeObject[] selectedNodes) {
for (ImdiTreeObject currentNode : selectedNodes) {
URI targetUri = null;
if (currentNode.hasResource()) {
targetUri = currentNode.getFullResourceURI();
} else {
targetUri = currentNode.getURI();
}
GuiHelper.getSingleInstance().openFileInExternalApplication(targetUri);
}
}
public void initAddMenu(JMenu addMenu, Object targetNodeUserObject) {
boolean menuItemsAdded = false;
addMenu.removeAll();
// System.out.println("initAddMenu: " + targetNodeUserObject);
ArbilTemplate currentTemplate;
if (targetNodeUserObject instanceof ImdiTreeObject && !((ImdiTreeObject) targetNodeUserObject).isCorpus()) {
ImdiIcons imdiIcons = ImdiIcons.getSingleInstance();
currentTemplate = ((ImdiTreeObject) targetNodeUserObject).getNodeTemplate();
for (Enumeration menuItemName = currentTemplate.listTypesFor(targetNodeUserObject); menuItemName.hasMoreElements();) {
String[] currentField = (String[]) menuItemName.nextElement();
// System.out.println("MenuText: " + currentField[0]);
// System.out.println("ActionCommand: " + currentField[1]);
JMenuItem addMenuItem;
addMenuItem = new JMenuItem();
addMenuItem.setText(currentField[0]);
addMenuItem.setName(currentField[0]);
addMenuItem.setToolTipText(currentField[1]);
addMenuItem.setActionCommand(currentField[1]);
if (null != currentTemplate.pathIsChildNode(currentField[1])) {
addMenuItem.setIcon(imdiIcons.dataIcon);
} else {
addMenuItem.setIcon(imdiIcons.fieldIcon);
}
addMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
// boolean nodesFoundToAddTo = false;
// for (ImdiTreeObject currentNode : selectedTreeNodes) {
// if (currentNode != null) {
// currentNode.requestAddNode(evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
// nodesFoundToAddTo = true;
// if (!nodesFoundToAddTo) {
// // no nodes found that were valid imdi tree objects so we can assume that tis is the tree root
// ImdiTreeObject imdiTreeObject;
// imdiTreeObject = new ImdiTreeObject(LinorgSessionStorage.getSingleInstance().getSaveLocation(LinorgSessionStorage.getSingleInstance().getNewImdiFileName()));
// imdiTreeObject.requestAddNode(evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
if (leadSelectedTreeNode != null) {
new MetadataBuilder().requestAddNode(leadSelectedTreeNode, evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
} else {
// no nodes found that were valid imdi tree objects so we can assume that tis is the tree root
new MetadataBuilder().requestRootAddNode(evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
addMenu.add(addMenuItem);
menuItemsAdded = true;
}
} else {
// consume the selected templates here rather than the clarin profile list
for (MenuItemData currentAddable : ArbilTemplateManager.getSingleInstance().getSelectedTemplates()) {
JMenuItem addMenuItem;
addMenuItem = new JMenuItem();
addMenuItem.setText(currentAddable.menuText);
addMenuItem.setName(currentAddable.menuText);
addMenuItem.setActionCommand(currentAddable.menuAction);
addMenuItem.setToolTipText(currentAddable.menuToolTip);
addMenuItem.setIcon(currentAddable.menuIcon);
addMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
if (leadSelectedTreeNode != null) {
new MetadataBuilder().requestAddNode(leadSelectedTreeNode, evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
} else {
// no nodes found that were valid imdi tree objects so we can assume that tis is the tree root
new MetadataBuilder().requestRootAddNode(evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
addMenu.add(addMenuItem);
}
//if ((targetNodeUserObject instanceof ImdiTreeObject && ((ImdiTreeObject) targetNodeUserObject).isCorpus()) || !(targetNodeUserObject instanceof ImdiTreeObject)) {
// Allow clarin add menu for corpus nodes and the tree root node
// CmdiProfileReader cmdiProfileReader = new CmdiProfileReader();
// if (menuItemsAdded && cmdiProfileReader.cmdiProfileArray.size() > 0) {
// addMenu.add(new JSeparator());
// JMenu clarinAddMenu = new JMenu("Clarin Profiles");
// addMenu.add(clarinAddMenu);
// for (CmdiProfileReader.CmdiProfile currentCmdiProfile : cmdiProfileReader.cmdiProfileArray) {
// JMenuItem addMenuItem;
// addMenuItem = new JMenuItem();
// addMenuItem.setText(currentCmdiProfile.name);
// addMenuItem.setName(currentCmdiProfile.name);
// addMenuItem.setActionCommand(currentCmdiProfile.getXsdHref());
// addMenuItem.setToolTipText(currentCmdiProfile.description);
// addMenuItem.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(java.awt.event.ActionEvent evt) {
// try {
// if (leadSelectedTreeNode != null) {
// leadSelectedTreeNode.requestAddNode(evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
// } else {
// // no nodes found that were valid imdi tree objects so we can assume that tis is the tree root
// ImdiTreeObject.requestRootAddNode(evt.getActionCommand(), ((JMenuItem) evt.getSource()).getText());
// } catch (Exception ex) {
// GuiHelper.linorgBugCatcher.logError(ex);
// clarinAddMenu.add(addMenuItem);
// clarinAddMenu.add(new JSeparator());
// JMenuItem reloadProfilesMenuItem;
// reloadProfilesMenuItem = new JMenuItem();
// reloadProfilesMenuItem.setText("<Reload This List>");
// reloadProfilesMenuItem.setToolTipText("Reload this Clarin profile list from the server");
// reloadProfilesMenuItem.addActionListener(new java.awt.event.ActionListener() {
// public void actionPerformed(java.awt.event.ActionEvent evt) {
// CmdiProfileReader cmdiProfileReader = new CmdiProfileReader();
// cmdiProfileReader.refreshProfiles();
// clarinAddMenu.add(reloadProfilesMenuItem);
}
}
public void initHistoryMenu() {
historyMenu.removeAll();
for (String[] currentHistory : leadSelectedTreeNode.getHistoryList()) {
JMenuItem revertHistoryMenuItem;
revertHistoryMenuItem = new JMenuItem();
revertHistoryMenuItem.setText(currentHistory[0]);
revertHistoryMenuItem.setName(currentHistory[0]);
revertHistoryMenuItem.setActionCommand(currentHistory[1]);
revertHistoryMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
if (!leadSelectedTreeNode.resurrectHistory(evt.getActionCommand())) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Could not revert version, no changes made", "History");
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
historyMenu.add(revertHistoryMenuItem);
}
}
public void initAddFromFavouritesMenu() {
addFromFavouritesMenu.removeAll();
for (Enumeration menuItemName = LinorgFavourites.getSingleInstance().listFavouritesFor(leadSelectedTreeNode); menuItemName.hasMoreElements();) {
String[] currentField = (String[]) menuItemName.nextElement();
// System.out.println("MenuText: " + currentField[0]);
// System.out.println("ActionCommand: " + currentField[1]);
JMenuItem addFavouriteMenuItem;
addFavouriteMenuItem = new JMenuItem();
addFavouriteMenuItem.setText(currentField[0]);
addFavouriteMenuItem.setName(currentField[0]);
addFavouriteMenuItem.setActionCommand(currentField[1]);
addFavouriteMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
String imdiFavouriteUrlString = evt.getActionCommand();
ImdiTreeObject templateImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, ImdiTreeObject.conformStringToUrl(imdiFavouriteUrlString));
if (leadSelectedTreeNode != null) {
new MetadataBuilder().requestAddNode(leadSelectedTreeNode, ((JMenuItem) evt.getSource()).getText(), templateImdiObject);
}
// treeHelper.getImdiChildNodes(targetNode);
// String addedNodeUrlString = treeHelper.addImdiChildNode(targetNode, linorgFavourites.getNodeType(imdiTemplateUrlString), ((JMenuItem) evt.getSource()).getText());
// imdiLoader.getImdiObject("", addedNodeUrlString).requestMerge(imdiLoader.getImdiObject("", imdiTemplateUrlString));
// loop child nodes and insert them into the new node
// ImdiTreeObject templateImdiObject = GuiHelper.imdiLoader.getImdiObject("", imdiTemplateUrlString);
// ImdiTreeObject targetImdiObject = GuiHelper.imdiLoader.getImdiObject("", addedNodeUrl);
// for (Enumeration<ImdiTreeObject> childTemplateEnum = templateImdiObject.getChildEnum(); childTemplateEnum.hasMoreElements();) {
// ImdiTreeObject currentTemplateChild = childTemplateEnum.nextElement();
// String addedNodeUrl = treeHelper.addImdiChildNode(targetNode, linorgFavourites.getNodeType(currentTemplateChild.getUrlString()), currentTemplateChild.toString());
// linorgFavourites.mergeFromFavourite(addedNodeUrl, imdiTemplateUrlString, true);
// treeHelper.reloadLocalCorpusTree(targetNode);
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
addFromFavouritesMenu.add(addFavouriteMenuItem);
}
}
public void showTreePopup(Object eventSource, int posX, int posY) {
if (((java.awt.Component) eventSource).isShowing()) {
// set up the context menu
removeCachedCopyMenuItem.setVisible(false);
removeLocalDirectoryMenuItem.setVisible(false);
addLocalDirectoryMenuItem.setVisible(false);
showHiddenFilesMenuItem.setVisible(false);
removeRemoteCorpusMenuItem.setVisible(false);
addRemoteCorpusMenuItem.setVisible(false);
copyBranchMenuItem.setVisible(false);
searchRemoteBranchMenuItem.setVisible(false);
copyImdiUrlMenuItem.setVisible(false);
pasteMenuItem1.setVisible(false);
viewXmlMenuItem.setVisible(false);
viewXmlMenuItemFormatted.setVisible(false);
openXmlMenuItemFormatted.setVisible(false);
exportHtmlMenuItemFormatted.setVisible(false);
overrideTypeCheckerDecision.setVisible(false);
viewInBrrowserMenuItem.setVisible(false);
browseForResourceFileMenuItem.setVisible(false);
searchSubnodesMenuItem.setVisible(false);
reloadSubnodesMenuItem.setVisible(false);
addDefaultLocationsMenuItem.setVisible(false);
addMenu.setVisible(false);
deleteMenuItem.setVisible(false);
viewSelectedNodesMenuItem.setVisible(false);
addFromFavouritesMenu.setVisible(false);
saveMenuItem.setVisible(false);
viewChangesMenuItem.setVisible(false);
sendToServerMenuItem.setVisible(false);
validateMenuItem.setVisible(false);
historyMenu.setVisible(false);
exportMenuItem.setVisible(false);
importCsvMenuItem.setVisible(false);
importBranchMenuItem.setVisible(false);
reImportBranchMenuItem.setVisible(false);
addToFavouritesMenuItem.setVisible(false);
// table menu items
copySelectedRowsMenuItem.setVisible(false);
pasteIntoSelectedRowsMenuItem.setVisible(false);
viewSelectedRowsMenuItem.setVisible(false);
matchingRowsMenuItem.setVisible(false);
removeSelectedRowsMenuItem.setVisible(false);
hideSelectedColumnsMenuItem.setVisible(false);
deleteFieldMenuItem.setVisible(false);
revertFieldMenuItem.setVisible(false);
copyCellToColumnMenuItem.setVisible(false);
matchingCellsMenuItem.setVisible(false);
openInLongFieldEditorMenuItem.setVisible(false);
clearCellColoursMenuItem.setVisible(false);
searchReplaceMenuItem.setVisible(false);
jumpToNodeInTreeMenuItem.setVisible(false);
showChildNodesMenuItem.setVisible(false);
// menu separators
// treePopupMenuSeparator1.setVisible(true);
// treePopupMenuSeparator2.setVisible(true);
// cellMenuDivider.setVisible(true);
// cellTableDivider.setVisible(true);
currentTable = null;
if (eventSource instanceof ImdiTable) {
currentTable = ((ImdiTable) eventSource);
selectedTreeNodes = currentTable.getSelectedRowsFromTable();
leadSelectedTreeNode = currentTable.getImdiNodeForSelection();
// selectionCount = selectedTreeNodes.length;
setupTableMenuItems();
} else if (eventSource instanceof JList) {
JList currentJList = ((JList) eventSource);
Object[] selectedObjects = currentJList.getSelectedValues();
selectedTreeNodes = new ImdiTreeObject[selectedObjects.length];
for (int objectCounter = 0; objectCounter < selectedObjects.length; objectCounter++) {
selectedTreeNodes[objectCounter] = (ImdiTreeObject) selectedObjects[objectCounter];
}
leadSelectedTreeNode = (ImdiTreeObject) currentJList.getSelectedValue();
// selectionCount = selectedTreeNodes.length;
setUpImagePreviewMenu();
} else if (eventSource instanceof ImdiTree) {
selectedTreeNodes = ((ImdiTree) eventSource).getSelectedNodes();
leadSelectedTreeNode = ((ImdiTree) eventSource).getLeadSelectionNode();
setUpTreeMenuItems(eventSource);
}
setCommonMenuItems();
if (eventSource instanceof Component) {
// store the event source
treePopupMenu.setInvoker((Component) eventSource);
}
configureMenuSeparators();
// show the context menu
treePopupMenu.show((java.awt.Component) eventSource, posX, posY);
treePopupMenu.requestFocusInWindow();
}
}
private void configureMenuSeparators() {
// hide and show the separators so that no two separators are displayed without a menu item inbetween
boolean lastWasSeparator = true;
Component lastVisibleComponent = null;
for (Component currentComponent : treePopupMenu.getComponents()) {
if (currentComponent instanceof JSeparator) {
// if (lastWasSeparator == true) {
currentComponent.setVisible(!lastWasSeparator);
lastWasSeparator = true;
} else if (currentComponent.isVisible()) {
lastWasSeparator = false;
}
if (currentComponent.isVisible()) {
lastVisibleComponent = currentComponent;
}
}
if (lastVisibleComponent != null && lastVisibleComponent instanceof JSeparator) {
lastVisibleComponent.setVisible(false);
}
}
private void setCommonMenuItems() {
// todo: continue moving common menu items here
if (leadSelectedTreeNode != null) {
// TODO: test that the node is editable
//if (leadSelectedTreeNode.is)
if (leadSelectedTreeNode.hasResource()) {
browseForResourceFileMenuItem.setVisible(true);
}
if (!leadSelectedTreeNode.isImdiChild() && leadSelectedTreeNode.isMetaDataNode()) {
viewXmlMenuItem.setVisible(true);
viewXmlMenuItemFormatted.setVisible(true);
openXmlMenuItemFormatted.setVisible(true);
exportHtmlMenuItemFormatted.setVisible(true);
}
viewInBrrowserMenuItem.setVisible(true);
overrideTypeCheckerDecision.setVisible(!leadSelectedTreeNode.isMetaDataNode() && leadSelectedTreeNode.mpiMimeType == null);
}
}
private void setUpTreeMenuItems(Object eventSource) {
int nodeLevel = -1;
int selectionCount = 0;
// boolean showContextMenu = true;
boolean showRemoveLocationsTasks = false;
boolean showAddLocationsTasks = false;
selectionCount = ((JTree) eventSource).getSelectionCount();
if (selectionCount > 0) {
nodeLevel = ((JTree) eventSource).getSelectionPath().getPathCount();
}
showRemoveLocationsTasks = (selectionCount == 1 && nodeLevel == 2) || selectionCount > 1;
showAddLocationsTasks = selectionCount == 1 && nodeLevel == 1;
// Object leadSelectedTreeObject = ((ImdiTree) eventSource).getSingleSelectedNode();
//System.out.println("path count: " + ((JTree) evt.getSource()).getSelectionPath().getPathCount());
viewSelectedNodesMenuItem.setText("View Selected");
mergeWithFavouritesMenu.setEnabled(false);
deleteMenuItem.setEnabled(true);
if (TreeHelper.getSingleInstance().arbilTreePanel != null) {
if (eventSource == TreeHelper.getSingleInstance().arbilTreePanel.remoteCorpusTree) {
removeRemoteCorpusMenuItem.setVisible(showRemoveLocationsTasks);
addRemoteCorpusMenuItem.setVisible(showAddLocationsTasks);
copyBranchMenuItem.setVisible(selectionCount > 0 && nodeLevel > 1);
searchRemoteBranchMenuItem.setVisible(selectionCount > 0 && nodeLevel > 1);
addDefaultLocationsMenuItem.setVisible(showAddLocationsTasks);
}
if (eventSource == TreeHelper.getSingleInstance().arbilTreePanel.localCorpusTree) {
viewSelectedNodesMenuItem.setText("View/Edit Selected");
//removeCachedCopyMenuItem.setVisible(showRemoveLocationsTasks);
pasteMenuItem1.setVisible(selectionCount > 0 && nodeLevel > 1);
searchSubnodesMenuItem.setVisible(selectionCount > 0 && nodeLevel > 1);
// a corpus can be added even at the root node
addMenu.setVisible(selectionCount == 1); // && /*nodeLevel > 1 &&*/ TreeHelper.getSingleInstance().arbilTreePanel.localCorpusTree.getSelectionCount() > 0/* && ((DefaultMutableTreeNode)localCorpusTree.getSelectionPath().getLastPathComponent()).getUserObject() instanceof */); // could check for imdi childnodes
// addMenu.setEnabled(nodeLevel > 1); // not yet functional so lets dissable it for now
// addMenu.setToolTipText("test balloon on dissabled menu item");
deleteMenuItem.setVisible(nodeLevel > 1);
boolean nodeIsImdiChild = false;
if (leadSelectedTreeNode != null) {
nodeIsImdiChild = leadSelectedTreeNode.isImdiChild();
//if (leadSelectedTreeNode.getNeedsSaveToDisk()) {
// saveMenuItem.setVisible(true);
//} else if (leadSelectedTreeNode.hasHistory()) {
//viewChangesMenuItem.setVisible(true);
//sendToServerMenuItem.setVisible(true);
validateMenuItem.setVisible(!nodeIsImdiChild);
historyMenu.setVisible(leadSelectedTreeNode.hasHistory());
exportMenuItem.setVisible(!nodeIsImdiChild);
importCsvMenuItem.setVisible(leadSelectedTreeNode.isCorpus());
importBranchMenuItem.setVisible(leadSelectedTreeNode.isCorpus());
reImportBranchMenuItem.setVisible(leadSelectedTreeNode.archiveHandle != null && !leadSelectedTreeNode.isImdiChild());
// set up the favourites menu
addFromFavouritesMenu.setVisible(true);
}
//deleteMenuItem.setEnabled(!nodeIsImdiChild && selectionCount == 1);
// addMenu.setEnabled(!nodeIsImdiChild);
// showContextMenu = true; //nodeLevel != 1;
}
if (eventSource == TreeHelper.getSingleInstance().arbilTreePanel.localDirectoryTree) {
removeLocalDirectoryMenuItem.setVisible(showRemoveLocationsTasks);
if (showAddLocationsTasks) {
showHiddenFilesMenuItem.setState(TreeHelper.getSingleInstance().showHiddenFilesInTree);
showHiddenFilesMenuItem.setVisible(true);
}
addLocalDirectoryMenuItem.setVisible(showAddLocationsTasks);
if (leadSelectedTreeNode != null) {
copyBranchMenuItem.setVisible(leadSelectedTreeNode.isCorpus() || leadSelectedTreeNode.isSession());
}
}
}
if (leadSelectedTreeNode != null) {
saveMenuItem.setVisible(leadSelectedTreeNode.getNeedsSaveToDisk());// save sould always be available if the node has been edited
if (leadSelectedTreeNode.isFavorite()) {
addToFavouritesMenuItem.setVisible(true);
addToFavouritesMenuItem.setEnabled(true);
addMenu.setVisible(selectedTreeNodes.length == 1);// for now adding is limited to single node selections
viewSelectedNodesMenuItem.setText("View/Edit Selected");
addToFavouritesMenuItem.setText("Remove From Favourites List");
addToFavouritesMenuItem.setActionCommand("false");
deleteMenuItem.setEnabled(false);
} else {
addToFavouritesMenuItem.setVisible(leadSelectedTreeNode.isMetaDataNode());
addToFavouritesMenuItem.setEnabled(!leadSelectedTreeNode.isCorpus() && leadSelectedTreeNode.isMetaDataNode());
addToFavouritesMenuItem.setText("Add To Favourites List");
addToFavouritesMenuItem.setActionCommand("true");
}
} else {
addToFavouritesMenuItem.setVisible(false);
}
copyImdiUrlMenuItem.setVisible((selectionCount == 1 && nodeLevel > 1) || selectionCount > 1); // show the copy menu providing some nodes are selected and the root node is not the only one selected
viewSelectedNodesMenuItem.setVisible(selectionCount >= 1 && nodeLevel > 1);
reloadSubnodesMenuItem.setVisible(selectionCount > 0 && nodeLevel > 1);
// hide show the separators
//treePopupMenuSeparator2.setVisible(nodeLevel != 1 && showRemoveLocationsTasks && eventSource != TreeHelper.getSingleInstance().arbilTreePanel.localDirectoryTree);
//treePopupMenuSeparator1.setVisible(nodeLevel != 1 && eventSource == TreeHelper.getSingleInstance().arbilTreePanel.localCorpusTree);
}
private void setupTableMenuItems() {
if (currentTable != null) {
if (currentTable.getSelectedRow() != -1) {
copySelectedRowsMenuItem.setVisible(true);
pasteIntoSelectedRowsMenuItem.setVisible(true);
if (currentTable.imdiTableModel.horizontalView) {
viewSelectedRowsMenuItem.setVisible(true);
matchingRowsMenuItem.setVisible(true);
removeSelectedRowsMenuItem.setVisible(true);
showChildNodesMenuItem.setVisible(true);
}
boolean canDeleteSelectedFields = true;
ImdiField[] currentSelection = currentTable.getSelectedFields();
for (ImdiField currentField : currentSelection) {
if (!currentField.parentImdi.getNodeTemplate().pathIsDeleteableField(currentField.getGenericFullXmlPath())) {
canDeleteSelectedFields = false;
break;
}
}
if (canDeleteSelectedFields && currentSelection.length > 0) {
String menuText = "Delete " + currentSelection[0].getTranslateFieldName();
if (currentSelection.length > 1) {
menuText = menuText + " X " + currentSelection.length;
}
deleteFieldMenuItem.setText(menuText);
deleteFieldMenuItem.setVisible(true);
}
// set up the revert field menu
for (ImdiField currentField : currentSelection) {
if (currentField.fieldNeedsSaveToDisk()) {
revertFieldMenuItem.setVisible(true);
break;
}
}
}
if (currentTable.getSelectedRow() != -1 && currentTable.getSelectedColumn() != -1) {
// add a divider for the cell functions
//cellMenuDivider.setVisible(true);
if (currentTable.imdiTableModel.horizontalView && currentTable.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_INTERVAL_SELECTION) {
copyCellToColumnMenuItem.setVisible(true);
hideSelectedColumnsMenuItem.setVisible(true);
}
if (!currentTable.imdiTableModel.horizontalView || currentTable.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_INTERVAL_SELECTION) {
// show the cell only menu items
openInLongFieldEditorMenuItem.setVisible(true); // this should not show for the node icon cell
matchingCellsMenuItem.setVisible(true);
}
jumpToNodeInTreeMenuItem.setVisible(true);
clearCellColoursMenuItem.setVisible(true);
}
if (currentTable.getParent().getParent().getParent().getParent() instanceof LinorgSplitPanel) {
// test the LinorgSplitPanel exists before showing this
searchReplaceMenuItem.setVisible(true);
}
}
}
private void setUpImagePreviewMenu() {
}
public static void main(String args[]) {
new ContextMenu().treePopupMenu.setVisible(true);
}
} |
package hudson.security;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;
import com.octo.captcha.service.image.ImageCaptchaService;
import groovy.lang.Binding;
import hudson.ExtensionPoint;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.cli.CLICommand;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.security.FederatedLoginService.FederatedIdentity;
import hudson.util.DescriptorList;
import hudson.util.PluginServletFilter;
import hudson.util.spring.BeanBuilder;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationManager;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.ui.rememberme.RememberMeServices;
import static org.acegisecurity.ui.rememberme.TokenBasedRememberMeServices.ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.dao.DataAccessException;
import javax.imageio.ImageIO;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class SecurityRealm extends AbstractDescribableImpl<SecurityRealm> implements ExtensionPoint {
/**
* Creates fully-configured {@link AuthenticationManager} that performs authentication
* against the user realm. The implementation hides how such authentication manager
* is configured.
*
* <p>
* {@link AuthenticationManager} instantiation often depends on the user-specified parameters
* (for example, if the authentication is based on LDAP, the user needs to specify
* the host name of the LDAP server.) Such configuration is expected to be
* presented to the user via <tt>config.jelly</tt> and then
* captured as instance variables inside the {@link SecurityRealm} implementation.
*
* <p>
* Your {@link SecurityRealm} may also wants to alter {@link Filter} set up by
* overriding {@link #createFilter(FilterConfig)}.
*/
public abstract SecurityComponents createSecurityComponents();
/**
* Creates a {@link CliAuthenticator} object that authenticates an invocation of a CLI command.
* See {@link CliAuthenticator} for more details.
*
* @param command
* The command about to be executed.
* @return
* never null. By default, this method returns a no-op authenticator that always authenticates
* the session as authenticated by the transport (which is often just {@link Hudson#ANONYMOUS}.)
*/
public CliAuthenticator createCliAuthenticator(final CLICommand command) {
return new CliAuthenticator() {
public Authentication authenticate() {
return command.getTransportAuthentication();
}
};
}
/**
* {@inheritDoc}
*
* <p>
* {@link SecurityRealm} is a singleton resource in Hudson, and therefore
* it's always configured through <tt>config.jelly</tt> and never with
* <tt>global.jelly</tt>.
*/
public Descriptor<SecurityRealm> getDescriptor() {
return super.getDescriptor();
}
/**
* Returns the URL to submit a form for the authentication.
* There's no need to override this, except for {@link LegacySecurityRealm}.
*/
public String getAuthenticationGatewayUrl() {
return "j_acegi_security_check";
}
/**
* Gets the target URL of the "login" link.
* There's no need to override this, except for {@link LegacySecurityRealm}.
* On legacy implementation this should point to {@code loginEntry}, which
* is protected by <tt>web.xml</tt>, so that the user can be eventually authenticated
* by the container.
*
* <p>
* Path is relative from the context root of the Hudson application.
* The URL returned by this method will get the "from" query parameter indicating
* the page that the user was at.
*/
public String getLoginUrl() {
return "login";
}
/**
* Returns true if this {@link SecurityRealm} supports explicit logout operation.
*
* <p>
* If the method returns false, "logout" link will not be displayed. This is useful
* when authentication doesn't require an explicit login activity (such as NTLM authentication
* or Kerberos authentication, where Hudson has no ability to log off the current user.)
*
* <p>
* By default, this method returns true.
*
* @since 1.307
*/
public boolean canLogOut() {
return true;
}
/**
* Controls where the user is sent to after a logout. By default, it's the top page
* of Hudson, but you can return arbitrary URL.
*
* @param req
* {@link StaplerRequest} that represents the current request. Primarily so that
* you can get the context path. By the time this method is called, the session
* is already invalidated. Never null.
* @param auth
* The {@link Authentication} object that represents the user that was logging in.
* This parameter allows you to redirect people to different pages depending on who they are.
* @return
* never null.
* @since 1.314
* @see #doLogout(StaplerRequest, StaplerResponse)
*/
protected String getPostLogOutUrl(StaplerRequest req, Authentication auth) {
return req.getContextPath()+"/";
}
/**
* Handles the logout processing.
*
* <p>
* The default implementation erases the session and do a few other clean up, then
* redirect the user to the URL specified by {@link #getPostLogOutUrl(StaplerRequest, Authentication)}.
*
* @since 1.314
*/
public void doLogout(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
HttpSession session = req.getSession(false);
if(session!=null)
session.invalidate();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
SecurityContextHolder.clearContext();
// reset remember-me cookie
Cookie cookie = new Cookie(ACEGI_SECURITY_HASHED_REMEMBER_ME_COOKIE_KEY,"");
cookie.setPath(req.getContextPath().length()>0 ? req.getContextPath() : "/");
rsp.addCookie(cookie);
rsp.sendRedirect2(getPostLogOutUrl(req,auth));
}
public boolean allowsSignup() {
Class clz = getClass();
return clz.getClassLoader().getResource(clz.getName().replace('.','/')+"/signup.jelly")!=null;
}
/**
* Shortcut for {@link UserDetailsService#loadUserByUsername(String)}.
*
* @throws UserMayOrMayNotExistException
* If the security realm cannot even tell if the user exists or not.
* @return
* never null.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
return getSecurityComponents().userDetails.loadUserByUsername(username);
}
/**
* If this {@link SecurityRealm} supports a look up of {@link GroupDetails} by their names, override this method
* to provide the look up.
*
* <p>
* This information, when available, can be used by {@link AuthorizationStrategy}s to improve the UI and
* error diagnostics for the user.
*/
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
throw new UserMayOrMayNotExistException(groupname);
}
/**
* Starts the user registration process for a new user that has the given verified identity.
*
* <p>
* If the user logs in through a {@link FederatedLoginService}, verified that the current user
* owns an {@linkplain FederatedIdentity identity}, but no existing user account has claimed that identity,
* then this method is invoked.
*
* <p>
* The expected behaviour is to confirm that the user would like to create a new account, and
* associate this federated identity to the newly created account (via {@link FederatedIdentity#addToCurrentUser()}.
*
* @throws UnsupportedOperationException
* If this implementation doesn't support the signup through this mechanism.
* This is the default implementation.
*
* @since 1.394
*/
public HttpResponse commenceSignup(FederatedIdentity identity) {
throw new UnsupportedOperationException();
}
/**
* {@link DefaultManageableImageCaptchaService} holder to defer initialization.
*/
public static final class CaptchaService {
public static ImageCaptchaService INSTANCE = new DefaultManageableImageCaptchaService();
}
/**
* Generates a captcha image.
*/
public final void doCaptcha(StaplerRequest req, StaplerResponse rsp) throws IOException {
String id = req.getSession().getId();
rsp.setContentType("image/png");
rsp.addHeader("Cache-Control","no-cache");
ImageIO.write( CaptchaService.INSTANCE.getImageChallengeForID(id), "PNG", rsp.getOutputStream() );
}
/**
* Validates the captcha.
*/
protected final boolean validateCaptcha(String text) {
try {
String id = Stapler.getCurrentRequest().getSession().getId();
Boolean b = CaptchaService.INSTANCE.validateResponseForID(id, text);
return b!=null && b;
} catch (CaptchaServiceException e) {
LOGGER.log(Level.INFO, "Captcha validation had a problem",e);
return false;
}
}
protected static <T> T findBean(Class<T> type, ApplicationContext context) {
Map m = context.getBeansOfType(type);
switch(m.size()) {
case 0:
throw new IllegalArgumentException("No beans of "+type+" are defined");
case 1:
return type.cast(m.values().iterator().next());
default:
throw new IllegalArgumentException("Multiple beans of "+type+" are defined: "+m);
}
}
/**
* Holder for the SecurityComponents.
*/
private transient SecurityComponents securityComponents;
/**
* Use this function to get the security components, without necessarily
* recreating them.
*/
public synchronized SecurityComponents getSecurityComponents() {
if (this.securityComponents == null) {
this.securityComponents = this.createSecurityComponents();
}
return this.securityComponents;
}
/**
* Creates {@link Filter} that all the incoming HTTP requests will go through
* for authentication.
*
* <p>
* The default implementation uses {@link #getSecurityComponents()} and builds
* a standard filter chain from /WEB-INF/security/SecurityFilters.groovy.
* But subclasses can override this to completely change the filter sequence.
*
* <p>
* For other plugins that want to contribute {@link Filter}, see
* {@link PluginServletFilter}.
*
* @since 1.271
*/
public Filter createFilter(FilterConfig filterConfig) {
LOGGER.entering(SecurityRealm.class.getName(), "createFilter");
Binding binding = new Binding();
SecurityComponents sc = getSecurityComponents();
binding.setVariable("securityComponents", sc);
binding.setVariable("securityRealm",this);
BeanBuilder builder = new BeanBuilder();
builder.parse(filterConfig.getServletContext().getResourceAsStream("/WEB-INF/security/SecurityFilters.groovy"),binding);
WebApplicationContext context = builder.createApplicationContext();
return (Filter) context.getBean("filter");
}
/**
* Singleton constant that represents "no authentication."
*/
public static final SecurityRealm NO_AUTHENTICATION = new None();
private static class None extends SecurityRealm {
public SecurityComponents createSecurityComponents() {
return new SecurityComponents(new AuthenticationManager() {
public Authentication authenticate(Authentication authentication) {
return authentication;
}
}, new UserDetailsService() {
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException(username);
}
});
}
/**
* This special instance is not configurable explicitly,
* so it doesn't have a descriptor.
*/
@Override
public Descriptor<SecurityRealm> getDescriptor() {
return null;
}
/**
* There's no group.
*/
@Override
public GroupDetails loadGroupByGroupname(String groupname) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException(groupname);
}
/**
* We don't need any filter for this {@link SecurityRealm}.
*/
@Override
public Filter createFilter(FilterConfig filterConfig) {
return new ChainedServletFilter();
}
/**
* Maintain singleton semantics.
*/
private Object readResolve() {
return NO_AUTHENTICATION;
}
}
/**
* Just a tuple so that we can create various inter-related security related objects and
* return them all at once.
*
* <p>
* None of the fields are ever null.
*
* @see SecurityRealm#createSecurityComponents()
*/
public static final class SecurityComponents {
public final AuthenticationManager manager;
public final UserDetailsService userDetails;
public final RememberMeServices rememberMe;
public SecurityComponents() {
// we use AuthenticationManagerProxy here just as an implementation that fails all the time,
// not as a proxy. No one is supposed to use this as a proxy.
this(new AuthenticationManagerProxy());
}
public SecurityComponents(AuthenticationManager manager) {
// we use UserDetailsServiceProxy here just as an implementation that fails all the time,
// not as a proxy. No one is supposed to use this as a proxy.
this(manager,new UserDetailsServiceProxy());
}
public SecurityComponents(AuthenticationManager manager, UserDetailsService userDetails) {
this(manager,userDetails,createRememberMeService(userDetails));
}
public SecurityComponents(AuthenticationManager manager, UserDetailsService userDetails, RememberMeServices rememberMe) {
assert manager!=null && userDetails!=null && rememberMe!=null;
this.manager = manager;
this.userDetails = userDetails;
this.rememberMe = rememberMe;
}
private static RememberMeServices createRememberMeService(UserDetailsService uds) {
// create our default TokenBasedRememberMeServices, which depends on the availability of the secret key
TokenBasedRememberMeServices2 rms = new TokenBasedRememberMeServices2();
rms.setUserDetailsService(uds);
rms.setKey(Hudson.getInstance().getSecretKey());
rms.setParameter("remember_me"); // this is the form field name in login.jelly
return rms;
}
}
/**
* All registered {@link SecurityRealm} implementations.
*
* @deprecated as of 1.286
* Use {@link #all()} for read access, and use {@link Extension} for registration.
*/
public static final DescriptorList<SecurityRealm> LIST = new DescriptorList<SecurityRealm>(SecurityRealm.class);
/**
* Returns all the registered {@link SecurityRealm} descriptors.
*/
public static DescriptorExtensionList<SecurityRealm,Descriptor<SecurityRealm>> all() {
return Hudson.getInstance().<SecurityRealm,Descriptor<SecurityRealm>>getDescriptorList(SecurityRealm.class);
}
private static final Logger LOGGER = Logger.getLogger(SecurityRealm.class.getName());
/**
* {@link GrantedAuthority} that represents the built-in "authenticated" role, which is granted to
* anyone non-anonymous.
*/
public static final GrantedAuthority AUTHENTICATED_AUTHORITY = new GrantedAuthorityImpl("authenticated");
} |
package ru.thewizardplusplus.wizardbudget;
import java.text.*;
import java.util.*;
import org.json.*;
import android.content.*;
import android.database.*;
import android.database.sqlite.*;
import android.net.*;
import android.webkit.*;
public class SpendingManager {
public SpendingManager(Context context) {
this.context = context;
}
@JavascriptInterface
public String getSpendingsSum() {
SQLiteDatabase database = Utils.getDatabase(context);
Cursor cursor = database.query(
"spendings",
new String[]{"ROUND(SUM(amount), 2)"},
null,
null,
null,
null,
null
);
double spendings_sum = 0.0;
boolean moved = cursor.moveToFirst();
if (moved) {
spendings_sum = cursor.getDouble(0);
}
database.close();
return String.valueOf(spendings_sum);
}
@JavascriptInterface
public String getAllSpendings() {
SQLiteDatabase database = Utils.getDatabase(context);
Cursor spendings_cursor = database.query(
"spendings",
new String[]{"_id", "timestamp", "amount", "comment"},
null,
null,
null,
null,
"timestamp DESC"
);
JSONArray spendings = new JSONArray();
boolean moved = spendings_cursor.moveToFirst();
while (moved) {
try {
JSONObject spending = new JSONObject();
spending.put("id", spendings_cursor.getDouble(0));
long timestamp = spendings_cursor.getLong(1);
spending.put("timestamp", String.valueOf(timestamp));
spending.put("date", formatDate(timestamp));
spending.put("time", formatTime(timestamp));
spending.put("amount", spendings_cursor.getDouble(2));
String comment = spendings_cursor.getString(3);
spending.put("comment", comment);
boolean has_credit_card_tag = false;
String credit_card_tag =
Settings
.getCurrent(context)
.getCreditCardTag();
if (!credit_card_tag.isEmpty()) {
String[] tags = comment.split(",");
for (String tag: tags) {
if (tag.trim().equals(credit_card_tag)) {
has_credit_card_tag = true;
break;
}
}
}
spending.put("has_credit_card_tag", has_credit_card_tag);
spendings.put(spending);
} catch (JSONException exception) {}
moved = spendings_cursor.moveToNext();
}
database.close();
return spendings.toString();
}
@JavascriptInterface
public String getSpendingsFromSms() {
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = context.getContentResolver().query(
uri,
null,
null,
null,
null
);
JSONArray spendings = new JSONArray();
if (cursor.moveToFirst()) {
do {
long timestamp = 0;
try {
String timestamp_string =
cursor
.getString(cursor.getColumnIndexOrThrow("date"))
.toString();
timestamp = Long.valueOf(timestamp_string) / 1000L;
} catch (NumberFormatException exception) {
continue;
}
String number =
cursor
.getString(cursor.getColumnIndexOrThrow("address"))
.toString();
String text =
cursor
.getString(cursor.getColumnIndexOrThrow("body"))
.toString();
SmsData sms_data = Utils.getSpendingFromSms(
context,
number,
text
);
if (sms_data == null) {
continue;
}
try {
JSONObject spending = new JSONObject();
spending.put("timestamp", timestamp);
spending.put("date", formatDate(timestamp));
spending.put("time", formatTime(timestamp));
spending.put("amount", sms_data.getSpending());
spendings.put(spending);
} catch (JSONException exception) {
continue;
}
} while (cursor.moveToNext());
}
cursor.close();
return spendings.toString();
}
@JavascriptInterface
public String getSpendingTags() {
JSONArray tags = new JSONArray();
List<String> tag_list = getTagList();
for (String tag: tag_list) {
tags.put(tag);
}
return tags.toString();
}
@JavascriptInterface
public String getPrioritiesTags() {
Map<String, Long> tag_map = new HashMap<String, Long>();
List<String> tag_list = getTagList();
for (String tag: tag_list) {
if (tag_map.containsKey(tag)) {
tag_map.put(tag, tag_map.get(tag) + 1L);
} else {
tag_map.put(tag, 1L);
}
}
JSONObject serialized_tag_map = new JSONObject();
try {
for (Map.Entry<String, Long> entry: tag_map.entrySet()) {
serialized_tag_map.put(entry.getKey(), entry.getValue());
}
} catch (JSONException exception) {}
return serialized_tag_map.toString();
}
@JavascriptInterface
public String getStatsSum(int number_of_last_days, String prefix) {
SQLiteDatabase database = Utils.getDatabase(context);
String prefix_length = String.valueOf(prefix.length());
Cursor spendings_cursor = database.query(
"spendings",
new String[]{"ROUND(SUM(amount), 2)"},
"amount > 0 "
+ "AND date(timestamp, 'unixepoch')"
+ ">= date("
+ "'now',"
+ "'-"
+ String.valueOf(Math.abs(number_of_last_days))
+ " days'"
+ ")"
+ "AND comment LIKE "
+ DatabaseUtils.sqlEscapeString(prefix + "%")
+ "AND ("
+ prefix_length + " == 0 "
+ "OR length(comment) == " + prefix_length + " "
+ "OR substr(comment, " + prefix_length + " + 1, 1) == ','"
+ ")",
null,
null,
null,
null
);
double spendings_sum = 0.0;
boolean moved = spendings_cursor.moveToFirst();
if (moved) {
spendings_sum = spendings_cursor.getDouble(0);
}
return String.valueOf(spendings_sum);
}
@JavascriptInterface
public String getStats(int number_of_last_days, String prefix) {
SQLiteDatabase database = Utils.getDatabase(context);
int prefix_length = prefix.length();
String prefix_length_in_string = String.valueOf(prefix_length);
Cursor spendings_cursor = database.query(
"spendings",
new String[]{"comment", "amount"},
"amount > 0 "
+ "AND date(timestamp, 'unixepoch')"
+ ">= date("
+ "'now',"
+ "'-"
+ String.valueOf(Math.abs(number_of_last_days))
+ " days'"
+ ")"
+ "AND comment LIKE "
+ DatabaseUtils.sqlEscapeString(prefix + "%")
+ "AND ("
+ prefix_length_in_string + " == 0 "
+ "OR length(comment) == " + prefix_length_in_string + " "
+ "OR substr("
+ "comment,"
+ prefix_length_in_string + " + 1,"
+ "1"
+ ") == ','"
+ ")",
null,
null,
null,
null
);
Map<String, Double> spendings = new HashMap<String, Double>();
boolean moved = spendings_cursor.moveToFirst();
while (moved) {
String comment = spendings_cursor.getString(0);
if (prefix_length != 0) {
if (comment.length() > prefix_length) {
comment = comment.substring(prefix_length + 1).trim();
} else if (comment.length() == prefix_length) {
comment = "";
}
}
if (comment.isEmpty()) {
comment = UUID.randomUUID().toString();
} else {
int separator_index = comment.indexOf(",");
if (separator_index != -1) {
comment = comment.substring(0, separator_index).trim();
}
}
double amount = spendings_cursor.getDouble(1);
if (spendings.containsKey(comment)) {
spendings.put(comment, spendings.get(comment) + amount);
} else {
spendings.put(comment, amount);
}
moved = spendings_cursor.moveToNext();
}
JSONObject serialized_spendings = new JSONObject();
for (Map.Entry<String, Double> entry: spendings.entrySet()) {
try {
String comment = entry.getKey();
double amount = entry.getValue();
serialized_spendings.put(comment, amount);
} catch (JSONException exception) {}
}
database.close();
return serialized_spendings.toString();
}
@JavascriptInterface
public void createSpending(double amount, String comment) {
ContentValues values = new ContentValues();
values.put("timestamp", System.currentTimeMillis() / 1000L);
values.put("amount", amount);
values.put("comment", comment);
SQLiteDatabase database = Utils.getDatabase(context);
database.insert("spendings", null, values);
database.close();
}
@JavascriptInterface
public void updateSpending(
int id,
String date,
String time,
double amount,
String comment
) {
try {
String formatted_timestamp = date + " " + time + ":00";
SimpleDateFormat timestamp_format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss",
Locale.US
);
Date parsed_timestamp = timestamp_format.parse(
formatted_timestamp
);
long timestamp = parsed_timestamp.getTime() / 1000L;
ContentValues values = new ContentValues();
values.put("timestamp", timestamp);
values.put("amount", amount);
values.put("comment", comment);
SQLiteDatabase database = Utils.getDatabase(context);
database.update(
"spendings",
values,
"_id = ?",
new String[]{String.valueOf(id)}
);
database.close();
} catch (java.text.ParseException exception) {}
}
@JavascriptInterface
public void deleteSpending(int id) {
SQLiteDatabase database = Utils.getDatabase(context);
database.delete(
"spendings",
"_id = ?",
new String[]{String.valueOf(id)}
);
database.close();
}
@JavascriptInterface
public void importSms(String sms_data) {
String sql = "";
try {
JSONArray spendings = new JSONArray(sms_data);
for (int i = 0; i < spendings.length(); i++) {
if (!sql.isEmpty()) {
sql += ",";
}
JSONObject spending = spendings.getJSONObject(i);
double amount = spending.getDouble("amount");
String comment =
amount >= 0.0
? Settings.getCurrent(context).getSmsSpendingComment()
: Settings.getCurrent(context).getSmsIncomeComment();
String credit_card_tag =
Settings
.getCurrent(context)
.getCreditCardTag();
if (!credit_card_tag.isEmpty()) {
comment += ", " + credit_card_tag;
}
sql += "("
+ String.valueOf(spending.getLong("timestamp")) + ","
+ String.valueOf(amount) + ","
+ DatabaseUtils.sqlEscapeString(comment)
+ ")";
}
} catch (JSONException exception) {}
if (!sql.isEmpty()) {
SQLiteDatabase database = Utils.getDatabase(context);
database.execSQL(
"INSERT INTO spendings"
+ "(timestamp, amount, comment)"
+ "VALUES" + sql
);
database.close();
if (Settings.getCurrent(context).isSmsImportNotification()) {
Date current_date = new Date();
DateFormat notification_timestamp_format =
DateFormat
.getDateTimeInstance(
DateFormat.DEFAULT,
DateFormat.DEFAULT,
Locale.US
);
String notification_timestamp =
notification_timestamp_format
.format(current_date);
Utils.showNotification(
context,
context.getString(R.string.app_name),
"SMS imported at " + notification_timestamp + ".",
null
);
}
}
}
private Context context;
private String formatDate(long timestamp) {
Date date = new Date(timestamp * 1000L);
DateFormat date_format = DateFormat.getDateInstance(
DateFormat.DEFAULT,
Locale.US
);
return date_format.format(date);
}
private String formatTime(long timestamp) {
Date date = new Date(timestamp * 1000L);
DateFormat date_format = DateFormat.getTimeInstance(
DateFormat.DEFAULT,
Locale.US
);
return date_format.format(date);
}
private List<String> getTagList() {
SQLiteDatabase database = Utils.getDatabase(context);
Cursor spendings_cursor = database.query(
"spendings",
new String[]{"comment"},
null,
null,
null,
null,
null
);
List<String> tags = new ArrayList<String>();
boolean moved = spendings_cursor.moveToFirst();
while (moved) {
String comment = spendings_cursor.getString(0);
if (!comment.isEmpty()) {
String[] comment_parts = comment.split(",");
for (String part: comment_parts) {
String trimmed_part = part.trim();
if (!trimmed_part.isEmpty()) {
tags.add(trimmed_part);
}
}
}
moved = spendings_cursor.moveToNext();
}
database.close();
return tags;
}
} |
package io.grpc.internal;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.grpc.LoadBalancer;
import io.grpc.Status;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
/**
* Transports for a single server.
*/
@ThreadSafe
final class TransportSet {
private static final Logger log = Logger.getLogger(TransportSet.class.getName());
private static final SettableFuture<ClientTransport> NULL_VALUE_FUTURE;
static {
NULL_VALUE_FUTURE = SettableFuture.create();
NULL_VALUE_FUTURE.set(null);
}
private final Object lock = new Object();
private final SocketAddress server;
private final String authority;
private final BackoffPolicy.Provider backoffPolicyProvider;
private final Callback callback;
private final ClientTransportFactory transportFactory;
private final ScheduledExecutorService scheduledExecutor;
@GuardedBy("lock")
@Nullable
private BackoffPolicy reconnectPolicy;
@GuardedBy("lock")
@Nullable
private ScheduledFuture<?> reconnectTask;
/**
* All transports that are not stopped. At the very least the value of {@link
* activeTransportFuture} will be present, but previously used transports that still have streams
* or are stopping may also be present.
*/
@GuardedBy("lock")
private final Collection<ClientTransport> transports = new ArrayList<ClientTransport>();
private final LoadBalancer loadBalancer;
@GuardedBy("lock")
private boolean shutdown;
/**
* The future for the transport for new outgoing requests. 'lock' lock must be held when assigning
* to activeTransportFuture.
*/
private volatile SettableFuture<ClientTransport> activeTransportFuture;
TransportSet(SocketAddress server, String authority, LoadBalancer loadBalancer,
BackoffPolicy.Provider backoffPolicyProvider, ClientTransportFactory transportFactory,
ScheduledExecutorService scheduledExecutor, Callback callback) {
this.server = server;
this.authority = authority;
this.loadBalancer = loadBalancer;
this.backoffPolicyProvider = backoffPolicyProvider;
this.transportFactory = transportFactory;
this.scheduledExecutor = scheduledExecutor;
this.callback = callback;
createActiveTransportFuture();
}
/**
* Returns a future for the active transport that will be used to create new streams.
*
* <p>If this {@code TransportSet} has been shut down, the returned future will have {@code null}
* value.
*/
ListenableFuture<ClientTransport> obtainActiveTransport() {
return activeTransportFuture;
}
/**
* Creates a new activeTransportFuture, overwrites the current value and initiates the connection.
*
* <p>This method MUST ONLY be called in one of the following cases:
* <ol>
* <li>activeTransportFuture has never been assigned, thus it's null;</li>
* <li>activeTransportFuture is done and its transport has been shut down.</li>
* </ol>
*/
private void createActiveTransportFuture() {
synchronized (lock) {
if (shutdown) {
return;
}
Preconditions.checkState(activeTransportFuture == null || activeTransportFuture.isDone(),
"activeTransportFuture is neither null nor done");
activeTransportFuture = SettableFuture.create();
scheduleConnection();
}
}
// Can only be called when shutdown == false
@GuardedBy("lock")
private void scheduleConnection() {
Preconditions.checkState(!shutdown, "Already shut down");
Preconditions.checkState(reconnectTask == null || reconnectTask.isDone(),
"previous reconnectTask is not done");
Runnable createTransportRunnable = new Runnable() {
@Override
public void run() {
synchronized (lock) {
if (shutdown) {
return;
}
ClientTransport newActiveTransport = transportFactory.newClientTransport(
server, authority);
log.log(Level.INFO, "Created transport {0} for {1}",
new Object[] {newActiveTransport, server});
transports.add(newActiveTransport);
newActiveTransport.start(
new TransportListener(newActiveTransport, activeTransportFuture));
Preconditions.checkState(activeTransportFuture.set(newActiveTransport),
"failed to set the new transport to the future");
}
}
};
if (reconnectPolicy == null) {
// First connect attempt
reconnectPolicy = backoffPolicyProvider.get();
createTransportRunnable.run();
reconnectTask = null;
} else {
// Reconnect attempts
long delayMillis = reconnectPolicy.nextBackoffMillis();
reconnectTask = scheduledExecutor.schedule(
createTransportRunnable, delayMillis, TimeUnit.MILLISECONDS);
}
}
/**
* Shut down all transports, may run callback inline.
*/
void shutdown() {
SettableFuture<ClientTransport> savedActiveTransportFuture;
boolean runCallback = false;
synchronized (lock) {
if (shutdown) {
return;
}
shutdown = true;
savedActiveTransportFuture = activeTransportFuture;
activeTransportFuture = NULL_VALUE_FUTURE;
if (transports.isEmpty()) {
runCallback = true;
}
if (reconnectTask != null) {
reconnectTask.cancel(false);
}
// else: the callback will be run once all transports have been terminated
}
if (savedActiveTransportFuture != null) {
if (savedActiveTransportFuture.isDone()) {
try {
// Should not throw any exception here
savedActiveTransportFuture.get().shutdown();
} catch (Exception e) {
throw Throwables.propagate(e);
}
} else {
savedActiveTransportFuture.set(null);
}
}
if (runCallback) {
callback.onTerminated();
}
}
private class TransportListener implements ClientTransport.Listener {
private final ClientTransport transport;
private final SettableFuture<ClientTransport> transportFuture;
public TransportListener(ClientTransport transport,
SettableFuture<ClientTransport> transportFuture) {
this.transport = transport;
this.transportFuture = transportFuture;
}
@GuardedBy("lock")
private boolean isAttachedToActiveTransport() {
return activeTransportFuture == transportFuture;
}
@Override
public void transportReady() {
synchronized (lock) {
log.log(Level.INFO, "Transport {0} for {1} is ready", new Object[] {transport, server});
Preconditions.checkState(transportFuture.isDone(), "the transport future is not done");
if (isAttachedToActiveTransport()) {
reconnectPolicy = null;
}
}
loadBalancer.transportReady(server, transport);
}
@Override
public void transportShutdown(Status s) {
synchronized (lock) {
log.log(Level.INFO, "Transport {0} for {1} is being shutdown",
new Object[] {transport, server});
Preconditions.checkState(transportFuture.isDone(), "the transport future is not done");
if (isAttachedToActiveTransport()) {
createActiveTransportFuture();
}
}
loadBalancer.transportShutdown(server, transport, s);
}
@Override
public void transportTerminated() {
boolean runCallback = false;
synchronized (lock) {
log.log(Level.INFO, "Transport {0} for {1} is terminated",
new Object[] {transport, server});
Preconditions.checkState(!isAttachedToActiveTransport(),
"Listener is still attached to activeTransportFuture. "
+ "Seems transportTerminated was not called.");
transports.remove(transport);
if (shutdown && transports.isEmpty()) {
runCallback = true;
}
}
if (runCallback) {
callback.onTerminated();
}
}
}
interface Callback {
void onTerminated();
}
} |
package com.necla.am.zwutils.Tasks.Samples;
import java.io.File;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.regex.Pattern;
import com.necla.am.zwutils.Config.DataMap;
import com.necla.am.zwutils.Logging.GroupLogger;
import com.necla.am.zwutils.Logging.IGroupLogger;
import com.necla.am.zwutils.Misc.Misc;
import com.necla.am.zwutils.Misc.Misc.TimeUnit;
import com.necla.am.zwutils.Misc.Parsers;
import com.necla.am.zwutils.Reflection.PackageClassIterable;
/**
* Process statistic collection task
* <p>
* Gather performance statistics of current program, such as up-time and memory uesage
*
* @author Zhenyu Wu
* @version 0.1 - Dec. 2012: Initial implementation
* @version 0.2 - Dec. 2015: Renamed from Stats to ProcStats
* @version 0.2 - Jan. 20 2016: Initial public release
*/
public class ProcStats extends Companion {
public static final String LogGroup = ProcStats.class.getSimpleName();
public static class ConfigData {
public static enum StatType {
RUNTIME,
CPUUSE,
THREADS,
MEMINFO,
APPINFO,
NETINFO;
public static StatType parse(String Str) {
if (RUNTIME.toString().equals(Str)) return RUNTIME;
if (CPUUSE.toString().equals(Str)) return CPUUSE;
if (THREADS.toString().equals(Str)) return THREADS;
if (MEMINFO.toString().equals(Str)) return MEMINFO;
if (APPINFO.toString().equals(Str)) return APPINFO;
if (NETINFO.toString().equals(Str)) return NETINFO;
Misc.FAIL(NoSuchElementException.class, "Not status type named '%s'", Str);
return null;
}
/**
* String to log level parser
*/
public static class StringToStatType extends Parsers.SimpleStringParse<StatType> {
@Override
public StatType parseOrFail(String From) {
if (From == null) {
Misc.FAIL(NullPointerException.class, Parsers.ERROR_NULL_POINTER);
}
return StatType.parse(From.toUpperCase());
}
}
public static final StringToStatType StringToStatType = new StringToStatType();
public static final Parsers.AnyToString<StatType> StringFromStatType =
new Parsers.AnyToString<StatType>();
}
public static class Mutable extends Companion.ConfigData.Mutable {
public int LogInterval;
protected Set<StatType> Stats;
public String CompNS;
@Override
public void loadDefaults() {
super.loadDefaults();
TimeRes = 100; // 0.1s
LogInterval = 60000;
Stats = EnumSet.allOf(StatType.class);
CompNS = "_Namespace";
}
public static final String CONFIG_LOGINTERVAL = "LogInterval";
public static final String CONFIG_TYPES = "Types";
public static final String CONFIG_COMPNS = "ComponentNS";
private static final Pattern DataItemToken = Pattern.compile("(?<!\\\\), *");
@Override
public void loadFields(DataMap confMap) {
super.loadFields(confMap);
LogInterval = confMap.getIntDef(CONFIG_LOGINTERVAL, LogInterval);
ILog.Fine("Loading stats types descripter...");
String StatStr = confMap.getTextDef(CONFIG_TYPES, "").trim();
if (!StatStr.isEmpty()) {
Stats.clear();
String[] StatToks = DataItemToken.split(StatStr);
for (String StatTok : StatToks) {
String StatDesc = StatTok.trim();
if (!StatDesc.isEmpty()) {
Stats.add(ConfigData.StatType.StringToStatType.parseOrFail(StatDesc));
}
}
}
CompNS = confMap.getTextDef(CONFIG_COMPNS, CompNS);
}
protected class Validation extends Companion.ConfigData.Mutable.Validation {
@Override
public void validateFields() throws Throwable {
super.validateFields();
ILog.Fine("Checking log interval...");
if (LogInterval > 0) {
ILog.Info("Logging interval: %s", Misc.FormatDeltaTime(LogInterval));
}
ILog.Fine("Checking stats descriptor...");
if (Stats.isEmpty()) {
Misc.FAIL(NoSuchElementException.class, "Missing stats types descriptor");
}
}
}
@Override
protected Validation needValidation() {
return new Validation();
}
}
public static class ReadOnly extends Companion.ConfigData.ReadOnly {
public final int LogInterval;
public final Set<StatType> Stats;
public final String CompNS;
public ReadOnly(IGroupLogger Logger, Mutable Source) {
super(Logger, Source);
LogInterval = Source.LogInterval;
Stats = EnumSet.copyOf(Source.Stats);
CompNS = Source.CompNS;
}
}
}
protected ConfigData.ReadOnly Config;
// Last Log time
protected long LastTime = 0;
// Last up time
protected long LastUpTime = 0;
// Last GC time
protected long LastGCTime = 0;
// Last CPU time
protected long LastCPUTime = 0;
public static final String ZBXLogGroup = "Application.Statistics";
public final GroupLogger.Zabbix ZBXLog;
public ProcStats(String Name) {
super(Name);
ZBXLog = new GroupLogger.Zabbix(ZBXLogGroup);
}
@Override
protected Class<? extends ConfigData.Mutable> MutableConfigClass() {
return ConfigData.Mutable.class;
}
@Override
protected Class<? extends ConfigData.ReadOnly> ReadOnlyConfigClass() {
return ConfigData.ReadOnly.class;
}
@Override
protected void PreStartConfigUpdate(Poller.ConfigData.ReadOnly NewConfig) {
super.PreStartConfigUpdate(NewConfig);
Config = ConfigData.ReadOnly.class.cast(NewConfig);
}
protected RuntimeMXBean RuntimeMX;
protected OperatingSystemMXBean OSMX;
protected ThreadMXBean ThreadMX;
protected MemoryMXBean MemoryMX;
public static final String COMPNS_NAME = "COMPONENT";
public static final String COMPNS_VER = "VERSION";
public static final String COMPNS_BLD = "BUILD";
public static final String COMPNS_MAIN = "PACKAGE_MAIN";
protected Object[] StaticLogItems = null;
@Override
protected void preTask() {
super.preTask();
if (Config.Stats.contains(ConfigData.StatType.RUNTIME)
|| Config.Stats.contains(ConfigData.StatType.CPUUSE)
|| Config.Stats.contains(ConfigData.StatType.APPINFO)) {
RuntimeMX = ManagementFactory.getRuntimeMXBean();
}
if (Config.Stats.contains(ConfigData.StatType.CPUUSE)) {
OSMX = ManagementFactory.getOperatingSystemMXBean();
}
if (Config.Stats.contains(ConfigData.StatType.THREADS)) {
ThreadMX = ManagementFactory.getThreadMXBean();
}
if (Config.Stats.contains(ConfigData.StatType.MEMINFO)) {
MemoryMX = ManagementFactory.getMemoryMXBean();
}
// Collect static information
List<Object> LogItems = new ArrayList<>();
if (Config.Stats.contains(ConfigData.StatType.RUNTIME)) {
// JVM info
ILog.Info("JVM: %s %s (%s %s)", RuntimeMX.getVmName(), RuntimeMX.getVmVersion(),
RuntimeMX.getSpecName(), RuntimeMX.getSpecVersion());
LogItems.add("JVMInfo");
LogItems.add(String.format("%s|%s|%s|%s", RuntimeMX.getVmName(), RuntimeMX.getVmVersion(),
RuntimeMX.getSpecName(), RuntimeMX.getSpecVersion()));
}
if (Config.Stats.contains(ConfigData.StatType.NETINFO)) {
InetAddress LocalHost = null;
try {
LocalHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
ILog.Warn("Failed to get LocalHost - %s", e);
}
String HostName = LocalHost != null? LocalHost.getHostName() : "(unknown)";
ILog.Info("HostName: %s", HostName);
LogItems.add("HostName");
LogItems.add(HostName);
}
if (Config.Stats.contains(ConfigData.StatType.APPINFO)) {
// Class info
try {
String[] ClassPaths = RuntimeMX.getClassPath().split(File.pathSeparator);
int PackageMainCount = 0;
for (String ClassPath : ClassPaths) {
URL ClassRoot;
if (ClassPath.endsWith(".jar") || ClassPath.endsWith(".zip")) {
ClassRoot = new URL("jar:" + new File(ClassPath).toURI().toURL() + "!/");
} else {
ClassRoot = new File(ClassPath).toURI().toURL();
}
for (String NSClass : new PackageClassIterable(ClassRoot, "", Entry -> {
return Entry.SimpleName().equals(Config.CompNS);
})) {
try {
// Component Version
Class<?> NS = Class.forName(NSClass);
Field NS_NAME = NS.getDeclaredField(COMPNS_NAME);
if (!Modifier.isStatic(NS_NAME.getModifiers())) {
Misc.FAIL("Field '%s' is not static", COMPNS_NAME);
}
NS_NAME.setAccessible(true);
String NAME = (String) NS_NAME.get(null);
Field NS_VER = NS.getDeclaredField(COMPNS_VER);
if (!Modifier.isStatic(NS_VER.getModifiers())) {
Misc.FAIL("Field '%s' is not static", COMPNS_VER);
}
NS_VER.setAccessible(true);
String VER = (String) NS_VER.get(null);
Field NS_BUILD = NS.getDeclaredField(COMPNS_BLD);
if (!Modifier.isStatic(NS_BUILD.getModifiers())) {
Misc.FAIL("Field '%s' is not static", COMPNS_BLD);
}
NS_BUILD.setAccessible(true);
String BUILD = (String) NS_BUILD.get(null);
boolean MainComponent = false;
try {
Field NS_MAIN = NS.getDeclaredField(COMPNS_MAIN);
if (!Modifier.isStatic(NS_MAIN.getModifiers())) {
Misc.FAIL("Field '%s' is not static", COMPNS_BLD);
}
NS_MAIN.setAccessible(true);
MainComponent = NS_MAIN.getBoolean(null);
} catch (NoSuchFieldException e) {
// Eat Exception
} catch (Throwable e) {
ILog.Warn("Error probing 'package-main' attribute - %s", e);
}
ILog.Info("%s '%s': %s (%s)", MainComponent? "Application" : "Component", NAME, VER,
BUILD);
if (MainComponent) {
PackageMainCount++;
LogItems.add("Application,Name");
LogItems.add(NAME);
LogItems.add("Application,Version");
LogItems.add(String.format("%s|%s", VER, BUILD));
} else {
LogItems.add(String.format("Component,%s", NAME));
LogItems.add(String.format("%s|%s", VER, BUILD));
}
} catch (Throwable e) {
ILog.Warn("Unable to probe component information from '%s' - %s", NSClass, e);
}
}
}
if (PackageMainCount != 1) {
if (PackageMainCount < 1) {
ILog.Warn("Missing main component specification!");
} else {
ILog.Error("Multiple main component specifications!");
}
}
} catch (Throwable e) {
Misc.CascadeThrow(e);
}
}
if (!LogItems.isEmpty()) {
StaticLogItems = LogItems.toArray();
}
}
@SuppressWarnings("restriction")
@Override
public void PollWait() {
if (Config.LogInterval > 0) {
long CurTime = System.currentTimeMillis();
long Interval = Math.abs(CurTime - LastTime);
if (Interval > Config.LogInterval) {
ILog.Info("+ Periodical statistics");
if (StaticLogItems != null) {
ZBXLog.ZInfo(StaticLogItems);
}
List<Object> LogItems = new ArrayList<>();
if (Config.Stats.contains(ConfigData.StatType.RUNTIME)
|| Config.Stats.contains(ConfigData.StatType.CPUUSE)) {
long UpTime = RuntimeMX.getUptime();
if (Config.Stats.contains(ConfigData.StatType.RUNTIME)) {
ILog.Info("Up-time: %s", Misc.FormatDeltaTime(UpTime));
double UpDays = (double) UpTime / Misc.TimeUnit.DAY.Convert(1, Misc.TimeUnit.MSEC);
LogItems.add("UpTime");
LogItems.add(UpDays);
}
if (Config.Stats.contains(ConfigData.StatType.CPUUSE)) {
long CPUTime = ((com.sun.management.OperatingSystemMXBean) OSMX).getProcessCpuTime();
long DeltaTime = TimeUnit.NSEC.Convert(CPUTime - LastCPUTime, TimeUnit.MSEC);
LastCPUTime = CPUTime;
long ITime = UpTime - LastUpTime;
LastUpTime = UpTime;
double CPUUsage = (DeltaTime * 100.0) / ITime;
long GCTime = 0;
for (GarbageCollectorMXBean GCMX : ManagementFactory.getGarbageCollectorMXBeans()) {
GCTime += GCMX.getCollectionTime();
}
long DeltaGCTime = GCTime - LastGCTime;
LastGCTime = GCTime;
double GCUsage = (DeltaGCTime * 100.0) / ITime;
ILog.Info("CPU Usage: %.2f%% (%.2f%% GC)", CPUUsage, GCUsage);
LogItems.add("CPU,App");
LogItems.add(CPUUsage);
LogItems.add("CPU,GC");
LogItems.add(GCUsage);
}
}
if (Config.Stats.contains(ConfigData.StatType.THREADS)) {
long[] ThreadIDs = ThreadMX.getAllThreadIds();
long ThreadTotal = ThreadMX.getTotalStartedThreadCount();
ILog.Info("Thread: %d running, %d total", ThreadIDs.length, ThreadTotal);
LogItems.add("Thread,Running");
LogItems.add(ThreadIDs.length);
LogItems.add("Thread,Total");
LogItems.add(ThreadTotal);
}
if (Config.Stats.contains(ConfigData.StatType.MEMINFO)) {
MemoryUsage Heap = MemoryMX.getHeapMemoryUsage();
int AllocUseHeap = (int) ((Heap.getUsed() * 100) / Heap.getCommitted());
MemoryUsage NHeap = MemoryMX.getNonHeapMemoryUsage();
int AllocUseNHeap = (int) ((NHeap.getUsed() * 100) / NHeap.getCommitted());
ILog.Info("Memory: Heap %s/%s (%d%%), Non-Heap %s/%s (%d%%)",
Misc.FormatSize(Heap.getUsed()), Misc.FormatSize(Heap.getCommitted()), AllocUseHeap,
Misc.FormatSize(NHeap.getUsed()), Misc.FormatSize(NHeap.getCommitted()),
AllocUseNHeap);
LogItems.add("Memory,Heap");
LogItems.add(Heap.getUsed());
LogItems.add("Memory,NonHeap");
LogItems.add(NHeap.getUsed());
}
if (!LogItems.isEmpty()) {
ZBXLog.ZInfo(LogItems.toArray());
}
if (LastTime == 0) {
Interval = Config.LogInterval;
}
ILog.Info("* Interval %s", Misc.FormatDeltaTime(Interval));
LastTime = CurTime;
}
}
super.PollWait();
}
@SuppressWarnings("restriction")
@Override
protected void postTask(State RefState) {
if (Config.Stats.contains(ConfigData.StatType.RUNTIME)
|| Config.Stats.contains(ConfigData.StatType.CPUUSE)) {
long UpTime = RuntimeMX.getUptime();
if (Config.Stats.contains(ConfigData.StatType.RUNTIME)) {
ILog.Info("Run-time: %s", Misc.FormatDeltaTime(UpTime));
}
if (Config.Stats.contains(ConfigData.StatType.CPUUSE)) {
long CPUTime = ((com.sun.management.OperatingSystemMXBean) OSMX).getProcessCpuTime();
long DeltaTime = TimeUnit.NSEC.Convert(CPUTime, TimeUnit.MSEC);
double CPUUsage = (DeltaTime * 100.0) / UpTime;
long GCTime = 0;
for (GarbageCollectorMXBean GCMX : ManagementFactory.getGarbageCollectorMXBeans()) {
GCTime += GCMX.getCollectionTime();
}
double GCUsage = (GCTime * 100.0) / DeltaTime;
ILog.Info("Total CPU Usage: %.2f%% (%.2f%% GC)", CPUUsage, GCUsage);
}
}
super.postTask(RefState);
}
} |
package ai.susi.server.api.cms;
import ai.susi.DAO;
import ai.susi.json.JsonObjectWithDefault;
import ai.susi.server.*;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.json.JSONObject;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class CreateSkillService extends AbstractAPIHandler implements APIHandler {
private static final long serialVersionUID = 2461878194569824151L;
@Override
public BaseUserRole getMinimalBaseUserRole() {
return BaseUserRole.ANONYMOUS;
}
@Override
public JSONObject getDefaultPermissions(BaseUserRole baseUserRole) {
return null;
}
@Override
public String getAPIPath() {
return "/cms/createSkill.txt";
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JSONObject json = new JSONObject();
Part file = req.getPart("image");
if (file == null) {
json.put("accepted", false);
json.put("message", "Image not given");
} else {
String filename = getFileName(file);
InputStream filecontent = file.getInputStream();
String model_name = req.getParameter("model");
if (model_name == null) {
model_name = "general";
}
File model = new File(DAO.model_watch_dir, model_name);
String group_name = req.getParameter("group");
if (group_name == null) {
group_name = "knowledge";
}
File group = new File(model, group_name);
String language_name = req.getParameter("language");
if (language_name == null) {
language_name = "en";
}
File language = new File(group, language_name);
String skill_name = req.getParameter("skill");
File skill = new File(language, skill_name + ".txt");
String image_name = req.getParameter("image_name");
Path p = Paths.get(language + File.separator + "images/" + image_name);
if (image_name == null || Files.exists(p)) {
// Checking for
json.put("accepted", false);
json.put("message", "The Image name not given or Image with same name is already present ");
} else {
// Checking for file existence
json.put("accepted", false);
if (skill.exists()) {
json.put("message", "The '" + skill + "' already exists.");
} else {
// Reading Content for skill
String content = req.getParameter("content");
if (content == null) {
content = "";
}
// Reading content for image
Image image = ImageIO.read(filecontent);
BufferedImage bi = this.createResizedCopy(image, 512, 512, true);
// Checks if images directory exists or not. If not then create one
if(!Files.exists(Paths.get(language.getPath() + File.separator + "images"))){
new File(language.getPath() + File.separator + "images").mkdirs();
}
ImageIO.write(bi, "jpg", new File(language.getPath() + File.separator + "images/" + image_name));
// Writing to Skill Data to File
try (FileWriter Skillfile = new FileWriter(skill)) {
Skillfile.write(content);
String path = skill.getPath().replace(DAO.model_watch_dir.toString(), "models");
//Add to git
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository = null;
try {
repository = builder.setGitDir((DAO.susi_skill_repo))
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
try (Git git = new Git(repository)) {
git.add()
.addFilepattern(path)
.call();
// commit the changes
git.commit()
.setMessage("Created " + skill_name)
.call();
json.put("accepted", true);
} catch (GitAPIException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
json.put("message", "error: " + e.getMessage());
}
}
}
}
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write(json.toString());
}
BufferedImage createResizedCopy(Image originalImage, int scaledWidth, int scaledHeight, boolean preserveAlpha) {
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
/**
* Utility method to get file name from HTTP header content-disposition
*/
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println("content-disposition header= "+contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}
@Override
public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization rights, final JsonObjectWithDefault permissions) {
return new ServiceResponse("");
}
} |
package io.mangoo;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.stream.Stream;
@SuppressWarnings("all")
public class Dependencies {
private static final String REPO = "https://repo.maven.apache.org/maven2/";
private static final String WORKDIR = System.getProperty("user.dir");
private static final String DEPENDENCIES_FILE = WORKDIR + "/dependencies.properties";
private static final String LIB_FOLDER = WORKDIR + "/lib/";
public static void main(String[] args) {
Properties properties = new Properties();
try (InputStream inputStream = Files.newInputStream(Paths.get(DEPENDENCIES_FILE))){
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
for (Entry<Object, Object> entry : properties.entrySet()) {
String dependency = (String) entry.getValue();
String[] parts = dependency.split(":");
String groupId = parts[0].replace('.', '/');
String artifact = parts[1];
String version = parts [2];
String jar = artifact + "-" + version + ".jar";
String url = REPO + groupId + "/" + artifact + "/" + version + "/" + jar;
Path file = Paths.get(LIB_FOLDER + jar);
if (!Files.exists(file)) {
deletePreviousVersion(artifact);
try (InputStream inputstream = new URL(url).openStream()){
Files.copy(inputstream, Paths.get(LIB_FOLDER + jar), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void deletePreviousVersion(String artifact) {
try (Stream<Path> stream = Files.list(Paths.get(LIB_FOLDER))) {
stream.filter(path -> path.toFile().getName().contains(artifact))
.forEach(c -> {
try {
Files.delete(c);
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
} |
package algorithms.disjointSets;
/**
* a disjoint set implemented with linked lists.
* each set is a linked list.
*
* based upon pseudocode from "Introduction to Algorithms" by Cormen et al.
*
* @author nichole
*/
public class DisjointSetHelper {
/**
* make a set out of the given node.
* runtime complexity is O(1).
*
* @param x
* @return
*/
public <T> DisjointSet<T> makeSet(DisjointSetNode<T> x) {
x.setRepresentative(x);
DisjointSet<T> list = new DisjointSet<T>();
list.setHead(x);
list.setTail(x);
list.setNumberOfNodes(1);
return list;
}
/**
* find the set representative for the given node.
* runtime complexity is O(1).
* @param x
* @return
*/
public <T> DisjointSetNode<T> findSet(DisjointSetNode<T> x) {
return x.getRepresentative();
}
/**
* append the shorter list onto the end of the longer's list.
* runtime complexity is O(N_shorter).
* @param x
* @param y
* @return
*/
public <T> DisjointSet<T> union(DisjointSet<T> x, DisjointSet<T> y) {
if (x.equals(y)) {
return x;
}
if (x.getHead().getRepresentative().equals(y.getHead().getRepresentative())) {
return x;
}
DisjointSet<T> longer, shorter;
if (x.getNumberOfNodes() >= y.getNumberOfNodes()) {
longer = x;
shorter = y;
} else {
longer = y;
shorter = x;
}
// add next references to longer
// longer.tail.next might not be pointing to last of next, so walk to end
if (longer.getTail().getNext() != null) {
DisjointSetNode<T> tmp = longer.getTail().getNext();
while (tmp.getNext() != null) {
tmp = tmp.getNext();
}
longer.setTail(tmp);
}
longer.getTail().setNext(shorter.getHead());
DisjointSetNode<T> latest = shorter.getHead();
while (latest != null) {
latest.setRepresentative(longer.getHead());
latest = latest.getNext();
}
longer.setTail(shorter.getTail());
longer.setNumberOfNodes(longer.getNumberOfNodes() + shorter.getNumberOfNodes());
return longer;
}
public static <T> String print(DisjointSet<T> x) {
DisjointSetNode<T> current = x.getHead();
StringBuilder sb = new StringBuilder();
while (current != null) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(current.getMember().toString());
current = current.getNext();
}
return sb.toString();
}
} |
/*
* $Id$
* $URL$
*/
package org.subethamail.core.lists;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RunAs;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.annotation.security.SecurityDomain;
import org.subethamail.common.ImportMessagesException;
import org.subethamail.common.MailUtils;
import org.subethamail.common.NotFoundException;
import org.subethamail.common.SearchException;
import org.subethamail.common.SubEthaMessage;
import org.subethamail.core.deliv.i.Deliverator;
import org.subethamail.core.filter.FilterRunner;
import org.subethamail.core.injector.Detacher;
import org.subethamail.core.injector.i.Injector;
import org.subethamail.core.lists.i.Archiver;
import org.subethamail.core.lists.i.ArchiverRemote;
import org.subethamail.core.lists.i.AttachmentPartData;
import org.subethamail.core.lists.i.InlinePartData;
import org.subethamail.core.lists.i.ListMgr;
import org.subethamail.core.lists.i.MailData;
import org.subethamail.core.lists.i.MailSummary;
import org.subethamail.core.lists.i.SearchHit;
import org.subethamail.core.lists.i.SearchResult;
import org.subethamail.core.lists.i.TextPartData;
import org.subethamail.core.search.i.Indexer;
import org.subethamail.core.search.i.SimpleHit;
import org.subethamail.core.search.i.SimpleResult;
import org.subethamail.core.util.PersonalBean;
import org.subethamail.core.util.Transmute;
import org.subethamail.entity.Attachment;
import org.subethamail.entity.Mail;
import org.subethamail.entity.MailingList;
import org.subethamail.entity.Person;
import org.subethamail.entity.i.Permission;
import org.subethamail.entity.i.PermissionException;
import com.sun.mail.util.LineInputStream;
/**
* Implementation of the Archiver interface.
*
* @author Jeff Schnitzer
* @author Scott Hernandez
*/
@Stateless(name="Archiver")
@SecurityDomain("subetha")
@PermitAll
@RunAs("siteAdmin")
public class ArchiverBean extends PersonalBean implements Archiver, ArchiverRemote
{
@EJB Deliverator deliverator;
@EJB FilterRunner filterRunner;
@EJB Detacher detacher;
@EJB ListMgr listManager;
@EJB Injector injector;
@EJB Indexer indexer;
private static Log log = LogFactory.getLog(ArchiverBean.class);
@Resource(mappedName="java:/Mail") private Session mailSession;
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#sendTo(java.lang.Long, String email)
*/
public void sendTo(Long mailId, String email) throws NotFoundException
{
this.deliverator.deliver(mailId, email);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getThreads(java.lang.Long)
*/
public List<MailSummary> getThreads(Long listId, int skip, int count) throws NotFoundException, PermissionException
{
Person me = this.getMe();
// Are we allowed to view archives?
MailingList list = this.getListFor(listId, Permission.VIEW_ARCHIVES, me);
List<Mail> mails = this.em.findMailByList(listId, skip, count);
// This is fun. Assemble the thread relationships.
SortedSet<Mail> roots = new TreeSet<Mail>();
for (Mail mail: mails)
{
Mail parent = mail;
while (parent.getParent() != null)
parent = parent.getParent();
roots.add(parent);
}
// Figure out if we're allowed to see emails
boolean showEmail = list.getPermissionsFor(me).contains(Permission.VIEW_ADDRESSES);
// Now generate the entire summary
return Transmute.mailSummaries(roots, showEmail, null);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#search(java.lang.Long, java.lang.String, int, int)
*/
public SearchResult search(Long listId, String query, int skip, int count) throws NotFoundException, PermissionException, SearchException
{
Person me = this.getMe();
// Are we allowed to view archives?
MailingList list = this.getListFor(listId, Permission.VIEW_ARCHIVES, me);
SimpleResult simpleResult = this.indexer.search(listId, query, skip, count);
List<SearchHit> hits = new ArrayList<SearchHit>(simpleResult.getHits().size());
// Since there might be deleted mail in the results, let's do a partial attempt
// to reduce the total number when we know about specific deleted mail. The number
// is not exact, of course, because there may be more deleted mail on different
// pages of search results. But at least the number isn't obviously wrong for
// small result sets.
int totalResults = simpleResult.getTotal();
for (SimpleHit simpleHit: simpleResult.getHits())
{
// Note that there might be deleted mail in the hits, so be careful
Mail mail = this.em.find(Mail.class, simpleHit.getId());
if (mail != null)
{
hits.add(new SearchHit(
mail.getId(),
mail.getSubject(),
list.getPermissionsFor(me).contains(Permission.VIEW_ADDRESSES)
? mail.getFromAddress().getAddress() : null,
mail.getFromAddress().getPersonal(),
mail.getSentDate(),
simpleHit.getScore()
));
}
else
{
totalResults
}
}
return new SearchResult(totalResults, hits);
}
/* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#countMailByList(java.lang.Long)
*/
public int countMailByList(Long listId)
{
return this.em.countMailByList(listId);
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getMessage(java.lang.Long, OutputStream)
*/
public void writeMessage(Long mailId, OutputStream stream) throws NotFoundException, PermissionException
{
Mail mail = this.getMailFor(mailId, Permission.VIEW_ARCHIVES);
try
{
SubEthaMessage msg = new SubEthaMessage(this.mailSession, mail.getContent());
this.filterRunner.onSend(msg, mail);
this.detacher.attach(msg);
msg.writeTo(stream);
}
catch (Exception e)
{
if (log.isDebugEnabled()) log.debug("error getting exception getting mail#" + mailId + "\n" + e.toString());
}
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#writeAttachment(java.lang.Long, java.io.OutputStream)
*/
public void writeAttachment(Long attachmentId, OutputStream stream) throws NotFoundException, PermissionException
{
Attachment a = this.em.get(Attachment.class, attachmentId);
a.getMail().getList().checkPermission(getMe(), Permission.VIEW_ARCHIVES);
Blob data = a.getContent();
try
{
BufferedInputStream bis = new BufferedInputStream(data.getBinaryStream());
int stuff;
while ((stuff = bis.read()) >= 0)
stream.write(stuff);
}
catch (SQLException ex)
{
throw new RuntimeException(ex);
}
catch (IOException ex)
{
throw new RuntimeException(ex);
}
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getAttachmentContentType(java.lang.Long)
*/
public String getAttachmentContentType(Long attachmentId) throws NotFoundException, PermissionException
{
Attachment a = this.em.get(Attachment.class, attachmentId);
a.getMail().getList().checkPermission(getMe(), Permission.VIEW_ARCHIVES);
return a.getContentType();
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#getMail(java.lang.Long)
*/
public MailData getMail(Long mailId) throws NotFoundException, PermissionException
{
Person me = this.getMe();
// Are we allowed to view archives?
Mail mail = this.getMailFor(mailId, Permission.VIEW_ARCHIVES, me);
// Figure out if we're allowed to see emails
boolean showEmail = mail.getList().getPermissionsFor(me).contains(Permission.VIEW_ADDRESSES);
MailData data = this.makeMailData(mail, showEmail);
Mail root = mail;
while (root.getParent() != null)
root = root.getParent();
// This trick inserts us into the thread hierarchy we create.
data.setThreadRoot(Transmute.mailSummary(root, showEmail, data));
return data;
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#importMessages(Long, InputStream)
*/
public int importMessages(Long listId, InputStream mboxStream) throws NotFoundException, PermissionException, ImportMessagesException
{
MailingList list = this.getListFor(listId, Permission.IMPORT_MESSAGES);
try
{
LineInputStream in = new LineInputStream(mboxStream);
String line = null;
String fromLine = null;
String envelopeSender = null;
ByteArrayOutputStream buf = null;
Date fallbackDate = new Date();
int count = 0;
for (line = in.readLine(); line != null; line = in.readLine())
{
if (line.indexOf("From ") == 0)
{
if (buf != null)
{
byte[] bytes = buf.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
Date sent = this.injector.importMessage(list.getId(), envelopeSender, bin, true, fallbackDate);
if (sent != null)
fallbackDate = sent;
count++;
}
fromLine = line;
envelopeSender = MailUtils.getMboxFrom(fromLine);
buf = new ByteArrayOutputStream();
}
else if (buf != null)
{
byte[] bytes = MailUtils.decodeMboxFrom(line).getBytes();
buf.write(bytes, 0, bytes.length);
buf.write(10);
}
}
if (buf != null)
{
byte[] bytes = buf.toByteArray();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
this.injector.importMessage(list.getId(), envelopeSender, bin, true, fallbackDate);
count++;
}
return count;
}
catch (IOException ex)
{
throw new ImportMessagesException(ex);
}
catch (MessagingException ex)
{
throw new ImportMessagesException(ex);
}
}
/**
* Makes the base mail data. Doesn't set the threadRoot.
*/
protected MailData makeMailData(Mail raw, boolean showEmail) throws NotFoundException
{
try
{
InternetAddress addy = raw.getFromAddress();
SubEthaMessage msg = new SubEthaMessage(this.mailSession, raw.getContent());
List<InlinePartData> inlineParts = new ArrayList<InlinePartData>();
List<AttachmentPartData> attachmentParts = new ArrayList<AttachmentPartData>();
for (Part part: msg.getParts())
{
String contentType = part.getContentType();
if (contentType.startsWith(SubEthaMessage.DETACHMENT_MIME_TYPE))
{
//we need the orig Content-Type before the message was munged
contentType = part.getHeader(SubEthaMessage.HDR_ORIGINAL_CONTENT_TYPE)[0];
//put back the orig Content-Type
part.setHeader(SubEthaMessage.HDR_CONTENT_TYPE, contentType);
String name = part.getFileName();
// just in case we are working with something that isn't
// C-D: attachment; filename=""
if (name == null || name.length() == 0)
name = MailUtils.getNameFromContentType(contentType);
Long id = (Long) part.getContent();
//TODO: Set the correct size. This should be the size of the Attachment.content (Blob)
AttachmentPartData apd = new AttachmentPartData(id, contentType, name, 0);
attachmentParts.add(apd);
}
else
{
// not an attachment cause it isn't stored as a detached part.
Object content = part.getContent();
String name = part.getFileName();
// just in case we are working with something that isn't
// C-D: attachment; filename=""
if (name == null || name.length() == 0)
name = MailUtils.getNameFromContentType(contentType);
InlinePartData ipd;
if (content instanceof String)
{
ipd = new TextPartData((String)content, part.getContentType(), name, part.getSize());
}
else
{
ipd = new InlinePartData(content, part.getContentType(), name, part.getSize());
}
inlineParts.add(ipd);
}
}
return new MailData(
raw.getId(),
raw.getSubject(),
showEmail ? addy.getAddress() : null,
addy.getPersonal(),
raw.getSentDate(),
Transmute.mailSummaries(raw.getReplies(), showEmail, null),
raw.getList().getId(),
inlineParts,
attachmentParts);
}
catch (MessagingException ex)
{
// Should be impossible since everything was already run through
// JavaMail when the data was imported.
throw new RuntimeException(ex);
}
catch (IOException ex)
{
// Ditto
throw new RuntimeException(ex);
}
}
/*
* (non-Javadoc)
* @see org.subethamail.core.lists.i.Archiver#deleteMail(java.lang.Long)
*/
public Long deleteMail(Long mailId) throws NotFoundException, PermissionException
{
Mail mail = this.getMailFor(mailId, Permission.DELETE_ARCHIVES);
// Make all the children belong to the parent
Mail parent = mail.getParent();
if (parent != null)
parent.getReplies().remove(mail);
for (Mail child: mail.getReplies())
{
child.setParent(parent);
if (parent != null)
parent.getReplies().add(child);
}
mail.getReplies().clear();
this.em.remove(mail);
// TODO: figure out how to remove it from the search index
return mail.getList().getId();
}
} |
package soot.dex.instructions;
import static soot.dex.Util.dottedClassName;
import static soot.dex.Util.isFloatLike;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jf.dexlib.MethodIdItem;
import org.jf.dexlib.ProtoIdItem;
import org.jf.dexlib.TypeIdItem;
import org.jf.dexlib.TypeListItem;
import org.jf.dexlib.Code.Instruction;
import org.jf.dexlib.Code.InstructionWithReference;
import org.jf.dexlib.Code.Format.Instruction35c;
import org.jf.dexlib.Code.Format.Instruction3rc;
import soot.Local;
import soot.RefType;
import soot.Scene;
import soot.SootClass;
import soot.SootMethodRef;
import soot.SootResolver;
import soot.Type;
import soot.dex.DexBody;
import soot.dex.DexType;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.tagkit.SourceLineNumberTag;
public abstract class MethodInvocationInstruction extends DexlibAbstractInstruction implements DanglingInstruction {
// stores the dangling InvokeExpr
protected InvokeExpr invocation;
public MethodInvocationInstruction(Instruction instruction, int codeAddress) {
super(instruction, codeAddress);
}
public void finalize(DexBody body, DexlibAbstractInstruction successor) {
// defer final jimplification to move result
if (successor instanceof MoveResultInstruction) {
MoveResultInstruction i = (MoveResultInstruction)successor;
i.setExpr(invocation);
if (lineNumber != -1)
i.setTag(new SourceLineNumberTag(lineNumber));
// this is a invoke statement (the MoveResult had to be the direct successor for an expression)
} else {
InvokeStmt invoke = Jimple.v().newInvokeStmt(invocation);
defineBlock(invoke);
tagWithLineNumber(invoke);
body.add(invoke);
}
}
public Set<DexType> introducedTypes() {
Set<DexType> types = new HashSet<DexType>();
MethodIdItem method = (MethodIdItem) (((InstructionWithReference) instruction).getReferencedItem());
types.add(new DexType(method.getContainingClass()));
ProtoIdItem prototype = method.getPrototype();
types.add(new DexType(prototype.getReturnType()));
List<TypeIdItem> paramTypes = TypeListItem.getTypes(prototype.getParameters());
if (paramTypes != null)
for (TypeIdItem type : paramTypes)
types.add(new DexType(type));
return types;
}
// overriden in InvokeStaticInstruction
@Override
boolean isUsedAsFloatingPoint(DexBody body, int register) {
return isUsedAsFloatingPoint(body, register, false);
}
/**
* Determine if register is used as floating point.
*
* Abstraction for static and non-static methods. Non-static methods need to ignore the first parameter (this)
* @param isStatic if this method is static
*/
protected boolean isUsedAsFloatingPoint(DexBody body, int register, boolean isStatic) {
MethodIdItem item = (MethodIdItem) ((InstructionWithReference) instruction).getReferencedItem();
List<TypeIdItem> paramTypes = TypeListItem.getTypes(item.getPrototype().getParameters());
List<Integer> regs = getUsedRegistersNums();
if (paramTypes == null)
return false;
for (int i = 0, j = 0; i < regs.size(); i++, j++) {
if (!isStatic && i == 0) {
j
continue;
}
if (regs.get(i) == register && isFloatLike(DexType.toSoot(paramTypes.get(j))))
return true;
if (DexType.isWide(paramTypes.get(j)))
i++;
}
return false;
}
/**
* Determine if register is used as object.
*
* Abstraction for static and non-static methods. Non-static methods need to ignore the first parameter (this)
* @param isStatic if this method is static
*/
protected boolean isUsedAsObject(DexBody body, int register, boolean isStatic) {
MethodIdItem item = (MethodIdItem) ((InstructionWithReference) instruction).getReferencedItem();
List<TypeIdItem> paramTypes = TypeListItem.getTypes(item.getPrototype().getParameters());
List<Integer> regs = getUsedRegistersNums();
if (paramTypes == null)
return false;
// we call a method on the register
if (!isStatic && regs.get(0) == register)
return true;
// we call a method with register as a reftype paramter
for (int i = 0, j = 0; i < regs.size(); i++, j++) {
if (!isStatic && i == 0) {
j
continue;
}
if (regs.get(i) == register && (DexType.toSoot(paramTypes.get(j)) instanceof RefType))
return true;
if (DexType.isWide(paramTypes.get(j)))
i++;
}
return false;
}
/**
* Return the SootMethodRef for the invoked method.
*
*/
protected SootMethodRef getSootMethodRef() {
return getSootMethodRef(false);
}
/**
* Return the static SootMethodRef for the invoked method.
*
*/
protected SootMethodRef getStaticSootMethodRef() {
return getSootMethodRef(true);
}
/**
* Return the SootMethodRef for the invoked method.
*
* @param isStatic for a static method ref
*/
private SootMethodRef getSootMethodRef(boolean isStatic) {
MethodIdItem item = (MethodIdItem) ((InstructionWithReference) instruction).getReferencedItem();
String className = dottedClassName(((TypeIdItem) item.getContainingClass()).getTypeDescriptor());
SootClass sc = SootResolver.v().makeClassRef(className);
String methodName = item.getMethodName().getStringValue();
ProtoIdItem prototype = item.getPrototype();
Type returnType = DexType.toSoot(prototype.getReturnType());
List<Type> parameterTypes = new ArrayList<Type>();
List<TypeIdItem> paramTypes = TypeListItem.getTypes(prototype.getParameters());
if (paramTypes != null)
for (TypeIdItem type : paramTypes)
parameterTypes.add(DexType.toSoot(type));
return Scene.v().makeMethodRef(sc, methodName, parameterTypes, returnType, isStatic);
}
/**
* Build the parameters of this invocation.
*
* The first parameter is the instance for which the method is invoked (if method is non-static).
*
* @param body the body to build for and into
* @param isStatic if method is static
*
* @return the converted parameters
*/
protected List<Local> buildParameters(DexBody body, boolean isStatic) {
MethodIdItem item = (MethodIdItem) ((InstructionWithReference) instruction).getReferencedItem();
List<TypeIdItem> paramTypes = TypeListItem.getTypes(item.getPrototype().getParameters());
List<Local> parameters = new ArrayList<Local>();
List<Integer> regs = getUsedRegistersNums();
for (int i = 0, j = 0; i < regs.size(); i++, j++) {
parameters.add(body.getRegisterLocal(regs.get(i)));
// if method is non-static the first parameter is the instance
// pointer and has no corresponding parameter
if (!isStatic && i == 0) {
j
continue;
}
// if current parameter is wide ignore the next register
if (paramTypes != null && DexType.isWide(paramTypes.get(j)))
i++;
}
return parameters;
}
/**
* Return the indices used in this instruction.
*
* @return a list of register indices
*/
protected List<Integer> getUsedRegistersNums() {
if (instruction instanceof Instruction35c)
return getUsedRegistersNums((Instruction35c) instruction);
else if (instruction instanceof Instruction3rc)
return getUsedRegistersNums((Instruction3rc) instruction);
throw new RuntimeException("Instruction is neither a InvokeInstruction nor a InvokeRangeInstruction");
}
/**
* Return the indices used in the given instruction.
*
* @param instruction a invocation instruction
* @return a list of register indices
*/
private static List<Integer> getUsedRegistersNums(Instruction35c instruction) {
int[] regs = {
instruction.getRegisterD(),
instruction.getRegisterE(),
instruction.getRegisterF(),
instruction.getRegisterG(),
instruction.getRegisterA()
};
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < instruction.getRegCount(); i++)
l.add(regs[i]);
return l;
}
/**
* Return the indices used in the given instruction.
*
* @param instruction a range invocation instruction
* @return a list of register indices
*/
private static List<Integer> getUsedRegistersNums(Instruction3rc instruction) {
List<Integer> regs = new ArrayList<Integer>();
int start = instruction.getStartRegister();
for (int i = start; i < start + instruction.getRegCount(); i++)
regs.add(i);
return regs;
}
} |
package org.openmrs.maven.plugins;
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.openmrs.maven.plugins.model.Server;
import org.openmrs.maven.plugins.utility.Project;
import org.twdata.maven.mojoexecutor.MojoExecutor;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration;
import static org.twdata.maven.mojoexecutor.MojoExecutor.element;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo;
import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment;
import static org.twdata.maven.mojoexecutor.MojoExecutor.goal;
import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId;
import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin;
import static org.twdata.maven.mojoexecutor.MojoExecutor.version;
/**
* @goal build
* @requiresProject false
*/
public class Build extends AbstractTask {
/**
* @parameter expression="${serverId}"
*/
private String serverId;
private final static String FRONTEND_BUILDER_GROUP_ID = "com.github.eirslett";
private final static String FRONTEND_BUILDER_ARTIFACT_ID = "frontend-maven-plugin";
private final static String FRONTEND_BUILDER_VERSION = "1.0";
public Build(){}
public Build(AbstractTask other) { super(other); }
public Build(AbstractTask other, String serverId){
super(other);
this.serverId = serverId;
}
@Override
public void executeTask() throws MojoExecutionException, MojoFailureException {
File configFile = new File("webpack.config.js");
if (configFile.exists()) {
boolean buildOwa = wizard.promptYesNo("OWA Project found in this directory, do You want to build it?");
if (buildOwa) {
buildOwaProject();
}
else {
boolean buildWatchedProjects = wizard.promptYesNo("Do You want to build all watched projects instead?");
if (buildWatchedProjects) {
buildWatchedProjects();
}
else {
throw new IllegalStateException("Task aborted");
}
}
}
else {
buildWatchedProjects();
}
}
private void buildWatchedProjects() throws MojoExecutionException, MojoFailureException {
serverId = wizard.promptForExistingServerIdIfMissing(serverId);
Server server = loadValidatedServer(serverId);
if (server.getWatchedProjects().isEmpty()) {
wizard.showMessage("There are no watched projects for " + serverId + " server.");
return;
}
File tempFolder = createTempReactorProject(server);
try {
cleanInstallServerProject(tempFolder);
} catch (Exception e) {
throw new IllegalStateException("Failed to build project in "+tempFolder.getAbsolutePath(), e);
} finally {
deleteTempReactorProject(tempFolder);
}
try {
deployWatchedModules(server);
} catch (MavenInvocationException e) {
throw new MojoFailureException("Failed to deploy watched modules", e);
}
}
private void buildOwaProject() throws MojoExecutionException {
System.out.println("Building OWA project...");
List<MojoExecutor.Element> configuration = new ArrayList<MojoExecutor.Element>();
configuration.add(element("nodeVersion", "v4.4.5"));
configuration.add(element("npmVersion", "2.15.5"));
executeMojo(
plugin(
groupId(FRONTEND_BUILDER_GROUP_ID),
artifactId(FRONTEND_BUILDER_ARTIFACT_ID),
version(FRONTEND_BUILDER_VERSION)
),
goal("install-node-and-npm"),
configuration(configuration.toArray(new MojoExecutor.Element[0])),
executionEnvironment(mavenProject, mavenSession, pluginManager)
);
configuration = new ArrayList<MojoExecutor.Element>();
configuration.add(element("arguments", "install"));
executeMojo(
plugin(
groupId(FRONTEND_BUILDER_GROUP_ID),
artifactId(FRONTEND_BUILDER_ARTIFACT_ID),
version(FRONTEND_BUILDER_VERSION)
),
goal("npm"),
configuration(configuration.toArray(new MojoExecutor.Element[0])),
executionEnvironment(mavenProject, mavenSession, pluginManager)
);
configuration = new ArrayList<MojoExecutor.Element>();
configuration.add(element("arguments", "run build"));
executeMojo(
plugin(
groupId(FRONTEND_BUILDER_GROUP_ID),
artifactId(FRONTEND_BUILDER_ARTIFACT_ID),
version(FRONTEND_BUILDER_VERSION)
),
goal("npm"),
configuration(configuration.toArray(new MojoExecutor.Element[0])),
executionEnvironment(mavenProject, mavenSession, pluginManager)
);
System.out.println("Build done.");
}
/**
* Creates temporary Maven reactor project to build dependencies in the correct order
*
* @param server
* @return
* @throws MojoFailureException
* @throws MojoExecutionException
*/
private File createTempReactorProject(Server server) throws MojoFailureException, MojoExecutionException {
File tempFolder = new File(server.getServerDirectory(), "temp-project");
if (!tempFolder.exists()) {
tempFolder.mkdir();
}
Model tempModel = createModel();
Set<Project> watchedModules = server.getWatchedProjects();
for(Project module: watchedModules){
Path newLink = Paths.get(new File(tempFolder, module.getArtifactId()).getAbsolutePath());
Path existingfile = Paths.get(module.getPath());
try {
Files.createSymbolicLink(newLink, existingfile);
} catch (IOException e) {
copyModuleToTempServer(module.getPath(), newLink.toString());
} finally {
tempModel.addModule(module.getArtifactId());
}
}
try {
Writer writer = new FileWriter(new File(tempFolder, "pom.xml"));
new MavenXpp3Writer().write(writer, tempModel);
} catch (IOException e) {
throw new RuntimeException("Failed to write pom.xml", e);
}
return tempFolder;
}
private void copyModuleToTempServer(String orginalPath, String newPath){
File module = new File(orginalPath);
File copiedModule = new File(newPath);
try {
FileUtils.copyDirectory(module, copiedModule);
} catch (IOException e) {
throw new RuntimeException("Could not copy modules", e);
}
}
/**
* Deletes temporary Maven reactor project
*
* @param tempFolder
*/
private void deleteTempReactorProject(File tempFolder) {
FileUtils.deleteQuietly(tempFolder);
}
/**
* Creates Model to generate pom.xml for temporary project
*
* @return
*/
private Model createModel(){
Model model = new Model();
model.setArtifactId(String.format("openmrs-sdk-server-%s", serverId));
model.setVersion("1.0.0-SNAPSHOT");
model.setGroupId("org.openmrs");
model.setPackaging("pom");
model.setModelVersion("4.0.0");
return model;
}
/**
* Deploy all watched modules to server
*
* @param server
* @throws MojoFailureException
* @throws MojoExecutionException
* @throws MavenInvocationException
*/
private void deployWatchedModules(Server server) throws MojoFailureException, MojoExecutionException, MavenInvocationException {
Set<Project> watchedProject = server.getWatchedProjects();
for (Project module: watchedProject) {
Project project = Project.loadProject(new File(module.getPath()));
new Deploy(this).deployModule(project.getGroupId(), project.getArtifactId(), project.getVersion(), server);
}
}
/**
* Run "mvn clean install -DskipTests" command in the given directory
* @param tempProject
* @throws MojoFailureException
*/
private void cleanInstallServerProject(File tempProject) throws MojoFailureException, MavenInvocationException {
Properties properties = new Properties();
properties.put("skipTests", "true");
InvocationRequest request = new DefaultInvocationRequest();
request.setGoals(Arrays.asList("clean install"))
.setProperties(properties)
.setShowErrors(mavenSession.getRequest().isShowErrors())
.setOffline(mavenSession.getRequest().isOffline())
.setLocalRepositoryDirectory(mavenSession.getRequest().getLocalRepositoryPath())
.setUpdateSnapshots(mavenSession.getRequest().isUpdateSnapshots())
.setShowVersion(true)
.setBaseDirectory(tempProject);
Invoker invoker = new DefaultInvoker();
InvocationResult result = invoker.execute(request);
if (result.getExitCode() != 0 ) {
throw new IllegalStateException("Failed building project in "+tempProject.getAbsolutePath(), result.getExecutionException());
}
}
} |
package hudson.model;
import junit.framework.TestCase;
import java.util.Random;
/**
* @author Stephen Connolly
*/
public class ResourceListTest extends TestCase {
private Resource a1, a2, a3, a4, a;
private Resource b1, b2, b3, b4, b;
private Resource c1, c2, c3, c4, c;
private Resource d, e, f;
private int fWriteCount;
private Random entropy;
private ResourceList x;
private ResourceList y;
private ResourceList z;
public void setUp() {
entropy = new Random();
a = new Resource("A" + entropy.nextLong());
a1 = new Resource(a, "A" + entropy.nextLong());
a2 = new Resource(a, "A" + entropy.nextLong());
a3 = new Resource(a, "A" + entropy.nextLong());
a4 = new Resource(a, "A" + entropy.nextLong());
b = new Resource("B" + entropy.nextLong());
b1 = new Resource(b, "B" + entropy.nextLong());
b2 = new Resource(b, "B" + entropy.nextLong());
b3 = new Resource(b, "B" + entropy.nextLong());
b4 = new Resource(b, "B" + entropy.nextLong());
c = new Resource(null, "C" + entropy.nextLong(), 3);
c1 = new Resource(c, "C" + entropy.nextLong(), 3);
c2 = new Resource(c, "C" + entropy.nextLong(), 3);
c3 = new Resource(c, "C" + entropy.nextLong(), 3);
c4 = new Resource(c, "C" + entropy.nextLong(), 3);
d = new Resource("D" + entropy.nextLong());
e = new Resource(null, "E" + entropy.nextLong());
fWriteCount = 5 + entropy.nextInt(100);
f = new Resource(null, "F" + entropy.nextLong(), 5);
x = new ResourceList();
y = new ResourceList();
z = new ResourceList();
}
public void testEmptyLists() throws Exception {
z.r(a);
ResourceList w = new ResourceList();
w.w(a);
assertFalse("Empty vs Empty", x.isCollidingWith(y));
assertFalse("Empty vs Empty", y.isCollidingWith(x));
assertFalse("Empty vs Read", x.isCollidingWith(z));
assertFalse("Read vs Empty", z.isCollidingWith(x));
assertFalse("Empty vs Write", x.isCollidingWith(w));
assertFalse("Write vs Empty", w.isCollidingWith(x));
}
public void testSimpleR() throws Exception {
x.r(a);
y.r(b);
z.r(a);
assertFalse("Read-Read", x.isCollidingWith(y));
assertFalse("Read-Read", y.isCollidingWith(x));
assertFalse("Read-Read", x.isCollidingWith(z));
assertFalse("Read-Read", z.isCollidingWith(x));
assertFalse("Read-Read", z.isCollidingWith(y));
assertFalse("Read-Read", y.isCollidingWith(z));
}
public void testSimpleRW() throws Exception {
x.r(a);
y.r(b);
z.w(a);
assertFalse("Read-Read different resources", x.isCollidingWith(y));
assertFalse("Read-Read different resources", y.isCollidingWith(x));
assertTrue("Read-Write same resource", x.isCollidingWith(z));
assertTrue("Read-Write same resource", z.isCollidingWith(x));
assertFalse("Read-Write different resources", z.isCollidingWith(y));
assertFalse("Read-Write different resources", y.isCollidingWith(z));
}
public void testSimpleW() throws Exception {
x.w(a);
y.w(b);
z.w(a);
assertFalse(x.isCollidingWith(y));
assertFalse(y.isCollidingWith(x));
assertTrue(x.isCollidingWith(z));
assertTrue(z.isCollidingWith(x));
assertFalse(z.isCollidingWith(y));
assertFalse(y.isCollidingWith(z));
ResourceList w = ResourceList.union(x,y);
assertTrue(w.isCollidingWith(z));
assertTrue(z.isCollidingWith(w));
ResourceList v = new ResourceList();
v.w(a1);
assertTrue(w.isCollidingWith(v));
assertTrue(z.isCollidingWith(w));
}
public void testParentChildR() throws Exception {
x.r(a1);
x.r(a2);
y.r(a3);
y.r(a4);
z.r(a);
assertFalse("Reads should never conflict", x.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(x));
assertFalse("Reads should never conflict", x.isCollidingWith(z));
assertFalse("Reads should never conflict", z.isCollidingWith(x));
assertFalse("Reads should never conflict", z.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(z));
}
public void testParentChildW() throws Exception {
x.w(a1);
x.w(a2);
y.w(a3);
y.w(a4);
z.w(a);
assertFalse("Sibling resources should not conflict", x.isCollidingWith(y));
assertFalse("Sibling resources should not conflict", y.isCollidingWith(x));
assertTrue("Taking parent resource assumes all children are taken too", x.isCollidingWith(z));
assertTrue("Taking parent resource assumes all children are taken too", z.isCollidingWith(x));
assertTrue("Taking parent resource assumes all children are taken too", z.isCollidingWith(y));
assertTrue("Taking parent resource assumes all children are taken too", y.isCollidingWith(z));
}
public void testParentChildR3() throws Exception {
x.r(c1);
x.r(c2);
y.r(c3);
y.r(c4);
z.r(c);
assertFalse("Reads should never conflict", x.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(x));
assertFalse("Reads should never conflict", x.isCollidingWith(z));
assertFalse("Reads should never conflict", z.isCollidingWith(x));
assertFalse("Reads should never conflict", z.isCollidingWith(y));
assertFalse("Reads should never conflict", y.isCollidingWith(z));
}
public void testParentChildW3() throws Exception {
x.w(c1);
x.w(c2);
y.w(c3);
y.w(c4);
z.w(c);
assertFalse("Sibling resources should not conflict", x.isCollidingWith(y));
assertFalse("Sibling resources should not conflict", y.isCollidingWith(x));
assertFalse("Using less than the limit of child resources should not be a problem", x.isCollidingWith(z));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(x));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(y));
assertFalse("Using less than the limit of child resources should not be a problem", y.isCollidingWith(z));
ResourceList w = ResourceList.union(x,y);
assertFalse("Using less than the limit of child resources should not be a problem", w.isCollidingWith(z));
assertFalse("Using less than the limit of child resources should not be a problem", z.isCollidingWith(w));
assertFalse("Total count = 2, limit is 3", w.isCollidingWith(x));
assertFalse("Total count = 2, limit is 3", x.isCollidingWith(w));
ResourceList v = ResourceList.union(x,x); // write count is two
assertFalse("Total count = 3, limit is 3", v.isCollidingWith(x));
assertFalse("Total count = 3, limit is 3", x.isCollidingWith(v));
v = ResourceList.union(v,x); // write count is three
assertTrue("Total count = 4, limit is 3", v.isCollidingWith(x));
assertTrue("Total count = 4, limit is 3", x.isCollidingWith(v));
}
public void testMultiWrite1() throws Exception {
y.w(e);
assertFalse(x.isCollidingWith(y));
assertFalse(y.isCollidingWith(x));
for (int i = 0; i < fWriteCount; i++) {
x.w(e);
assertTrue("Total = W" + (i + 1) + ", Limit = W1", x.isCollidingWith(y));
assertTrue("Total = W" + (i + 1) + ", Limit = W1", y.isCollidingWith(x));
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertTrue("Total = W" + (i + fWriteCount) + ", Limit = W1", x.isCollidingWith(y));
assertTrue("Total = W" + (i + fWriteCount) + ", Limit = W1", y.isCollidingWith(x));
x.w(e);
}
}
public void testMultiWriteN() throws Exception {
y.w(f);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = W" + (i + 1) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = W" + (i + 1) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.w(f);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertTrue("Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertTrue("Total = W" + (fWriteCount + i) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.w(f);
}
}
public void testMultiRead1() throws Exception {
y.r(e);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = R" + (i + 1) + ", Limit = W1", x.isCollidingWith(y));
assertFalse("Total = R" + (i + 1) + ", Limit = W1", y.isCollidingWith(x));
x.r(e);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertFalse("Total = R" + (i + fWriteCount) + ", Limit = W1", x.isCollidingWith(y));
assertFalse("Total = R" + (i + fWriteCount) + ", Limit = W1", y.isCollidingWith(x));
x.r(e);
}
}
public void testMultiReadN() throws Exception {
y.r(f);
for (int i = 0; i < fWriteCount; i++) {
assertFalse("Total = R" + (i + 1) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = R" + (i + 1) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.r(f);
}
int j = entropy.nextInt(50) + 3;
for (int i = 1; i < j; i++) {
assertFalse("Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount, x.isCollidingWith(y));
assertFalse("Total = R" + (fWriteCount + i) + ", Limit = W" + fWriteCount, y.isCollidingWith(x));
x.r(f);
}
}
} |
package plugin.google.maps;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.CordovaWebView;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class AsyncLoadImage extends AsyncTask<Void, Void, AsyncLoadImage.AsyncLoadImageResult> {
private AsyncLoadImageInterface callback;
private float density = Resources.getSystem().getDisplayMetrics().density;
private AsyncLoadImageOptions mOptions;
private String userAgent;
private String currentPageUrl;
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception.
static int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
public static BitmapCache mIconCache = new BitmapCache(maxMemory / 8);
private final String TAG = "AsyncLoadImage";
private CordovaWebView webView;
private CordovaInterface cordova;
public static class AsyncLoadImageOptions {
String url;
int width;
int height;
boolean noCaching;
}
public static class AsyncLoadImageResult {
Bitmap image;
boolean cacheHit;
String cacheKey;
}
public AsyncLoadImage(CordovaInterface cordova, CordovaWebView webView, AsyncLoadImageOptions options, AsyncLoadImageInterface callback) {
this.callback = callback;
this.mOptions = options;
this.webView = webView;
this.cordova = cordova;
}
public static String getCacheKey(String url, int width, int height) {
if (url == null) {
return null;
}
try {
return getCacheKey(new URL(url), width, height);
} catch (MalformedURLException e) {
return url.hashCode() + "/" + width + "x" + height;
}
}
public static String getCacheKey(URL url, int width, int height) {
return url.hashCode() + "/" + width + "x" + height;
}
public static void addBitmapToMemoryCache(String key, Bitmap image) {
if (getBitmapFromMemCache(key) == null) {
mIconCache.put(key, image.copy(image.getConfig(), true));
}
}
public static void removeBitmapFromMemCahce(String key) {
Bitmap image = mIconCache.remove(key);
if (image == null || image.isRecycled()) {
return;
}
image.recycle();
}
public static Bitmap getBitmapFromMemCache(String key) {
Bitmap image = mIconCache.get(key);
if (image == null || image.isRecycled()) {
return null;
}
return image.copy(image.getConfig(), true);
}
@Override
protected void onCancelled(AsyncLoadImageResult result) {
super.onCancelled(result);
if (result == null) {
return;
}
if (!result.image.isRecycled()) {
result.image.recycle();
}
result.image = null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// If icon url contains "cdvfile://", convert to physical path.
if (mOptions.url.indexOf("cdvfile:
CordovaResourceApi resourceApi = webView.getResourceApi();
mOptions.url = PluginUtil.getAbsolutePathFromCDVFilePath(resourceApi, mOptions.url);
}
String currentPage = webView.getUrl();
if (currentPage != null) {
// Maybe someone close the map page.
this.cancel(true);
return;
}
currentPage = currentPage.replaceAll("
currentPage = currentPage.replaceAll("\\?.*$", "");
currentPage = currentPage.replaceAll("[^\\/]*$", "");
this.currentPageUrl = currentPage;
//Log.d(TAG, "-->currentPageUrl = " + this.currentPageUrl);
//View browserView = webView.getView();
//String browserViewName = browserView.getClass().getName();
this.userAgent = "Mozilla";
/*
if("org.xwalk.core.XWalkView".equals(browserViewName) ||
"org.crosswalk.engine.XWalkCordovaView".equals(browserViewName)) {
CordovaPreferences preferences = webView.getPreferences();
// Set xwalk webview settings by Cordova preferences.
String xwalkUserAgent = preferences == null ? "" : preferences.getString("xwalkUserAgent", "");
if (!xwalkUserAgent.isEmpty()) {
this.userAgent = xwalkUserAgent;
}
String appendUserAgent = preferences.getString("AppendUserAgent", "");
if (!appendUserAgent.isEmpty()) {
this.userAgent = this.userAgent + " " + appendUserAgent;
}
if ("".equals(this.userAgent)) {
this.userAgent = "Mozilla";
}
} else {
this.userAgent = ((WebView) webView.getEngine().getView()).getSettings().getUserAgentString();
}
*/
}
protected AsyncLoadImageResult doInBackground(Void... params) {
int mWidth = mOptions.width;
int mHeight = mOptions.height;
String iconUrl = mOptions.url;
String orgIconUrl = iconUrl;
Bitmap image = null;
if (iconUrl == null) {
return null;
}
String cacheKey = null;
cacheKey = getCacheKey(orgIconUrl, mWidth, mHeight);
image = getBitmapFromMemCache(cacheKey);
if (image != null) {
AsyncLoadImageResult result = new AsyncLoadImageResult();
result.image = image;
result.cacheHit = true;
result.cacheKey = cacheKey;
return result;
}
//Log.d(TAG, "--> iconUrl = " + iconUrl);
// Load image from local path
if (!iconUrl.startsWith("data:image")) {
if (currentPageUrl.startsWith("http://localhost") ||
currentPageUrl.startsWith("http://127.0.0.1")) {
if (iconUrl.contains(":
iconUrl = iconUrl.replaceAll("http://.+?/", "file:///android_asset/www/");
} else {
// Avoid WebViewLocalServer (because can not make a connection for some reason)
iconUrl = "file:///android_asset/www/".concat(iconUrl);
}
}
if (!iconUrl.contains(":
!iconUrl.startsWith("/") &&
!iconUrl.startsWith("www/") &&
!iconUrl.startsWith("data:image") &&
!iconUrl.startsWith("./") &&
!iconUrl.startsWith("../")) {
iconUrl = "./" + iconUrl;
//Log.d(TAG, "--> iconUrl = " + iconUrl);
}
if (iconUrl.startsWith("./") || iconUrl.startsWith("../")) {
iconUrl = iconUrl.replace("(\\.\\/)+", "./");
String currentPage = this.currentPageUrl;
currentPage = currentPage.replaceAll("[^\\/]*$", "");
currentPage = currentPage.replaceAll("
currentPage = currentPage.replaceAll("\\/[^\\/]+\\.[^\\/]+$", "");
if (!currentPage.endsWith("/")) {
currentPage = currentPage + "/";
}
iconUrl = currentPage + iconUrl;
iconUrl = iconUrl.replaceAll("(\\/\\.\\/+)+", "/");
//Log.d(TAG, "--> iconUrl = " + iconUrl);
}
if (iconUrl.indexOf("file:
!iconUrl.contains("file:///android_asset/")) {
iconUrl = iconUrl.replace("file:
} else {
//Log.d(TAG, "--> iconUrl = " + iconUrl);
// if (iconUrl.indexOf("file:///android_asset/") == 0) {
// iconUrl = iconUrl.replace("file:///android_asset/", "");
//Log.d(TAG, "iconUrl(222) = " + iconUrl);
if (iconUrl.contains("./")) {
try {
boolean isAbsolutePath = iconUrl.startsWith("/");
File relativePath = new File(iconUrl);
iconUrl = relativePath.getCanonicalPath();
//Log.d(TAG, "iconUrl = " + iconUrl);
if (!isAbsolutePath) {
iconUrl = iconUrl.substring(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
cacheKey = getCacheKey(iconUrl, mWidth, mHeight);
image = getBitmapFromMemCache(cacheKey);
if (image != null) {
AsyncLoadImageResult result = new AsyncLoadImageResult();
result.image = image;
result.cacheHit = true;
result.cacheKey = cacheKey;
return result;
}
cacheKey = getCacheKey(orgIconUrl, mWidth, mHeight);
if (iconUrl.indexOf("http") == 0) {
// Load image from the Internet
try {
URL url = new URL(iconUrl);
boolean redirect = true;
HttpURLConnection http = null;
String cookies = null;
int redirectCnt = 0;
while(redirect && redirectCnt < 10) {
redirect = false;
http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("GET");
if (cookies != null) {
http.setRequestProperty("Cookie", cookies);
}
http.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
http.addRequestProperty("User-Agent", this.userAgent);
http.setInstanceFollowRedirects(true);
HttpURLConnection.setFollowRedirects(true);
// normally, 3xx is redirect
try {
int status = http.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
if (redirect) {
// get redirect url from "location" header field
url = new URL(http.getHeaderField("Location"));
// get the cookie if need, for login
cookies = http.getHeaderField("Set-Cookie");
// Disconnect the current connection
http.disconnect();
redirectCnt++;
continue;
}
if (status == HttpURLConnection.HTTP_OK) {
break;
} else {
return null;
}
} catch (Exception e) {
Log.e(TAG, "can not connect to " + iconUrl, e);
}
}
Bitmap myBitmap = null;
InputStream inputStream = http.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
inputStream.close();
byte[] imageBytes = buffer.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Config.ARGB_8888;
// The below line just checking the bitmap size (width,height).
// Returned value is always null.
BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
if (mWidth < 1 && mHeight < 1) {
mWidth = options.outWidth;
mHeight = options.outHeight;
}
// Resize
int newWidth = (int)(mWidth * density);
int newHeight = (int)(mHeight * density);
if (newWidth > 2000 || newHeight > 2000) {
float rationResize;
if (newWidth >= newHeight) {
rationResize = 2000.0f / ((float) newWidth);
} else {
rationResize = 2000.0f / ((float) newHeight);
}
newWidth = (int)(((float)newWidth) * rationResize);
newHeight = (int)(((float)newHeight) * rationResize);
Log.w(TAG, "Since the image size is too large, the image size resizes down mandatory");
}
Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
float ratioX = newWidth / (float) options.outWidth;
float ratioY = newHeight / (float) options.outHeight;
float middleX = newWidth / 2.0f;
float middleY = newHeight / 2.0f;
options.inJustDecodeBounds = false;
//options.inSampleSize = (int) Math.max(ratioX, ratioY);
options.outWidth = newWidth;
options.outHeight = newHeight;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
myBitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length, options);
canvas.drawBitmap(myBitmap, middleX - options.outWidth / 2, middleY - options.outHeight / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
myBitmap.recycle();
myBitmap = null;
canvas = null;
imageBytes = null;
AsyncLoadImageResult result = new AsyncLoadImageResult();
result.image = scaledBitmap;
result.cacheHit = false;
if (!mOptions.noCaching) {
result.cacheKey = cacheKey;
addBitmapToMemoryCache(cacheKey, scaledBitmap);
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
//Log.d(TAG, "--> iconUrl = " + iconUrl);
if (iconUrl.indexOf("data:image/") == 0 && iconUrl.contains(";base64,")) {
String[] tmp = iconUrl.split(",");
image = PluginUtil.getBitmapFromBase64encodedImage(tmp[1]);
} else {
try {
InputStream inputStream = null;
if (iconUrl.startsWith("file:/android_asset/")) {
AssetManager assetManager = cordova.getActivity().getAssets();
iconUrl = iconUrl.replace("file:/android_asset/", "");
inputStream = assetManager.open(iconUrl);
//Log.d(TAG, "--> iconUrl = " + iconUrl);
} else if (iconUrl.startsWith("file:///android_asset/")) {
AssetManager assetManager = cordova.getActivity().getAssets();
iconUrl = iconUrl.replace("file:///android_asset/", "");
inputStream = assetManager.open(iconUrl);
//Log.d(TAG, "--> iconUrl = " + iconUrl);
} else if (iconUrl.startsWith("/")) {
File file = new File(iconUrl);
inputStream = new FileInputStream(file);
}
if (inputStream != null) {
image = BitmapFactory.decodeStream(inputStream);
inputStream.close();
} else {
Log.e(TAG, "Can not load the file from '" + iconUrl + "'");
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
if (mWidth > 0 && mHeight > 0) {
mWidth = Math.round(mWidth * density);
mHeight = Math.round(mHeight * density);
image = PluginUtil.resizeBitmap(image, mWidth, mHeight);
} else {
image = PluginUtil.scaleBitmapForDevice(image);
}
AsyncLoadImageResult result = new AsyncLoadImageResult();
result.image = image;
result.cacheHit = false;
if (!mOptions.noCaching) {
result.cacheKey = cacheKey;
addBitmapToMemoryCache(cacheKey, image);
}
return result;
}
}
@Override
protected void onPostExecute(AsyncLoadImageResult result) {
this.callback.onPostExecute(result);
}
} |
package imagej.ui;
import imagej.ImageJ;
import imagej.event.EventHandler;
import imagej.event.EventService;
import imagej.event.StatusService;
import imagej.ext.InstantiableException;
import imagej.ext.display.Display;
import imagej.ext.display.DisplayService;
import imagej.ext.display.event.DisplayActivatedEvent;
import imagej.ext.display.event.DisplayCreatedEvent;
import imagej.ext.display.event.DisplayDeletedEvent;
import imagej.ext.display.event.DisplayUpdatedEvent;
import imagej.ext.display.ui.DisplayViewer;
import imagej.ext.display.ui.DisplayWindow;
import imagej.ext.menu.MenuService;
import imagej.ext.plugin.PluginInfo;
import imagej.ext.plugin.PluginService;
import imagej.ext.tool.ToolService;
import imagej.log.LogService;
import imagej.options.OptionsService;
import imagej.platform.AppService;
import imagej.platform.PlatformService;
import imagej.platform.event.AppQuitEvent;
import imagej.service.AbstractService;
import imagej.service.Service;
import imagej.thread.ThreadService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Default service for handling ImageJ user interfaces.
*
* @author Curtis Rueden
*/
@Service
public final class DefaultUIService extends AbstractService implements
UIService
{
private final LogService log;
private final EventService eventService;
private final StatusService statusService;
private final ThreadService threadService;
private final PlatformService platformService;
private final PluginService pluginService;
private final MenuService menuService;
private final ToolService toolService;
private final OptionsService optionsService;
private final AppService appService;
/**
* A list of extant display viewers. It's needed in order to find the viewer
* associated with a display.
*/
protected final List<DisplayViewer<?>> displayViewers =
new ArrayList<DisplayViewer<?>>();
/** The active user interface. */
private UserInterface userInterface;
/** Available user interfaces. */
private List<UserInterface> availableUIs;
private boolean activationInvocationPending = false;
// -- Constructors --
public DefaultUIService() {
// NB: Required by SezPoz.
super(null);
throw new UnsupportedOperationException();
}
public DefaultUIService(final ImageJ context, final LogService log,
final ThreadService threadService, final EventService eventService,
final StatusService statusService, final PlatformService platformService,
final PluginService pluginService, final MenuService menuService,
final ToolService toolService, final OptionsService optionsService,
final AppService appService)
{
super(context);
this.log = log;
this.threadService = threadService;
this.eventService = eventService;
this.statusService = statusService;
this.platformService = platformService;
this.pluginService = pluginService;
this.menuService = menuService;
this.toolService = toolService;
this.optionsService = optionsService;
this.appService = appService;
launchUI();
subscribeToEvents(eventService);
}
// -- UIService methods --
@Override
public LogService getLog() {
return log;
}
@Override
public ThreadService getThreadService() {
return threadService;
}
@Override
public EventService getEventService() {
return eventService;
}
@Override
public StatusService getStatusService() {
return statusService;
}
@Override
public PlatformService getPlatformService() {
return platformService;
}
@Override
public PluginService getPluginService() {
return pluginService;
}
@Override
public MenuService getMenuService() {
return menuService;
}
@Override
public ToolService getToolService() {
return toolService;
}
@Override
public OptionsService getOptionsService() {
return optionsService;
}
@Override
public AppService getAppService() {
return appService;
}
@Override
public void createUI() {
if (userInterface == null) return;
userInterface.create();
}
@Override
public void processArgs(final String[] args) {
log.info("Received command line arguments:");
for (final String arg : args) {
log.info("\t" + arg);
}
if (userInterface == null) return;
userInterface.processArgs(args);
}
@Override
public UserInterface getUI() {
return userInterface;
}
@Override
public List<UserInterface> getAvailableUIs() {
return availableUIs;
}
@Override
public DisplayViewer<?> getDisplayViewer(final Display<?> display) {
for (final DisplayViewer<?> displayViewer : displayViewers) {
if (displayViewer.getDisplay() == display) return displayViewer;
}
log.warn("No viewer found for display: '" + display.getName() + "'");
return null;
}
@Override
public OutputWindow createOutputWindow(final String title) {
if (userInterface == null) return null;
return userInterface.newOutputWindow(title);
}
@Override
public DialogPrompt.Result showDialog(final String message) {
return showDialog(message, "ImageJ");
}
@Override
public DialogPrompt.Result showDialog(final String message,
final String title)
{
return showDialog(message, title,
DialogPrompt.MessageType.INFORMATION_MESSAGE);
}
@Override
public DialogPrompt.Result showDialog(final String message,
final String title, final DialogPrompt.MessageType messageType)
{
return showDialog(message, title, messageType,
DialogPrompt.OptionType.DEFAULT_OPTION);
}
@Override
public DialogPrompt.Result showDialog(final String message,
final String title, final DialogPrompt.MessageType messageType,
final DialogPrompt.OptionType optionType)
{
if (userInterface == null) return null;
final DialogPrompt dialogPrompt =
userInterface.dialogPrompt(message, title, messageType, optionType);
return dialogPrompt.prompt();
}
@Override
public void showContextMenu(final String menuRoot, final Display<?> display,
final int x, final int y)
{
if (userInterface == null) return;
userInterface.showContextMenu(menuRoot, display, x, y);
}
// -- Event handlers --
/**
* Called when a display is created. This is the magical place where the
* display model is connected with the real UI.
*/
@EventHandler
protected void onEvent(final DisplayCreatedEvent e) {
final Display<?> display = e.getObject();
for (@SuppressWarnings("rawtypes")
final PluginInfo<? extends DisplayViewer> info : pluginService
.getPluginsOfType(DisplayViewer.class))
{
try {
final DisplayViewer<?> displayViewer = info.createInstance();
if (displayViewer.canView(display)) {
final DisplayWindow displayWindow =
getUI().createDisplayWindow(display);
displayViewer.view(displayWindow, display);
displayWindow.setTitle(display.getName());
displayViewers.add(displayViewer);
displayWindow.showDisplay(true);
return;
}
}
catch (final InstantiableException exc) {
log.warn("Failed to create instance of " + info.getClassName(), exc);
}
}
log.warn("No suitable DisplayViewer found for display");
}
/**
* Called when a display is deleted. The display viewer is not removed
* from the list of viewers until after this returns.
*/
@EventHandler
protected void onEvent(final DisplayDeletedEvent e) {
final Display<?> display = e.getObject();
final DisplayViewer<?> displayViewer = getDisplayViewer(display);
if (displayViewer != null) {
displayViewer.onDisplayDeletedEvent(e);
displayViewers.remove(displayViewer);
}
}
/** Called when a display is updated. */
@EventHandler
protected void onEvent(final DisplayUpdatedEvent e) {
final Display<?> display = e.getDisplay();
final DisplayViewer<?> displayViewer = getDisplayViewer(display);
if (displayViewer != null) {
displayViewer.onDisplayUpdatedEvent(e);
}
}
/**
* Called when a display is activated.
* <p>
* The goal here is to eventually synchronize the window activation state with
* the display activation state if the display activation state changed
* programatically. We queue a call on the UI thread to activate the display
* viewer of the currently active window.
* </p>
*/
@EventHandler
protected void onEvent(final DisplayActivatedEvent e) {
if (activationInvocationPending) return;
activationInvocationPending = true;
threadService.queue(new Runnable() {
@Override
public void run() {
final DisplayService displayService =
e.getContext().getService(DisplayService.class);
final Display<?> activeDisplay = displayService.getActiveDisplay();
if (activeDisplay != null) {
final DisplayViewer<?> displayViewer =
getDisplayViewer(activeDisplay);
if (displayViewer != null) displayViewer.onDisplayActivatedEvent(e);
}
activationInvocationPending = false;
}
});
}
@Override
@EventHandler
public void onEvent(final AppQuitEvent event) {
userInterface.saveLocation();
}
// -- Helper methods --
/** Discovers and launches the user interface. */
private void launchUI() {
final List<UserInterface> uis = discoverUIs();
availableUIs = Collections.unmodifiableList(uis);
if (uis.size() > 0) {
final UserInterface ui = uis.get(0);
log.info("Launching user interface: " + ui.getClass().getName());
ui.initialize(this);
userInterface = ui;
}
else {
log.warn("No user interfaces found.");
userInterface = null;
}
}
/** Discovers available user interfaces. */
private List<UserInterface> discoverUIs() {
final List<UserInterface> uis = new ArrayList<UserInterface>();
for (final PluginInfo<? extends UserInterface> info : pluginService
.getPluginsOfType(UserInterface.class))
{
try {
final UserInterface ui = info.createInstance();
log.info("Discovered user interface: " + ui.getClass().getName());
uis.add(ui);
}
catch (final InstantiableException e) {
log.warn("Invalid user interface: " + info.getClassName(), e);
}
}
return uis;
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.micromanager.acquisition.engine;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.micromanager.api.Autofocus;
import org.micromanager.api.EngineTask;
import mmcorej.CMMCore;
import mmcorej.Configuration;
import mmcorej.TaggedImage;
import org.json.JSONObject;
import org.micromanager.navigation.MultiStagePosition;
import org.micromanager.navigation.StagePosition;
import org.micromanager.utils.JavaUtils;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.ReportingUtils;
/**
*
* @author arthur
*/
public class ImageTask implements EngineTask {
public final ImageRequest imageRequest_;
private Engine eng_;
private CMMCore core_;
private boolean stopRequested_;
private boolean pauseRequested_;
boolean setZPosition_ = false;
private final JSONObject md_;
private double zPosition_;
private final SimpleDateFormat iso8601modified;
ImageTask(ImageRequest imageRequest) {
imageRequest_ = imageRequest;
stopRequested_ = false;
md_ = new JSONObject();
iso8601modified = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss Z");
}
private void log(String msg) {
ReportingUtils.logMessage("ImageTask: " + msg);
}
public void run(Engine eng) {
eng_ = eng;
core_ = eng.core_;
if (!isStopRequested() && !core_.isSequenceRunning()) {
updateChannel();
}
if (!isStopRequested()) {
updatePosition();
}
if (!isStopRequested()) {
sleep();
}
if (!isStopRequested() && !core_.isSequenceRunning()) {
autofocus();
}
if (!isStopRequested() && !core_.isSequenceRunning()) {
updateSlice();
}
if (!isStopRequested()) {
acquireImage();
}
}
void updateChannel() {
if (imageRequest_.UseChannel) {
try {
core_.setExposure(imageRequest_.Channel.exposure_);
imageRequest_.exposure = imageRequest_.Channel.exposure_;
String chanGroup = imageRequest_.Channel.name_;
if (chanGroup.length() == 0) {
chanGroup = core_.getChannelGroup();
}
core_.setConfig(chanGroup, imageRequest_.Channel.config_);
core_.waitForConfig(chanGroup,imageRequest_.Channel.config_);
log("channel set");
} catch (Exception ex) {
ReportingUtils.logError(ex, "Channel setting failed.");
}
}
}
void updateSlice() {
try {
if (imageRequest_.UseSlice) {
setZPosition_ = true;
if (imageRequest_.relativeZSlices) {
zPosition_ += imageRequest_.SlicePosition;
System.out.println(zPosition_);
} else {
zPosition_ = imageRequest_.SlicePosition;
}
} else {
zPosition_ = core_.getPosition(core_.getFocusDevice());
}
if (imageRequest_.UseChannel && imageRequest_.Channel.zOffset_ != 0) {
setZPosition_ = true;
zPosition_ += imageRequest_.Channel.zOffset_;
}
if (setZPosition_) {
imageRequest_.zPosition = zPosition_;
core_.setPosition(core_.getFocusDevice(), zPosition_);
core_.waitForDevice(core_.getFocusDevice());
}
} catch (Exception e) {
ReportingUtils.logError(e);
}
}
void updatePosition() {
try {
zPosition_ = imageRequest_.zReference;
if (imageRequest_.UsePosition) {
MultiStagePosition msp = imageRequest_.Position;
for (int i = 0; i < msp.size(); ++i) {
StagePosition sp = msp.get(i);
if (sp.numAxes == 1) {
if (sp.stageName.equals(core_.getFocusDevice())) {
zPosition_ = sp.x; // Surprisingly it should be sp.x!
setZPosition_ = true;
} else {
core_.setPosition(sp.stageName, sp.x);
core_.waitForDevice(sp.stageName);
md_.put("Acquisition-"+sp.stageName+"RequestedZPosition",
sp.x);
}
} else if (sp.numAxes == 2) {
core_.setXYPosition(sp.stageName, sp.x, sp.y);
core_.waitForDevice(sp.stageName);
md_.put("Acquisition-"+sp.stageName+"RequestedXPosition",
sp.x);
md_.put("Acquisition-"+sp.stageName+"RequestedYPosition",
sp.y);
}
log("position set\n");
}
}
String focusDevice = core_.getFocusDevice();
if (!focusDevice.equals(""))
core_.waitForDevice(focusDevice);
} catch (Exception ex) {
ReportingUtils.logError(ex, "Set position failed.");
}
}
public synchronized void sleep() {
if (imageRequest_.UseFrame) {
while (!stopRequested_ && eng_.lastWakeTime_ > 0) {
double sleepTime = (eng_.lastWakeTime_ + imageRequest_.WaitTime)
- (System.nanoTime() / 1000000);
if (sleepTime > 0) {
try {
wait((long) sleepTime);
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
} else {
if (imageRequest_.WaitTime > 0) {
try {
md_.put("Acquisition-TimingState", "Lagging");
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
break;
}
}
log("wait finished");
eng_.lastWakeTime_ = (System.nanoTime() / 1000000);
}
}
public void autofocus() {
String afResult = "AutofocusResult";
StagePosition sp;
Autofocus afDevice;
if (imageRequest_.AutoFocus) {
try {
String focusDevice = core_.getFocusDevice();
core_.setPosition(focusDevice, zPosition_);
core_.waitForDevice(focusDevice);
afDevice = eng_.getAutofocusManager().getDevice();
afDevice.fullFocus();
md_.put(afResult, "Success");
if (imageRequest_.UsePosition) {
sp = imageRequest_.Position.get(core_.getFocusDevice());
if (sp != null)
sp.x = core_.getPosition(core_.getFocusDevice());
}
zPosition_ = core_.getPosition(focusDevice);
core_.waitForDevice(focusDevice);
} catch (Exception ex) {
ReportingUtils.logError(ex);
try {
md_.put("AutofocusResult", "Failure");
} catch (Exception ex1) {
ReportingUtils.logError(ex1);
}
}
}
}
void acquireImage() {
waitDuringPause();
try {
md_.put("Slice", imageRequest_.SliceIndex);
if (imageRequest_.UseChannel) {
md_.put("Channel", imageRequest_.Channel.config_);
}
md_.put("PositionIndex", imageRequest_.PositionIndex);
md_.put("ChannelIndex", imageRequest_.ChannelIndex);
md_.put("Frame", imageRequest_.FrameIndex);
if (imageRequest_.UsePosition) {
md_.put("PositionName", imageRequest_.Position.getLabel());
}
md_.put("SlicePosition", imageRequest_.SlicePosition);
long bits = core_.getBytesPerPixel() * 8;
String lbl = "";
if (core_.getNumberOfComponents() == 1) {
lbl = "GRAY";
} else if (core_.getNumberOfComponents() == 4) {
lbl = "RGB";
}
md_.put("Exposure-ms", imageRequest_.exposure);
md_.put("PixelSizeUm", core_.getPixelSizeUm());
try {
String focusDevice = core_.getFocusDevice();
if (!focusDevice.equals(""))
md_.put("ZPositionUm", core_.getPosition(core_.getFocusDevice()));
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
md_.put("PixelType", lbl + bits);
try {
MDUtils.setWidth(md_, (int) core_.getImageWidth());
MDUtils.setHeight(md_, (int) core_.getImageHeight());
} catch (Exception e) {
ReportingUtils.logError(e);
}
long dTime = System.nanoTime() - eng_.getStartTimeNs();
md_.put("ElapsedTime-ms", ((double) dTime) / 1e9);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
try {
String shutterDevice = core_.getShutterDevice();
if (!shutterDevice.equals(""))
core_.waitForDevice(shutterDevice);
if (core_.getAutoShutter())
core_.setAutoShutter(false);
if (eng_.autoShutterSelected_ && !core_.getShutterOpen()) {
core_.setShutterOpen(true);
log("opened shutter");
}
Object pixels;
if (!imageRequest_.collectBurst) {
core_.snapImage(); //Should be: core_.snapImage(jsonMetadata);
log("snapped image");
if (eng_.autoShutterSelected_ && imageRequest_.CloseShutter) {
if (!shutterDevice.equals(""))
core_.waitForDevice(shutterDevice);
core_.setShutterOpen(false);
log("closed shutter");
}
pixels = core_.getImage();
} else {
while (core_.getRemainingImageCount() == 0)
JavaUtils.sleep(5);
pixels = core_.popNextImage();
log("collected burst image");
}
md_.put("Source",core_.getCameraDevice());
Configuration config = core_.getSystemStateCache();
MDUtils.addConfiguration(md_, config);
if (imageRequest_.NextWaitTime > 0) {
long nextFrameTimeMs = (long)
(imageRequest_.NextWaitTime + eng_.lastWakeTime_);
md_.put("NextFrameTimeMs", nextFrameTimeMs);
}
MDUtils.addRandomUUID(md_);
md_.put("Time", iso8601modified.format(new Date()));
md_.put("Binning",
core_.getProperty(core_.getCameraDevice(), "Binning"));
TaggedImage taggedImage = new TaggedImage(pixels, md_);
eng_.imageReceivingQueue_.put(taggedImage);
} catch (Exception ex) {
ReportingUtils.logError(ex);
}
}
public synchronized void requestStop() {
stopRequested_ = true;
notify();
}
public synchronized void requestPause() {
pauseRequested_ = true;
}
public synchronized void requestResume() {
pauseRequested_ = false;
this.notify();
}
private synchronized boolean isPauseRequested() {
return pauseRequested_;
}
private synchronized void waitDuringPause() {
try {
if (isPauseRequested()) {
wait();
}
} catch (InterruptedException ex) {
ReportingUtils.logError(ex);
}
}
private synchronized boolean isStopRequested() {
return stopRequested_;
}
} |
package com.itpos.itposcheckin.Fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.itpos.itposcheckin.R;
public class ToDo extends DefaultFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.todo, container, false);
return view;
}
@Override
public void onBackStackChanged() {
}
//TODO parse JSON returned from http request and add them to list
} |
package org.springframework.roo.model;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.StringUtils;
/**
* The declaration of a Java type (i.e. contains no details of its members).
* Instances are immutable.
*
* <p>
* Note that a Java type can be contained within a package, but a package is not a type.
*
* <p>
* This class is used whenever a formal reference to a Java type is required.
* It provides convenient ways to determine the type's simple name and package name.
* A related {@link org.springframework.core.convert.converter.Converter} is also offered.
*
* @author Ben Alex
* @since 1.0
*/
public class JavaType implements Comparable<JavaType> {
// Constants
public static final JavaType CLASS = new JavaType("java.lang.Class");
public static final JavaType OBJECT = new JavaType("java.lang.Object");
public static final JavaType STRING = new JavaType("java.lang.String");
public static final JavaType BOOLEAN_OBJECT = new JavaType("java.lang.Boolean");
public static final JavaType CHAR_OBJECT = new JavaType("java.lang.Character");
public static final JavaType BYTE_OBJECT = new JavaType("java.lang.Byte");
public static final JavaType SHORT_OBJECT = new JavaType("java.lang.Short");
public static final JavaType INT_OBJECT = new JavaType("java.lang.Integer");
public static final JavaType LONG_OBJECT = new JavaType("java.lang.Long");
public static final JavaType FLOAT_OBJECT = new JavaType("java.lang.Float");
public static final JavaType DOUBLE_OBJECT = new JavaType("java.lang.Double");
public static final JavaType VOID_OBJECT = new JavaType("java.lang.Void");
public static final JavaType BOOLEAN_PRIMITIVE = new JavaType("java.lang.Boolean", 0, DataType.PRIMITIVE, null, null);
public static final JavaType CHAR_PRIMITIVE = new JavaType("java.lang.Character", 0, DataType.PRIMITIVE, null, null);
public static final JavaType BYTE_PRIMITIVE = new JavaType("java.lang.Byte", 0, DataType.PRIMITIVE, null, null);
public static final JavaType BYTE_ARRAY_PRIMITIVE = new JavaType("java.lang.Byte", 1, DataType.PRIMITIVE, null, null);
public static final JavaType SHORT_PRIMITIVE = new JavaType("java.lang.Short", 0, DataType.PRIMITIVE, null, null);
public static final JavaType INT_PRIMITIVE = new JavaType("java.lang.Integer", 0, DataType.PRIMITIVE, null, null);
public static final JavaType LONG_PRIMITIVE = new JavaType("java.lang.Long", 0, DataType.PRIMITIVE, null, null);
public static final JavaType FLOAT_PRIMITIVE = new JavaType("java.lang.Float", 0, DataType.PRIMITIVE, null, null);
public static final JavaType DOUBLE_PRIMITIVE = new JavaType("java.lang.Double", 0, DataType.PRIMITIVE, null, null);
public static final JavaType VOID_PRIMITIVE = new JavaType("java.lang.Void", 0, DataType.PRIMITIVE, null, null);
/**
* @deprecated use {@link #STRING} instead
*/
@Deprecated
public static final JavaType STRING_OBJECT = STRING;
// Used for wildcard type parameters; it must be one or the other
public static final JavaSymbolName WILDCARD_EXTENDS = new JavaSymbolName("_ROO_WILDCARD_EXTENDS_"); // List<? extends YY>
public static final JavaSymbolName WILDCARD_SUPER = new JavaSymbolName("_ROO_WILDCARD_SUPER_"); // List<? super XXXX>
public static final JavaSymbolName WILDCARD_NEITHER = new JavaSymbolName("_ROO_WILDCARD_NEITHER_"); // List<?>
// The fully-qualified names of common collection types
private static final Set<String> COMMON_COLLECTION_TYPES = new HashSet<String>();
static {
COMMON_COLLECTION_TYPES.add(ArrayList.class.getName());
COMMON_COLLECTION_TYPES.add(Collection.class.getName());
COMMON_COLLECTION_TYPES.add(HashMap.class.getName());
COMMON_COLLECTION_TYPES.add(HashSet.class.getName());
COMMON_COLLECTION_TYPES.add(List.class.getName());
COMMON_COLLECTION_TYPES.add(Map.class.getName());
COMMON_COLLECTION_TYPES.add(Set.class.getName());
COMMON_COLLECTION_TYPES.add(TreeMap.class.getName());
COMMON_COLLECTION_TYPES.add(Vector.class.getName());
}
/**
* Returns a {@link JavaType} for a list of the given element type
*
* @param elementType the type of element in the list (required)
* @return a non-<code>null</code> type
*/
public static JavaType listOf(final JavaType elementType) {
return new JavaType(List.class.getName(), 0, DataType.TYPE, null, Arrays.asList(elementType));
}
/**
* Factory method for a {@link JavaType} with full details. Recall that
* {@link JavaType} is immutable and therefore this is the only way of
* setting these non-default values.
*
* This is a factory method rather than a constructor so as not to cause
* ambiguity problems for existing callers of {@link #JavaType(String, int, DataType, JavaSymbolName, List)}
*
* @param fullyQualifiedTypeName the name (as per the rules above)
* @param arrayDimensions the number of array dimensions (0 = not an array, 1 = one-dimensional array, etc.)
* @param dataType the {@link DataType} (required)
* @param argName the type argument name to this particular Java type (can be null if unassigned)
* @param parameters the type parameters applicable (can be null if there aren't any)
* @since 1.2.0
*/
public static JavaType getInstance(final String fullyQualifiedTypeName, final int arrayDimensions, final DataType dataType, final JavaSymbolName argName, final JavaType... parameters) {
return new JavaType(fullyQualifiedTypeName, arrayDimensions, dataType, argName, Arrays.asList(parameters));
}
// Fields
private final boolean defaultPackage;
private final int arrayDimensions;
private final DataType dataType;
private final JavaSymbolName argName;
private final List<JavaType> parameters;
private final String fullyQualifiedTypeName;
private final String simpleTypeName;
public JavaType(String fullyQualifiedTypeName) {
this(fullyQualifiedTypeName, 0, DataType.TYPE, null, null);
}
/**
* Constructor equivalent to {@link #JavaType(String)}, but takes a Class
* for convenience and type safety.
*
* @param type the class for which to create an instance (required)
* @since 1.2.0
*/
public JavaType(final Class<?> type) {
this(type.getName());
}
/**
* Construct a {@link JavaType} with full details. Recall that {@link JavaType} is immutable and therefore this is the only way of
* setting these non-default values.
*
* @param fullyQualifiedTypeName the name (as per the rules above)
* @param arrayDimensions the number of array dimensions (0 = not an array, 1 = one-dimensional array, etc.)
* @param dataType the {@link DataType} (required)
* @param argName the type argument name to this particular Java type (can be null if unassigned)
* @param parameters the type parameters applicable (can be null if there aren't any)
*/
public JavaType(final String fullyQualifiedTypeName, final int arrayDimensions, final DataType dataType, final JavaSymbolName argName, final List<JavaType> parameters) {
Assert.hasText(fullyQualifiedTypeName, "Fully qualified type name required");
Assert.notNull(dataType, "Data type required");
JavaSymbolName.assertJavaNameLegal(fullyQualifiedTypeName);
this.argName = argName;
this.arrayDimensions = arrayDimensions;
this.dataType = dataType;
this.fullyQualifiedTypeName = fullyQualifiedTypeName;
this.defaultPackage = !fullyQualifiedTypeName.contains(".");
if (defaultPackage) {
this.simpleTypeName = fullyQualifiedTypeName;
} else {
final int offset = fullyQualifiedTypeName.lastIndexOf(".");
this.simpleTypeName = fullyQualifiedTypeName.substring(offset + 1);
}
this.parameters = new ArrayList<JavaType>();
if (parameters != null) {
this.parameters.addAll(parameters);
}
}
/**
* @return the name (does not contain any periods; never null or empty)
*/
public String getSimpleTypeName() {
return simpleTypeName;
}
/**
* @return the fully qualified name (complies with the rules specified in the constructor)
*/
public String getFullyQualifiedTypeName() {
return fullyQualifiedTypeName;
}
public String getNameIncludingTypeParameters() {
return getNameIncludingTypeParameters(false, null, new HashMap<String, String>());
}
public String getNameIncludingTypeParameters(boolean staticForm, ImportRegistrationResolver resolver) {
return getNameIncludingTypeParameters(staticForm, resolver, new HashMap<String, String>());
}
private String getNameIncludingTypeParameters(boolean staticForm, ImportRegistrationResolver resolver, Map<String, String> types) {
if (DataType.PRIMITIVE == dataType) {
Assert.isTrue(parameters.isEmpty(), "A primitive cannot have parameters");
if (this.fullyQualifiedTypeName.equals(Integer.class.getName())) {
return "int" + getArraySuffix();
} else if (this.fullyQualifiedTypeName.equals(Character.class.getName())) {
return "char" + getArraySuffix();
} else if (this.fullyQualifiedTypeName.equals(Void.class.getName())) {
return "void";
}
return StringUtils.uncapitalize(this.getSimpleTypeName() + getArraySuffix());
}
StringBuilder sb = new StringBuilder();
if (WILDCARD_EXTENDS.equals(argName)) {
sb.append("?");
if (dataType == DataType.TYPE || !staticForm) {
sb.append(" extends ");
} else if (types.containsKey(fullyQualifiedTypeName)) {
sb.append(" extends ").append(types.get(fullyQualifiedTypeName));
}
} else if (WILDCARD_SUPER.equals(argName)) {
sb.append("?");
if (dataType == DataType.TYPE || !staticForm) {
sb.append(" super ");
} else if (types.containsKey(fullyQualifiedTypeName)) {
sb.append(" extends ").append(types.get(fullyQualifiedTypeName));
}
} else if (WILDCARD_NEITHER.equals(argName)) {
sb.append("?");
} else if (argName != null && !staticForm) {
sb.append(argName);
if (dataType == DataType.TYPE) {
if (!fullyQualifiedTypeName.equals(OBJECT.getFullyQualifiedTypeName())) {
sb.append(" extends ");
}
}
}
if (!WILDCARD_NEITHER.equals(argName)) {
// It wasn't a WILDCARD_NEITHER, so we might need to continue with more details
if (dataType == DataType.TYPE || !staticForm) {
if (resolver != null) {
if (resolver.isFullyQualifiedFormRequiredAfterAutoImport(this)) {
sb.append(fullyQualifiedTypeName);
} else {
sb.append(getSimpleTypeName());
}
} else {
if (fullyQualifiedTypeName.equals(OBJECT.getFullyQualifiedTypeName())) {
// It's Object, so we need to only append if this isn't a type arg
if (argName == null) {
sb.append(fullyQualifiedTypeName);
}
} else {
// It's ok to just append it as it's not Object
sb.append(fullyQualifiedTypeName);
}
}
}
if (this.parameters.size() > 0 && (dataType == DataType.TYPE || !staticForm)) {
sb.append("<");
int counter = 0;
for (JavaType param : this.parameters) {
counter++;
if (counter > 1) {
sb.append(", ");
}
sb.append(param.getNameIncludingTypeParameters(staticForm, resolver, types));
counter++;
}
sb.append(">");
}
sb.append(getArraySuffix());
}
if (argName != null && !argName.equals(WILDCARD_EXTENDS) && !argName.equals(WILDCARD_SUPER) && !argName.equals(WILDCARD_NEITHER)) {
types.put(this.argName.getSymbolName(), sb.toString());
}
return sb.toString();
}
/**
* @return the package name (never null)
*/
public JavaPackage getPackage() {
if (isDefaultPackage() && !Character.isUpperCase(fullyQualifiedTypeName.charAt(0))) {
return new JavaPackage("");
}
JavaType enclosingType = getEnclosingType();
if (enclosingType != null) {
String enclosingTypeFullyQualifiedTypeName = enclosingType.getFullyQualifiedTypeName();
int offset = enclosingTypeFullyQualifiedTypeName.lastIndexOf(".");
// Handle case where the package name after the last period starts with a capital letter.
if (offset > -1 && Character.isUpperCase(enclosingTypeFullyQualifiedTypeName.charAt(offset + 1))) {
return new JavaPackage(enclosingTypeFullyQualifiedTypeName);
}
return enclosingType.getPackage();
}
int offset = fullyQualifiedTypeName.lastIndexOf(".");
return offset == -1 ? new JavaPackage("") : new JavaPackage(fullyQualifiedTypeName.substring(0, offset));
}
/**
* @return the enclosing type, if any (will return null if there is no enclosing type)
*/
public JavaType getEnclosingType() {
int offset = fullyQualifiedTypeName.lastIndexOf(".");
if (offset == -1) {
// There is no dot in the name, so there's no way there's an enclosing type
return null;
}
String possibleName = fullyQualifiedTypeName.substring(0, offset);
int offset2 = possibleName.lastIndexOf(".");
// Start by handling if the type name is Foo.Bar (ie an enclosed type within the default package)
String enclosedWithinPackage = null;
String enclosedWithinTypeName = possibleName;
// Handle the probability the type name is within a package like com.alpha.Foo.Bar
if (offset2 > -1) {
enclosedWithinPackage = possibleName.substring(0, offset2);
enclosedWithinTypeName = possibleName.substring(offset2 + 1);
}
if (Character.isUpperCase(enclosedWithinTypeName.charAt(0))) {
// First letter is upper-case, so treat it as a type name for now
String preTypeNamePortion = enclosedWithinPackage == null ? "" : (enclosedWithinPackage + ".");
return new JavaType(preTypeNamePortion + enclosedWithinTypeName);
}
return null;
}
public boolean isDefaultPackage() {
return defaultPackage;
}
public boolean isPrimitive() {
return DataType.PRIMITIVE == dataType;
}
public boolean isCommonCollectionType() {
return COMMON_COLLECTION_TYPES.contains(this.fullyQualifiedTypeName);
}
public List<JavaType> getParameters() {
return Collections.unmodifiableList(this.parameters);
}
public boolean isArray() {
return arrayDimensions > 0;
}
public int getArray() {
return arrayDimensions;
}
private String getArraySuffix() {
if (arrayDimensions == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arrayDimensions; i++) {
sb.append("[]");
}
return sb.toString();
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((fullyQualifiedTypeName == null) ? 0 : fullyQualifiedTypeName.hashCode());
result = prime * result + ((dataType == null) ? 0 : dataType.hashCode());
result = prime * result + arrayDimensions;
return result;
}
public boolean equals(final Object obj) {
// NB: Not using the normal convention of delegating to compareTo (for efficiency reasons)
return obj != null
&& obj instanceof JavaType
&& this.fullyQualifiedTypeName.equals(((JavaType) obj).getFullyQualifiedTypeName())
&& this.dataType == ((JavaType) obj).getDataType()
&& this.arrayDimensions == ((JavaType) obj).getArray()
&& ((JavaType) obj).getParameters().containsAll(this.parameters);
}
public int compareTo(JavaType o) {
// NB: If adding more fields to this class ensure the equals(Object) method is updated accordingly
if (o == null) return -1;
if (equals(o)) return 0;
return toString().compareTo(o.toString());
}
public String toString() {
return getNameIncludingTypeParameters();
}
public JavaSymbolName getArgName() {
return argName;
}
public DataType getDataType() {
return dataType;
}
} |
package subobjectjava.translate;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jnome.core.language.Java;
import jnome.input.JavaFactory;
import jnome.output.JavaCodeWriter;
import subobjectjava.model.language.JLo;
import chameleon.core.compilationunit.CompilationUnit;
import chameleon.core.lookup.LookupException;
import chameleon.exception.ModelException;
import chameleon.oo.plugin.ObjectOrientedFactory;
import chameleon.plugin.build.BuildProgressHelper;
import chameleon.plugin.output.Syntax;
import chameleon.support.translate.IncrementalTranslator;
public class IncrementalJavaTranslator extends IncrementalTranslator<JLo, Java> {
public IncrementalJavaTranslator(JLo source, Java target) {
super(source, target);
_translator = new JavaTranslator();
}
public IncrementalJavaTranslator(JLo source) {
this(source,createJava());
}
private static Java createJava() {
Java java = new Java();
java.setPlugin(Syntax.class, new JavaCodeWriter());
java.setPlugin(ObjectOrientedFactory.class, new JavaFactory());
return java;
}
private JavaTranslator _translator;
public AbstractTranslator basicTranslator() {
return _translator;
}
/*@
@ public behavior
@
@ pre compilationUnit != null;
@
@ post \result != null;
@ post \fresh(\result);
@*/
public Collection<CompilationUnit> build(CompilationUnit source, List<CompilationUnit> allProjectCompilationUnits, BuildProgressHelper buildProgressHelper) throws ModelException {
//initTargetLanguage();
List<CompilationUnit> result = translate(source,implementationCompilationUnit(source));
CompilationUnit ifaceCU = (result.size() > 1 ? result.get(1) : null);
store(source, ifaceCU,_interfaceMap);
buildProgressHelper.addWorked(1);
return result;
}
public List<CompilationUnit> translate(CompilationUnit source, CompilationUnit implementationCompilationUnit) throws LookupException, ModelException {
return _translator.translate(source, implementationCompilationUnit);
}
private Map<CompilationUnit,CompilationUnit> _interfaceMap = new HashMap<CompilationUnit,CompilationUnit>();
} |
package edu.cmu.cs.diamond.opendiamond;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.Spring;
import javax.swing.SpringLayout;
public class Util {
private Util() {
}
// XXX endian specific
public static int extractInt(byte[] value) {
return (value[3] & 0xFF) << 24 | (value[2] & 0xFF) << 16
| (value[1] & 0xFF) << 8 | (value[0] & 0xFF);
}
public static long extractLong(byte[] value) {
return ((long) (value[7] & 0xFF) << 56)
| ((long) (value[6] & 0xFF) << 48)
| ((long) (value[5] & 0xFF) << 40)
| ((long) (value[4] & 0xFF) << 32)
| ((long) (value[3] & 0xFF) << 24)
| ((long) (value[2] & 0xFF) << 16)
| ((long) (value[1] & 0xFF) << 8) | (value[0] & 0xFF);
}
public static double extractDouble(byte[] value) {
return Double.longBitsToDouble(extractLong(value));
}
public static double getScaleForResize(int w, int h, int maxW, int maxH) {
double scale = 1.0;
double imgAspect = (double) w / h;
double targetAspect = (double) maxW / maxH;
if (imgAspect > targetAspect) {
// more wide
if (w > maxW) {
scale = (double) maxW / w;
}
} else {
// more tall
if (h > maxH) {
scale = (double) maxH / h;
}
}
return scale;
}
public static BufferedImage possiblyShrinkImage(BufferedImage img,
int maxW, int maxH) {
int w = img.getWidth();
int h = img.getHeight();
double scale = getScaleForResize(w, h, maxW, maxH);
if (scale == 1.0) {
return img;
} else {
return scaleImage(img, scale, img.getType());
}
}
public static BufferedImage scaleImage(BufferedImage img, double scale,
int type) {
BufferedImage dest = new BufferedImage((int) (img.getWidth() * scale),
(int) (img.getHeight() * scale), type);
return scaleImage(img, dest, true);
}
public static BufferedImage scaleImage(BufferedImage img,
BufferedImage dest, boolean highQuality) {
Graphics2D g = dest.createGraphics();
if (highQuality) {
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
g.drawImage(img, 0, 0, dest.getWidth(), dest.getHeight(), null);
g.dispose();
return dest;
}
/* Used by makeCompactGrid. */
private static SpringLayout.Constraints getConstraintsForCell(int row,
int col, Container parent, int cols) {
SpringLayout layout = (SpringLayout) parent.getLayout();
Component c = parent.getComponent(row * cols + col);
return layout.getConstraints(c);
}
/**
* Aligns the first <code>rows</code> * <code>cols</code> components of
* <code>parent</code> in a grid. Each component in a column is as wide as
* the maximum preferred width of the components in that column; height is
* similarly determined for each row. The parent is made just big enough to
* fit them all.
*
* @param parent
* container to put grid in
* @param rows
* number of rows
* @param cols
* number of columns
* @param initialX
* x location to start the grid at
* @param initialY
* y location to start the grid at
* @param xPad
* x padding between cells
* @param yPad
* y padding between cells
*/
public static void makeCompactGrid(Container parent, int rows, int cols,
int initialX, int initialY, int xPad, int yPad) {
SpringLayout layout;
try {
layout = (SpringLayout) parent.getLayout();
} catch (ClassCastException exc) {
System.err
.println("The first argument to makeCompactGrid must use SpringLayout.");
return;
}
// Align all cells in each column and make them the same width.
Spring x = Spring.constant(initialX);
for (int c = 0; c < cols; c++) {
Spring width = Spring.constant(0);
for (int r = 0; r < rows; r++) {
width = Spring.max(width, getConstraintsForCell(r, c, parent,
cols).getWidth());
}
for (int r = 0; r < rows; r++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r,
c, parent, cols);
constraints.setX(x);
constraints.setWidth(width);
}
x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad)));
}
// Align all cells in each row and make them the same height.
Spring y = Spring.constant(initialY);
for (int r = 0; r < rows; r++) {
Spring height = Spring.constant(0);
for (int c = 0; c < cols; c++) {
height = Spring.max(height, getConstraintsForCell(r, c, parent,
cols).getHeight());
}
for (int c = 0; c < cols; c++) {
SpringLayout.Constraints constraints = getConstraintsForCell(r,
c, parent, cols);
constraints.setY(y);
constraints.setHeight(height);
}
y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad)));
}
// Set the parent's size.
SpringLayout.Constraints pCons = layout.getConstraints(parent);
pCons.setConstraint(SpringLayout.SOUTH, y);
pCons.setConstraint(SpringLayout.EAST, x);
}
public static String extractString(byte[] value) {
return new String(value, 0, value.length - 1);
}
} |
package boa.test.datagen.php;
import java.io.IOException;
import org.junit.Test;
public class TestPHPPrefixExpression extends PHPBaseTest {
@Test
public void testPrefixExpression() throws IOException, Exception{
nodeTest(load("test/datagen/PHP/PreFixExpressionUnpack.boa"),
load("test/datagen/PHP/PreFixExpressionUnpack.php"));
}
} |
package com.akiban.ais.io;
import com.akiban.ais.model.AISBuilder;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.Column;
import com.akiban.ais.model.Index;
import com.akiban.ais.model.Table;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.nio.ByteBuffer;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class TableSubsetWriterTest {
private AkibanInformationSchema srcAIS;
@Before
public void setUp() {
AISBuilder builder = new AISBuilder();
builder.setTableIdOffset(1);
builder.userTable("foo", "bar");
builder.column("foo", "bar", "id", 0, "int", null, null, false, false, null, null);
builder.userTable("t", "c");
builder.column("t", "c", "id", 0, "int", null, null, false, false, null, null);
builder.index("t", "c", Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn("t", "c", Index.PRIMARY_KEY_CONSTRAINT, "id", 0, true, null);
builder.userTable("t", "o");
builder.column("t", "o", "id", 0, "int", null, null, false, false, null, null);
builder.column("t", "o", "cid", 1, "int", null, null, false, false, null, null);
builder.joinTables("co", "t", "c", "t", "o");
builder.joinColumns("co", "t", "c", "id", "t", "o", "cid");
builder.basicSchemaIsComplete();
builder.createGroup("c", "t", "__akiban_c");
builder.addJoinToGroup("c", "co", 0);
builder.createGroup("bar", "foo", "__akiban_bar");
builder.addTableToGroup("bar", "foo", "bar");
srcAIS = builder.akibanInformationSchema();
srcAIS.checkIntegrity();
}
@After
public void tearDown() {
srcAIS = null;
}
@Test
public void allTables() throws Exception {
ByteBuffer buffer1 = ByteBuffer.allocate(4096);
ByteBuffer buffer2 = ByteBuffer.allocate(4096);
new Writer(new MessageTarget(buffer1)).save(srcAIS);
new TableSubsetWriter(new MessageTarget(buffer2)) {
@Override
public boolean shouldSaveTable(Table table) {
return true;
}
}.save(srcAIS);
// Basic smoke test (buffer sizes), but can't compare actual
// content as Writer interface imposes no ordering. More checks
// are done in the following tests.
buffer1.flip();
buffer2.flip();
assertEquals("limit", buffer1.limit(), buffer2.limit());
}
@Test
public void tSchemaOnlyCheckStaticData() throws Exception {
AkibanInformationSchema dstAIS = new AkibanInformationSchema();
new TableSubsetWriter(new AISTarget(dstAIS)) {
@Override
public boolean shouldSaveTable(Table table) {
return table.getName().getSchemaName().equals("t");
}
}.save(srcAIS);
assertEquals("type count", srcAIS.getTypes().size(), dstAIS.getTypes().size());
}
@Test
public void tSchemaOnlyCheckAll() throws Exception {
AkibanInformationSchema dstAIS = new AkibanInformationSchema();
new TableSubsetWriter(new AISTarget(dstAIS)) {
@Override
public boolean shouldSaveTable(Table table) {
return table.getName().getSchemaName().equals("t");
}
}.save(srcAIS);
dstAIS.checkIntegrity();
assertNotNull("t.c exists", dstAIS.getUserTable("t", "c"));
assertNotNull("t.o exists", dstAIS.getUserTable("t", "o"));
assertEquals("user table count", 2, dstAIS.getUserTables().size());
assertNotNull("co join exists", dstAIS.getJoin("co"));
assertEquals("join count", 1, dstAIS.getJoins().size());
assertNotNull("t.__akiban_c exists", dstAIS.getGroupTable("t", "__akiban_c"));
assertEquals("group table count", 1, dstAIS.getGroupTables().size());
assertNotNull("c group exists", dstAIS.getGroup("c"));
assertEquals("group count", 1, dstAIS.getGroups().size());
}
@Test
public void fooSchemaOnlyCheckAll() throws Exception {
AkibanInformationSchema dstAIS = new AkibanInformationSchema();
new TableSubsetWriter(new AISTarget(dstAIS)) {
@Override
public boolean shouldSaveTable(Table table) {
return table.getName().getSchemaName().equals("foo");
}
}.save(srcAIS);
dstAIS.checkIntegrity();
assertNotNull("foo.bar exists", dstAIS.getUserTable("foo", "bar"));
assertEquals("user table count", 1, dstAIS.getUserTables().size());
assertEquals("join count", 0, dstAIS.getJoins().size());
assertNotNull("foo.__akiban_bar exists", dstAIS.getGroupTable("foo", "__akiban_bar"));
assertEquals("group table count", 1, dstAIS.getGroupTables().size());
assertNotNull("bar group exists", dstAIS.getGroup("bar"));
assertEquals("group count", 1, dstAIS.getGroups().size());
}
@Test
public void singleTableBreaksGroup() throws Exception {
AkibanInformationSchema dstAIS = new AkibanInformationSchema();
new TableSubsetWriter(new AISTarget(dstAIS)) {
@Override
public boolean shouldSaveTable(Table table) {
return table.getName().getTableName().equals("c");
}
}.save(srcAIS);
// try/catch below as above is expected to succeed
try {
dstAIS.checkIntegrity(); // Group is missing its GroupTable
Assert.fail("Exception expected!");
}
catch(IllegalStateException e) {
// Expected
}
}
@Test
public void singleGroupCheckColumns() throws Exception {
AkibanInformationSchema dstAIS = new AkibanInformationSchema();
new TableSubsetWriter(new AISTarget(dstAIS)) {
@Override
public boolean shouldSaveTable(Table table) {
return table.getGroup().getName().equals("c");
}
}.save(srcAIS);
dstAIS.checkIntegrity();
Table cTable = dstAIS.getUserTable("t", "c");
assertNotNull("t.c exists", cTable);
for(Column c : cTable.getColumns()) {
assertNotNull(c.getName() + " has group column", c.getGroupColumn());
}
Table oTable = dstAIS.getUserTable("t", "o");
assertNotNull("t.o exists", oTable);
for(Column c : oTable.getColumns()) {
assertNotNull(c.getName() + " has group column", c.getGroupColumn());
}
Table groupTable = dstAIS.getGroupTable("t", "__akiban_c");
for(Column c : groupTable.getColumns()) {
assertNotNull(c.getName() + " has user column", c.getUserColumn());
}
assertNotNull("t.__akiban_c exists", groupTable);
}
/*
@Test
public void bug857741()
{
AISBuilder builder = new AISBuilder();
builder.setTableIdOffset(1);
builder.userTable("schema", "customer");
builder.column("schema", "customer", "cid", 0, "int", null, null, false, true, null, null);
builder.column("schema", "customer", "name", 1, "int", null, null, true, false, null, null);
builder.column("schema", "customer", "dob", 2, "int", null, null, true, false, null, null);
builder.index("schema", "customer", Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn("schema", "customer", Index.PRIMARY_KEY_CONSTRAINT, "cid", 0, true, null);
builder.userTable("schema", "orders");
builder.column("schema", "orders", "oid", 0, "int", null, null, false, true, null, null);
builder.column("schema", "orders", "cid", 1, "int", null, null, false, false, null, null);
builder.column("schema", "orders", "order_date", 2, "int", null, null, false, false, null, null);
builder.index("schema", "orders", Index.PRIMARY_KEY_CONSTRAINT, true, Index.PRIMARY_KEY_CONSTRAINT);
builder.indexColumn("schema", "orders", Index.PRIMARY_KEY_CONSTRAINT, "oid", 0, true, null);
builder.joinTables("co", "schema", "customer", "schema", "orders");
builder.joinColumns("co", "schema", "customer", "cid", "schema", "orders", "cid");
builder.basicSchemaIsComplete();
builder.createGroup("group", "schema", "__akiban_customer");
builder.addJoinToGroup("group", "co", 0);
builder.groupingIsComplete();
AkibanInformationSchema ais = builder.akibanInformationSchema();
ais.checkIntegrity();
AISBuilder indexBuilder = new AISBuilder();
builder.groupIndex("group", "name_date", false);
builder.groupIndexColumn("group", "name_date", "schema", "customer", "name", 0);
builder.groupIndexColumn("group", "name_date", "schema", "orders", "order_date", 1);
builder.index("schema", "customer", "idx_pad_2", false, Index.KEY_CONSTRAINT);
builder.indexColumn("schema", "customer", "idx_pad_2", "name", 0, true, null);
}
*/
} |
package com.github.nsnjson.encoding;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
import com.github.nsnjson.AbstractFormatTest;
import org.junit.*;
import static com.github.nsnjson.format.Format.*;
public class EncoderTest extends AbstractFormatTest {
@Test
public void processTestNull() {
shouldEncodeWhenGivenNull(getNull(), getNullPresentation());
}
@Test
public void processTestNumberInt() {
NumericNode value = getNumberInt();
shouldEncodeWhenGivenNumber(value, getNumberIntPresentation(value));
}
@Test
public void processTestNumberLong() {
NumericNode value = getNumberLong();
shouldEncodeWhenGivenNumber(value, getNumberLongPresentation(value));
}
@Test
public void processTestNumberDouble() {
NumericNode value = getNumberDouble();
shouldEncodeWhenGivenNumber(value, getNumberDoublePresentation(value));
}
@Test
public void processTestEmptyString() {
TextNode value = getEmptyString();
shouldEncodeWhenGivenString(value, getStringPresentation(value));
}
@Test
public void processTestString() {
TextNode value = getString();
shouldEncodeWhenGivenString(value, getStringPresentation(value));
}
@Test
public void processTestBooleanTrue() {
BooleanNode value = getBooleanTrue();
shouldEncodeWhenGivenBoolean(value, getBooleanPresentation(value));
}
@Test
public void processTestBooleanFalse() {
BooleanNode value = getBooleanFalse();
shouldEncodeWhenGivenBoolean(value, getBooleanPresentation(value));
}
@Test
public void processTestEmptyArray() {
ArrayNode array = getEmptyArray();
shouldEncodeWhenGivenArray(array, getArrayPresentation(array));
}
@Test
public void processTestArray() {
ArrayNode array = getArray();
shouldEncodeWhenGivenArray(array, getArrayPresentation(array));
}
@Test
public void processTestEmptyObject() {
ObjectNode object = getEmptyObject();
shouldEncodeWhenGivenObject(object, getObjectPresentation(object));
}
@Test
public void processTestObject() {
ObjectNode object = getObject();
shouldEncodeWhenGivenObject(object, getObjectPresentation(object));
}
private void shouldEncodeWhenGivenNull(NullNode value, ObjectNode presentation) {
assertEncoding(value, presentation);
}
private void shouldEncodeWhenGivenNumber(NumericNode value, ObjectNode presentation) {
assertEncoding(value, presentation);
}
private void shouldEncodeWhenGivenString(TextNode value, ObjectNode presentation) {
assertEncoding(value, presentation);
}
private void shouldEncodeWhenGivenBoolean(BooleanNode value, ObjectNode presentation) {
assertEncoding(value, presentation);
}
private void shouldEncodeWhenGivenArray(ArrayNode array, ObjectNode presentation) {
assertEncoding(array, presentation);
}
private void shouldEncodeWhenGivenObject(ObjectNode object, ObjectNode presentation) {
assertEncoding(object, presentation);
}
private static void assertEncoding(JsonNode value, ObjectNode presentation) {
Assert.assertEquals(presentation, Encoder.encode(value));
}
} |
package com.insano10.puzzlers.sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class PowersetTest
{
@Parameterized.Parameters(name = "Implementation: {0}")
public static Collection<Object[]> data()
{
return Arrays.<Object[]>asList(new Object[] {"Binary Group", (PowerSetProvider) Powerset::of});
}
private final PowerSetProvider powerSetProvider;
public PowersetTest(String name, PowerSetProvider powerSetProvider)
{
this.powerSetProvider = powerSetProvider;
}
@Test
public void shouldGeneratePowersetOfASetContainingMoreThan1Element() throws Exception
{
Set<Integer> set = newHashSet(1, 2, 3, 4); // powerset should have 2^size elements
Set<Set<Integer>> powerset = newHashSet(
newHashSet(),
newHashSet(1),
newHashSet(2),
newHashSet(3),
newHashSet(4),
newHashSet(1, 2),
newHashSet(1, 3),
newHashSet(1, 4),
newHashSet(2, 3),
newHashSet(2, 4),
newHashSet(3, 4),
newHashSet(1, 2, 3),
newHashSet(2, 3, 4),
newHashSet(1, 2, 4),
newHashSet(1, 3, 4),
newHashSet(1, 2, 3, 4));
assertThat(powerSetProvider.getPowerSet(set)).containsOnlyElementsOf(powerset);
}
@Test
public void shouldGeneratePowersetOfASetContainingSets() throws Exception
{
Set<Set<Integer>> set = newHashSet(
newHashSet(1),
newHashSet(2),
newHashSet(3));
Set<Set<Set<Integer>>> powerset = newHashSet();
powerset.add(newHashSet(newHashSet()));
addSetWithSingleElementToPowersetOfSets(powerset, 1);
addSetWithSingleElementToPowersetOfSets(powerset, 2);
addSetWithSingleElementToPowersetOfSets(powerset, 3);
powerset.add(newHashSet(newHashSet(1), newHashSet(2)));
powerset.add(newHashSet(newHashSet(2), newHashSet(3)));
powerset.add(newHashSet(newHashSet(1), newHashSet(3)));
powerset.add(newHashSet(newHashSet(1), newHashSet(2), newHashSet(3)));
assertThat(powerSetProvider.getPowerSet(set)).containsOnlyElementsOf(powerset);
}
@Test
public void shouldGeneratePowersetOfAnEmptySet() throws Exception
{
Set<Integer> set = newHashSet();
//The power set of the empty set is the set which contains itself
Set<Set<Integer>> expectedPowerSet = newHashSet();
expectedPowerSet.add(newHashSet());
assertThat(powerSetProvider.getPowerSet(set)).containsOnlyElementsOf(expectedPowerSet);
}
@Test
public void shouldGeneratePowersetOfSetContainingTheEmptySet() throws Exception
{
Set<Set<Integer>> set = newHashSet();
set.add(newHashSet());
//The power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set
Set<Set<Set<Integer>>> powerset = newHashSet();
powerset.add(newHashSet());
Set<Set<Integer>> setOfEmptySet = newHashSet();
setOfEmptySet.add(newHashSet());
powerset.add(setOfEmptySet);
assertThat(powerSetProvider.getPowerSet(set)).containsOnlyElementsOf(powerset);
}
private void addSetWithSingleElementToPowersetOfSets(Set<Set<Set<Integer>>> powersetOfSets, int setSingleElement)
{
/*
It looks like you cannot create a triple nested collection with a single element as types cannot be inferred correctly
So take the long way round
*/
HashSet<Set<Integer>> subset = new HashSet<>();
subset.add(newHashSet(setSingleElement));
powersetOfSets.add(subset);
}
interface PowerSetProvider
{
<T> Set<Set<T>> getPowerSet(Set<T> set);
}
} |
package com.qiniu.testing;
import java.net.SocketTimeoutException;
import junit.framework.TestCase;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import com.qiniu.api.config.Config;
import com.qiniu.api.net.Http;
public class HttpClientTimeOutTest extends TestCase {
private int CONNECTION_TIMEOUT;
private int SO_TIMEOUT;
@Override
public void setUp() {
CONNECTION_TIMEOUT = Config.CONNECTION_TIMEOUT;
SO_TIMEOUT = Config.SO_TIMEOUT;
Http.setClient(null);
}
@Override
public void tearDown() {
Config.CONNECTION_TIMEOUT = CONNECTION_TIMEOUT;
Config.SO_TIMEOUT = SO_TIMEOUT;
Http.setClient(null);
}
public void testCONNECTION_TIMEOUT() {
Throwable tx = null;
long s = 0;
try {
Config.CONNECTION_TIMEOUT = 5;
Config.SO_TIMEOUT = 20 * 1000;
HttpClient client = Http.getClient();
HttpGet httpget = new HttpGet("http://kyfxbl.iteye.com/blog/1616849");
s = System.currentTimeMillis();
HttpResponse ret = client.execute(httpget);
fail(" ConnectTimeoutException");
} catch (Exception e) {
long end = System.currentTimeMillis();
System.out.println("CONNECTION_TIMEOUT test : " + (end - s));
tx = e;
}
assertNotNull(tx.getMessage());
assertEquals(ConnectTimeoutException.class, tx.getClass());
}
public void testSO_TIMEOUT() {
Throwable tx = null;
long s = 0;
try {
Config.CONNECTION_TIMEOUT = 20 * 1000;
Config.SO_TIMEOUT = 5;
HttpClient client = Http.getClient();
HttpGet httpget = new HttpGet("http:
s = System.currentTimeMillis();
HttpResponse ret = client.execute(httpget);
fail(" SocketTimeoutException");
} catch (Exception e) {
long end = System.currentTimeMillis();
System.out.println("SO_TIMEOUT test : " + (end - s));
tx = e;
}
assertNotNull(tx.getMessage());
assertEquals(SocketTimeoutException.class, tx.getClass());
}
} |
package imagej.patcher;
import static imagej.patcher.TestUtils.construct;
import static imagej.patcher.TestUtils.invokeStatic;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import ij.ImageJ;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests whether the headless functionality is complete.
*
* @author Johannes Schindelin
*/
public class HeadlessCompletenessTest {
static {
try {
LegacyInjector.preinit();
}
catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException("Got exception (see error log)");
}
}
private File tmpDir;
private String threadName;
private ClassLoader threadLoader;
@Before
public void before() throws IOException {
threadName = Thread.currentThread().getName();
threadLoader = Thread.currentThread().getContextClassLoader();
tmpDir = TestUtils.createTemporaryDirectory("legacy-");
}
@After
public void after() {
if (threadName != null) Thread.currentThread().setName(threadName);
if (threadLoader != null) Thread.currentThread().setContextClassLoader(threadLoader);
if (tmpDir != null && tmpDir.isDirectory()) {
TestUtils.deleteRecursively(tmpDir);
}
}
@Test
public void missingGenericDialogMethods() throws Exception {
final ClassPool pool = new ClassPool();
pool.appendClassPath(new ClassClassPath(getClass()));
final String originalName = "ij.gui.GenericDialog";
final CtClass original = pool.get(originalName);
final String headlessName = HeadlessGenericDialog.class.getName();
final CtClass headless = pool.get(headlessName);
final Map<String, CtMethod> methods = new HashMap<String, CtMethod>();
for (final CtMethod method : headless.getMethods()) {
if (headless != method.getDeclaringClass()) continue;
String name = method.getLongName();
assertTrue(name.startsWith(headlessName + "."));
name = name.substring(headlessName.length() + 1);
methods.put(name, method);
}
// these do not need to be overridden
for (final String name : new String[] {
"actionPerformed(java.awt.event.ActionEvent)",
"adjustmentValueChanged(java.awt.event.AdjustmentEvent)",
"getInsets(int,int,int,int)",
"getValue(java.lang.String)",
"isMatch(java.lang.String,java.lang.String)",
"itemStateChanged(java.awt.event.ItemEvent)",
"keyPressed(java.awt.event.KeyEvent)",
"keyReleased(java.awt.event.KeyEvent)",
"keyTyped(java.awt.event.KeyEvent)",
"paint(java.awt.Graphics)",
"parseDouble(java.lang.String)",
"setCancelLabel(java.lang.String)",
"textValueChanged(java.awt.event.TextEvent)",
"windowActivated(java.awt.event.WindowEvent)",
"windowClosed(java.awt.event.WindowEvent)",
"windowClosing(java.awt.event.WindowEvent)",
"windowDeactivated(java.awt.event.WindowEvent)",
"windowDeiconified(java.awt.event.WindowEvent)",
"windowIconified(java.awt.event.WindowEvent)",
"windowOpened(java.awt.event.WindowEvent)"
}) {
methods.put(name, null);
}
for (final CtMethod method : original.getMethods()) {
if (original != method.getDeclaringClass()) continue;
String name = method.getLongName();
assertTrue(name.startsWith(originalName + "."));
name = name.substring(originalName.length() + 1);
assertTrue(name + " is not overridden", methods.containsKey(name));
}
}
@Test
public void testMenuStructure() throws Exception {
assumeTrue(!GraphicsEnvironment.isHeadless());
final File jarFile = new File(tmpDir, "Set_Property.jar");
TestUtils.makeJar(jarFile, Set_Property.class.getName());
System.setProperty("ij1.plugin.dirs", "/no-no-no/");
final LegacyEnvironment headlessIJ1 = new LegacyEnvironment(null, true);
headlessIJ1.addPluginClasspath(jarFile);
headlessIJ1.runMacro("", "");
final Map<String, String> menuItems =
new LinkedHashMap<String, String>(headlessIJ1.getMenuStructure());
assertTrue("does not have 'Set Property'", menuItems.containsKey("Plugins>Set Property"));
final LegacyEnvironment ij1 = new LegacyEnvironment(null, false);
ij1.addPluginClasspath(jarFile);
final Frame ij1Frame = construct(ij1.getClassLoader(), "ij.ImageJ", ImageJ.NO_SHOW);
final MenuBar menuBar = ij1Frame.getMenuBar();
final Hashtable<String, String> commands =
invokeStatic(ij1.getClassLoader(), "ij.Menus", "getCommands");
for (int i = 0; i < menuBar.getMenuCount(); i++) {
final Menu menu = menuBar.getMenu(i);
assertMenuItems(menuItems, commands, menu.getLabel() + ">", menu);
}
assertTrue("Left-over menu items: " + menuItems.keySet(),
menuItems.size() == 0);
}
private void assertMenuItems(final Map<String, String> menuItems,
final Hashtable<String, String> commands, final String prefix,
final Menu menu)
{
int separatorCounter = 0;
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem item = menu.getItem(i);
final String label = item.getLabel();
String menuPath = prefix + label;
if (item instanceof Menu) {
assertMenuItems(menuItems, commands, menuPath + ">", (Menu) item);
}
else if ("-".equals(label)) {
final String menuPath2 = menuPath + ++separatorCounter;
assertTrue("Not found: " + menuPath2, menuItems.containsKey(menuPath2));
menuItems.remove(menuPath2);
}
else if (!menuPath.startsWith("File>Open Recent>")){
assertTrue("Not found: " + menuPath, menuItems.containsKey(menuPath));
assertEquals("Command for menu path: " + menuPath, commands.get(label),
menuItems.get(menuPath));
menuItems.remove(menuPath);
}
}
}
} |
package net.caseydunham.coderwall;
import net.caseydunham.coderwall.data.User;
import net.caseydunham.coderwall.exception.CoderWallException;
import net.caseydunham.coderwall.service.CoderWall;
import net.caseydunham.coderwall.service.impl.CoderWallImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestCoderWall {
@Test(expected = CoderWallException.class)
public void testGetUserThrowsExceptionWhenUsernameIsNull() throws CoderWallException {
CoderWall cw = new CoderWallImpl();
cw.getUser(null);
}
@Test(expected = CoderWallException.class)
public void testGetUserThrowsExceptionWhenUsernameIsEmpty() throws CoderWallException {
CoderWall cw = new CoderWallImpl();
cw.getUser("");
}
@Test(expected = CoderWallException.class)
public void testGetUserThrowsExceptionWhenUserIsNotFound() throws CoderWallException {
CoderWall cw = new CoderWallImpl();
cw.getUser("this is not a valid user");
}
@Test(expected = CoderWallException.class)
public void testGetUserThrowsExceptionOnInvalidURL() throws CoderWallException {
CoderWall cw = new CoderWallImpl();
cw.setBaseUrl("ht
cw.getUser("caseydunham");
}
} |
package org.davidmoten.hilbert;
import static org.davidmoten.hilbert.GeoUtil.scalePoint;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import com.github.davidmoten.guavamini.Lists;
public class HilbertCurveTest {
private static final HilbertCurve c = HilbertCurve.bits(5).dimensions(2);
private static SmallHilbertCurve small = HilbertCurve.small().bits(5).dimensions(2);
@Test
public void testIndex1() {
HilbertCurve c = HilbertCurve.bits(2).dimensions(2);
assertEquals(7, c.index(1, 2).intValue());
}
@Test
public void testIndex2() {
assertEquals(256, c.index(0, 16).intValue());
}
@Test
public void testToBigInteger() {
long[] ti = { 0, 16 };
assertEquals(256, c.toIndex(ti).intValue());
}
@Test
public void testBitSet() {
BitSet b = new BitSet(10);
b.set(8);
byte[] a = b.toByteArray();
Util.reverse(a);
assertEquals(256, new BigInteger(1, a).intValue());
}
@Test
public void testPrintOutIndexValues() throws IOException {
for (int bits = 1; bits <= 7; bits++) {
HilbertCurve c = HilbertCurve.bits(bits).dimensions(2);
int n = 2 << (bits - 1);
PrintStream out = new PrintStream("target/indexes-2d-bits-" + bits + ".txt");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
out.print(c.index(i, j));
if (j != n - 1)
out.print("\t");
}
out.println();
}
out.close();
String actual = new String(
Files.readAllBytes(
new File("target/indexes-2d-bits-" + bits + ".txt").toPath()),
StandardCharsets.UTF_8);
String expected = new String(Files.readAllBytes(
new File("src/test/resources/expected/indexes-2d-bits-" + bits + ".txt")
.toPath()),
StandardCharsets.UTF_8);
assertEquals(expected, actual);
}
}
@Test
public void testTranspose() {
long[] ti = c.transpose(BigInteger.valueOf(256));
assertEquals(2, ti.length);
assertEquals(0, ti[0]);
assertEquals(16, ti[1]);
}
@Test
public void testTransposeZero() {
long[] ti = c.transpose(BigInteger.valueOf(0));
assertEquals(2, ti.length);
assertEquals(0, ti[0]);
assertEquals(0, ti[1]);
}
@Test
public void testPointFromIndexBits1() {
int bits = 2;
HilbertCurve c = HilbertCurve.bits(bits).dimensions(2);
for (long i = 0; i < Math.round(Math.pow(2, bits)); i++) {
System.out.println(i + "\t" + Arrays.toString(c.point(BigInteger.valueOf(i))));
}
}
@Test
public void testRoundTrips() {
boolean failed = false;
for (int bits = 1; bits <= 10; bits++) {
for (int dimensions = 2; dimensions <= 10; dimensions++)
for (long i = 0; i < Math.pow(2, bits + 1); i++) {
if (!checkRoundTrip(bits, dimensions, i)) {
System.out.println("failed round trip for bits=" + bits + ", dimensions="
+ dimensions + ", index=" + i);
failed = true;
}
}
}
if (failed) {
Assert.fail("round trips failed (listed in log)");
}
}
@Test
public void testRoundTripsSmall() {
boolean failed = false;
for (int bits = 1; bits <= 10; bits++) {
for (int dimensions = 2; dimensions <= Math.min(5, 63 / bits); dimensions++)
for (long i = 0; i < 1 << bits + 1; i++) {
if (!checkRoundTripSmall(bits, dimensions, i)) {
System.out.println("failed round trip for bits=" + bits + ", dimensions="
+ dimensions + ", index=" + i);
failed = true;
}
}
}
if (failed) {
Assert.fail("round trips failed (listed in log)");
}
}
@Test
public void testPointManyBits() {
HilbertCurve c = HilbertCurve.bits(60).dimensions(3);
String num = "1000000000000000000000000000000000000000000000";
System.out.println("length = " + num.length());
BigInteger n = new BigInteger(num);
System.out.println(Arrays.toString(c.point(n)));
assertEquals(n, c.index(c.point(n)));
}
@Test
public void testRoundTripLotsOfBits() {
for (int i = 1; i <= 100000; i++)
assertTrue(checkRoundTrip(63, 10, i));
}
@Test
public void testRoundTripLotsOfDimensions() {
for (int i = 1; i <= 100; i++)
assertTrue(checkRoundTrip(63, 10000, i));
}
@Test(expected = IllegalArgumentException.class)
public void testTooManyBits() {
HilbertCurve.bits(64);
}
@Test
public void testRoundTrip3Dimensions3BitsIndex1() {
assertTrue(checkRoundTrip(3, 3, 1));
}
@Test
public void checkPathIsSingleStepOnly() {
for (int bits = 1; bits <= 10; bits++) {
for (int dimensions = 2; dimensions <= 10; dimensions++) {
HilbertCurve c = HilbertCurve.bits(bits).dimensions(dimensions);
long[] point = c.point(0);
for (long i = 1; i < Math.pow(2, bits + 1); i++) {
long[] point2 = c.point(i);
int sum = 0;
for (int j = 0; j < point.length; j++) {
sum += Math.abs(point2[j] - point[j]);
}
assertEquals(1, sum);
point = point2;
}
}
}
}
@Test
public void testPointFromIndexBits1Point0_1() {
HilbertCurve c = HilbertCurve.bits(1).dimensions(2);
long[] ti = HilbertCurve.transposedIndex(1, 0, 1);
assertEquals("0,1", ti[0] + "," + ti[1]);
assertEquals(1, c.index(0, 1).intValue());
long[] ti2 = c.transpose(BigInteger.valueOf(1));
assertEquals("0,1", ti2[0] + "," + ti2[1]);
}
@Test
public void testPointFromIndexBits1Point0_1MutateAllowed() {
HilbertCurve c = HilbertCurve.bits(1).dimensions(2);
long[] ti = HilbertCurve.transposedIndex(1, 0, 1);
assertEquals("0,1", ti[0] + "," + ti[1]);
assertEquals(1, c.index(0, 1).intValue());
long[] ti2 = c.transpose(BigInteger.valueOf(1));
assertEquals("0,1", ti2[0] + "," + ti2[1]);
}
@Test
public void testPointFromIndexBits1Point1_1() {
HilbertCurve c = HilbertCurve.bits(1).dimensions(2);
long[] ti = HilbertCurve.transposedIndex(1, 1, 1);
assertEquals("1,0", ti[0] + "," + ti[1]);
assertEquals(2, c.index(1, 1).intValue());
long[] ti2 = c.transpose(BigInteger.valueOf(2));
assertEquals("1,0", ti2[0] + "," + ti2[1]);
}
@Test(expected = IllegalArgumentException.class)
public void testBitsPositive() {
HilbertCurve.bits(0);
}
@Test(expected = IllegalArgumentException.class)
public void testDimensionAtLeastTwo() {
HilbertCurve.bits(2).dimensions(1);
}
@Test(expected = IllegalArgumentException.class)
public void testPointMatchesDimensions() {
HilbertCurve c = HilbertCurve.bits(2).dimensions(2);
long[] point = { 1 };
c.index(point);
}
@Test(expected = NullPointerException.class)
public void testIndexCannotBeNull() {
HilbertCurve c = HilbertCurve.bits(2).dimensions(2);
c.point((BigInteger) null);
}
@Test(expected = IllegalArgumentException.class)
public void testIndexCannotBeNegative() {
HilbertCurve c = HilbertCurve.bits(2).dimensions(2);
c.point(BigInteger.valueOf(-1));
}
@Test(expected = IllegalArgumentException.class)
public void smallBitsTimesDimensionsMustBeLessThan63() {
HilbertCurve.small().bits(8).dimensions(8);
}
@Test(expected = IllegalArgumentException.class)
public void smallPointDimensionsForSmallCurve() {
SmallHilbertCurve c = HilbertCurve.small().bits(8).dimensions(2);
c.index(1, 2, 3);
}
private static boolean checkRoundTrip(int bits, int dimensions, long value) {
HilbertCurve c = HilbertCurve.bits(bits).dimensions(dimensions);
long[] point = c.point(value);
assertEquals(dimensions, point.length);
return value == c.index(point).longValue();
}
private static boolean checkRoundTripSmall(int bits, int dimensions, long value) {
SmallHilbertCurve c = HilbertCurve.small().bits(bits).dimensions(dimensions);
long[] point = c.point(value);
assertEquals(dimensions, point.length);
return value == c.index(point);
}
@Test
public void testSplitOnHigh() {
List<Range> list = new Range(3, 7).split(1);
System.out.println(list);
assertEquals(Lists.newArrayList(
Range.create(3, 3), Range.create(4, 7)), list);
}
@Test
public void testSplitOnLow() {
List<Range> list = new Range(3, 6).split(1);
System.out.println(list);
assertEquals(Lists.newArrayList(
Range.create(3, 3),
Range.create(4, 6)), list);
}
@Test
public void testSplitOnMiddle() {
List<Range> list = new Range(5, 10).split(1);
System.out.println(list);
assertEquals(Lists.newArrayList(
Range.create(5, 7),
Range.create(8, 10)), list);
}
@Test
public void testSmallQueryPerimeterAlgorithm() {
Ranges r = small.query(point(0, 0), point(1, 1));
assertEquals(1, r.size());
assertEquals(Range.create(0, 3), r.get().get(0));
}
@Test
public void testIssue1() {
int bits = 16;
int dimensions = 2;
long index = Math.round(Math.pow(2, bits * dimensions - 1) + 1);
assertTrue(checkRoundTripSmall(bits, dimensions, index));
}
@Test
public void testTotalRangeExpandingWithIncreasingSplitDepth() {
// get ranges for Sydney query to measure effectiveness
float lat1 = -33.806477f;
float lon1 = 151.181767f;
long minTime = 1510779675000L;
long maxTime = 1510876800000L;
long t1 = minTime + (maxTime - minTime) / 2;
float lat2 = -33.882896f;
float lon2 = 151.281330f;
long t2 = t1 + TimeUnit.HOURS.toMillis(1);
int bits = 10;
int dimensions = 3;
SmallHilbertCurve h = HilbertCurve.small().bits(bits).dimensions(dimensions);
long maxOrdinates = 1L << bits;
long[] point1 = scalePoint(lat1, lon1, t1, minTime, maxTime, maxOrdinates);
long[] point2 = scalePoint(lat2, lon2, t2, minTime, maxTime, maxOrdinates);
Ranges ranges = h.query(point1, point2);
DecimalFormat df = new DecimalFormat("0.00");
DecimalFormat df2 = new DecimalFormat("00");
for (int i = 0; i < ranges.get().size(); i++) {
Ranges r = ranges.join(i);
System.out.println(df2.format(r.get().size()) + "\t"
+ df.format((double) r.totalLength() / ranges.totalLength()));
}
if (false) {
long t = System.currentTimeMillis();
h.query(new long[] { 0, 0, 0 },
new long[] { maxOrdinates, maxOrdinates, maxOrdinates });
System.out.println("full domain query took " + (System.currentTimeMillis() - t) + "ms");
}
if (true) {
long t = System.currentTimeMillis();
int count = h.query(new long[] { 0, 0, 0 },
new long[] { maxOrdinates, maxOrdinates, maxOrdinates / 24 }).size();
System.out.println("full domain query for first hour took "
+ (System.currentTimeMillis() - t) + "ms with "+ count + " ranges");
}
}
@Test
public void testPointSaveAllocationsSmall() {
long[] x = new long[2];
SmallHilbertCurve c = HilbertCurve.small().bits(5).dimensions(2);
c.point(682, x);
assertEquals(31L, x[0]);
assertEquals(31L, x[1]);
c.point(100L, x);
assertEquals(14L, x[0]);
assertEquals(4L, x[1]);
}
@Test
public void testSmallQueryVisitWholeRegion() {
SmallHilbertCurve c = HilbertCurve.small().bits(5).dimensions(2);
long[] a = new long[] { 0, 0 };
long[] b = new long[] { 31, 31 };
Ranges r = c.query(a, b);
assertEquals(Lists.newArrayList(Range.create(0, 1023)), r.get());
}
@Test
public void testSmallQueryVisitWholeRegionMultipleRanges() {
SmallHilbertCurve c = HilbertCurve.small().bits(4).dimensions(2);
long[] a = new long[] { 1, 1 };
long[] b = new long[] { 7, 4 };
Ranges result = c.query(a, b);
Ranges expected = Ranges.create()
.add(2, 2)
.add(6, 13)
.add(17, 18)
.add(22, 32)
.add(35, 37)
.add(53, 54)
.add(57, 57);
assertEquals(expected.get(), result.get());
}
@Test
public void testPointSaveAllocations() {
long[] x = new long[2];
HilbertCurve c = HilbertCurve.bits(5).dimensions(2);
c.point(682L, x);
assertEquals(31L, x[0]);
assertEquals(31L, x[1]);
c.point(100L, x);
assertEquals(14L, x[0]);
assertEquals(4L, x[1]);
}
@Test
public void testQuery1() {
SmallHilbertCurve c = HilbertCurve.small().bits(5).dimensions(2);
long[] point1 = new long[] { 3, 3 };
long[] point2 = new long[] { 8, 10 };
Ranges ranges = c.query(point1, point2, 1);
assertEquals(Lists.newArrayList(Range.create(10, 229)), ranges.get());
}
@Test
public void testQueryJoin0() {
SmallHilbertCurve c = HilbertCurve.small().bits(5).dimensions(2);
long[] point1 = new long[] { 3, 3 };
long[] point2 = new long[] { 8, 10 };
Ranges ranges = c.query(point1, point2, 0);
ranges.stream().forEach(System.out::println);
}
@Test
public void testQueryJoin3() {
SmallHilbertCurve c = HilbertCurve.small().bits(5).dimensions(2);
long[] point1 = new long[] { 3, 3 };
long[] point2 = new long[] { 8, 10 };
Ranges ranges = c.query(point1, point2, 3);
ranges.stream().forEach(System.out::println);
}
@Test
public void testQueryJoin6() {
SmallHilbertCurve c = HilbertCurve.small().bits(5).dimensions(2);
long[] point1 = new long[] { 3, 3 };
long[] point2 = new long[] { 8, 10 };
Ranges ranges = c.query(point1, point2, 6);
ranges.stream().forEach(System.out::println);
}
private static long[] point(long... values) {
return values;
}
} |
package org.geepawhill.contentment;
import static org.junit.Assert.*;
import org.geepawhill.contentment.core.Context;
import org.geepawhill.contentment.core.Step;
import org.geepawhill.contentment.step.TransitionStep;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import javafx.animation.Animation;
import javafx.animation.Transition;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.text.Text;
import javafx.util.Duration;
@RunWith(JfxTestRunner.class)
public class StepBaseTest
{
protected EventHandler<ActionEvent> onFinished;
@Ignore
@Test
public void failsOkay()
{
System.out.println("Test2 running.");
fail("Let's see a test fail.");
}
@Test
public void animationTest()
{
System.out.println("About to animate.");
Pane region = new Pane();
region.setMaxSize(1600d, 900d);
region.setMinSize(1600d, 900d);
Group group = new Group();
region.getChildren().add(group);
Context context = new Context(group);
Text label = new Text(800d,450d,"");
Transition animation = new Transition()
{
{
setCycleDuration(Duration.millis(3000d));
}
@Override
protected void interpolate(double frac)
{
if(frac==0d)
{
System.out.println("0");
}
String text = "Hi Mom!";
String newText = text.substring(0, (int) (frac * text.length()));
label.setText(newText);
label.setX(800d-label.getBoundsInParent().getWidth()/2d);
label.setY(450d);
label.setText(newText);
System.out.println("Interpolate: " + frac+" "+newText);
}
};
TransitionStep step = new TransitionStep(animation);
waitForFinish(context,step);
assertEquals("Hi Mom!",label.getText());
System.out.println("Animation played.");
}
private void waitForFinish(Context context,Step step)
{
if (Platform.isFxApplicationThread()) throw new IllegalThreadStateException("Cannot be executed on main JavaFX thread");
final Thread currentThread = Thread.currentThread();
context.onFinished=(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
synchronized (currentThread)
{
currentThread.notify();
}
}
});
Platform.runLater(new Runnable()
{
@Override
public void run()
{
step.play(context);
}
});
synchronized (currentThread)
{
try
{
currentThread.wait();
}
catch (InterruptedException ex)
{
// somebody interrupted me, OK
}
}
}
private synchronized void playAnimationAndWaitForFinish(final Animation animation)
{
if (Platform.isFxApplicationThread()) throw new IllegalThreadStateException("Cannot be executed on main JavaFX thread");
final Thread currentThread = Thread.currentThread();
final EventHandler<ActionEvent> originalOnFinished = animation.getOnFinished();
animation.setOnFinished(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
if (originalOnFinished != null)
{
originalOnFinished.handle(event);
}
synchronized (currentThread)
{
currentThread.notify();
}
}
});
Platform.runLater(new Runnable()
{
@Override
public void run()
{
animation.play();
}
});
synchronized (currentThread)
{
try
{
currentThread.wait();
}
catch (InterruptedException ex)
{
// somebody interrupted me, OK
}
}
}
} |
package org.gitlab4j.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeNotNull;
import java.util.List;
import java.util.Map;
import org.gitlab4j.api.models.Project;
import org.gitlab4j.api.models.Visibility;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* In order for these tests to run you must set the following properties in ~/test-gitlab4j.properties
*
* TEST_NAMESPACE
* TEST_HOST_URL
* TEST_PRIVATE_TOKEN
*
* If any of the above are NULL, all tests in this class will be skipped.
*/
@Category(IntegrationTest.class)
public class TestGitLabApiException extends AbstractIntegrationTest {
private static final String TEST_PROJECT_NAME_DUPLICATE = "test-gitlab4j-create-project-duplicate";
private static GitLabApi gitLabApi;
public TestGitLabApiException() {
super();
}
@BeforeClass
public static void setup() {
// Must setup the connection to the GitLab test server
gitLabApi = baseTestSetup();
deleteAllTestProjects();
}
@AfterClass
public static void teardown() throws GitLabApiException {
deleteAllTestProjects();
}
private static void deleteAllTestProjects() {
if (gitLabApi != null) {
try {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME_DUPLICATE);
gitLabApi.getProjectApi().deleteProject(project);
} catch (GitLabApiException ignore) {}
}
}
@Before
public void beforeMethod() {
assumeNotNull(gitLabApi);
}
@Test
public void testNotFoundError() throws GitLabApiException {
try {
gitLabApi.getProjectApi().getProject(123456789);
fail("GitLabApiException not thrown");
} catch (GitLabApiException gae) {
assertFalse(gae.hasValidationErrors());
assertEquals(404, gae.getHttpStatus());
assertTrue(gae.getMessage().contains("404"));
}
}
@Test
public void testValidationErrors() throws GitLabApiException {
Project project = new Project()
.withName(TEST_PROJECT_NAME_DUPLICATE)
.withDescription("GitLab4J test project.")
.withVisibility(Visibility.PUBLIC);
Project newProject = gitLabApi.getProjectApi().createProject(project);
assertNotNull(newProject);
try {
newProject = gitLabApi.getProjectApi().createProject(project);
fail("GitLabApiException not thrown");
} catch (GitLabApiException gae) {
assertTrue(gae.hasValidationErrors());
Map<String, List<String>> validationErrors = gae.getValidationErrors();
assertNotNull(validationErrors);
assertFalse(validationErrors.isEmpty());
}
}
} |
package org.openremote.model.persistence.jpa;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import java.io.File;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
/**
* An utility class that can be used to create a Hibernate session factory configurations
* for various H2 database setups.
*
* @author <a href = "mailto:juha@openremote.org">Juha Lindfors</a>
*/
public class H2
{
// TODO:
// Currently uses Hibernate API to establish persistence sessions due to Hibernate
// offering a more convenient programmatic configuration API. These could (should?)
// be migrated to JPA EntityManager API instead.
/**
* Creates a persistence session factory with a configuration for a single persistence class
* using a given persistence mapping file.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param mappingFile
* name of the domain object's relational entity mapping file under
* /resources/jpa directory, e.g. "Account.xml"
*
* @param entityClass
* relational entity class
*
* @return Hibernate session factory configured to a H2 database with given entity mapping
* configuration
*/
public static SessionFactory createConfiguration(PersistenceMode persistenceMode,
String mappingFile, Class<?> entityClass)
{
Set<String> files = new HashSet<String>();
files.add(mappingFile);
Set<Class<?>> entities = new HashSet<Class<?>>();
entities.add(entityClass);
return createConfiguration(persistenceMode, files, entities);
}
/**
* Creates a persistence session factory with a configuration for a set persistence classes
* using corresponding persistence mapping files.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param mappingFiles
* names of the domain objects' relational entity mapping files under
* /resources/jpa directory, e.g. "Account.xml", "User.xml"
*
* @param entityClasses
* relational entity classes
*
* @return Hibernate session factory configured to a H2 database with given entity mapping
* configuration
*/
public static SessionFactory createConfiguration(PersistenceMode persistenceMode,
Set<String> mappingFiles,
Set<Class<?>> entityClasses)
{
boolean useLegacyBeehiveSchema = false;
return createConfiguration(persistenceMode, mappingFiles, entityClasses, useLegacyBeehiveSchema);
}
/**
* Creates a H2 session factory that maps a set of object model entities to a legacy Beehive 3.0
* relational model.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param mappingFiles
* names of the domain objects' relational entity mapping files under
* /resources/jpa/beehive30 directory,
* see {@link org.openremote.model.persistence.jpa.RelationalTest#getBeehiveResourceDirectoryURI()}
*
* @param entityClasses
* the relational entity classes
*
* @return
* Hibernate session factory
*/
public static SessionFactory createLegacyBeehiveConfiguration(PersistenceMode persistenceMode,
Set<String> mappingFiles,
Set<Class<?>> entityClasses)
{
boolean useLegacyBeehiveSchema = true;
return createConfiguration(persistenceMode, mappingFiles, entityClasses, useLegacyBeehiveSchema);
}
/**
* Creates a H2 session factory that maps an object model entity to a legacy Beehive 3.0
* relational model.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param mappingFile
* name of the domain object's relational entity mapping file under
* /resources/jpa/beehive30 directory,
* see {@link org.openremote.model.persistence.jpa.RelationalTest#getBeehiveResourceDirectoryURI()}
*
* @param entityClass
* the relational entity class
*
* @return
* Hibernate session factory
*/
public static SessionFactory createLegacyBeehiveConfiguration(PersistenceMode persistenceMode,
String mappingFile,
Class<?> entityClass)
{
boolean useLegacyBeehiveSchema = true;
return createConfiguration(persistenceMode, mappingFile, entityClass, useLegacyBeehiveSchema);
}
/**
* Creates a Hibernate session factory for a given single domain object and its relational
* entity model.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param mappingFile
* name of the domain object's relational entity mapping file under
* /resources/jpa or /resources/jpa/beehive30 directory, depending if use legacy
* Beehive schema value is true or not.
*
* @param entityClass
* the relational entity class
*
* @param useLegacyBeehiveSchema
* Set to true to use mapping files corresponding to legacy Beehive 3.0 schema, false
* otherwise.
* See {@link org.openremote.model.persistence.jpa.RelationalTest#getBeehiveResourceDirectoryURI()}
* and {@link org.openremote.model.persistence.jpa.RelationalTest#getJPAResourceDirectoryURI()}
*
* @return
* Hibernate session factory
*/
private static SessionFactory createConfiguration(PersistenceMode persistenceMode,
String mappingFile,
Class<?> entityClass,
boolean useLegacyBeehiveSchema)
{
Set<String> file = new HashSet<String>();
file.add(mappingFile);
Set<Class<?>> entity = new HashSet<Class<?>>();
entity.add(entityClass);
return createConfiguration(persistenceMode, file, entity, useLegacyBeehiveSchema);
}
/**
* Creates a Hibernate session factory for given domain objects and their relational
* entity models.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param mappingFiles
* name of the domain objects' relational entity mapping files under
* /resources/jpa or /resources/jpa/beehive30 directory, depending if use legacy
* Beehive schema value is true or not.
*
* @param entityClasses
* the relational entity classes
*
* @param useLegacyBeehiveSchema
* Set to true to use mapping files corresponding to legacy Beehive 3.0 schema, false
* otherwise.
* See {@link org.openremote.model.persistence.jpa.RelationalTest#getBeehiveResourceDirectoryURI()}
* and {@link org.openremote.model.persistence.jpa.RelationalTest#getJPAResourceDirectoryURI()}
*
* @return
* Hibernate session factory
*/
private static SessionFactory createConfiguration(PersistenceMode persistenceMode,
Set<String> mappingFiles,
Set<Class<?>> entityClasses,
boolean useLegacyBeehiveSchema)
{
Configuration config = new Configuration();
addClasses(config, entityClasses);
if (useLegacyBeehiveSchema)
{
addBeehiveFiles(config, mappingFiles);
if (persistenceMode == PersistenceMode.ON_DISK)
{
return createSessionFactory("~/BeehiveTest", config);
}
else
{
return createSessionFactory(config);
}
}
else
{
addFiles(config, mappingFiles);
if (persistenceMode == PersistenceMode.ON_DISK)
{
return createSessionFactory("~/AccountManagerTest", config);
}
else
{
return createSessionFactory(config);
}
}
}
/**
* Create a persistent H2 configuration for a Hibernate session factory.
*
* @param dbName
* file path for the database storage
*
* @param config
* Hibernate configuration to use as the base
*
* @return
* Hibernate session factory
*/
private static SessionFactory createSessionFactory(String dbName, Configuration config)
{
return createSessionFactory(PersistenceMode.ON_DISK, dbName, config);
}
/**
* Create an in-memory H2 configuration for Hibernate session factory.
*
* @param config
* Hibernate configuration to use as the base
*
* @return
* Hibernate session factory
*/
private static SessionFactory createSessionFactory(Configuration config)
{
return createSessionFactory(PersistenceMode.IN_MEMORY, "No Name", config);
}
/**
* Creates an H2 configuration for Hibernate session factory.
*
* @param persistenceMode
* see {@link PersistenceMode}
*
* @param dbName
* file path for the database storage -- only relevant when the persistence mode
* is {@link PersistenceMode#ON_DISK}
*
* @param config
* Hibernate configuration to use as the base
*
* @return
* Hibernate session factory
*/
private static SessionFactory createSessionFactory(PersistenceMode persistenceMode, String dbName,
Configuration config)
{
config.setProperty("hibernate.connection.url", "jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE");
if (persistenceMode == PersistenceMode.ON_DISK)
{
config.setProperty("hibernate.connection.url", "jdbc:h2:" + dbName);
}
config.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
config.setProperty("hibernate.connection.username", "sa");
config.setProperty("hibernate.connection.pool_size", "3");
config.setProperty("hibernate.cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider");
config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
config.setProperty("hibernate.hbm2ddl.auto", "create");
config.setProperty("hibernate.current_session_context_class", "managed");
ServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(config.getProperties())
.build();
return config.buildSessionFactory(registry);
}
public static void dropTable(Session session, String name)
{
SQLQuery query = session.createSQLQuery("drop table " + name.trim());
query.executeUpdate();
session.close();
}
private static void addBeehiveFiles(Configuration config, Set<String> files)
{
addFiles(config, files, RelationalTest.getBeehiveResourceDirectoryURI());
}
private static void addFiles(Configuration config, Set<String> files)
{
addFiles(config, files, RelationalTest.getJPAResourceDirectoryURI());
}
private static void addFiles(Configuration config, Set<String> files, URI filePath)
{
for (String mappingFile : files)
{
URI ormURI = filePath.resolve(filePath.getRawPath() + "/" + mappingFile);
config.addFile(new File(ormURI));
}
}
private static void addClasses(Configuration config, Set<Class<?>> files)
{
for (Class<?> clazz : files)
{
config.addAnnotatedClass(clazz);
}
}
public enum PersistenceMode
{
IN_MEMORY,
ON_DISK
}
} |
package test.com.smict.person;
import org.junit.Assert;
import org.junit.Test;
import org.joda.time.*;
public class TestGeneratePatID {
private int thisYear = DateTime.now().getYear();
private int yearFormat, yearBE;
private int nextNumber = 10, branchCode = 847;
private String expectID = "847-60-0000010", resultID;
@Test
public void testGenerateBranchID(){
/**
* GET YEAR AND CONVERT INTO RIGHT FORMAT
*/
this.yearBE = parseToBE(this.thisYear);
this.yearFormat = Integer.parseInt(parseYear(this.yearBE));
// Assert.assertEquals(60, yearFormat);
/**
* - FETCH NEXT NUMBER AND CONVERT INTO RIGHT FORMAT 0000003.
* - INCREMENT AND RETURN IT.
*/
resultID = String.valueOf(nextNumber);
for(;resultID.length()<7;){
resultID = "0" + resultID;
}
resultID = this.branchCode + "-" + this.yearFormat + "-" + resultID;
System.out.println(resultID);
Assert.assertEquals(this.expectID, resultID);
}
public String parseYear(int year){
return String.valueOf(year).substring(
2,
String.valueOf(year).length()
);
}
@Test
public void testParseYear(){
this.yearFormat = Integer.parseInt(parseYear(this.thisYear));
Assert.assertEquals(17, this.yearFormat);
}
public int parseToBE(int year){
return year + 543;
}
@Test
public void testParseToBE(){
this.yearBE = parseToBE(this.thisYear);
this.yearFormat = Integer.parseInt(parseYear(this.yearBE));
Assert.assertEquals(60, this.yearFormat);
}
} |
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
System.out.println(find(arr, 11) + " should be " + 10);
}
public static int find(int[] arr, int val) {
int comps = 0;
int lo = 0;
int hi = arr.length - 1;
for (;;) {
if (hi == lo) return -1;
int mid = (lo + hi) / 2;
int v = arr[mid];
comps++;
System.out.println(comps);
if (val == v) {
return mid;
} else if (val > v) {
lo = mid + 1;
} else if (val < v) {
hi = mid - 1;
}
}
}
} |
package io.quarkus.cli;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import io.quarkus.cli.core.BaseSubCommand;
import io.quarkus.cli.core.QuarkusCliVersion;
import io.quarkus.devtools.commands.CreateProject;
import io.quarkus.devtools.project.BuildTool;
import io.quarkus.devtools.project.QuarkusProject;
import io.quarkus.devtools.project.QuarkusProjectHelper;
import io.quarkus.devtools.project.codegen.SourceType;
import picocli.CommandLine;
@CommandLine.Command(name = "create", sortOptions = false, usageHelpAutoWidth = true, mixinStandardHelpOptions = false, description = "Create a new quarkus project.")
public class Create extends BaseSubCommand implements Callable<Integer> {
@CommandLine.Option(names = { "-g",
"--group-id" }, order = 1, paramLabel = "GROUP-ID", description = "The groupId for project")
String groupId = "org.acme";
@CommandLine.Option(names = { "-a",
"--artifact-id" }, order = 2, paramLabel = "ARTIFACT-ID", description = "The artifactId for project")
String artifactId = "code-with-quarkus";
@CommandLine.Option(names = { "-v",
"--version" }, order = 3, paramLabel = "VERSION", description = "The version for project")
String version = "1.0.0-SNAPSHOT";
@CommandLine.Option(names = { "-0",
"--no-examples" }, order = 4, description = "Generate without example code.")
boolean noExamples = false;
@CommandLine.Option(names = { "-x",
"--examples" }, order = 4, description = "Choose which example(s) you want in the generated Quarkus application.")
Set<String> examples;
@CommandLine.ArgGroup()
TargetBuildTool targetBuildTool = new TargetBuildTool();
static class TargetBuildTool {
@CommandLine.Option(names = { "--maven" }, order = 5, description = "Create a Maven project. (default)")
boolean maven = false;
@CommandLine.Option(names = { "--gradle" }, order = 6, description = "Create a Gradle project.")
boolean gradle = false;
@CommandLine.Option(names = {
"--grade-kotlin-dsl" }, order = 7, description = "Create a Gradle Kotlin DSL project.")
boolean gradleKotlinDsl = false;
}
@CommandLine.ArgGroup()
TargetLanguage language = new TargetLanguage();
static class TargetLanguage {
@CommandLine.Option(names = {
"--java" }, order = 8, description = "Generate Java examples. (default)")
boolean java = false;
@CommandLine.Option(names = {
"--kotlin" }, order = 9, description = "Generate Kotlin examples.")
boolean kotlin = false;
@CommandLine.Option(names = {
"--scala" }, order = 10, description = "Generate Scala examples.")
boolean scala = false;
}
@CommandLine.Parameters(arity = "0..1", paramLabel = "EXTENSION", description = "extension to add to project")
Set<String> extensions;
@Override
public Integer call() throws Exception {
try {
File projectDirectory = new File(System.getProperty("user.dir"));
File projectRoot = new File(projectDirectory.getAbsoluteFile(), artifactId);
if (projectRoot.exists()) {
err().println("Unable to create the project, " +
"the directory " + projectRoot.getAbsolutePath() + " already exists");
return CommandLine.ExitCode.SOFTWARE;
}
SourceType sourceType = SourceType.JAVA;
if (targetBuildTool.gradleKotlinDsl) {
sourceType = SourceType.KOTLIN;
if (extensions == null)
extensions = new HashSet<>();
if (!extensions.contains("kotlin"))
extensions.add("quarkus-kotlin");
} else if (language.scala) {
sourceType = SourceType.SCALA;
if (extensions == null)
extensions = new HashSet<>();
if (!extensions.contains("scala"))
extensions.add("quarkus-scala");
} else if (language.kotlin) {
sourceType = SourceType.KOTLIN;
if (extensions == null)
extensions = new HashSet<>();
if (!extensions.contains("kotlin"))
extensions.add("quarkus-kotlin");
} else if (extensions != null && !extensions.isEmpty()) {
sourceType = CreateProject.determineSourceType(extensions);
}
BuildTool buildTool = BuildTool.MAVEN;
if (targetBuildTool.gradle)
buildTool = BuildTool.GRADLE;
else if (targetBuildTool.gradleKotlinDsl)
buildTool = BuildTool.GRADLE_KOTLIN_DSL;
final QuarkusProject project = QuarkusProjectHelper.getProject(projectRoot.getAbsoluteFile().toPath(), buildTool,
QuarkusCliVersion.version());
boolean status = new CreateProject(project)
.groupId(groupId)
.artifactId(artifactId)
.version(version)
.sourceType(sourceType)
.overrideExamples(examples)
.extensions(extensions)
.noExamples(noExamples)
.execute().isSuccess();
if (status) {
out().println("Project " + artifactId +
" created.");
parent.setProjectDirectory(projectRoot.toPath().toAbsolutePath());
} else {
err().println("Failed to create project");
return CommandLine.ExitCode.SOFTWARE;
}
} catch (Exception e) {
err().println("Project creation failed, " + e.getMessage());
if (parent.showErrors)
e.printStackTrace(err());
return CommandLine.ExitCode.SOFTWARE;
}
return CommandLine.ExitCode.OK;
}
} |
package modules;
import java.util.List;
import java.util.logging.Level;
import org.skyve.bizport.BizPortWorkbook;
import org.skyve.domain.Bean;
import org.skyve.domain.PersistentBean;
import org.skyve.domain.messages.UploadException;
import org.skyve.domain.messages.ValidationException;
import org.skyve.metadata.controller.ImplicitActionName;
import org.skyve.metadata.controller.Interceptor;
import org.skyve.metadata.controller.ServerSideActionResult;
import org.skyve.metadata.controller.UploadAction.UploadedFile;
import org.skyve.metadata.model.document.Bizlet.DomainValue;
import org.skyve.metadata.model.document.Document;
import org.skyve.util.Util;
import org.skyve.web.WebContext;
public class LoggingInterceptor extends Interceptor {
private static final long serialVersionUID = 6991646689104206033L;
private boolean veto = false;
@Override
public boolean beforeNewInstance(Bean bean) {
Util.LOGGER.log(Level.INFO, "beforeNewInstance - {0}", bean);
return veto;
}
@Override
public void afterNewInstance(Bean bean) {
Util.LOGGER.log(Level.INFO, "afterNewInstance - {0}", bean);
}
@Override
public boolean beforeValidate(Bean bean, ValidationException e) {
Util.LOGGER.log(Level.INFO, "beforeValidate - {0}", bean);
return veto;
}
@Override
public void afterValidate(Bean bean, ValidationException e) {
Util.LOGGER.log(Level.INFO, "afterValidate - {0}", bean);
}
@Override
public boolean beforeGetConstantDomainValues(String attributeName) {
Util.LOGGER.log(Level.INFO, "beforeGetConstantDomainValues - attribute = {0}", attributeName);
return veto;
}
@Override
public void afterGetConstantDomainValues(String attributeName, List<DomainValue> result) {
Util.LOGGER.log(Level.INFO, "afterGetConstantDomainValues - attribute = {0}", attributeName);
}
@Override
public boolean beforeGetVariantDomainValues(String attributeName) {
Util.LOGGER.log(Level.INFO, "beforeGetVariantDomainValues - attribute = {0}", attributeName);
return veto;
}
@Override
public void afterGetVariantDomainValues(String attributeName, List<DomainValue> result) {
Util.LOGGER.log(Level.INFO, "afterGetVariantDomainValues - attribute = {0}", attributeName);
}
@Override
public boolean beforeGetDynamicDomainValues(String attributeName, Bean bean) {
Util.LOGGER.log(Level.INFO, "beforeGetDynamicDomainValues - attribute = {0}", attributeName);
return veto;
}
@Override
public void afterGetDynamicDomainValues(String attributeName, Bean bean, List<DomainValue> result) {
Util.LOGGER.log(Level.INFO, "afterGetDynamicDomainValues - attribute = {0}", attributeName);
}
@Override
public boolean beforeSave(Document document, PersistentBean bean) throws Exception {
Util.LOGGER.log(Level.INFO, "beforeSave - bean = {0}", bean);
return veto;
}
@Override
public void afterSave(Document document, final PersistentBean result) throws Exception {
Util.LOGGER.log(Level.INFO, "afterSave - result = {0}", result);
}
@Override
public boolean beforePreSave(Bean bean) {
Util.LOGGER.log(Level.INFO, "beforePreSave - {0}", bean);
return veto;
}
@Override
public void afterPreSave(Bean bean) {
Util.LOGGER.log(Level.INFO, "afterPreSave - {0}", bean);
}
@Override
public boolean beforePostSave(Bean bean) {
Util.LOGGER.log(Level.INFO, "beforePostSave - {0}", bean);
return veto;
}
@Override
public void afterPostSave(Bean bean) {
Util.LOGGER.log(Level.INFO, "afterPostSave - {0}", bean);
}
@Override
public boolean beforeDelete(Document document, PersistentBean bean) {
Util.LOGGER.log(Level.INFO, "beforeDelete - {0}", bean);
return veto;
}
@Override
public void afterDelete(Document document, PersistentBean bean) {
Util.LOGGER.log(Level.INFO, "afterDelete - {0}", bean);
}
@Override
public boolean beforePreDelete(PersistentBean bean) {
Util.LOGGER.log(Level.INFO, "beforePreDelete - {0}", bean);
return veto;
}
@Override
public void afterPreDelete(PersistentBean bean) {
Util.LOGGER.log(Level.INFO, "afterPreDelete - {0}", bean);
}
@Override
public boolean beforePostLoad(PersistentBean bean) {
Util.LOGGER.log(Level.INFO, "beforePostLoad - {0}", bean);
return veto;
}
@Override
public void afterPostLoad(PersistentBean bean) {
Util.LOGGER.log(Level.INFO, "afterPostLoad - {0}", bean);
}
@Override
public boolean beforePreExecute(ImplicitActionName actionName, Bean bean, Bean parentBean, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"beforePreExecute - action = {0}, bean = {1}, parent = {2}",
new Object[] {actionName, bean, parentBean});
return veto;
}
@Override
public void afterPreExecute(ImplicitActionName actionName, Bean result, Bean parentBean, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"afterPreExecute - action = {0}, bean = {1}, parent = {2}",
new Object[] {actionName, result, parentBean});
}
@Override
public boolean beforeServerSideAction(Document document, String actionName, Bean bean, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"beforeServerSideAction - doc = {0}.{1}, action = {2}, bean = {3}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, bean});
return veto;
}
@Override
public void afterServerSideAction(Document document, String actionName, ServerSideActionResult<Bean> result, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"afterServerSideAction - doc = {0}.{1}, action = {2}, result = {3}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, result});
}
@Override
public boolean beforeUploadAction(Document document, String actionName, Bean bean, UploadedFile file, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"beforeUploadAction - doc = {0}.{1}, action = {2}, bean = {3}, file = {4}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, bean, file});
return veto;
}
@Override
public void afterUploadAction(Document document, String actionName, Bean bean, UploadedFile file, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"afterUploadAction - doc = {0}.{1}, action = {2}, bean = {3}, file = {4}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, bean, file});
}
@Override
public boolean beforeBizImportAction(Document document, String actionName, BizPortWorkbook bizPortable, UploadException problems) {
Util.LOGGER.log(Level.INFO,
"beforeBizImportAction - doc = {0}.{1}, action = {2}, bean = {3}, workbook = {4}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, bizPortable});
return veto;
}
@Override
public void afterBizImportAction(Document document, String actionName, BizPortWorkbook bizPortable, UploadException problems) {
Util.LOGGER.log(Level.INFO,
"afterBizImportAction - doc = {0}.{1}, action = {2}, bean = {3}, workbook = {4}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, bizPortable});
}
@Override
public boolean beforeBizExportAction(Document document, String actionName, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"beforeBizExportAction - doc = {0}.{1}, action = {2}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName});
return veto;
}
@Override
public void afterBizExportAction(Document document, String actionName, BizPortWorkbook result, WebContext webContext) {
Util.LOGGER.log(Level.INFO,
"beforeBizExportAction - doc = {0}.{1}, action = {2}, result = {3}",
new Object[] {document.getOwningModuleName(), document.getName(), actionName, result});
}
} |
// Unless required by applicable law or agreed to in writing, software /
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /
package br.shura.venus.component;
import br.shura.venus.resultor.Resultor;
public class ForEachContainer extends Container {
private final Resultor adjustment;
private final Resultor from;
private final Resultor to;
private final String varName;
public ForEachContainer(String varName, Resultor from, Resultor to, Resultor adjustment) {
this.adjustment = adjustment;
this.from = from;
this.to = to;
this.varName = varName;
}
public Resultor getAdjustment() {
return adjustment;
}
@Override
public String getDisplayName() {
return "foreach(" + getVarName() + " in [" + getFrom() + ", " + getTo() + "])";
}
public Resultor getFrom() {
return from;
}
public Resultor getTo() {
return to;
}
public String getVarName() {
return varName;
}
} |
package bisq.monitor.metric;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import org.jetbrains.annotations.NotNull;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import bisq.common.app.Version;
import bisq.common.proto.network.NetworkEnvelope;
import bisq.core.proto.network.CoreNetworkProtoResolver;
import bisq.monitor.AvailableTor;
import bisq.monitor.Metric;
import bisq.monitor.Monitor;
import bisq.monitor.OnionParser;
import bisq.monitor.Reporter;
import bisq.monitor.StatisticsHelper;
import bisq.monitor.ThreadGate;
import bisq.network.p2p.CloseConnectionMessage;
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.network.Connection;
import bisq.network.p2p.network.MessageListener;
import bisq.network.p2p.network.NetworkNode;
import bisq.network.p2p.network.SetupListener;
import bisq.network.p2p.network.TorNetworkNode;
import bisq.network.p2p.peers.keepalive.messages.Ping;
import bisq.network.p2p.peers.keepalive.messages.Pong;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class P2PRoundTripTime extends Metric implements MessageListener, SetupListener {
private static final String SAMPLE_SIZE = "run.sampleSize";
private static final String HOSTS = "run.hosts";
private static final String TOR_PROXY_PORT = "run.torProxyPort";
private NetworkNode networkNode;
private final File torHiddenServiceDir = new File("metric_p2pRoundTripTime");
private int nonce;
private long start;
private List<Long> samples;
private final ThreadGate gate = new ThreadGate();
private final ThreadGate hsReady = new ThreadGate();
public P2PRoundTripTime(Reporter reporter) {
super(reporter);
Version.setBaseCryptoNetworkId(0); // set to BTC_MAINNET
}
@Override
public void configure(Properties properties) {
super.configure(properties);
}
@Override
protected void execute() {
if (null == networkNode) {
// close the gate
hsReady.engage();
networkNode = new TorNetworkNode(Integer.parseInt(configuration.getProperty(TOR_PROXY_PORT, "9052")),
new CoreNetworkProtoResolver(), false,
new AvailableTor(Monitor.TOR_WORKING_DIR, torHiddenServiceDir.getName()));
networkNode.start(this);
// wait for the gate to be reopened
hsReady.await();
}
// for each configured host
for (String current : configuration.getProperty(HOSTS, "").split(",")) {
try {
// parse Url
NodeAddress target = OnionParser.getNodeAddress(current);
// init sample bucket
samples = new ArrayList<>();
while (samples.size() < Integer.parseInt(configuration.getProperty(SAMPLE_SIZE, "1"))) {
// so we do not get disconnected due to DoS protection mechanisms
Thread.sleep(1000);
nonce = new Random().nextInt();
// close the gate
gate.engage();
start = System.currentTimeMillis();
SettableFuture<Connection> future = networkNode.sendMessage(target, new Ping(nonce, 42));
Futures.addCallback(future, new FutureCallback<Connection>() {
@Override
public void onSuccess(Connection connection) {
connection.addMessageListener(P2PRoundTripTime.this);
log.debug("Send ping to " + connection + " succeeded.");
}
@Override
public void onFailure(@NotNull Throwable throwable) {
log.error("Sending ping failed. That is expected if the peer is offline.\n\tException="
+ throwable.getMessage());
}
});
// wait for the gate to open again
gate.await();
}
// report
reporter.report(StatisticsHelper.process(samples),
"bisq." + getName() + "." + OnionParser.prettyPrint(target));
} catch (Exception e) {
gate.proceed(); // release the gate on error
e.printStackTrace();
}
}
}
@Override
public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) {
if (networkEnvelope instanceof Pong) {
Pong pong = (Pong) networkEnvelope;
if (pong.getRequestNonce() == nonce) {
samples.add(System.currentTimeMillis() - start);
} else {
log.warn("Nonce not matching. That should never happen.\n\t" +
"We drop that message. nonce={} / requestNonce={}",
nonce, pong.getRequestNonce());
}
connection.removeMessageListener(this);
// open the gate
gate.proceed();
} else if (networkEnvelope instanceof CloseConnectionMessage) {
gate.unlock();
} else {
log.warn("Got a message of type <{}>, expected <Pong>", networkEnvelope.getClass().getSimpleName());
}
}
@Override
public void onTorNodeReady() {
// TODO Auto-generated method stub
}
@Override
public void onHiddenServicePublished() {
hsReady.proceed();
}
@Override
public void onSetupFailed(Throwable throwable) {
// TODO Auto-generated method stub
}
@Override
public void onRequestCustomBridges() {
// TODO Auto-generated method stub
}
} |
package nars.concept;
import nars.Memory;
import nars.process.NAL;
import nars.task.Task;
import nars.truth.Truth;
import static nars.nal.UtilityFunctions.or;
import static nars.nal.nal1.LocalRules.revisibleTermsAlreadyEqual;
import static nars.nal.nal1.LocalRules.tryRevision;
/**
* Stores beliefs ranked in a sorted ArrayList, with strongest beliefs at lowest indexes (first iterated)
*/
public class ArrayListBeliefTable extends ArrayListTaskTable implements BeliefTable {
private final Ranker rank;
public ArrayListBeliefTable(int cap, Ranker rank) {
super(cap);
this.rank = rank;
}
@Override
public Ranker getRank() {
return rank;
}
// @Override
// public Task top(boolean hasQueryVar, long now, long occTime, Truth truth) {
// throw new RuntimeException("not supposed to be called");
@Override
public Task top(final boolean eternal, final boolean temporal) {
if (isEmpty()) {
return null;
} else if (eternal && temporal) {
return get(0);
} else if (eternal ^ temporal) {
final int n = size();
for (int i = 0; i < n; i++) {
Task t = get(i);
if (eternal && t.isEternal()) return t;
if (temporal && !t.isEternal()) return t;
}
}
return null;
}
@Override
public Task top(Ranker r) {
float s = Float.NEGATIVE_INFINITY;
Task b = null;
final int n = size();
for (int i = 0; i < n; i++) {
Task t = get(i);
float x = r.rank(t, s);
if (x > s) {
s = x;
b = t;
}
}
return b;
}
/**
* Select a belief to interact with the given task in logic
* <p>
* get the first qualified one
* <p>
* only called in RuleTables.rule
*
* @param now the current time, or Stamp.TIMELESS to disable projection
* @param task The selected task
* @return The selected isBelief
*/
// @Override
// public Task match(final Task task, long now) {
// if (isEmpty()) return null;
// long occurrenceTime = task.getOccurrenceTime();
// final int b = size();
// if (task.isEternal()) {
// Task eternal = top(true, false);
// else {
// for (final Task belief : this) {
// //if (task.sentence.isEternal() && belief.isEternal()) return belief;
// return belief;
// Task projectedBelief = belief.projectTask(occurrenceTime, now);
// //TODO detect this condition before constructing Task
// if (projectedBelief.getOccurrenceTime()!=belief.getOccurrenceTime()) {
// //belief = nal.derive(projectedBelief); // return the first satisfying belief
// return projectedBelief;
// return null;
// @Override
// public Task project(Task t, long now) {
// Task closest = topRanked();
// if (closest == null) return null;
// return closest.projectTask(t.getOccurrenceTime(), now);
@Override
public Task add(Task t, Ranker r, Concept c, NAL nal) {
final Memory memory = c.getMemory();
final Task input = t; //store in case input changes
long now = memory.time();
if (isEmpty()) {
add(t);
return t;
} else {
if (r == null) {
//just return thie top item if no ranker is provided
return top();
}
Task existing = top(t, now);
if (existing != null) {
//equal instance, or equal truth and stamp:
if ((existing == t) || t.equivalentTo(existing, false, false, true, true, false)) {
/*if (!t.isInput() && t.isJudgment()) {
existing.decPriority(0); // duplicated task
} // else: activated belief*/
memory.removed(t, "Duplicated");
return null;
} else if (revisibleTermsAlreadyEqual(t, existing)) {
Task revised = tryRevision(t, existing, false, nal);
if (revised != null) {
//nal.setCurrentBelief( revised );
}
}
}
float rankInput = r.rank(t); // for the new isBelief
final int siz = size();
boolean atCapacity = (cap == siz);
int i;
for (i = 0; i < siz; i++) {
Task b = get(i);
float existingRank = r.rank(b, rankInput);
boolean inputGreater = (Float.isFinite(existingRank) && rankInput >= existingRank);
if (inputGreater) {
//item will be inserted at this index
break;
}
}
if (atCapacity) {
if (i == siz) {
//reached the end of the list and there is no room to add at the end
memory.removed(t, "Unbelievable/Undesirable");
return null; //try projecting existing belief?
} else {
Task removed = remove(siz - 1);
memory.removed(removed, "Forgotten");
add(i, t);
}
} else {
add(i, t);
}
}
// if (size()!=preSize)
// c.onTableUpdated(goalOrJudgment.getPunctuation(), preSize);
// if (removed != null) {
// if (removed == goalOrJudgment) return false;
// m.emit(eventRemove, this, removed.sentence, goalOrJudgment.sentence);
// if (preSize != table.size()) {
// m.emit(eventAdd, this, goalOrJudgment.sentence);
//the new task was not added, so remove it
return t;
}
//TODO provide a projected belief
// //first create a projected
// /*if (t.sentence == belief.sentence) {
// return false;
// }*/
// if (belief.sentence.equalStamp(t.sentence, true, false, true)) {
//// if (task.getParentTask() != null && task.getParentTask().sentence.isJudgment()) {
//// //task.budget.decPriority(0); // duplicated task
//// } // else: activated belief
// getMemory().removed(belief, "Duplicated");
// return false;
// } else if (revisible(belief.sentence, t.sentence)) {
// //final long now = getMemory().time();
//// if (nal.setTheNewStamp( //temporarily removed
//// /*
//// if (equalBases(first.getBase(), second.getBase())) {
//// return null; // do not merge identical bases
//// }
//// */
//// // if (first.baseLength() > second.baseLength()) {
//// new Stamp(newStamp, oldStamp, memory.time()) // keep the order for projection
//// // } else {
//// // return new Stamp(second, first, time);
//// ) != null) {
// //TaskSeed projectedBelief = t.projection(nal.memory, now, task.getOccurrenceTime());
// //Task r = t.projection(nal.memory, now, newBelief.getOccurrenceTime());
// //Truth r = t.projection(now, newBelief.getOccurrenceTime());
// /*
// if (projectedBelief.getOccurrenceTime()!=t.getOccurrenceTime()) {
// }
// */
// Task revised = tryRevision(belief, t, false, nal);
// if (revised != null) {
// belief = revised;
// nal.setCurrentBelief(revised);
// if (!addToTable(belief, getBeliefs(), getMemory().param.conceptBeliefsMax.get(), Events.ConceptBeliefAdd.class, Events.ConceptBeliefRemove.class)) {
// //wasnt added to table
// getMemory().removed(belief, "Insufficient Rank"); //irrelevant
// return false;
// @Override
// public Task addGoal(Task goal, Concept c) {
// if (goal.equalStamp(t, true, true, false)) {
// return false; // duplicate
// if (revisible(goal.sentence, oldGoal)) {
// //nal.setTheNewStamp(newStamp, oldStamp, memory.time());
// //Truth projectedTruth = oldGoal.projection(now, task.getOccurrenceTime());
// /*if (projectedGoal!=null)*/
// // if (goal.after(oldGoal, nal.memory.param.duration.get())) { //no need to project the old goal, it will be projected if selected anyway now
// // nal.singlePremiseTask(projectedGoal, task.budget);
// //return;
// //nal.setCurrentBelief(projectedGoal);
// Task revisedTask = tryRevision(goal, oldGoalT, false, nal);
// if (revisedTask != null) { // it is revised, so there is a new task for which this function will be called
// goal = revisedTask;
// //return true; // with higher/lower desire
// //nal.setCurrentBelief(revisedTask);
// public static float rankBeliefConfidence(final Sentence judg) {
// return judg.getTruth().getConfidence();
// public static float rankBeliefOriginal(final Sentence judg) {
// final float confidence = judg.truth.getConfidence();
// final float originality = judg.getOriginality();
// return or(confidence, originality);
// boolean addToTable(final Task goalOrJudgment, final List<Task> table, final int max, final Class eventAdd, final Class eventRemove, Concept c) {
// int preSize = table.size();
// final Memory m = c.getMemory();
// Task removed = addToTable(goalOrJudgment, table, max, c);
// if (size()!=preSize)
// c.onTableUpdated(goalOrJudgment.getPunctuation(), preSize);
// if (removed != null) {
// if (removed == goalOrJudgment) return false;
// m.emit(eventRemove, this, removed.sentence, goalOrJudgment.sentence);
// if (preSize != table.size()) {
// m.emit(eventAdd, this, goalOrJudgment.sentence);
// return true;
} |
package com.Litterfeldt.AStory.dbConnector;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import com.Litterfeldt.AStory.models.Book;
import com.Litterfeldt.AStory.models.Chapter;
import java.util.ArrayList;
public class dbBook {
public static void purge(Context c){
(new dbBook(c)).purgeAllBooks();
}
public static ArrayList<Book> getBooks(Context c){
return (new dbBook(c)).getAllBooks();
}
public static void addBook(Context c, Book b){
(new dbBook(c)).addBook(b);
}
public static Book bookById(Context c, int id){
return (new dbBook(c)).getBookById(id);
}
public static int bookIdByName(Context c, String name){
return (new dbBook(c)).getBookId(name);
}
private static final String ALL_BOOKS = "SELECT * FROM "+ dbConnector.TABLE_NAME_BOOK_LIST + " ;";
private static final String ALL_BOOKS_BY_ID = "SELECT * FROM " + dbConnector.TABLE_NAME_BOOK_LIST + " WHERE "+dbConnector.COLUMN_BOOK_LIST_ID+" = ? ;";
private static final String ALL_CHAPTERS_BY_BOOK = "SELECT * FROM " + dbConnector.TABLE_NAME_CHAPTER_LIST + " WHERE BOOK_ID = ? ;";
private static final String IMAGE = "Select IMG_BLOB from " + dbConnector.TABLE_NAME_BOOK_IMG + " where BOOK_ID = ?;";
private static final String PURGE = "DELETE FROM ";
private dbConnector connector;
public dbBook(Context c) {
connector = dbConnector.getInstance(c);
}
public void addImg (int bookId, byte[] img){
ContentValues initialValues = new ContentValues();
initialValues.put(dbConnector.COLUMN_BOOK_IMG_BOOK_IMG,img);
initialValues.put(dbConnector.COLUMN_BOOK_IMG_BOOK_ID,bookId);
connector.write().insert(dbConnector.TABLE_NAME_BOOK_IMG, null, initialValues);
}
public void addChapter(Chapter chapter, int bookID){
ContentValues initialValues = new ContentValues();
initialValues.put(dbConnector.COLUMN_CHAPTER_LIST_CHAPTER_PATH,chapter.Path());
initialValues.put(dbConnector.COLUMN_CHAPTER_LIST_CHAPTER_NR,chapter.Nr());
initialValues.put(dbConnector.COLUMN_CHAPTER_LIST_CHAPTER_DURATION,chapter.Duration());
initialValues.put(dbConnector.COLUMN_CHAPTER_LIST_BOOK_ID,bookID);
connector.write().insert(dbConnector.TABLE_NAME_CHAPTER_LIST, null, initialValues);
}
public void addBook(Book book) {
ContentValues initialValues = new ContentValues();
initialValues.put(dbConnector.COLUMN_BOOK_LIST_NAME,book.name());
initialValues.put(dbConnector.COLUMN_BOOK_LIST_AUTHOR,book.author());
connector.write().insert(dbConnector.TABLE_NAME_BOOK_LIST, null, initialValues);
int bookID = getBookId(book.name());
for (Chapter chapter : book.getChapters()){
addChapter(chapter, bookID);
}
addImg(bookID,book.image());
}
public int getBookId(String bookName){
Cursor c = connector.read().query(dbConnector.TABLE_NAME_BOOK_LIST,
new String[]{dbConnector.COLUMN_BOOK_LIST_ID},
dbConnector.COLUMN_BOOK_LIST_NAME+"="+"\""+bookName+"\"",
null,null,null,null);
c.moveToFirst();
return c.getInt(0);
}
private Book getBookById(int id){
Cursor bookCursor = connector.read().rawQuery(ALL_BOOKS_BY_ID.replace("?",Integer.toString(id)), null);
boolean notEmpty = bookCursor.moveToFirst();
if (notEmpty) {
String name = bookCursor.getString(1);
String author = bookCursor.getString(2);
ArrayList<Chapter> chapters = getAllChapters(id);
byte[] img = getImageById(id);
Book book = new Book(id,name, author, chapters, img);
return book;
} else {
return null;
}
}
public void purgeAllBooks(){
connector.write().execSQL(PURGE + dbConnector.TABLE_NAME_BOOK_LIST +";" );
connector.write().execSQL(PURGE + dbConnector.TABLE_NAME_CHAPTER_LIST+";" );
connector.write().execSQL(PURGE + dbConnector.TABLE_NAME_BOOK_IMG+";" );
}
public ArrayList<Book> getAllBooks() {
Cursor bookCursor = connector.read().rawQuery(ALL_BOOKS, null);
boolean notEmpty = bookCursor.moveToFirst();
if (notEmpty) {
ArrayList<Book> books = new ArrayList<Book>();
while(!bookCursor.isAfterLast()){
int id = bookCursor.getInt(0);
String name = bookCursor.getString(1);
String author = bookCursor.getString(2);
ArrayList<Chapter> chapters = getAllChapters(id);
byte[] img = getImageById(id);
Book book = new Book(id,name, author, chapters, img);
books.add(book);
bookCursor.moveToNext();
}
return books;
} else {
return new ArrayList<Book>();
}
}
public byte[] getImageById(int bookId) {
Cursor imageCursor = connector.read().rawQuery(IMAGE.replace("?", Integer.toString(bookId)), null);
boolean notEmpty = imageCursor.moveToFirst();
if (notEmpty) {
return imageCursor.getBlob(0);
} else {
return null;
}
}
public ArrayList<Chapter> getAllChapters(int bookId) {
Cursor chapterCursor = connector.read()
.rawQuery(ALL_CHAPTERS_BY_BOOK.replace("?", Integer.toString(bookId)), null);
boolean notEmpty = chapterCursor.moveToFirst();
if (notEmpty) {
ArrayList<Chapter> chapters = new ArrayList<Chapter>();
while(!chapterCursor.isAfterLast()){
int chapterID = chapterCursor.getInt(0);
int chapterNr = chapterCursor.getInt(2);
String chapterPath = chapterCursor.getString(3);
int chapterDuration = chapterCursor.getInt(4);
Chapter chapter = new Chapter(chapterID, chapterPath, chapterNr, chapterDuration);
chapters.add(chapter);
chapterCursor.moveToNext();
}
return chapters;
} else {
return null;
}
}
} |
package us.kbase.narrativejobservice.sdkjobs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.kbase.auth.AuthToken;
import us.kbase.common.executionengine.LineLogger;
import us.kbase.common.utils.ProcessHelper;
import ch.qos.logback.classic.Level;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.model.AccessMode;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
public class DockerRunner {
private final URI dockerURI;
public DockerRunner(final URI dockerURI) {
this.dockerURI = dockerURI;
}
public File run(
String imageName,
final String moduleName,
final File inputData,
final AuthToken token,
final LineLogger log,
final File outputFile,
final boolean removeImage,
final File refDataDir,
final File optionalScratchDir,
final URL callbackUrl,
final String jobId,
final List<Bind> additionalBinds,
final CancellationChecker cancellationChecker)
throws IOException, InterruptedException {
if (!inputData.getName().equals("input.json"))
throw new IllegalStateException("Input file has wrong name: " +
inputData.getName() + "(it should be named input.json)");
File workDir = inputData.getCanonicalFile().getParentFile();
File tokenFile = new File(workDir, "token");
final DockerClient cl = createDockerClient();
imageName = checkImagePulled(cl, imageName, log);
String cntName = null;
try {
FileWriter fw = new FileWriter(tokenFile);
fw.write(token.toString());
fw.close();
if (outputFile.exists())
outputFile.delete();
long suffix = System.currentTimeMillis();
while (true) {
cntName = moduleName.toLowerCase() + "_" + jobId.replace('-', '_') + "_" + suffix;
if (findContainerByNameOrIdPrefix(cl, cntName) == null)
break;
suffix++;
}
List<Bind> binds = new ArrayList<Bind>(Arrays.asList(new Bind(workDir.getAbsolutePath(),
new Volume("/kb/module/work"))));
if (refDataDir != null)
binds.add(new Bind(refDataDir.getAbsolutePath(), new Volume("/data"), AccessMode.ro));
if (optionalScratchDir != null)
binds.add(new Bind(optionalScratchDir.getAbsolutePath(), new Volume("/kb/module/work/tmp")));
if (additionalBinds != null)
binds.addAll(additionalBinds);
CreateContainerCmd cntCmd = cl.createContainerCmd(imageName)
.withName(cntName).withTty(true).withCmd("async").withBinds(
binds.toArray(new Bind[binds.size()]));
if (callbackUrl != null)
cntCmd = cntCmd.withEnv("SDK_CALLBACK_URL=" + callbackUrl);
CreateContainerResponse resp = cntCmd.exec();
final String cntId = resp.getId();
Process p = Runtime.getRuntime().exec(new String[] {"docker", "start", "-a", cntId});
List<Thread> workers = new ArrayList<Thread>();
InputStream[] inputStreams = new InputStream[] {p.getInputStream(), p.getErrorStream()};
for (int i = 0; i < inputStreams.length; i++) {
final InputStream is = inputStreams[i];
final boolean isError = i == 1;
Thread ret = new Thread(new Runnable() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true) {
String line = br.readLine();
if (line == null)
break;
log.logNextLine(line, isError);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Error reading data from executed container", e);
}
}
});
ret.start();
workers.add(ret);
}
Thread cancellationCheckingThread = null;
if (cancellationChecker != null) {
cancellationCheckingThread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(1000);
if (cancellationChecker.isJobCancelled()) {
// Stop the container
try {
cl.stopContainerCmd(cntId).exec();
log.logNextLine("Docker container for module [" + moduleName + "]" +
" was successfully stopped during job cancellation", false);
} catch (Exception ex) {
ex.printStackTrace();
log.logNextLine("Error stopping docker container for module [" +
moduleName + "] during job cancellation: " + ex.getMessage(),
true);
}
break;
}
} catch (InterruptedException ex) {
break;
}
}
}
});
cancellationCheckingThread.start();
}
for (Thread t : workers)
t.join();
p.waitFor();
cl.waitContainerCmd(cntId).exec();
if (cancellationCheckingThread != null)
cancellationCheckingThread.interrupt();
InspectContainerResponse resp2 = cl.inspectContainerCmd(cntId).exec();
if (resp2.getState().isRunning()) {
try {
Container cnt = findContainerByNameOrIdPrefix(cl, cntName);
cl.stopContainerCmd(cnt.getId()).exec();
} catch (Exception ex) {
ex.printStackTrace();
}
throw new IllegalStateException("Container was still running");
}
InputStream is = cl.logContainerCmd(cntId).withStdOut().withStdErr().exec();
OutputStream os = new FileOutputStream(new File(workDir, "docker.log"));
IOUtils.copy(is, os);
os.close();
is.close();
if (outputFile.exists()) {
return outputFile;
} else {
if (cancellationChecker != null && cancellationChecker.isJobCancelled())
return null;
int exitCode = resp2.getState().getExitCode();
StringBuilder err = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(
cl.logContainerCmd(cntId).withStdErr(true).exec()));
while (true) {
String l = br.readLine();
if (l == null)
break;
err.append(l).append("\n");
}
br.close();
String msg = "Output file is not found, exit code is " + exitCode;
if (err.length() > 0)
msg += ", errors: " + err;
throw new IllegalStateException(msg);
}
} finally {
if (cntName != null) {
Container cnt = findContainerByNameOrIdPrefix(cl, cntName);
if (cnt != null) {
try {
cl.removeContainerCmd(cnt.getId()).withRemoveVolumes(true).exec();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
if (removeImage) {
try {
Image img = findImageId(cl, imageName);
cl.removeImageCmd(img.getId()).exec();
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (tokenFile.exists())
try {
tokenFile.delete();
} catch (Exception ignore) {}
}
}
public String checkImagePulled(DockerClient cl, String imageName, LineLogger log)
throws IOException {
if (findImageId(cl, imageName) == null) {
log.logNextLine("Image " + imageName + " is not pulled yet, pulling...", false);
ProcessHelper.cmd("docker", "pull", imageName).exec(new File("."));
if (findImageId(cl, imageName) == null) {
throw new IllegalStateException("Image was not found: " + imageName);
} else {
log.logNextLine("Image " + imageName + " is pulled successfully", false);
}
}
return imageName;
}
private Image findImageId(DockerClient cl, String imageTagOrIdPrefix) {
return findImageId(cl, imageTagOrIdPrefix, false);
}
private Image findImageId(DockerClient cl, String imageTagOrIdPrefix, boolean all) {
for (Image image: cl.listImagesCmd().withShowAll(all).exec()) {
if (image.getId().startsWith(imageTagOrIdPrefix))
return image;
if (image.getRepoTags() == null)
continue;
for (String tag : image.getRepoTags())
if (tag.equals(imageTagOrIdPrefix))
return image;
}
return null;
}
private Container findContainerByNameOrIdPrefix(DockerClient cl, String nameOrIdPrefix) {
for (Container cnt : cl.listContainersCmd().withShowAll(true).exec()) {
if (cnt.getId().startsWith(nameOrIdPrefix))
return cnt;
if (cnt.getNames() == null)
continue;
for (String name : cnt.getNames())
if (name.equals(nameOrIdPrefix) || name.equals("/" + nameOrIdPrefix))
return cnt;
}
return null;
}
public DockerClient createDockerClient() {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "ERROR");
Logger log = LoggerFactory.getLogger("com.github.dockerjava");
if (log instanceof ch.qos.logback.classic.Logger) {
ch.qos.logback.classic.Logger log2 = (ch.qos.logback.classic.Logger)log;
log2.setLevel(Level.ERROR);
}
if (dockerURI != null) {
DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder()
.withUri(dockerURI.toASCIIString()).build();
return DockerClientBuilder.getInstance(config).build();
} else {
return DockerClientBuilder.getInstance().build();
}
}
} |
package com.adam.aslfms.service;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import com.adam.aslfms.util.AppSettings;
import com.adam.aslfms.util.InternalTrackTransmitter;
import com.adam.aslfms.util.ScrobblesDatabase;
import com.adam.aslfms.util.Track;
import com.adam.aslfms.util.Util;
import com.adam.aslfms.util.enums.AdvancedOptionsWhen;
import com.adam.aslfms.util.enums.PowerOptions;
/**
*
* @author tgwizard
*
*/
public class ScrobblingService extends Service {
private static final String TAG = "ScrobblingService";
public static final String ACTION_AUTHENTICATE = "com.adam.aslfms.service.authenticate";
public static final String ACTION_CLEARCREDS = "com.adam.aslfms.service.clearcreds";
public static final String ACTION_JUSTSCROBBLE = "com.adam.aslfms.service.justscrobble";
public static final String ACTION_PLAYSTATECHANGED = "com.adam.aslfms.service.playstatechanged";
public static final String BROADCAST_ONAUTHCHANGED = "com.adam.aslfms.service.bcast.onauth";
public static final String BROADCAST_ONSTATUSCHANGED = "com.adam.aslfms.service.bcast.onstatus";
private static final long MIN_LISTENING_TIME = 30 * 1000;
private static final long UPPER_SCROBBLE_MIN_LIMIT = 240 * 1000;
private static final long MAX_PLAYTIME_DIFF_TO_SCROBBLE = 3000;
private AppSettings settings;
private ScrobblesDatabase mDb;
private NetworkerManager mNetManager;
private Track mCurrentTrack = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
settings = new AppSettings(this);
mDb = new ScrobblesDatabase(this);
mDb.open();
mNetManager = new NetworkerManager(this, mDb);
}
@Override
public void onDestroy() {
mDb.close();
}
@Override
public void onStart(Intent i, int startId) {
if(i==null){
Log.e(TAG, "got null intent");
return;
}
String action = i.getAction();
Bundle extras = i.getExtras();
if (action.equals(ACTION_CLEARCREDS)) {
if (extras.getBoolean("clearall", false)) {
mNetManager.launchClearAllCreds();
} else {
String snapp = extras.getString("netapp");
if (snapp != null) {
mNetManager.launchClearCreds(NetApp.valueOf(snapp));
} else
Log.e(TAG, "launchClearCreds got null napp");
}
} else if (action.equals(ACTION_AUTHENTICATE)) {
String snapp = extras.getString("netapp");
if (snapp != null)
mNetManager.launchAuthenticator(NetApp.valueOf(snapp));
else
Log.e(TAG, "launchHandshaker got null napp");
} else if (action.equals(ACTION_JUSTSCROBBLE)) {
if (extras.getBoolean("scrobbleall", false)) {
mNetManager.launchAllScrobblers();
} else {
String snapp = extras.getString("netapp");
if (snapp != null) {
mNetManager.launchScrobbler(NetApp.valueOf(snapp));
} else
Log.e(TAG, "launchScrobbler got null napp");
}
} else if (action.equals(ACTION_PLAYSTATECHANGED)) {
if (extras == null) {
Log.e(TAG, "Got null extras on playstatechange");
return;
}
Track.State state = Track.State.valueOf(extras.getString("state"));
Track track = InternalTrackTransmitter.popTrack();
if (track == null) {
Log.e(TAG, "A null track got through!! (Ignoring it)");
return;
}
onPlayStateChanged(track, state);
} else {
Log.e(TAG, "Weird action in onStart: " + action);
}
}
private synchronized void onPlayStateChanged(Track track, Track.State state) {
Log.d(TAG, "State: " + state.name());
if (track == Track.SAME_AS_CURRENT) {
// this only happens for apps implementing Scrobble Droid's API
Log.d(TAG, "Got a SAME_AS_CURRENT track");
if (mCurrentTrack != null) {
track = mCurrentTrack;
} else {
Log
.e(TAG,
"Got a SAME_AS_CURRENT track, but current was null!");
return;
}
}
if (state == Track.State.START || state == Track.State.RESUME) { // start/resume
if (mCurrentTrack != null) {
mCurrentTrack.updateTimePlayed(Util.currentTimeMillisUTC());
tryQueue(mCurrentTrack);
if (track.equals(mCurrentTrack)) {
return;
} else {
tryScrobble();
}
}
mCurrentTrack = track;
mCurrentTrack.updateTimePlayed(Util.currentTimeMillisUTC());
tryNotifyNP(mCurrentTrack);
} else if (state == Track.State.PAUSE) { // pause
// TODO: test this state
if (mCurrentTrack == null) {
// just ignore the track
} else {
if (!track.equals(mCurrentTrack)) {
Log.e(TAG, "PStopped track doesn't equal currentTrack!");
Log.e(TAG, "t: " + track);
Log.e(TAG, "c: " + mCurrentTrack);
} else {
mCurrentTrack.updateTimePlayed(Util.currentTimeMillisUTC());
// below: to be set on RESUME
mCurrentTrack.updateTimePlayed(Track.UNKNOWN_COUNT_POINT);
tryQueue(mCurrentTrack);
}
}
} else if (state == Track.State.COMPLETE) { // "complete"
// TODO test this state
if (mCurrentTrack == null) {
// just ignore the track
} else {
if (!track.equals(mCurrentTrack)) {
Log.e(TAG, "CStopped track doesn't equal currentTrack!");
Log.e(TAG, "t: " + track);
Log.e(TAG, "c: " + mCurrentTrack);
} else {
mCurrentTrack.updateTimePlayed(Util.currentTimeMillisUTC());
tryQueue(mCurrentTrack);
tryScrobble();
mCurrentTrack = null;
}
}
} else if (state == Track.State.PLAYLIST_FINISHED) { // playlist end
if (mCurrentTrack == null) {
tryQueue(track); // TODO: this can't succeed (time played = 0)
tryScrobble(true);
} else {
if (!track.equals(mCurrentTrack)) {
Log.e(TAG, "PFStopped track doesn't equal currentTrack!");
Log.e(TAG, "t: " + track);
Log.e(TAG, "c: " + mCurrentTrack);
} else {
mCurrentTrack.updateTimePlayed(Util.currentTimeMillisUTC());
tryQueue(mCurrentTrack);
tryScrobble(true);
}
}
mCurrentTrack = null;
} else if (state == Track.State.UNKNOWN_NONPLAYING) {
// similar to PAUSE, but might scrobble if close enough
if (mCurrentTrack == null) {
// just ignore the track
} else {
mCurrentTrack.updateTimePlayed(Util.currentTimeMillisUTC());
// below: to be set on RESUME
mCurrentTrack.updateTimePlayed(Track.UNKNOWN_COUNT_POINT);
tryQueue(mCurrentTrack);
if (!mCurrentTrack.hasUnknownDuration()) {
long diff = Math.abs(mCurrentTrack.getDuration() * 1000
- mCurrentTrack.getTimePlayed());
if (diff < MAX_PLAYTIME_DIFF_TO_SCROBBLE) {
tryScrobble();
}
}
}
} else {
Log.e(TAG, "Unknown track state: " + state.toString());
}
}
/**
* Launches a Now Playing notification of <code>track</code>, if we're
* authenticated and Now Playing is enabled.
*
* @param track
* the currently playing track
*/
private void tryNotifyNP(Track track) {
PowerOptions pow = Util.checkPower(this);
if (!settings.isAnyAuthenticated()
|| !settings.isNowPlayingEnabled(pow)) {
Log.d(TAG, "Won't notify NP, unauthed or disabled");
return;
}
mNetManager.launchNPNotifier(track);
}
private void tryQueue(Track track) {
if (!settings.isAnyAuthenticated()
|| !settings.isScrobblingEnabled(Util.checkPower(this))) {
Log.d(TAG, "Won't prepare scrobble, unauthed or disabled");
return;
}
if (track.hasBeenQueued()) {
Log.d(TAG, "Trying to queue a track that already has been queued");
// Log.d(TAG, track.toString());
return;
}
double sp = settings.getScrobblePoint() / (double) 100;
sp -= 0.01; // to be safe
long mintime = (long) (sp * 1000 * track.getDuration());
if (track.hasUnknownDuration() || mintime < MIN_LISTENING_TIME) {
mintime = MIN_LISTENING_TIME;
} else if (mintime > UPPER_SCROBBLE_MIN_LIMIT) {
mintime = UPPER_SCROBBLE_MIN_LIMIT;
}
if (track.getTimePlayed() >= mintime) {
Log.d(TAG, "Will try to queue track, played: "
+ track.getTimePlayed() + " vs " + mintime);
queue(mCurrentTrack);
} else {
Log.d(TAG, "Won't queue track, not played long enough: "
+ track.getTimePlayed() + " vs " + mintime);
Log.d(TAG, track.toString());
}
}
/**
* Only to be called by tryQueue(Track track).
*
* @param track
*/
private void queue(Track track) {
long rowId = mDb.insertTrack(track);
if (rowId != -1) {
track.setQueued();
Log.d(TAG, "queued track after playtime: " + track.getTimePlayed());
Log.d(TAG, track.toString());
// now set up scrobbling rels
for (NetApp napp : NetApp.values()) {
if (settings.isAuthenticated(napp)) {
Log.d(TAG, "inserting scrobble: " + napp.getName());
mDb.insertScrobble(napp, rowId);
// tell interested parties
Intent i = new Intent(
ScrobblingService.BROADCAST_ONSTATUSCHANGED);
i.putExtra("netapp", napp.getIntentExtraValue());
sendBroadcast(i);
}
}
} else {
Log.e(TAG, "Could not insert scrobble into the db");
Log.e(TAG, track.toString());
}
}
private void tryScrobble() {
tryScrobble(false);
}
private void tryScrobble(boolean playbackComplete) {
if (!settings.isAnyAuthenticated()
|| !settings.isScrobblingEnabled(Util.checkPower(this))) {
Log.d(TAG, "Won't prepare scrobble, unauthed or disabled");
return;
}
scrobble(playbackComplete);
}
/**
* Only to be called by tryScrobble(...).
*
* @param playbackComplete
*/
private void scrobble(boolean playbackComplete) {
PowerOptions pow = Util.checkPower(this);
boolean aoc = settings.getAdvancedOptionsAlsoOnComplete(pow);
if (aoc && playbackComplete) {
Log.d(TAG, "Launching scrobbler because playlist is finished");
mNetManager.launchAllScrobblers();
return;
}
AdvancedOptionsWhen aow = settings.getAdvancedOptionsWhen(pow);
for (NetApp napp : NetApp.values()) {
int numInCache = mDb.queryNumberOfScrobbles(napp);
if (numInCache >= aow.getTracksToWaitFor()) {
mNetManager.launchScrobbler(napp);
}
}
}
} |
package com.bellaire.aerbot.custom;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.SensorBase;
public class DoubleSolenoid extends SensorBase {
private Relay relayOne, relayTwo;
private boolean defaultState = true;
/**
* init the the relays with the port numbers
* @param portOne port for the first relay
* @param portTwo port for the second relay
*/
public DoubleSolenoid(int portOne, int portTwo){
relayOne = new Relay(portOne);
relayTwo = new Relay(portTwo);
}
/**
* init the two relays
* @param relayOne first relay
* @param relayTwo second relay
*/
public DoubleSolenoid(Relay relayOne, Relay relayTwo){
this.relayOne = relayOne;
this.relayTwo = relayTwo;
}
/**
* toggles the relays
*/
public void toggle(){
if(defaultState){
relayOne.set(Relay.Value.kForward);
relayTwo.set(Relay.Value.kOff);
defaultState = !defaultState;
}
if(!defaultState){
relayOne.set(Relay.Value.kOff);
relayTwo.set(Relay.Value.kForward);
defaultState = !defaultState;
}
}
/**
* @return returns the state of pneumatics (default or not default)
*/
public boolean isDefaultState() {
return defaultState;
}
/**
* @param defaultState state of pneumatics
*/
protected void setDefaultState(boolean defaultState) {
this.defaultState = defaultState;
}
} |
package com.bellaire.aerbot.systems;
import com.bellaire.aerbot.Environment;
import com.bellaire.aerbot.input.InputMethod;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.Victor;
public class ShooterSystem implements RobotSystem {
private Environment env;
private Victor shooter;
private Relay lift;
// v2 code
private boolean shooting = false;
private long shootStart = 0, lastPress = 0;
private boolean shotPress;
private boolean manualShooting;
public void init(Environment e) {
this.env = e;
shooter = new Victor(4);
shooter.set(0);
lift = new Relay(6);
lift.set(Relay.Value.kOff);
}
public void open() {
lift.set(Relay.Value.kForward);
}
public void close() {
lift.set(Relay.Value.kOff);
}
public void setMotor(double speed){
shooter.set(speed);
}
public void destroy() {
}
public void shoot(InputMethod input) {
long current = System.currentTimeMillis();
if(env.getInput().shoot() && current - lastPress > 500) { // fix da toggle
lastPress = current;
if(shooting == false) {
close();
shooter.set(1);
shooting = true;
shootStart = current;
} else {
if(current - shootStart < 2000) {
shooter.set(0);
shooting = false;
shootStart = 0;
}
}
}
if(shooting) {
if(current - shootStart >= 4000 && current - shootStart < 4500) {
open();
} else if(current - shootStart >= 4500) {
close();
shooter.set(0);
shooting = false;
shootStart = 0;
}
}else if(!shotPress && input.shooterLift()){
if(manualShooting){
close();
shooter.set(0);
}else{
open();
shooter.set(1);
}
manualShooting = !manualShooting;
}
shotPress = input.shooterLift();
}
} |
package com.bluetag.rest.resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/test")
public class HelloWorldREST {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHello(){
return "HELLO MY NAME IS JOHNNY";
}
} |
package com.cleverCloud.cleverIdea.ui;
import com.cleverCloud.cleverIdea.api.json.Application;
import com.intellij.dvcs.DvcsRememberedInputs;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import git4idea.remote.GitRememberedInputs;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
public class CleverClone extends DialogWrapper {
private JTextField myParentDirectory;
private JTextField myDirectoryName;
private JComboBox<Application> myRepositoryUrl;
private JPanel jpanel;
public CleverClone(@Nullable Project project, List<Application> applications) {
super(project);
init();
setTitle("Clone Clever Cloud Application");
for (Application application : applications) myRepositoryUrl.addItem(application);
if (project != null) {
myParentDirectory.setText(project.getBaseDir().getParent().getPath());
}
else {
DvcsRememberedInputs gitRememberedInputs = GitRememberedInputs.getInstance();
myParentDirectory.setText(gitRememberedInputs.getCloneParentDir());
}
myDirectoryName.setText(((Application)myRepositoryUrl.getSelectedItem()).name);
myRepositoryUrl.addActionListener(evt -> myDirectoryName.setText(((Application)myRepositoryUrl.getSelectedItem()).name));
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return jpanel;
}
public String getRepositoryUrl() {
return ((Application)myRepositoryUrl.getSelectedItem()).deployment.url;
}
public String getParentDirectory() {
return myParentDirectory.getText();
}
public String getDirectoryName() {
return myDirectoryName.getText();
}
} |
package com.fafica.projeto_pi.modelos;
public class Pesquisador {
private int idPesquisador;
private String nome;
private String cpf;
private int idade;
private String tipo;
//metodo toString
@Override
public String toString() {
return "Pesquisador [idPesquisador=" + idPesquisador + ", nome=" + nome
+ ", cpf=" + cpf + ", idade=" + idade + ", tipo=" + tipo + "]";
}
//construtor com campos
public Pesquisador(int idPesquisador, String nome, String cpf, int idade,
String tipo) {
this.idPesquisador = idPesquisador;
this.nome = nome;
this.cpf = cpf;
this.idade = idade;
this.tipo = tipo;
}
//metodos gets e sets
public int getIdPesquisador() {
return idPesquisador;
}
public void setIdPesquisador(int idPesquisador) {
this.idPesquisador = idPesquisador;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getTipo() {
return tipo;
}
public void setTipo(String tipo) {
this.tipo = tipo;
}
} |
package com.github.jcpp.jathenaeum.db.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.text.ParseException;
import java.util.ArrayList;
import com.github.jcpp.jathenaeum.Copy;
import com.github.jcpp.jathenaeum.Loan;
import com.github.jcpp.jathenaeum.beans.LoanForm;
import com.github.jcpp.jathenaeum.db.Database;
import com.github.jcpp.jathenaeum.exceptions.LoanNotFoundException;
import com.github.jcpp.jathenaeum.utils.Converter;
import com.github.jcpp.jathenaeum.utils.Validator;
public class LoanDAO {
private static Database db = Database.getInstance();
/**
* Get all Loan instances.
* @return Returns all Loan instances in an ArrayList<Loan>.
*/
public static ArrayList<Loan> getAll(){
Connection con = db.getConnection();
ArrayList<Loan> loans = new ArrayList<Loan>();
PreparedStatement stmt = null;
try {
con.setAutoCommit(false);
final String select = "SELECT * FROM Loan";
stmt = con.prepareStatement(select);
ResultSet resultSet = stmt.executeQuery();
Loan loan;
while(resultSet.next()){
loan = new Loan();
loan.setId(resultSet.getInt(1));
loan.setCustomerCardNumber(resultSet.getInt(2));
loan.setCopyId(resultSet.getInt(3));
loan.setStartDate(resultSet.getDate(4));
loan.setEndDate(resultSet.getDate(5));
loan.setReturned(resultSet.getBoolean(6));
loans.add(loan);
}
con.commit();
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return loans;
}
/**
* Get the Loan by id.
* @param id the id of the Loan.
* @return Returns the Loan instance.
* @throws LoanNotFoundException Throws an exception if the Loan is not found.
*/
public static Loan getById(int id) throws LoanNotFoundException{
Connection con = db.getConnection();
Loan loan;
PreparedStatement stmt = null;
try {
con.setAutoCommit(false);
final String select = "SELECT * FROM Loan WHERE LoanID = ?";
stmt = con.prepareStatement(select);
stmt.setInt(1, id);
ResultSet resultSet = stmt.executeQuery();
con.commit();
if(resultSet.next()){
loan = new Loan();
loan.setId(resultSet.getInt(1));
loan.setCustomerCardNumber(resultSet.getInt(2));
loan.setCopyId(resultSet.getInt(3));
loan.setStartDate(resultSet.getDate(4));
loan.setEndDate(resultSet.getDate(5));
loan.setReturned(resultSet.getBoolean(6));
}
else{
throw new LoanNotFoundException();
}
return loan;
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Get all Loan instances of an User.
* @param customerCardNumber the CustomerCardNumber.
* @return Returns all Loan instances in an ArrayList<Loan> of an User.
*/
public static ArrayList<Loan> getAllByCustomerCardNumber(int customerCardNumber){
Connection con = db.getConnection();
ArrayList<Loan> loans = new ArrayList<Loan>();
PreparedStatement stmt = null;
try {
con.setAutoCommit(false);
final String select = "SELECT * FROM Loan WHERE CustomerCardNumber = ?";
stmt = con.prepareStatement(select);
stmt.setInt(1, customerCardNumber);
ResultSet resultSet = stmt.executeQuery();
Loan loan;
while(resultSet.next()){
loan = new Loan();
loan.setId(resultSet.getInt(1));
loan.setCustomerCardNumber(resultSet.getInt(2));
loan.setCopyId(resultSet.getInt(3));
loan.setStartDate(resultSet.getDate(4));
loan.setEndDate(resultSet.getDate(5));
loan.setReturned(resultSet.getBoolean(6));
loans.add(loan);
}
con.commit();
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return loans;
}
/**
* Get all Loan instances of a Book.
* @param bookId the bookId.
* @return Returns all Loan instances in an ArrayList<Loan> of a Book.
*/
public static ArrayList<Loan> getAllByBookId(int bookId){
Connection con = db.getConnection();
ArrayList<Loan> loans = new ArrayList<Loan>();
PreparedStatement stmt = null;
try {
con.setAutoCommit(false);
final String select = "SELECT * FROM Loan WHERE BookID = ?";
stmt = con.prepareStatement(select);
stmt.setInt(1, bookId);
ResultSet resultSet = stmt.executeQuery();
Loan loan;
while(resultSet.next()){
loan = new Loan();
loan.setId(resultSet.getInt(1));
loan.setCustomerCardNumber(resultSet.getInt(2));
loan.setCopyId(resultSet.getInt(3));
loan.setStartDate(resultSet.getDate(4));
loan.setEndDate(resultSet.getDate(5));
loan.setReturned(resultSet.getBoolean(6));
loans.add(loan);
}
con.commit();
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return loans;
}
/**
* Insert a new loan.
* @param loan the loan to insert.
* @return Returns the id of the inserted loan.
*/
public static long insert(Loan loan){
Connection con = db.getConnection();
PreparedStatement stmt = null;
long result = 0;
try {
con.setAutoCommit(false);
String insert = "INSERT INTO Loan (CustomerCardNumber, CopyID, LoanStartDate, LoanEndDate, LoanReturned) VALUES (?, ?, ?, ?, ?)";
stmt = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, loan.getCustomerCardNumber());
stmt.setInt(2, loan.getCopyId());
if(loan.getStartDate() == null){
stmt.setNull(3, Types.DATE);
}
else{
stmt.setDate(3, Converter.fromUtilDateToSqlDate(loan.getStartDate()));
}
if(loan.getEndDate() == null){
stmt.setNull(4, Types.DATE);
}
else{
stmt.setDate(4, Converter.fromUtilDateToSqlDate(loan.getEndDate()));
}
stmt.setBoolean(5, loan.isReturned());
result = stmt.executeUpdate();
ResultSet generatedKeys = stmt.getGeneratedKeys();
if (generatedKeys.next()) {
result = generatedKeys.getLong(1);
}
con.commit();
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
/**
* Update a loan.
* @param loan the loan to update.
* @return Returns the id of the updated loan.
*/
public static long update(Loan loan){
Connection con = db.getConnection();
PreparedStatement stmt = null;
long result = 0;
try {
con.setAutoCommit(false);
String insert = "UPDATE Loan SET CustomerCardNumber = ?, CopyId = ?, LoanStartDate = ?, LoanEndDate = ?, LoanReturned = ? WHERE LoanID = ?";
stmt = con.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
stmt.setInt(1, loan.getCustomerCardNumber());
stmt.setInt(2, loan.getCopyId());
if(loan.getStartDate() == null){
stmt.setNull(3, Types.DATE);
}
else{
stmt.setDate(3, Converter.fromUtilDateToSqlDate(loan.getStartDate()));
}
if(loan.getEndDate() == null){
stmt.setNull(4, Types.DATE);
}
else{
stmt.setDate(4, Converter.fromUtilDateToSqlDate(loan.getEndDate()));
}
stmt.setBoolean(5, loan.isReturned());
stmt.setInt(6, loan.getId());
result = stmt.executeUpdate();
con.commit();
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return loan.getId();
}
/**
* Delete a loan.
* @param id the id of the loan to delete.
* @return Returns the id of the deleted loan.
*/
public static long delete(int id){
Connection con = db.getConnection();
PreparedStatement stmt = null;
long result = 0;
try {
con.setAutoCommit(false);
final String delete = "DELETE FROM Loan WHERE LoanID = ?";
stmt = con.prepareStatement(delete);
stmt.setInt(1, id);
result = stmt.executeUpdate();
con.commit();
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return id;
}
/**
* Search all the loans that has the form fields.
* @param loanForm the form with all the fields.
* @return Returns an ArrayList<Loan> with all the found loans.
*/
public static ArrayList<Loan> search(LoanForm loanForm){
Connection con = db.getConnection();
PreparedStatement stmt = null;
ArrayList<Loan> loans = new ArrayList<Loan>();
ArrayList<Copy> copies = new ArrayList<Copy>();
try {
con.setAutoCommit(false);
String firstPart = "SELECT L.* FROM Loan L WHERE (L.CustomerCardNumber = ? OR ? = '') AND (L.CopyID ";
//Create a dynamic query for the <b>in</b> clause
if(Validator.isValidInt(loanForm.getBookId())){
copies = CopyDAO.getAllByBookId(Integer.parseInt(loanForm.getBookId()));
if(!copies.isEmpty()){
firstPart += "IN(";
for(int i = 0; i < copies.size(); i++){
firstPart += "?,";
}
//Delete last character
firstPart = firstPart.substring(0, firstPart.length()-1);
if(!copies.isEmpty()){
firstPart += ")";
}
}
else{
firstPart += "= ?";
}
}
else{
firstPart += "= ?";
}
String secondPart = " OR ? = '') AND (L.LoanStartDate = ? OR ? = '') AND (L.LoanEndDate = ? OR ? = '') AND (L.LoanReturned = ? OR ? = '')";
final String select = firstPart + secondPart;
int counter = 1;
stmt = con.prepareStatement(select);
//Customer Card Number
if(Validator.isValidInt(loanForm.getCustomerCardNumber())){
stmt.setInt(counter++, Integer.parseInt(loanForm.getCustomerCardNumber()));
stmt.setInt(counter++, Integer.parseInt(loanForm.getCustomerCardNumber()));
}
else{
stmt.setString(counter++, "");
stmt.setString(counter++, "");
}
//Copy ID
if(!copies.isEmpty()){
for(int i = 0; i < copies.size(); i++){
stmt.setInt(counter++, copies.get(i).getId());
}
stmt.setString(counter++, "PINGAS");
}
else{
stmt.setString(counter++, "");
if(!Validator.isValidInt(loanForm.getBookId())){
stmt.setString(counter++, "");
}
else{
stmt.setString(counter++, "PINGAS");
}
}
//Start Date
try {
if(Validator.isValidDate(loanForm.getStartDate())){
stmt.setDate(counter++, Converter.fromUtilDateToSqlDate(Converter.fromStringToDate(loanForm.getStartDate())));
stmt.setDate(counter++, Converter.fromUtilDateToSqlDate(Converter.fromStringToDate(loanForm.getStartDate())));
}
else{
stmt.setString(counter++, "");
stmt.setString(counter++, "");
}
} catch (ParseException e) {
}
//End Date
try {
if(Validator.isValidDate(loanForm.getEndDate())){
stmt.setDate(counter++, Converter.fromUtilDateToSqlDate(Converter.fromStringToDate(loanForm.getEndDate())));
stmt.setDate(counter++, Converter.fromUtilDateToSqlDate(Converter.fromStringToDate(loanForm.getEndDate())));
}
else{
stmt.setString(counter++, "");
stmt.setString(counter++, "");
}
} catch (ParseException e) {
}
System.out.println("Query: " + stmt.toString());
//Returned
if(loanForm.getReturned() == null){
stmt.setBoolean(counter++, false);
stmt.setBoolean(counter++, false);
}
else{
stmt.setBoolean(counter++, true);
stmt.setBoolean(counter++, true);
}
System.out.println("Query: " + stmt.toString());
ResultSet resultSet = stmt.executeQuery();
con.commit();
Loan loan;
while(resultSet.next()){
loan = new Loan();
loan.setId(resultSet.getInt(1));
loan.setCustomerCardNumber(resultSet.getInt(2));
loan.setCopyId(resultSet.getInt(3));
loan.setStartDate(resultSet.getDate(4));
loan.setEndDate(resultSet.getDate(5));
loan.setReturned(resultSet.getBoolean(6));
loans.add(loan);
System.out.println("Found: " + loan.getId());
}
} catch (SQLException sqle) {
sqle.printStackTrace();
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
db.closeConnection(con);
} catch (SQLException e) {
e.printStackTrace();
}
}
return loans;
}
} |
package com.ids1024.whitakerswords;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.EditText;
import android.widget.ToggleButton;
import android.os.Bundle;
import android.content.Intent;
import android.content.res.AssetManager;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.graphics.Typeface;
public class WhitakersWords extends Activity
implements OnEditorActionListener {
/** Called when the activity is first created. */
public void copyFiles() throws IOException {
for (String filename: getAssets().list("words")) {
InputStream ins = getAssets().open("words/" + filename);
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
ins.close();
FileOutputStream fos = openFileOutput(filename, MODE_PRIVATE);
fos.write(buffer);
fos.close();
}
File wordsbin = getFileStreamPath("words");
wordsbin.setExecutable(true);
}
public String executeWords(String text, boolean fromenglish) {
String wordspath = getFilesDir().getPath() + "/words";
Process process;
try {
String[] command;
if (fromenglish) {
command = new String[] {wordspath, "~E", text};
} else {
command = new String[] {wordspath, text};
}
process = Runtime.getRuntime().exec(command, null, getFilesDir());
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
reader.close();
process.waitFor();
return output.toString();
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
} catch(InterruptedException e) {
throw new RuntimeException(e.getMessage());
}
}
public void searchWord(View view) {
TextView result_text = (TextView)findViewById(R.id.result_text);
EditText search_term = (EditText)findViewById(R.id.search_term);
ToggleButton english_to_latin = (ToggleButton)findViewById(R.id.english_to_latin);
String term = search_term.getText().toString();
String result = executeWords(term, english_to_latin.isChecked());
SpannableStringBuilder processed_result = new SpannableStringBuilder();
for (String line: result.split("\n")) {
String[] words = line.split(" +");
String handled_line = TextUtils.join(" ", words);
if (words[0].equals("01") || words[0].equals("02")
|| words[0].equals("03")) {
handled_line = handled_line.substring(3);
}
int startindex = processed_result.length();
processed_result.append(handled_line + "\n");
// Forms
if (words[0].equals("01")) {
processed_result.setSpan(
new StyleSpan(Typeface.BOLD),
startindex,
startindex + words[1].length(),
0);
}
// Dictionary forms
else if (words[0].equals("02")) {
int index = 1;
int endindex = startindex;
do {
endindex += words[index].length() + 1;
index += 1;
} while (words[index-1].endsWith(","));
processed_result.setSpan(
new StyleSpan(Typeface.BOLD),
startindex,
endindex,
0);
}
// Meaning
else if (words[0].equals("03")) {
processed_result.setSpan(
new StyleSpan(Typeface.ITALIC),
startindex,
processed_result.length(),
0);
}
}
result_text.setText((CharSequence)processed_result);
}
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
searchWord((View)v);
handled = true;
}
return handled;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
copyFiles();
} catch(IOException e) {
throw new RuntimeException(e.getMessage());
}
setContentView(R.layout.main);
EditText search_term = (EditText)findViewById(R.id.search_term);
search_term.setOnEditorActionListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, WhitakersSettings.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} |
package com.android.utils.wificonnecter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.utils.wificonnecter.WiFiConnecter.ActionListener;
public class TestActivity extends Activity {
private WifiManager mWifiManager;
private TextView tv_CurrentSsid;
private EditText et_Ssid;
private EditText et_Password;
private WiFiConnecter mWiFiConnecter;
private ProgressDialog mDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
init();
}
private void init() {
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWiFiConnecter = new WiFiConnecter(this);
mDialog = new ProgressDialog(this);
tv_CurrentSsid = (TextView) findViewById(R.id.tv_currentSsid);
et_Ssid = (EditText) findViewById(R.id.et_ssid);
et_Password = (EditText) findViewById(R.id.et_password);
//Debug only
//et_Ssid.setText("OTT_IPTV_3");
//et_Password.setText("12345678");
setCurrentSsid();
findViewById(R.id.btn_connect).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String ssid = et_Ssid.getText().toString();
final String password = et_Password.getText().toString();
mWiFiConnecter.connect(ssid, password, new ActionListener() {
@Override
public void onStart() {
System.out.println("
Toast.makeText(TestActivity.this, "onStart", Toast.LENGTH_SHORT).show();
mDialog.setMessage("Connecting to "+ssid+" ...");
mDialog.show();
}
@Override
public void onSuccess() {
System.out.println("
Toast.makeText(TestActivity.this, "onSuccess", Toast.LENGTH_SHORT).show();
setCurrentSsid();
}
@Override
public void onFailure() {
System.out.println("
Toast.makeText(TestActivity.this, "onFailure", Toast.LENGTH_SHORT).show();
}
@Override
public void onFinished() {
System.out.println("
mDialog.dismiss();
Toast.makeText(TestActivity.this, "onFinished", Toast.LENGTH_SHORT).show();
}
});
}
});
}
private void setCurrentSsid(){
WifiInfo info = mWifiManager.getConnectionInfo();
tv_CurrentSsid.setText(String.format(getString(R.string.current_ssid), (info == null) ? "null" : info.getSSID()));
}
} |
package com.mebigfatguy.fbcontrib.detect;
import java.util.Set;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.FQMethod;
import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
import edu.umd.cs.findbugs.ba.ClassContext;
/**
* looks for various issues around input/output/streaming library use
*/
@CustomUserValue
public class IOIssues extends BytecodeScanningDetector {
enum IOIUserValue {
BUFFER, READER
};
private static final String ANY_PARMS = "(*)";
private static Set<FQMethod> COPY_METHODS = UnmodifiableSet.create(
//@formatter:off
new FQMethod("java/nio/file/Files", "copy", ANY_PARMS),
new FQMethod("org/apache/commons/io/IOUtils", "copy", ANY_PARMS),
new FQMethod("org/apache/commons/io/IOUtils", "copyLarge", ANY_PARMS),
new FQMethod("org/springframework/util/FileCopyUtils", "copy", ANY_PARMS),
new FQMethod("org/springframework/util/FileCopyUtils", "copyToByteArray", ANY_PARMS),
new FQMethod("com/google/common/io/Files", "copy", ANY_PARMS),
new FQMethod("org/apache/poi/openxml4j/opc/StreamHelper", "copyStream", ANY_PARMS)
//@formatter:on
);
private static final Set<String> BUFFERED_CLASSES = UnmodifiableSet.create(
//@formatter:off
"java.io.BufferedInputStream",
"java.io.BufferedOutputStream",
"java.io.BufferedReader",
"java.io.BufferedWriter"
//@formatter:on
);
private JavaClass readerClass;
private BugReporter bugReporter;
private OpcodeStack stack;
/**
* constructs a IOI detector given the reporter to report bugs on
*
* @param bugReporter
* the sync of bug reports
*/
public IOIssues(BugReporter bugReporter) {
this.bugReporter = bugReporter;
try {
readerClass = Repository.lookupClass("java.io.Reader");
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
}
/**
* implements the visitor to create and tear down the opcode stack
*
* @param clsContext
* the context object of the currently parsed class
*/
@Override
public void visitClassContext(ClassContext clsContext) {
try {
stack = new OpcodeStack();
super.visitClassContext(clsContext);
} finally {
stack = null;
}
}
/**
* implements the visitor to reset the opcode stack
*
* @param obj
* the currently parsed code block
*/
@Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
super.visitCode(obj);
}
/**
* implements the visitor to look for common api copy utilities to copy streams where the passed in Stream is Buffered. Since these libraries already handle
* the buffering, you are just slowing them down by the extra copy. Also look for copies where the source is a Reader, as this is just wasteful. Can't wrap
* my head around whether a Writer output is sometime valid, might be, so for now ignoring that.
*
* @param seen
* the currently parsed opcode
*/
@Override
public void sawOpcode(int seen) {
IOIUserValue uvSawBuffer = null;
try {
switch (seen) {
case INVOKESPECIAL:
uvSawBuffer = processInvokeSpecial();
break;
case INVOKESTATIC:
processInvokeStatic();
break;
default:
break;
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
stack.sawOpcode(this, seen);
if ((uvSawBuffer != null) && (stack.getStackDepth() > 0)) {
OpcodeStack.Item itm = stack.getStackItem(0);
itm.setUserValue(uvSawBuffer);
}
}
}
private IOIUserValue processInvokeSpecial() throws ClassNotFoundException {
String methodName = getNameConstantOperand();
if (Values.CONSTRUCTOR.equals(methodName)) {
String clsName = getDottedClassConstantOperand();
if (BUFFERED_CLASSES.contains(clsName)) {
return IOIUserValue.BUFFER;
} else {
JavaClass cls = Repository.lookupClass(clsName);
if (cls.instanceOf(readerClass)) {
return IOIUserValue.READER;
}
}
}
return null;
}
private void processInvokeStatic() {
String clsName = getClassConstantOperand();
String methodName = getNameConstantOperand();
FQMethod m = new FQMethod(clsName, methodName, ANY_PARMS);
if (COPY_METHODS.contains(m)) {
String signature = getSigConstantOperand();
Type[] argTypes = Type.getArgumentTypes(signature);
if (stack.getStackDepth() >= argTypes.length) {
for (int i = 0; i < argTypes.length; i++) {
OpcodeStack.Item itm = stack.getStackItem(i);
IOIUserValue uv = (IOIUserValue) itm.getUserValue();
if (uv != null) {
switch (uv) {
case BUFFER:
bugReporter.reportBug(new BugInstance(this, BugType.IOI_DOUBLE_BUFFER_COPY.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
break;
case READER:
bugReporter.reportBug(new BugInstance(this, BugType.IOI_COPY_WITH_READER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this));
}
break;
}
}
}
}
}
} |
package com.example.shushuweather.db;
import java.util.ArrayList;
import java.util.List;
import com.example.shushuweather.models.City;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class ShushuWeatherDB {
public static final String DB_NAME = "shushu_weather";
public static final String TB_CITY = "city";
public static final int DB_VERSION = 1;
private static ShushuWeatherDB shushuWeatherDB;
private SQLiteDatabase db;
private ShushuWeatherDB(Context context) {
// TODO Auto-generated constructor stub
ShushuWeatherOpenHelper dbHelper = new ShushuWeatherOpenHelper(context, DB_NAME, null, DB_VERSION);
db = dbHelper.getWritableDatabase();
}
public synchronized static ShushuWeatherDB getinstance(Context context)
{
if(shushuWeatherDB==null)
{
shushuWeatherDB = new ShushuWeatherDB(context);
}
return shushuWeatherDB;
}
public void saveCity(City city)
{
if(city != null)
{
ContentValues values = new ContentValues();
values.put("weaid", city.getWeaid());
values.put("citynm", city.getCitynm());
values.put("cityno", city.getCityno());
values.put("cityid", city.getCityid());
values.put("province", city.getProvince());
values.put("municipality", city.getMunicipality());
values.put("county", city.getCounty());
db.insert(TB_CITY, null, values);
}
}
public List<City> getAllProvinces()
{
List<City> list = new ArrayList<City>();
Cursor cursor = db.query(TB_CITY, null, null, null, "province", null, null);
if(cursor.moveToFirst())
{
do{
City city = new City();
city.setProvince(cursor.getString(cursor.getColumnIndex("province")));
list.add(city);
}while(cursor.moveToNext());
}
return list;
}
public List<City> getAllMunicipality(String provincenm)
{
List<City> list = new ArrayList<City>();
Cursor cursor = db.query(TB_CITY, null, "province=?", new String[]{provincenm}, null, null, null);
if(cursor.moveToFirst())
{
do{
City city = new City();
city.setMunicipality(cursor.getString(cursor.getColumnIndex("municipality")));
list.add(city);
}while(cursor.moveToNext());
}
return list;
}
public List<City> getAllCounty(String municipality)
{
List<City> list = new ArrayList<City>();
Cursor cursor = db.query(TB_CITY, null, "municipality=?", new String[]{municipality}, null, null, null);
if(cursor.moveToFirst())
{
do{
City city = new City();
city.setMunicipality(cursor.getString(cursor.getColumnIndex("county")));
list.add(city);
}while(cursor.moveToNext());
}
return list;
}
} |
package com.namesny.binarysearchtree;
public class RedBlackTree<T extends Comparable<? super T>> implements BinarySearchTree<T> {
/**
* Tree root
*/
protected RedBlackNode<T> root;
public RedBlackTree() {
root = null;
}
/**
* This class represents a node of a Red-Black tree
*
* @param <T>
*/
protected static class RedBlackNode<T extends Comparable<? super T>> {
/**
* Node value
*/
protected T value;
/**
* Left child
*/
protected RedBlackNode<T> left;
/**
* Right child
*/
protected RedBlackNode<T> right;
/**
* Node color
*/
protected Color color;
/**
* Creates one node
*
* @param value node value
* @param left left child
* @param right right child
*/
public RedBlackNode(T value, RedBlackNode<T> left, RedBlackNode<T> right, Color color) {
this.value = value;
this.left = left;
this.right = right;
this.color = color;
}
/**
* Creates one node without children
*
* @param value
*/
public RedBlackNode(T value) {
this(value, null, null, Color.RED);
}
}
/**
* Represents the color of a node
*/
protected static enum Color {
RED, BLACK
}
@Override
public void insert(T value) throws DuplicateValueException {
root = insert(value, root);
}
@Override
public void delete(T key) {
root = delete(key, root);
}
@Override
public T find(T key) {
return find(key, root);
}
@Override
public void clear() {
this.root = null;
}
@Override
public boolean isEmpty() {
return root == null;
}
@Override
public T findMin() {
return findMin(root).value;
}
@Override
public T findMax() {
return findMax(root).value;
}
private RedBlackNode<T> insert(T value, RedBlackNode<T> node) throws DuplicateValueException {
// We found the place where to insert the value
if (node == null) {
// Create new node with the value
node = new RedBlackNode<>(value);
} else if (value.compareTo(node.value) < 0) {
// Insert into left subtree
node.left = insert(value, node.left);
} else if (value.compareTo(node.value) > 0) {
// Insert into right subtree
node.right = insert(value, node.right);
} else {
// The tree already contains the value
throw new DuplicateValueException("Duplicate value: " + value);
}
node = rebalanceInsert(node);
return node;
}
private RedBlackNode<T> delete(T value, RedBlackNode<T> node) {
if (node == null) {
return null;
}
if (node.value == value) {
if ((node.left == null) && (node.right == null)) {
node = null;
} else if (node.left == null) {
node = node.right;
} else if (node.right == null) {
node = node.left;
} else {
RedBlackNode<T> successor = findMin(node.right);
node.value = successor.value;
node = delete(successor.value, node);
}
} else if (value.compareTo(node.value) < 0) {
node = delete(value, node.left);
} else {
node = delete(value, node.right);
}
node = rebalanceDelete(node);
return node;
}
private RedBlackNode<T> findMin(RedBlackNode<T> node) {
while (node.left != null) {
node = node.left;
}
return node;
}
private RedBlackNode<T> findMax(RedBlackNode<T> node) {
while (node.right != null) {
node = node.right;
}
return node;
}
private T find(T key, RedBlackNode<T> node) {
if (node == null) {
return null;
}
if (node.value == key) {
return node.value;
} else if (key.compareTo(node.value) < 0) {
return find(key, node.left);
} else {
return find(key, node.right);
}
}
protected boolean isRed(RedBlackNode<T> node) {
return (node != null) && (node.color == Color.RED);
}
private RedBlackNode<T> rebalanceInsert(RedBlackNode<T> node) {
/**
* First situation. The inserted node, its parent and its uncle are red.
* This is corrected two levels up, so node variable represents the grandparent
* of the inserted node. Split into two ifs for readability
*/
if ((isRed(node.left.left) || isRed(node.left.right)) && isRed(node.left) && isRed(node.right)) {
node.left.color = Color.BLACK;
node.right.color = Color.BLACK;
node.color = Color.RED;
} else if ((isRed(node.right.left) || isRed(node.right.right)) && isRed(node.right) && isRed(node.right)) {
node.right.color = Color.BLACK;
node.left.color = Color.BLACK;
node.color = Color.RED;
}
/**
* Second situation. The inserted node and its parent are red. Parents
* sibling is black and the inserted node is the opposite child than the
* parent is the child of the grandparent. The node variable represents
* grandfather of the inserted node. This does not fix the problem but
* instead it transforms it into third situation
*/
if (isRed(node.left) && isRed(node.left.right) && !isRed(node.right)) {
node.left = rotateLeft(node.left);
} else if (isRed(node.right) && isRed(node.right.left) && !isRed(node.left)) {
node.right = rotateRight(node.right);
}
/**
* Third situation. The inserted node and its parent are red. Parents
* sibling is black and the inserted node is the same child as the parent
* node is the child of the grandparent.
*/
if (isRed(node.left) && isRed(node.left.left) && !isRed(node.right)) {
node = rotateRight(node);
} else if (isRed(node.right) && isRed(node.right.right) && !isRed(node.left)) {
node = rotateLeft(node);
}
return node;
}
private RedBlackNode<T> rebalanceDelete(RedBlackNode<T> node) {
return node;
}
/**
* Rotates tree to the left
*
* @param node the node where to rotate
* @return new rotated tree
*/
private RedBlackNode<T> rotateLeft(RedBlackNode<T> node) {
RedBlackNode<T> newRoot = node.right;
node.right = newRoot.left;
newRoot.left = node;
//updateHeight(node);
//updateHeight(newRoot);
return newRoot;
}
/**
* Rotates tree to the right
*
* @param node the node where to rotate
* @return new rotated tree
*/
private RedBlackNode<T> rotateRight(RedBlackNode<T> node) {
RedBlackNode<T> newRoot = node.left;
node.left = newRoot.right;
newRoot.right = node;
//node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
//newRoot.height = Math.max(getHeight(newRoot.left), getHeight(newRoot.right)) + 1;
return newRoot;
}
/**
* Rotates tree first left the right
*
* @param node the node where to rotate
* @return new rotated tree
*/
private RedBlackNode<T> rotateLeftRight(RedBlackNode<T> node) {
node.left = rotateLeft(node.left);
return rotateRight(node);
}
/**
* Rotates tree first right then left
*
* @param node the node where to rotate
* @return new rotated tree
*/
private RedBlackNode<T> rotateRightLeft(RedBlackNode<T> node) {
node.right = rotateRight(node.right);
return rotateLeft(node);
}
} |
package com.jetbrains.ther.console;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.console.LanguageConsoleImpl;
import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler;
import com.intellij.execution.process.ColoredProcessHandler;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.runners.AbstractConsoleRunnerWithHistory;
import com.intellij.openapi.project.Project;
import com.jetbrains.ther.TheRLanguage;
import com.jetbrains.ther.interpreter.TheRInterpreterService;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TheRConsoleRunner extends AbstractConsoleRunnerWithHistory<LanguageConsoleView> {
public TheRConsoleRunner(@NotNull final Project project, @Nullable final String workingDir) {
super(project, "The R Console", workingDir);
}
@Override
protected LanguageConsoleView createConsoleView() {
return new LanguageConsoleImpl(getProject(), getConsoleTitle(), TheRLanguage.getInstance());
}
private String getInterpreterPath() throws ExecutionException {
final String interpreterPath = TheRInterpreterService.getInstance().getInterpreterPath();
if (interpreterPath == null) {
throw new ExecutionException("Cannot find R interpreter for this run configuration");
}
return interpreterPath;
}
@Nullable
@Override
protected Process createProcess() throws ExecutionException {
final GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE);
commandLine.setExePath(getInterpreterPath());
commandLine.addParameter("--slave");
commandLine.withWorkDirectory(getWorkingDir());
return commandLine.createProcess();
}
@Override
protected OSProcessHandler createProcessHandler(@NotNull final Process process) {
return new ColoredProcessHandler(process, null);
}
@NotNull
@Override
protected ProcessBackedConsoleExecuteActionHandler createExecuteActionHandler() {
return new ProcessBackedConsoleExecuteActionHandler(getProcessHandler(), true);
}
} |
package me.nallar.patched.world;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.common.collect.ImmutableSetMultimap;
import javassist.is.faulty.ThreadLocals;
import me.nallar.tickthreading.Log;
import me.nallar.tickthreading.collections.ForcedChunksRedirectMap;
import me.nallar.tickthreading.minecraft.entitylist.EntityList;
import me.nallar.tickthreading.minecraft.entitylist.LoadedTileEntityList;
import me.nallar.tickthreading.patcher.Declare;
import net.minecraft.block.Block;
import net.minecraft.crash.CrashReport;
import net.minecraft.crash.CrashReportCategory;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityTracker;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.profiler.Profiler;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ReportedException;
import net.minecraft.world.ChunkCoordIntPair;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;
import net.minecraft.world.WorldServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraft.world.storage.ISaveHandler;
import net.minecraftforge.common.ForgeChunkManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import org.cliffc.high_scale_lib.NonBlockingHashMapLong;
@SuppressWarnings ("unchecked")
public abstract class PatchWorld extends World {
private int forcedUpdateCount;
@Declare
public org.cliffc.high_scale_lib.NonBlockingHashMapLong<Integer> redstoneBurnoutMap_;
@Declare
public Set<Entity> unloadedEntitySet_;
@Declare
public Set<TileEntity> tileEntityRemovalSet_;
@Declare
public com.google.common.collect.ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> forcedChunks_;
@Declare
public int tickCount_;
public void construct() {
tickCount = rand.nextInt(240); // So when different worlds do every N tick actions,
// they won't all happen at the same time even if the worlds loaded at the same time
tileEntityRemovalSet = new HashSet<TileEntity>();
unloadedEntitySet = new HashSet<Entity>();
redstoneBurnoutMap = new NonBlockingHashMapLong<Integer>();
}
public PatchWorld(ISaveHandler par1ISaveHandler, String par2Str, WorldProvider par3WorldProvider, WorldSettings par4WorldSettings, Profiler par5Profiler) {
super(par1ISaveHandler, par2Str, par3WorldProvider, par4WorldSettings, par5Profiler);
}
@Override
public void removeEntity(Entity entity) {
if (entity == null) {
return;
}
try {
if (entity.riddenByEntity != null) {
entity.riddenByEntity.mountEntity(null);
}
if (entity.ridingEntity != null) {
entity.mountEntity(null);
}
entity.setDead();
// The next instanceof, somehow, seems to throw NPEs. I don't even. :(
if (entity instanceof EntityPlayer) {
this.playerEntities.remove(entity);
this.updateAllPlayersSleepingFlag();
}
} catch (Exception e) {
Log.severe("Exception removing a player entity", e);
}
}
@Override
public int getBlockId(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y > 0 && y < 256) {
try {
return getChunkFromChunkCoords(x >> 4, z >> 4).getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t);
}
}
return 0;
}
@Override
@Declare
public int getBlockIdWithoutLoad(int x, int y, int z) {
if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000 && y > 0 && y < 256) {
try {
Chunk chunk = ((ChunkProviderServer) chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? -1 : chunk.getBlockID(x & 15, y, z & 15);
} catch (Throwable t) {
Log.severe("Exception getting block ID in " + Log.name(this) + " at x,y,z" + x + ',' + y + ',' + z, t);
}
}
return 0;
}
@Override
public EntityPlayer getClosestPlayer(double x, double y, double z, double maxRange) {
double closestRange = Double.MAX_VALUE;
EntityPlayer target = null;
for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) {
if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) {
double distanceSq = playerEntity.getDistanceSq(x, y, z);
if ((maxRange < 0.0D || distanceSq < (maxRange * maxRange)) && (distanceSq < closestRange)) {
closestRange = distanceSq;
target = playerEntity;
}
}
}
return target;
}
@SuppressWarnings ("ConstantConditions")
@Override
public EntityPlayer getClosestVulnerablePlayer(double x, double y, double z, double maxRange) {
double closestRange = Double.MAX_VALUE;
EntityPlayer target = null;
for (EntityPlayer playerEntity : (Iterable<EntityPlayer>) this.playerEntities) {
if (!playerEntity.capabilities.disableDamage && playerEntity.isEntityAlive()) {
double distanceSq = playerEntity.getDistanceSq(x, y, z);
double effectiveMaxRange = maxRange;
if (playerEntity.isSneaking()) {
effectiveMaxRange = maxRange * 0.800000011920929D;
}
if (playerEntity.getHasActivePotion()) {
float var18 = playerEntity.func_82243_bO();
if (var18 < 0.1F) {
var18 = 0.1F;
}
effectiveMaxRange *= (double) (0.7F * var18);
}
if ((maxRange < 0.0D || distanceSq < (effectiveMaxRange * effectiveMaxRange)) && (distanceSq < closestRange)) {
closestRange = distanceSq;
target = playerEntity;
}
}
}
return target;
}
@Override
public EntityPlayer getPlayerEntityByName(String name) {
for (EntityPlayer player : (Iterable<EntityPlayer>) playerEntities) {
if (name.equals(player.username)) {
return player;
}
}
return null;
}
@Override
protected void notifyBlockOfNeighborChange(int x, int y, int z, int par4) {
if (!this.editingBlocks && !this.isRemote) {
int var5 = this.getBlockIdWithoutLoad(x, y, z);
Block var6 = var5 < 1 ? null : Block.blocksList[var5];
if (var6 != null) {
try {
var6.onNeighborBlockChange(this, x, y, z, par4);
} catch (Throwable t) {
Log.severe("Exception while updating block neighbours", t);
}
}
}
}
@Override
public ImmutableSetMultimap<ChunkCoordIntPair, ForgeChunkManager.Ticket> getPersistentChunks() {
return forcedChunks == null ? ForcedChunksRedirectMap.emptyMap : forcedChunks;
}
@Override
public TileEntity getBlockTileEntity(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
@Declare
public TileEntity getTEWithoutLoad(int x, int y, int z) {
if (y >= 256) {
return null;
} else {
Chunk chunk = ((ChunkProviderServer) this.chunkProvider).getChunkIfExists(x >> 4, z >> 4);
return chunk == null ? null : chunk.getChunkBlockTileEntity(x & 15, y, z & 15);
}
}
@Override
public void updateEntityWithOptionalForce(Entity par1Entity, boolean par2) {
int x = MathHelper.floor_double(par1Entity.posX);
int z = MathHelper.floor_double(par1Entity.posZ);
Boolean isForced = par1Entity.isForced;
if (isForced == null || forcedUpdateCount++ % 7 == 0) {
par1Entity.isForced = isForced = getPersistentChunks().containsKey(new ChunkCoordIntPair(x >> 4, z >> 4));
}
byte range = isForced ? (byte) 0 : 32;
boolean canUpdate = !par2 || this.checkChunksExist(x - range, 0, z - range, x + range, 0, z + range);
if (canUpdate) {
par1Entity.lastTickPosX = par1Entity.posX;
par1Entity.lastTickPosY = par1Entity.posY;
par1Entity.lastTickPosZ = par1Entity.posZ;
par1Entity.prevRotationYaw = par1Entity.rotationYaw;
par1Entity.prevRotationPitch = par1Entity.rotationPitch;
if (par2 && par1Entity.addedToChunk) {
if (par1Entity.ridingEntity != null) {
par1Entity.updateRidden();
} else {
++par1Entity.ticksExisted;
par1Entity.onUpdate();
}
}
this.theProfiler.startSection("chunkCheck");
if (Double.isNaN(par1Entity.posX) || Double.isInfinite(par1Entity.posX)) {
par1Entity.posX = par1Entity.lastTickPosX;
}
if (Double.isNaN(par1Entity.posY) || Double.isInfinite(par1Entity.posY)) {
par1Entity.posY = par1Entity.lastTickPosY;
}
if (Double.isNaN(par1Entity.posZ) || Double.isInfinite(par1Entity.posZ)) {
par1Entity.posZ = par1Entity.lastTickPosZ;
}
if (Double.isNaN((double) par1Entity.rotationPitch) || Double.isInfinite((double) par1Entity.rotationPitch)) {
par1Entity.rotationPitch = par1Entity.prevRotationPitch;
}
if (Double.isNaN((double) par1Entity.rotationYaw) || Double.isInfinite((double) par1Entity.rotationYaw)) {
par1Entity.rotationYaw = par1Entity.prevRotationYaw;
}
int var6 = MathHelper.floor_double(par1Entity.posX / 16.0D);
int var7 = MathHelper.floor_double(par1Entity.posY / 16.0D);
int var8 = MathHelper.floor_double(par1Entity.posZ / 16.0D);
if (!par1Entity.addedToChunk || par1Entity.chunkCoordX != var6 || par1Entity.chunkCoordY != var7 || par1Entity.chunkCoordZ != var8) {
if (par1Entity.addedToChunk) {
Chunk chunk = getChunkIfExists(par1Entity.chunkCoordX, par1Entity.chunkCoordZ);
if (chunk != null) {
chunk.removeEntityAtIndex(par1Entity, par1Entity.chunkCoordY);
}
}
Chunk chunk = getChunkIfExists(var6, var8);
if (chunk != null) {
par1Entity.addedToChunk = true;
chunk.addEntity(par1Entity);
} else {
par1Entity.addedToChunk = false;
}
}
this.theProfiler.endSection();
if (par2 && par1Entity.addedToChunk && par1Entity.riddenByEntity != null) {
if (!par1Entity.riddenByEntity.isDead && par1Entity.riddenByEntity.ridingEntity == par1Entity) {
this.updateEntity(par1Entity.riddenByEntity);
} else {
par1Entity.riddenByEntity.ridingEntity = null;
par1Entity.riddenByEntity = null;
}
}
}
}
@Override
public void addLoadedEntities(List par1List) {
EntityTracker entityTracker = null;
//noinspection RedundantCast
if (((Object) this instanceof WorldServer)) {
entityTracker = ((WorldServer) (Object) this).getEntityTracker();
}
for (int var2 = 0; var2 < par1List.size(); ++var2) {
Entity entity = (Entity) par1List.get(var2);
if (MinecraftForge.EVENT_BUS.post(new EntityJoinWorldEvent(entity, this))) {
par1List.remove(var2
} else if (entityTracker == null || !entityTracker.isTracking(entity.entityId)) {
loadedEntityList.add(entity);
this.obtainEntitySkin(entity);
}
}
}
@Override
@Declare
public boolean hasCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get();
collidingBoundingBoxes.clear();
int minX = MathHelper.floor_double(par2AxisAlignedBB.minX);
int maxX = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int minY = MathHelper.floor_double(par2AxisAlignedBB.minY);
int maxY = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int minZ = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int maxZ = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((minY - 1) < 0) ? 0 : (minY - 1);
for (int chunkx = (minX >> 4); chunkx <= ((maxX - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (minZ >> 4); chunkz <= ((maxZ - 1) >> 4); chunkz++) {
Chunk chunk = this.getChunkIfExists(chunkx, chunkz);
if (chunk == null) {
continue;
}
// Compute ranges within chunk
int cz = chunkz << 4;
int xstart = (minX < cx) ? cx : minX;
int xend = (maxX < (cx + 16)) ? maxX : (cx + 16);
int zstart = (minZ < cz) ? cz : minZ;
int zend = (maxZ < (cz + 16)) ? maxZ : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < maxY; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
if (!collidingBoundingBoxes.isEmpty()) {
return true;
}
}
}
}
}
}
}
double var14 = 0.25D;
List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), 100);
for (Entity aVar16 : var16) {
AxisAlignedBB var13 = aVar16.getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
var13 = par1Entity.getCollisionBox(aVar16);
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
return true;
}
}
return false;
}
@Override
@Declare
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
List collidingBoundingBoxes = (List) ThreadLocals.collidingBoundingBoxes.get();
collidingBoundingBoxes.clear();
int var3 = MathHelper.floor_double(par2AxisAlignedBB.minX);
int var4 = MathHelper.floor_double(par2AxisAlignedBB.maxX + 1.0D);
int var5 = MathHelper.floor_double(par2AxisAlignedBB.minY);
int var6 = MathHelper.floor_double(par2AxisAlignedBB.maxY + 1.0D);
int var7 = MathHelper.floor_double(par2AxisAlignedBB.minZ);
int var8 = MathHelper.floor_double(par2AxisAlignedBB.maxZ + 1.0D);
int ystart = ((var5 - 1) < 0) ? 0 : (var5 - 1);
for (int chunkx = (var3 >> 4); chunkx <= ((var4 - 1) >> 4); chunkx++) {
int cx = chunkx << 4;
for (int chunkz = (var7 >> 4); chunkz <= ((var8 - 1) >> 4); chunkz++) {
Chunk chunk = this.getChunkIfExists(chunkx, chunkz);
if (chunk == null) {
continue;
}
// Compute ranges within chunk
int cz = chunkz << 4;
// Compute ranges within chunk
int xstart = (var3 < cx) ? cx : var3;
int xend = (var4 < (cx + 16)) ? var4 : (cx + 16);
int zstart = (var7 < cz) ? cz : var7;
int zend = (var8 < (cz + 16)) ? var8 : (cz + 16);
// Loop through blocks within chunk
for (int x = xstart; x < xend; x++) {
for (int z = zstart; z < zend; z++) {
for (int y = ystart; y < var6; y++) {
int blkid = chunk.getBlockID(x - cx, y, z - cz);
if (blkid > 0) {
Block block = Block.blocksList[blkid];
if (block != null) {
block.addCollidingBlockToList(this, x, y, z, par2AxisAlignedBB, collidingBoundingBoxes, par1Entity);
}
}
}
}
}
}
}
double var14 = 0.25D;
List<Entity> var16 = this.getEntitiesWithinAABBExcludingEntity(par1Entity, par2AxisAlignedBB.expand(var14, var14, var14), limit);
for (Entity aVar16 : var16) {
AxisAlignedBB var13 = aVar16.getBoundingBox();
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
var13 = par1Entity.getCollisionBox(aVar16);
if (var13 != null && var13.intersectsWith(par2AxisAlignedBB)) {
collidingBoundingBoxes.add(var13);
}
}
return collidingBoundingBoxes;
}
@Override
public List getCollidingBoundingBoxes(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
return getCollidingBoundingBoxes(par1Entity, par2AxisAlignedBB, 2000);
}
@Override
public void addTileEntity(Collection tileEntities) {
List dest = scanningTileEntities ? addedTileEntityList : loadedTileEntityList;
for (TileEntity tileEntity : (Iterable<TileEntity>) tileEntities) {
tileEntity.validate();
if (tileEntity.canUpdate()) {
dest.add(tileEntity);
}
}
}
@Override
@Declare
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB, int limit) {
List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get();
entitiesWithinAABBExcludingEntity.clear();
int minX = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D);
int maxX = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D);
int minZ = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D);
int maxZ = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D);
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
Chunk chunk = getChunkIfExists(x, z);
if (chunk != null) {
chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity, limit);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public List getEntitiesWithinAABBExcludingEntity(Entity par1Entity, AxisAlignedBB par2AxisAlignedBB) {
List entitiesWithinAABBExcludingEntity = (List) ThreadLocals.entitiesWithinAABBExcludingEntity.get();
entitiesWithinAABBExcludingEntity.clear();
int var3 = MathHelper.floor_double((par2AxisAlignedBB.minX - MAX_ENTITY_RADIUS) / 16.0D);
int var4 = MathHelper.floor_double((par2AxisAlignedBB.maxX + MAX_ENTITY_RADIUS) / 16.0D);
int var5 = MathHelper.floor_double((par2AxisAlignedBB.minZ - MAX_ENTITY_RADIUS) / 16.0D);
int var6 = MathHelper.floor_double((par2AxisAlignedBB.maxZ + MAX_ENTITY_RADIUS) / 16.0D);
for (int var7 = var3; var7 <= var4; ++var7) {
for (int var8 = var5; var8 <= var6; ++var8) {
Chunk chunk = getChunkIfExists(var7, var8);
if (chunk != null) {
chunk.getEntitiesWithinAABBForEntity(par1Entity, par2AxisAlignedBB, entitiesWithinAABBExcludingEntity);
}
}
}
return entitiesWithinAABBExcludingEntity;
}
@Override
public int countEntities(Class entityType) {
if (loadedEntityList instanceof EntityList) {
return ((EntityList) this.loadedEntityList).manager.getEntityCount(entityType);
}
int count = 0;
for (Entity e : (Iterable<Entity>) this.loadedEntityList) {
if (entityType.isAssignableFrom(e.getClass())) {
++count;
}
}
return count;
}
@Override
public boolean checkChunksExist(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
if (minY > 255 || maxY < 0) {
return false;
}
minX >>= 4;
minZ >>= 4;
maxX >>= 4;
maxZ >>= 4;
for (int x = minX; x <= maxX; ++x) {
for (int z = minZ; z <= maxZ; ++z) {
if (!chunkProvider.chunkExists(x, z)) {
return false;
}
}
}
return true;
}
@Override
public void unloadEntities(List entitiesToUnload) {
this.unloadedEntitySet.addAll(entitiesToUnload);
}
@Override
public void updateEntities() {
this.theProfiler.startSection("entities");
this.theProfiler.startSection("global");
int var1;
Entity var2;
CrashReport var4;
CrashReportCategory var5;
for (var1 = 0; var1 < this.weatherEffects.size(); ++var1) {
var2 = (Entity) this.weatherEffects.get(var1);
try {
++var2.ticksExisted;
var2.onUpdate();
} catch (Throwable var6) {
var4 = CrashReport.makeCrashReport(var6, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
if (var2.isDead) {
this.weatherEffects.remove(var1
}
}
this.theProfiler.endStartSection("remove");
int var3;
int var13;
if (this.loadedEntityList instanceof EntityList) {
((EntityList) this.loadedEntityList).manager.batchRemoveEntities(unloadedEntitySet);
} else {
this.loadedEntityList.removeAll(this.unloadedEntitySet);
for (Entity entity : unloadedEntitySet) {
var3 = entity.chunkCoordX;
var13 = entity.chunkCoordZ;
if (entity.addedToChunk) {
Chunk chunk = getChunkIfExists(var3, var13);
if (chunk != null) {
chunk.removeEntity(entity);
}
}
releaseEntitySkin(entity);
}
}
this.unloadedEntitySet.clear();
this.theProfiler.endStartSection("regular");
boolean shouldTickThreadingTick = true;
if (this.loadedEntityList instanceof EntityList) {
((EntityList) this.loadedEntityList).manager.doTick();
shouldTickThreadingTick = false;
} else {
for (var1 = 0; var1 < this.loadedEntityList.size(); ++var1) {
var2 = (Entity) this.loadedEntityList.get(var1);
if (var2.ridingEntity != null) {
if (!var2.ridingEntity.isDead && var2.ridingEntity.riddenByEntity == var2) {
continue;
}
var2.ridingEntity.riddenByEntity = null;
var2.ridingEntity = null;
}
this.theProfiler.startSection("tick");
if (!var2.isDead) {
try {
this.updateEntity(var2);
} catch (Throwable var7) {
var4 = CrashReport.makeCrashReport(var7, "Ticking entity");
var5 = var4.makeCategory("Entity being ticked");
var2.func_85029_a(var5);
throw new ReportedException(var4);
}
}
this.theProfiler.endSection();
this.theProfiler.startSection("remove");
if (var2.isDead) {
var3 = var2.chunkCoordX;
var13 = var2.chunkCoordZ;
if (var2.addedToChunk) {
Chunk chunk = getChunkIfExists(var3, var13);
if (chunk != null) {
chunk.removeEntity(var2);
}
}
this.loadedEntityList.remove(var1
this.releaseEntitySkin(var2);
}
this.theProfiler.endSection();
}
}
this.theProfiler.endStartSection("tileEntities");
if (this.loadedEntityList instanceof EntityList) {
if (shouldTickThreadingTick) {
((EntityList) this.loadedEntityList).manager.doTick();
}
} else {
this.scanningTileEntities = true;
Iterator var14 = this.loadedTileEntityList.iterator();
while (var14.hasNext()) {
TileEntity var9 = (TileEntity) var14.next();
if (!var9.isInvalid() && var9.func_70309_m() && this.blockExists(var9.xCoord, var9.yCoord, var9.zCoord)) {
try {
var9.updateEntity();
} catch (Throwable var8) {
var4 = CrashReport.makeCrashReport(var8, "Ticking tile entity");
var5 = var4.makeCategory("Tile entity being ticked");
var9.func_85027_a(var5);
throw new ReportedException(var4);
}
}
if (var9.isInvalid()) {
var14.remove();
Chunk var11 = this.getChunkIfExists(var9.xCoord >> 4, var9.zCoord >> 4);
if (var11 != null) {
var11.cleanChunkBlockTileEntity(var9.xCoord & 15, var9.yCoord, var9.zCoord & 15);
}
}
}
}
this.theProfiler.endStartSection("removingTileEntities");
if (!this.tileEntityRemovalSet.isEmpty()) {
if (loadedTileEntityList instanceof LoadedTileEntityList) {
((LoadedTileEntityList) loadedTileEntityList).manager.batchRemoveTileEntities(tileEntityRemovalSet);
} else {
for (TileEntity tile : tileEntityRemovalSet) {
tile.onChunkUnload();
}
this.loadedTileEntityList.removeAll(tileEntityRemovalSet);
}
tileEntityRemovalSet.clear();
}
this.scanningTileEntities = false;
this.theProfiler.endStartSection("pendingTileEntities");
if (!this.addedTileEntityList.isEmpty()) {
for (TileEntity te : (Iterable<TileEntity>) this.addedTileEntityList) {
if (te.isInvalid()) {
Chunk var15 = this.getChunkIfExists(te.xCoord >> 4, te.zCoord >> 4);
if (var15 != null) {
var15.cleanChunkBlockTileEntity(te.xCoord & 15, te.yCoord, te.zCoord & 15);
}
} else {
if (!this.loadedTileEntityList.contains(te)) {
this.loadedTileEntityList.add(te);
}
}
}
this.addedTileEntityList.clear();
}
this.theProfiler.endSection();
this.theProfiler.endSection();
}
@Override
@Declare
public Chunk getChunkIfExists(int x, int z) {
return ((ChunkProviderServer) chunkProvider).getChunkIfExists(x, z);
}
@Override
public void markTileEntityForDespawn(TileEntity tileEntity) {
tileEntityRemovalSet.add(tileEntity);
}
} |
package com.jmex.model.XMLparser.Converters;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import com.jme.image.Texture;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.MaterialState;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.util.geom.BufferUtils;
import com.jmex.model.XMLparser.JmeBinaryWriter;
public class ObjToJme extends FormatConverter{
private BufferedReader inFile;
/** Every vertex in the file*/
private ArrayList vertexList=new ArrayList();
/** Every texture coordinate in the file*/
private ArrayList textureList=new ArrayList();
/** Every normal in the file*/
private ArrayList normalList=new ArrayList();
/** Last 'material' flag in the file*/
private MaterialGrouping curGroup;
/** Default material group for groups without a material*/
private final MaterialGrouping DEFAULT_GROUP=new MaterialGrouping();
/** Maps material names to the actual material object **/
private HashMap materialNames=new HashMap();
/** Maps Materials to their vertex usage **/
private HashMap materialSets=new HashMap();
/**
* Converts an Obj file to jME format. The syntax is: "ObjToJme file.obj outfile.jme".
* @param args The array of parameters
*/
public static void main(String[] args){
new DummyDisplaySystem();
new ObjToJme().attemptFileConvert(args);
}
/**
* Converts an .obj file to .jme format. If you wish to use a .mtl to load the obj's material information please specify
* the base url where the .mtl is located with setProperty("mtllib",new URL(baseURL))
* @param format The .obj file's stream.
* @param jMEFormat The .jme file's stream.
* @throws IOException If anything bad happens.
*/
public void convert(InputStream format, OutputStream jMEFormat) throws IOException {
vertexList.clear();
textureList.clear();
normalList.clear();
materialSets.clear();
materialNames.clear();
inFile=new BufferedReader(new InputStreamReader(format));
String in;
curGroup=DEFAULT_GROUP;
materialSets.put(DEFAULT_GROUP,new ArraySet());
while ((in=inFile.readLine())!=null){
processLine(in);
}
new JmeBinaryWriter().writeScene(buildStructure(),jMEFormat);
nullAll();
}
/**
* Nulls all to let the gc do its job.
* @throws IOException
*/
private void nullAll() throws IOException {
vertexList.clear();
textureList.clear();
normalList.clear();
curGroup=null;
materialSets.clear();
materialNames.clear();
inFile.close();
inFile=null;
}
/**
* Converts the structures of the .obj file to a scene to write
* @return The TriMesh or Node that represents the .obj file.
*/
private Spatial buildStructure() {
Node toReturn=new Node("obj file");
Object[] o=materialSets.keySet().toArray();
for (int i=0;i<o.length;i++){
MaterialGrouping thisGroup=(MaterialGrouping) o[i];
ArraySet thisSet=(ArraySet) materialSets.get(thisGroup);
if (thisSet.indexes.size()<3) continue;
TriMesh thisMesh=new TriMesh("temp"+i);
Vector3f[] vert=new Vector3f[thisSet.vertexes.size()];
Vector3f[] norm=new Vector3f[thisSet.vertexes.size()];
Vector2f[] text=new Vector2f[thisSet.vertexes.size()];
for (int j=0;j<thisSet.vertexes.size();j++){
vert[j]=(Vector3f) thisSet.vertexes.get(j);
norm[j]=(Vector3f) thisSet.normals.get(j);
text[j]=(Vector2f) thisSet.textures.get(j);
}
int[] indexes=new int[thisSet.indexes.size()];
for (int j=0;j<thisSet.indexes.size();j++)
indexes[j]=((Integer)thisSet.indexes.get(j)).intValue();
thisMesh.reconstruct(BufferUtils.createFloatBuffer(vert),
BufferUtils.createFloatBuffer(norm), null,
BufferUtils.createFloatBuffer(text),
BufferUtils.createIntBuffer(indexes));
if (properties.get("sillycolors")!=null)
thisMesh.setRandomColors();
if (thisGroup.ts.isEnabled()) thisMesh.setRenderState(thisGroup.ts);
thisMesh.setRenderState(thisGroup.m);
if (thisGroup.as != null) {
thisMesh.setRenderState(thisGroup.as);
thisMesh.setRenderQueueMode(Renderer.QUEUE_TRANSPARENT);
}
toReturn.attachChild(thisMesh);
}
if (toReturn.getQuantity()==1)
return toReturn.getChild(0);
else
return toReturn;
}
/**
* Processes a line of text in the .obj file.
* @param s The line of text in the file.
* @throws IOException
*/
private void processLine(String s) throws IOException {
if (s==null) return ;
if (s.length()==0) return;
String[] parts=s.split(" ");
parts=removeEmpty(parts);
if ("#".equals(parts[0])) return;
if ("v".equals(parts[0])){
addVertextoList(parts);
return;
}else if ("vt".equals(parts[0])){
addTextoList(parts);
return;
} else if ("vn".equals(parts[0])){
addNormalToList(parts);
return;
} else if ("g".equals(parts[0])){
//see what the material name is if there isn't a name, assume its the default group
if (parts.length >= 2 && materialNames.get(parts[1]) != null
&& materialNames.get(parts[1]) != null)
curGroup = (MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("f".equals(parts[0])){
addFaces(parts);
return;
} else if ("mtllib".equals(parts[0])){
loadMaterials(parts);
return;
} else if ("newmtl".equals(parts[0])){
addMaterial(parts);
return;
} else if ("usemtl".equals(parts[0])){
if (materialNames.get(parts[1])!=null)
curGroup=(MaterialGrouping) materialNames.get(parts[1]);
else
setDefaultGroup();
return;
} else if ("Ka".equals(parts[0])){
curGroup.m.setAmbient(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Kd".equals(parts[0])){
curGroup.m.setDiffuse(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ks".equals(parts[0])){
curGroup.m.setSpecular(new ColorRGBA(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3]),1));
return;
} else if ("Ns".equals(parts[0])){
curGroup.m.setShininess(Float.parseFloat(parts[1]));
return;
} else if ("d".equals(parts[0])){
curGroup.m.setAlpha(Float.parseFloat(parts[1]));
ColorRGBA alpha = new ColorRGBA(1,1,1,curGroup.m.getAlpha());
curGroup.m.setAmbient(curGroup.m.getAmbient().mult(alpha));
curGroup.m.setDiffuse(curGroup.m.getDiffuse().mult(alpha));
curGroup.m.setSpecular(curGroup.m.getSpecular().mult(alpha));
if (curGroup.m.getAlpha() < 1.0f)
curGroup.createAlphaState();
return;
} else if ("map_d".equals(parts[0])) {
curGroup.createAlphaState();
return;
} else if ("map_Kd".equals(parts[0]) || "map_Ka".equals(parts[0])){
Texture t=new Texture();
t.setImageLocation("file:/"+s.trim().substring(6));
curGroup.ts.setTexture(t);
curGroup.ts.setEnabled(true);
return;
}
}
private String[] removeEmpty(String[] parts) {
int cnt=0;
for (int i=0;i<parts.length;i++){
if (!parts[i].equals(""))
cnt++;
}
String[] toReturn=new String[cnt];
int index=0;
for (int i=0;i<parts.length;i++){
if (!parts[i].equals("")){
toReturn[index++]=parts[i];
}
}
return toReturn;
}
private void addMaterial(String[] parts) {
MaterialGrouping newMat=new MaterialGrouping();
materialNames.put(parts[1],newMat);
materialSets.put(newMat,new ArraySet());
curGroup=newMat;
}
private void loadMaterials(String[] fileNames) throws IOException {
URL matURL=(URL) properties.get("mtllib");
if (matURL==null) return;
for (int i=1;i<fileNames.length;i++){
processMaterialFile(new URL(matURL,fileNames[i]).openStream());
}
}
private void processMaterialFile(InputStream inputStream) throws IOException {
BufferedReader matFile=new BufferedReader(new InputStreamReader(inputStream));
String in;
while ((in=matFile.readLine())!=null){
processLine(in);
}
}
private void addFaces(String[] parts) {
ArraySet thisMat=(ArraySet) materialSets.get(curGroup);
IndexSet first=new IndexSet(parts[1]);
int firstIndex=thisMat.findSet(first);
IndexSet second=new IndexSet(parts[2]);
int secondIndex=thisMat.findSet(second);
IndexSet third=new IndexSet();
for (int i=3;i<parts.length;i++){
third.parseStringArray(parts[i]);
thisMat.indexes.add(new Integer(firstIndex));
thisMat.indexes.add(new Integer(secondIndex));
int thirdIndex=thisMat.findSet(third);
thisMat.indexes.add(new Integer(thirdIndex));
}
}
private void setDefaultGroup() {
curGroup=DEFAULT_GROUP;
}
private void addNormalToList(String[] parts) {
normalList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3])));
}
private void addTextoList(String[] parts) {
if (parts.length==2)
textureList.add(new Vector2f(Float.parseFloat(parts[1]),0));
else
textureList.add(new Vector2f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2])));
}
private void addVertextoList(String[] parts) {
vertexList.add(new Vector3f(Float.parseFloat(parts[1]),Float.parseFloat(parts[2]),Float.parseFloat(parts[3])));
}
private class MaterialGrouping{
public MaterialGrouping(){
m=DisplaySystem.getDisplaySystem().getRenderer().createMaterialState();
m.setAmbient(new ColorRGBA(.2f,.2f,.2f,1));
m.setDiffuse(new ColorRGBA(.8f,.8f,.8f,1));
m.setSpecular(ColorRGBA.white);
m.setEnabled(true);
ts=DisplaySystem.getDisplaySystem().getRenderer().createTextureState();
}
public void createAlphaState() {
if (as != null)
return;
as = DisplaySystem.getDisplaySystem().getRenderer()
.createAlphaState();
as.setBlendEnabled(true);
as.setSrcFunction(AlphaState.SB_SRC_ALPHA);
as.setDstFunction(AlphaState.DB_ONE_MINUS_SRC_ALPHA);
as.setTestEnabled(true);
as.setTestFunction(AlphaState.TF_GREATER);
as.setEnabled(true);
}
MaterialState m;
TextureState ts;
AlphaState as;
}
/**
* Stores a complete set of vertex/texture/normal triplet set that is to be
* indexed by the TriMesh.
*/
private class IndexSet{
public IndexSet(){}
public IndexSet(String parts){
parseStringArray(parts);
}
public void parseStringArray(String parts){
int vIndex,nIndex,tIndex;
String[] triplet=parts.split("/");
vIndex=Integer.parseInt(triplet[0]);
if (vIndex<0){
vertex=(Vector3f) vertexList.get(vertexList.size()+vIndex);
} else{
vertex=(Vector3f) vertexList.get(vIndex-1); // obj is 1 indexed
}
if (triplet.length < 2 || triplet[1]==null || triplet[1].equals("")){
texture=null;
} else{
tIndex=Integer.parseInt(triplet[1]);
if (tIndex<0){
texture=(Vector2f) textureList.get(textureList.size()+tIndex);
} else{
texture=(Vector2f) textureList.get(tIndex-1); // obj is 1 indexed
}
}
if (triplet.length!=3 || triplet[2]==null || triplet[2].equals("")){
normal=null;
} else{
nIndex=Integer.parseInt(triplet[2]);
if (nIndex<0){
normal=(Vector3f) normalList.get(normalList.size()+nIndex);
} else{
normal=(Vector3f) normalList.get(nIndex-1); // obj is 1 indexed
}
}
}
Vector3f vertex;
Vector2f texture;
Vector3f normal;
}
/**
* An array of information that will become a renderable trimesh. Each material has it's own trimesh.
*/
private class ArraySet{
private ArrayList vertexes=new ArrayList();
private ArrayList normals=new ArrayList();
private ArrayList textures=new ArrayList();
private ArrayList indexes=new ArrayList();
public int findSet(IndexSet v) {
int i=0;
for (i=0;i<normals.size();i++){
if (compareObjects(v.normal,normals.get(i)) &&
compareObjects(v.texture,textures.get(i)) &&
compareObjects(v.vertex,vertexes.get(i)))
return i;
}
normals.add(v.normal);
textures.add(v.texture);
vertexes.add(v.vertex);
return i;
}
private boolean compareObjects(Object o1, Object o2) {
if (o1==null) return (o2==null);
if (o2==null) return false;
return o1.equals(o2);
}
}
} |
package com.opengamma.engine.position;
import java.util.Set;
import com.opengamma.id.UniqueIdentifier;
/**
* A master structure of all positions held by the organization.
* <p>
* The master is structured into a number of portfolios, each of which holds
* positions in a flexible tree structure.
*/
public interface PositionMaster {
/**
* Gets the list of all portfolio identifiers.
* @return the portfolio identifiers, unmodifiable, not null
*/
Set<UniqueIdentifier> getPortfolioIds();
Portfolio getPortfolio(UniqueIdentifier uid);
PortfolioNode getPortfolioNode(UniqueIdentifier uid);
Position getPosition(UniqueIdentifier uid);
} |
package com.readytalk.oss.dbms.imp;
import static com.readytalk.oss.dbms.util.Util.expect;
import static com.readytalk.oss.dbms.util.Util.list;
import static com.readytalk.oss.dbms.util.Util.copy;
import static com.readytalk.oss.dbms.SourceFactory.reference;
import com.readytalk.oss.dbms.RevisionBuilder;
import com.readytalk.oss.dbms.TableBuilder;
import com.readytalk.oss.dbms.RowBuilder;
import com.readytalk.oss.dbms.Index;
import com.readytalk.oss.dbms.View;
import com.readytalk.oss.dbms.Table;
import com.readytalk.oss.dbms.Column;
import com.readytalk.oss.dbms.Revision;
import com.readytalk.oss.dbms.DuplicateKeyResolution;
import com.readytalk.oss.dbms.DuplicateKeyException;
import com.readytalk.oss.dbms.PatchTemplate;
import com.readytalk.oss.dbms.TableReference;
import com.readytalk.oss.dbms.QueryResult;
import com.readytalk.oss.dbms.UpdateTemplate;
import com.readytalk.oss.dbms.InsertTemplate;
import com.readytalk.oss.dbms.DeleteTemplate;
import com.readytalk.oss.dbms.ColumnList;
import com.readytalk.oss.dbms.ForeignKey;
import com.readytalk.oss.dbms.ForeignKeyResolver;
import com.readytalk.oss.dbms.ForeignKeyResolvers;
import com.readytalk.oss.dbms.SourceVisitor;
import com.readytalk.oss.dbms.Source;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
class MyRevisionBuilder implements RevisionBuilder {
private static final Map<Class, PatchTemplateAdapter> adapters
= new HashMap<Class, PatchTemplateAdapter>();
static {
adapters.put(UpdateTemplate.class, new UpdateTemplateAdapter());
adapters.put(InsertTemplate.class, new InsertTemplateAdapter());
adapters.put(DeleteTemplate.class, new DeleteTemplateAdapter());
}
public Object token;
public final NodeStack stack;
public final Comparable[] keys;
public final Node[] blazedRoots;
public final Node[] blazedLeaves;
public final Node[] found;
public final Node.BlazeResult blazeResult = new Node.BlazeResult();
public NodeStack indexUpdateIterateStack;
public NodeStack indexUpdateBaseStack;
public NodeStack indexUpdateForkStack;
public MyRevision base;
public MyRevision indexBase;
public MyRevision result;
public int max = -1;
public boolean dirtyIndexes;
public MyRevisionBuilder(Object token,
MyRevision base,
NodeStack stack)
{
this.token = token;
this.base = base;
this.indexBase = base;
this.result = base;
this.stack = stack;
keys = new Comparable[Constants.MaxDepth + 1];
blazedRoots = new Node[Constants.MaxDepth + 1];
blazedLeaves = new Node[Constants.MaxDepth + 1];
found = new Node[Constants.MaxDepth + 1];
}
public void setToken(Object token) {
if (token != this.token) {
this.token = token;
for (int i = 0; i < max; ++i) {
found[i] = null;
blazedLeaves[i] = null;
blazedRoots[i + 1] = null;
}
}
}
public void setKey(int index, Comparable key) {
if (max < index || ! Compare.equal(key, keys[index])) {
max = index;
keys[index] = key;
found[index] = null;
blazedLeaves[index] = null;
blazedRoots[index + 1] = null;
}
}
public Node blaze(int index, Comparable key) {
setKey(index, key);
return blaze(index);
}
public void insertOrUpdate(int index, Comparable key, Object value) {
blaze(index, key).value = value;
}
public void delete(int index, Comparable key) {
setKey(index, key);
delete(index);
}
public void deleteAll() {
result = MyRevision.Empty;
max = -1;
}
private void delete(int index) {
Node root = blazedRoots[index];
if (root == null) {
if (index == 0) {
root = Node.delete(token, stack, result.root, keys[0]);
if (root != result.root) {
result = getRevision(token, result, root);
}
} else {
Node original = find(index);
Node originalRoot = (Node) find(index - 1).value;
if (original == Node.Null) {
return;
} else if (original == originalRoot
&& original.left == Node.Null
&& original.right == Node.Null)
{
delete(index - 1);
} else {
root = Node.delete
(token, stack, (Node) blaze(index - 1).value, keys[index]);
blazedLeaves[index - 1].value = root;
blazedRoots[index] = root;
blazedLeaves[index] = null;
}
}
} else {
deleteBlazed(index);
}
if (max >= index) {
max = index - 1;
}
}
private Node find(int index) {
Node n = blazedLeaves[index];
if (n == null) {
n = found[index];
if (n == null) {
if (index == 0) {
n = Node.find(result.root, keys[0]);
found[0] = n;
} else {
n = Node.find((Node) find(index - 1).value, keys[index]);
found[index] = n;
}
}
}
return n;
}
private void deleteBlazed(int index) {
blazedLeaves[index] = null;
Node root = Node.delete(token, stack, blazedRoots[index], keys[index]);
blazedRoots[index] = root;
blazedLeaves[index] = null;
if (root == null) {
if (index == 0) {
result.root = Node.delete(token, stack, result.root, keys[0]);
} else {
deleteBlazed(index - 1);
}
} else {
if (index == 0) {
result.root = root;
} else {
blazedLeaves[index - 1].value = root;
}
}
}
private Node blaze(int index) {
Node n = blazedLeaves[index];
if (n == null) {
if (index == 0) {
Node root = Node.blaze
(blazeResult, token, stack, result.root, keys[0]);
if (root != result.root) {
result = getRevision(token, result, root);
}
blazedRoots[0] = root;
blazedLeaves[0] = blazeResult.node;
blazedRoots[1] = (Node) blazeResult.node.value;
return blazeResult.node;
} else {
Node root = Node.blaze
(blazeResult, token, stack, (Node) blaze(index - 1).value,
keys[index]);
blazedLeaves[index - 1].value = root;
blazedRoots[index] = root;
blazedLeaves[index] = blazeResult.node;
return blazeResult.node;
}
} else {
return n;
}
}
public void updateIndexTree(Index index,
MyRevision base,
NodeStack baseStack,
NodeStack forkStack)
{
expect(! index.equals(index.table.primaryKey));
TableIterator iterator
= new TableIterator
(reference(index.table), base, baseStack, result, forkStack,
ConstantAdapter.True, new ExpressionContext(null), false);
setKey(Constants.TableDataDepth, index.table);
setKey(Constants.IndexDataDepth, index);
List<Column<?>> keyColumns = index.columns;
while (true) {
QueryResult.Type type = iterator.nextRow();
switch (type) {
case End:
return;
case Inserted: {
Node tree = (Node) iterator.pair.fork.value;
int i = 0;
for (; i < keyColumns.size() - 1; ++i) {
setKey
(i + Constants.IndexDataBodyDepth,
(Comparable) Node.find(tree, keyColumns.get(i)).value);
}
Node n = blaze
(i + Constants.IndexDataBodyDepth,
(Comparable) Node.find(tree, keyColumns.get(i)).value);
expect(n.value == Node.Null);
n.value = tree;
} break;
case Deleted: {
Node tree = (Node) iterator.pair.base.value;
int i = 0;
for (; i < keyColumns.size() - 1; ++i) {
setKey
(i + Constants.IndexDataBodyDepth,
(Comparable) Node.find(tree, keyColumns.get(i)).value);
}
delete
(i + Constants.IndexDataBodyDepth,
(Comparable) Node.find(tree, keyColumns.get(i)).value);
} break;
default:
throw new RuntimeException("unexpected result type: " + type);
}
}
}
private Node makeTree(NodeStack stack,
List<Column<?>> columns,
List<ExpressionAdapter> expressions)
{
Node.BlazeResult result = new Node.BlazeResult();
Node n = Node.Null;
for (int i = 0; i < columns.size(); ++i) {
Column<?> c = columns.get(i);
Object v = expressions.get(i).evaluate(true);
if (v != null && ! c.type.isInstance(v)) {
throw new ClassCastException
(v.getClass().getName() + " cannot be cast to " + c.type.getName());
}
n = Node.blaze(result, token, stack, n, c);
result.node.value = v;
}
return n;
}
public void updateViewTree(View view,
MyRevision base,
NodeStack baseStack,
NodeStack forkStack)
{
MyQueryResult qr = new MyQueryResult
(base, baseStack, result, forkStack, view.query,
view.parameters.toArray(new Object[view.parameters.size()]));
setKey(Constants.TableDataDepth, view.table);
setKey(Constants.IndexDataDepth, view.table.primaryKey);
List<Column<?>> keyColumns = view.table.primaryKey.columns;
final List<ExpressionAdapter> expressions = qr.expressions;
List<AggregateAdapter> aggregates;
int maxValues;
if (view.query.hasAggregates) {
aggregates = new ArrayList<AggregateAdapter>();
maxValues = 0;
for (int i = view.aggregateOffset; i < view.aggregateExpressionOffset;
++i)
{
AggregateAdapter aa = (AggregateAdapter) expressions.get(i);
if (maxValues < aa.aggregate.expressions.size()) {
maxValues = aa.aggregate.expressions.size();
}
aggregates.add(aa);
}
} else {
maxValues = 0;
aggregates = null;
}
Object[] values = new Object[maxValues];
NodeStack stack = new NodeStack();
boolean done = false;
while (! done) {
QueryResult.Type type = qr.nextRow();
switch (type) {
case End:
done = true;
break;
case Inserted: {
int i = 0;
for (; i < keyColumns.size() - 1; ++i) {
setKey
(i + Constants.IndexDataBodyDepth,
(Comparable) expressions.get
(view.primaryKeyOffset + i).evaluate(true));
}
Node n = blaze
(i + Constants.IndexDataBodyDepth,
(Comparable) expressions.get
(view.primaryKeyOffset + i).evaluate(true));
// System.out.println("inserted " + Util.toString(keys, 0, Constants.IndexDataBodyDepth + i + 1));
if (view.query.hasAggregates) {
int columnOffset = view.aggregateOffset;
int expressionOffset = view.aggregateExpressionOffset;
for (AggregateAdapter a: aggregates) {
for (int j = 0; j < a.aggregate.expressions.size(); ++j) {
values[j] = expressions.get(expressionOffset++).evaluate(true);
}
a.add
(Node.find
((Node) n.value, view.columns.get(columnOffset++)).value,
values);
}
} else {
expect(n.value == Node.Null);
}
n.value = makeTree(stack, view.columns, expressions);
for (AggregateAdapter a: aggregates) {
a.value = Compare.Undefined;
}
} break;
case Deleted: {
for (int i = 0; i < keyColumns.size(); ++i) {
setKey
(i + Constants.IndexDataBodyDepth,
(Comparable) expressions.get
(view.primaryKeyOffset + i).evaluate(true));
}
int index = keyColumns.size() - 1 + Constants.IndexDataBodyDepth;
// System.out.println("deleted " + Util.toString(keys, 0, index + 1));
if (view.query.hasAggregates) {
Node n = find(index);
int columnOffset = view.aggregateOffset;
int expressionOffset = view.aggregateOffset;
for (AggregateAdapter a: aggregates) {
for (int j = 0; j < a.aggregate.expressions.size(); ++j) {
values[j] = expressions.get(expressionOffset++).evaluate(true);
}
a.subtract
(Node.find
((Node) n.value, view.columns.get(columnOffset++)).value,
values);
}
}
if (view.query.hasAggregates
&& ((Integer) expressions.get(view.aggregateOffset).evaluate(true))
!= 0)
{
blaze(index).value = makeTree(stack, view.columns, expressions);
} else {
delete(index);
}
for (AggregateAdapter a: aggregates) {
a.value = Compare.Undefined;
}
} break;
default:
throw new RuntimeException("unexpected result type: " + type);
}
}
// now, filter out rows which fail the query test if that test
// uses an aggregate function
if (view.query.hasAggregates) {
// todo: only do this if the query test has aggregates
qr.reset();
while (true) {
QueryResult.Type type = qr.nextRow();
switch (type) {
case End:
return;
case Inserted:
case Deleted: {
for (int i = 0; i < keyColumns.size(); ++i) {
setKey
(i + Constants.IndexDataBodyDepth,
(Comparable) expressions.get
(view.primaryKeyOffset + i).evaluate(true));
}
int index = keyColumns.size() - 1 + Constants.IndexDataBodyDepth;
int columnOffset = view.aggregateOffset;
for (AggregateAdapter a: aggregates) {
a.value = Node.find
((Node) find(index).value,
view.columns.get(columnOffset++)).value;
}
// System.out.print("filter: ");
// for (ColumnReferenceAdapter r: qr.expressionContext.columnReferences)
// System.out.print(r.column + ":" + r.value + " ");
// System.out.println(": " + qr.test.evaluate(false));
if (qr.test.evaluate(false) == Boolean.FALSE) {
// todo: rather than delete this row from the view we
// should actually just undo whatever operation we did in
// the first pass, now that we know this query row should
// not be included. Note that we'll need to operate on a
// copy of the view rather than the tentative one we just
// built to make this work.
delete(index);
}
for (AggregateAdapter a: aggregates) {
a.value = Compare.Undefined;
}
} break;
default:
throw new RuntimeException("unexpected result type: " + type);
}
}
}
}
private void checkStacks() {
if (indexUpdateIterateStack == null) {
indexUpdateIterateStack = new NodeStack();
indexUpdateBaseStack = new NodeStack();
indexUpdateForkStack = new NodeStack();
}
}
private void updateIndexes() {
if (dirtyIndexes && indexBase != result) {
checkStacks();
DiffIterator iterator = new DiffIterator
(indexBase.root, indexUpdateBaseStack,
result.root, indexUpdateForkStack,
list(Interval.Unbounded).iterator(), false);
DiffIterator.DiffPair pair = new DiffIterator.DiffPair();
Set<View> viewSet = new HashSet();
while (iterator.next(pair)) {
if (pair.fork != null) {
for (NodeIterator indexes = new NodeIterator
(indexUpdateIterateStack, Node.pathFind
(result.root, Constants.IndexTable,
Constants.IndexTable.primaryKey, (Table) pair.fork.key));
indexes.hasNext();)
{
updateIndexTree
((Index) indexes.next().key, indexBase,
indexUpdateBaseStack, indexUpdateForkStack);
}
for (NodeIterator views = new NodeIterator
(indexUpdateIterateStack, Node.pathFind
(result.root, Constants.ViewTable,
Constants.ViewTable.primaryKey, (Table) pair.fork.key));
views.hasNext();)
{
viewSet.add((View) views.next().key);
}
}
}
for (View v: viewSet) {
updateViewTree
(v, indexBase, indexUpdateBaseStack, indexUpdateForkStack);
}
}
dirtyIndexes = false;
indexBase = result;
}
public void updateIndex(Index index) {
if (! Compare.equal(index.table.primaryKey, index)) {
updateIndexes();
}
}
private void checkForeignKeys(ForeignKeyResolver resolver) {
// todo: is there a performance problem with creating new
// NodeStacks every time this method is called? If so, are there
// common cases were we can avoid creating them, or should we try
// to recycle them somehow?
ForeignKeys.checkForeignKeys
(new NodeStack(), base, new NodeStack(), this, new NodeStack(),
resolver, null);
}
public void prepareForUpdate(Table table) {
// since we update non-primary-key indexes lazily, we may need to
// freeze a copy of the last revision which contained up-to-date
// indexes so we can do a diff later and use it to update them
if (Node.pathFind(result.root, Constants.IndexTable,
Constants.IndexTable.primaryKey, table) != Node.Null
|| Node.pathFind(result.root, Constants.ViewTable,
Constants.ViewTable.primaryKey, table) != Node.Null)
{
dirtyIndexes = true;
if (indexBase == result) {
setToken(new Object());
}
}
}
private void pathInsert(Table table, Comparable ... path) {
setKey(Constants.TableDataDepth, table);
setKey(Constants.IndexDataDepth, table.primaryKey);
Node tree = Node.Null;
Node.BlazeResult result = new Node.BlazeResult();
List<Column<?>> columns = table.primaryKey.columns;
for (int i = 0; i < columns.size(); ++i) {
tree = Node.blaze(result, token, stack, tree, columns.get(i));
result.node.value = path[i];
if (i == columns.size() - 1) {
insertOrUpdate(Constants.IndexDataBodyDepth + i, path[i], tree);
} else {
setKey(Constants.IndexDataBodyDepth + i, path[i]);
}
}
}
private void pathDelete(Table table, Comparable ... path) {
setKey(Constants.TableDataDepth, table);
setKey(Constants.IndexDataDepth, table.primaryKey);
List<Column<?>> columns = table.primaryKey.columns;
for (int i = 0; i < columns.size(); ++i) {
if (i == columns.size() - 1) {
delete(Constants.IndexDataBodyDepth + i, path[i]);
} else {
setKey(Constants.IndexDataBodyDepth + i, path[i]);
}
}
}
private void addIndex(Index index)
{
if (index.equals(index.table.primaryKey)
|| Node.pathFind
(result.root, Constants.IndexTable, Constants.IndexTable.primaryKey,
index.table, index) != Node.Null)
{
// the specified index is already present -- ignore
return;
}
// flush any changes out to the existing indexes, since we don't
// want to get confused later when some indexes are up-to-date and
// some aren't:
updateIndexes();
checkStacks();
updateIndexTree
(index, MyRevision.Empty, indexUpdateBaseStack, indexUpdateForkStack);
pathInsert(Constants.IndexTable, index.table, index);
}
private void removeIndex(Index index)
{
if (index.equals(index.table.primaryKey)) {
throw new IllegalArgumentException("cannot remove primary key");
}
pathDelete(Constants.IndexTable, index.table, index);
setKey(Constants.TableDataDepth, index.table);
delete(Constants.IndexDataDepth, index);
}
private void addView(View view)
{
addView(view, MyRevision.Empty);
}
void addView(final View view, MyRevision base)
{
view.query.source.visit(new SourceVisitor() {
public void visit(Source source) {
if (source instanceof TableReference) {
Table table = ((TableReference) source).table;
if (Node.pathFind
(result.root, Constants.ViewTable,
Constants.ViewTable.primaryKey, table, view) != Node.Null)
{
// the specified view is already present -- ignore
return;
}
pathInsert(Constants.ViewTable, table, view);
}
}
});
// flush any changes out to the existing indexes, since we don't
// want to get confused later when some indexes are up-to-date and
// some aren't:
updateIndexes();
checkStacks();
updateViewTree
(view, base, indexUpdateBaseStack, indexUpdateForkStack);
}
private void removeView(final View view)
{
view.query.source.visit(new SourceVisitor() {
public void visit(Source source) {
if (source instanceof TableReference) {
Table table = ((TableReference) source).table;
pathDelete(Constants.ViewTable, table, view);
}
}
});
delete(Constants.TableDataDepth, view.table);
}
private void addForeignKey(ForeignKey constraint)
{
if (Node.pathFind
(result.root, Constants.ForeignKeyTable,
Constants.ForeignKeyTable.primaryKey, constraint) != Node.Null)
{
// the specified foreign key is already present -- ignore
return;
}
insert(DuplicateKeyResolution.Throw, Constants.ForeignKeyTable, constraint,
Constants.ForeignKeyRefererColumn, constraint.refererTable);
insert(DuplicateKeyResolution.Throw, Constants.ForeignKeyTable, constraint,
Constants.ForeignKeyReferentColumn, constraint.referentTable);
add(Constants.ForeignKeyRefererIndex);
add(Constants.ForeignKeyReferentIndex);
dirtyIndexes = true;
updateIndexes();
}
private void removeForeignKey(ForeignKey constraint)
{
pathDelete(Constants.ForeignKeyTable, constraint);
if (Node.pathFind(result.root, Constants.ForeignKeyTable) == Node.Null) {
// the last foreign key constraint has been removed -- remove
// the indexes
remove(Constants.ForeignKeyRefererIndex);
remove(Constants.ForeignKeyReferentIndex);
} else {
dirtyIndexes = true;
updateIndexes();
}
}
private void delete(Comparable[] keys)
{
if (keys.length == 0) {
deleteAll();
return;
}
Table table = (Table) keys[0];
if (keys.length == 1) {
delete(Constants.TableDataDepth, table);
return;
}
prepareForUpdate(table);
setKey(Constants.TableDataDepth, table);
setKey(Constants.IndexDataDepth, table.primaryKey);
int i = 1;
for (; i < keys.length - 1; ++i) {
setKey(i - 1 + Constants.IndexDataBodyDepth, keys[i]);
}
delete(i - 1 + Constants.IndexDataBodyDepth, keys[i]);
}
private void insert(int depth,
List<Column<?>> columns,
Comparable[] path)
{
for (int i = 0; i < path.length; ++i) {
blaze(depth, columns.get(i)).value = path[i];
}
}
private void insert(DuplicateKeyResolution duplicateKeyResolution,
Table table,
Column<?> column,
Object value,
Comparable[] path)
{
prepareForUpdate(table);
setKey(Constants.TableDataDepth, table);
setKey(Constants.IndexDataDepth, table.primaryKey);
for (int i = 0; i < path.length; ++i) {
setKey(i + Constants.IndexDataBodyDepth, path[i]);
}
Node n;
if (column == null) {
n = blaze((path.length - 1) + Constants.IndexDataBodyDepth);
} else {
n = blaze(path.length + Constants.IndexDataBodyDepth, column);
}
if (n.value == Node.Null) {
if (column != null) {
n.value = value;
}
insert(path.length + Constants.IndexDataBodyDepth,
table.primaryKey.columns, path);
} else {
switch (duplicateKeyResolution) {
case Skip:
break;
case Overwrite:
if (column != null) {
n.value = value;
}
insert(path.length + Constants.IndexDataBodyDepth,
table.primaryKey.columns, path);
break;
case Throw:
throw new DuplicateKeyException();
default:
throw new RuntimeException
("unexpected resolution: " + duplicateKeyResolution);
}
}
}
private class MyTableBuilder implements TableBuilder {
private class MyRowBuilder implements RowBuilder {
private Object[] path;
public MyRowBuilder() {
path = new Object[3 + table.primaryKey.columns.size()];
}
public void init(Comparable[] keys) {
if(path.length != keys.length + 3) {
path = new Object[3 + keys.length];
}
path[0] = table;
for(int i = 0; i < keys.length; i++) {
path[i + 1] = keys[i];
}
}
public <T> RowBuilder column(Column<T> key,
T value)
{
path[path.length - 2] = key;
path[path.length - 1] = value;
insert(DuplicateKeyResolution.Overwrite, path);
return this;
}
public RowBuilder columns(ColumnList columns,
Object ... values)
{
// TODO: optimize
if(columns.columns.size() != values.length) {
throw new IllegalArgumentException
("wrong number of parameters (expected "
+ columns.columns.size() + "; got "
+ values.length + ")");
}
for(int i = 0; i < values.length; i++) {
column((Column)columns.columns.get(i), values[i]);
}
return this;
}
public RowBuilder delete(Column<?> key) {
path[path.length - 2] = key;
MyRevisionBuilder.this.delete(path, 0, path.length - 1);
return this;
}
public TableBuilder up() {
MyTableBuilder.this.rowBuilder = this;
return MyTableBuilder.this;
}
}
private Table table;
public MyRowBuilder rowBuilder;
public MyTableBuilder() {
}
public void init(Table table) {
this.table = table;
}
public RowBuilder row(Comparable ... key) {
if(rowBuilder != null) {
rowBuilder.init(key);
MyRowBuilder ret = rowBuilder;
rowBuilder = null;
return ret;
}
MyRowBuilder ret = new MyRowBuilder();
ret.init(key);
return ret;
}
public TableBuilder key(Comparable ... key) {
MyRowBuilder row = (MyRowBuilder) row(key);
insert(DuplicateKeyResolution.Overwrite, row.path, 0, key.length + 1);
return row.up(); // identically, return this (but up() can recycle the RowBuilder)
}
public TableBuilder delete(Comparable ... key) {
MyRowBuilder row = (MyRowBuilder) row(key);
MyRevisionBuilder.this.delete(row.path, 0, key.length + 1);
return this;
}
public RevisionBuilder up() {
MyRevisionBuilder.this.tableBuilder = this;
return MyRevisionBuilder.this;
}
}
private MyTableBuilder tableBuilder = null;
public TableBuilder table(Table table)
{
MyTableBuilder ret;
if(tableBuilder == null) {
ret = new MyTableBuilder();
} else {
ret = tableBuilder;
tableBuilder = null;
}
ret.init(table);
return ret;
}
public void drop(Table table) {
}
public int apply(PatchTemplate template,
Object ... parameters)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
if (parameters.length != template.parameterCount()) {
throw new IllegalArgumentException
("wrong number of parameters (expected "
+ template.parameterCount() + "; got "
+ parameters.length + ")");
}
return adapters.get
(template.getClass()).apply(this, template, copy(parameters));
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public void delete(Object[] path,
int pathOffset,
int pathLength)
{
Comparable[] myPath = new Comparable[pathLength];
for (int i = 0; i < pathLength; ++i) {
myPath[i] = (Comparable) path[pathOffset + i];
}
delete(myPath);
}
public void delete(Object ... path)
{
delete(path, 0, path.length);
}
public void insert(DuplicateKeyResolution duplicateKeyResolution,
Object[] path,
int pathOffset,
int pathLength)
{
Table table;
try {
table = (Table) path[pathOffset];
} catch (ClassCastException e) {
throw new IllegalArgumentException
("expected table as first path element");
}
List<Column<?>> columns = table.primaryKey.columns;
if (pathLength == columns.size() + 1) {
Comparable[] myPath = new Comparable[columns.size()];
for (int i = 0; i < myPath.length; ++i) {
myPath[i] = (Comparable) path[pathOffset + i + 1];
}
insert(duplicateKeyResolution, table, null, null, myPath);
} else if (pathLength == columns.size() + 3) {
Column<?> column;
try {
column = (Column<?>) path[pathOffset + columns.size() + 1];
} catch (ClassCastException e) {
throw new IllegalArgumentException
("expected column as second-to-last path element");
}
Object value = path[pathOffset + columns.size() + 2];
if (value != null && ! column.type.isInstance(value)) {
throw new ClassCastException
(value.getClass() + " cannot be cast to " + column.type);
}
Comparable[] myPath = new Comparable[columns.size()];
for (int i = 0; i < myPath.length; ++i) {
Comparable c = (Comparable) path[pathOffset + i + 1];
if (columns.get(i) == column) {
throw new IllegalArgumentException
("cannot use insert to update a primary key column");
}
myPath[i] = c;
}
insert(duplicateKeyResolution, table, column, value, myPath);
} else {
throw new IllegalArgumentException
("wrong number of parameters for primary key");
}
}
public void insert(DuplicateKeyResolution duplicateKeyResolution,
Object ... path)
{
insert(duplicateKeyResolution, path, 0, path.length);
}
public void add(Index index)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
addIndex(index);
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public void remove(Index index)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
removeIndex(index);
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public void add(View view)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
addView(view);
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public void remove(View view)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
removeView(view);
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public void add(ForeignKey constraint)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
addForeignKey(constraint);
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public void remove(ForeignKey constraint)
{
if (token == null) {
throw new IllegalStateException("builder already committed");
}
try {
removeForeignKey(constraint);
} catch (RuntimeException e) {
token = null;
throw e;
}
}
public boolean committed() {
return token != null;
}
public Revision commit() {
return commit(ForeignKeyResolvers.Restrict);
}
public Revision commit(ForeignKeyResolver foreignKeyResolver) {
if (token == null) {
return result;
}
updateIndexes();
checkForeignKeys(foreignKeyResolver);
token = null;
return result;
}
private static MyRevision getRevision(Object token,
MyRevision basis,
Node root)
{
if (token == basis.token) {
basis.root = root;
return basis;
} else {
return new MyRevision(token, root);
}
}
} |
package org.jfree.data.general;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.EventListener;
import java.util.List;
import javax.swing.event.EventListenerList;
/**
* An abstract implementation of the {@link Dataset} interface, containing a
* mechanism for registering change listeners.
*/
public abstract class AbstractDataset implements Dataset,
Cloneable,
Serializable,
ObjectInputValidation {
/** For serialization. */
private static final long serialVersionUID = 1918768939869230744L;
/** The group that the dataset belongs to. */
private DatasetGroup group;
/** Storage for registered change listeners. */
private transient EventListenerList listenerList;
/**
* Constructs a dataset. By default, the dataset is assigned to its own
* group.
*/
protected AbstractDataset() {
this.group = new DatasetGroup();
this.listenerList = new EventListenerList();
}
/**
* Returns the dataset group for the dataset.
*
* @return The group (never <code>null</code>).
*
* @see #setGroup(DatasetGroup)
*/
public DatasetGroup getGroup() {
return this.group;
}
/**
* Sets the dataset group for the dataset.
*
* @param group the group (<code>null</code> not permitted).
*
* @see #getGroup()
*/
public void setGroup(DatasetGroup group) {
if (group == null) {
throw new IllegalArgumentException("Null 'group' argument.");
}
this.group = group;
}
/**
* Registers an object to receive notification of changes to the dataset.
*
* @param listener the object to register.
*
* @see #removeChangeListener(DatasetChangeListener)
*/
public void addChangeListener(DatasetChangeListener listener) {
this.listenerList.add(DatasetChangeListener.class, listener);
}
/**
* Deregisters an object so that it no longer receives notification of
* changes to the dataset.
*
* @param listener the object to deregister.
*
* @see #addChangeListener(DatasetChangeListener)
*/
public void removeChangeListener(DatasetChangeListener listener) {
this.listenerList.remove(DatasetChangeListener.class, listener);
}
/**
* Returns <code>true</code> if the specified object is registered with
* the dataset as a listener. Most applications won't need to call this
* method, it exists mainly for use by unit testing code.
*
* @param listener the listener.
*
* @return A boolean.
*
* @see #addChangeListener(DatasetChangeListener)
* @see #removeChangeListener(DatasetChangeListener)
*/
public boolean hasListener(EventListener listener) {
List list = Arrays.asList(this.listenerList.getListenerList());
return list.contains(listener);
}
/**
* Notifies all registered listeners that the dataset has changed.
*
* @see #addChangeListener(DatasetChangeListener)
*/
protected void fireDatasetChanged() {
notifyListeners(new DatasetChangeEvent(this, this));
}
/**
* Notifies all registered listeners that the dataset has changed.
*
* @param event contains information about the event that triggered the
* notification.
*
* @see #addChangeListener(DatasetChangeListener)
* @see #removeChangeListener(DatasetChangeListener)
*/
protected void notifyListeners(DatasetChangeEvent event) {
Object[] listeners = this.listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == DatasetChangeListener.class) {
((DatasetChangeListener) listeners[i + 1]).datasetChanged(
event);
}
}
}
/**
* Returns a clone of the dataset. The cloned dataset will NOT include the
* {@link DatasetChangeListener} references that have been registered with
* this dataset.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the dataset does not support
* cloning.
*/
public Object clone() throws CloneNotSupportedException {
AbstractDataset clone = (AbstractDataset) super.clone();
clone.listenerList = new EventListenerList();
return clone;
}
/**
* Handles serialization.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O problem.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
}
/**
* Restores a serialized object.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O problem.
* @throws ClassNotFoundException if there is a problem loading a class.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.listenerList = new EventListenerList();
stream.registerValidation(this, 10); // see comments about priority of
// 10 in validateObject()
}
/**
* Validates the object. We use this opportunity to call listeners who have
* registered during the deserialization process, as listeners are not
* serialized. This method is called by the serialization system after the
* entire graph is read.
*
* This object has registered itself to the system with a priority of 10.
* Other callbacks may register with a higher priority number to be called
* before this object, or with a lower priority number to be called after
* the listeners were notified.
*
* All listeners are supposed to have register by now, either in their
* readObject or validateObject methods. Notify them that this dataset has
* changed.
*
* @exception InvalidObjectException If the object cannot validate itself.
*/
public void validateObject() throws InvalidObjectException {
fireDatasetChanged();
}
} |
package com.solacesystems.testtool.jnetpipe;
import java.awt.Dimension;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.net.Inet4Address;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import bsh.EvalError;
import bsh.Interpreter;
import bsh.util.JConsole;
import bsh.util.NameCompletionTable;
import com.solacesystems.testtool.jnetpipe.core.IoContext;
import com.solacesystems.testtool.jnetpipe.core.PipeController;
public class JNetPipe {
private static Interpreter interpreter;
public static void main(String[] args) {
boolean debug = false;
boolean stats = false;
boolean shell = false;
int localPort = 0, remotePort = 0;
String remoteHost = null;
for(int i = 0; i < args.length; i++) {
if (args[i].equals("-d")) {
debug = true;
} else if (args[i].equals("-h")) {
printUsage();
return;
} else if (args[i].equals("-s") || args[i].equals("--stats")) {
stats = true;
} else if (args[i].equals("--shell")) {
shell = true;
} else {
// Argument is a tunnel spec PORT:REMOTEHOST:REMOTEPORT
String[] tspec = args[i].split(":");
if (tspec.length != 3) {
printUsage();
return;
}
localPort = Integer.parseInt(tspec[0]);
remoteHost = tspec[1];
remotePort = Integer.parseInt(tspec[2]);
}
}
if (remoteHost == null) {
printUsage();
return;
}
configureLogging(debug);
IoContext ctx = new IoContext();
ctx.start();
try {
PipeController pc = new PipeController(
localPort,
Inet4Address.getByName(remoteHost),
remotePort,
ctx);
if (stats)
pc.enableStats();
// Start PipeController (accepts connections)
pc.start();
// Start the BeanShell ui
if (shell)
startConsole(pc);
// Wait forever
System.out.println("Sleeping...");
Thread.sleep(Long.MAX_VALUE);
} catch (IOException ex) {
System.err.println("MAIN>> " + ex);
ex.printStackTrace();
} catch (InterruptedException ex) {
System.err.println("MAIN>> " + ex);
ex.printStackTrace();
}
}
private static void printUsage() {
System.out.println("Usage: JNetPipe [-d] [--stats] [--shell] LOCALPORT:REMOTEHOST:REMOTEPORT");
System.out.println(" -d: Debug");
System.out.println(" --stats: Dump stats");
System.out.println(" --shell: Start shell");
}
private static void configureLogging(boolean debug) {
ConsoleAppender ap = new ConsoleAppender();
Layout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN);
ap.setLayout(layout);
ap.setThreshold(debug ? Level.DEBUG : Level.INFO);
ap.activateOptions();
BasicConfigurator.configure(ap);
}
private static void startConsole(final PipeController pipe) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// This is all standard boilerplate for creating a JFrame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(900, 600));
frame.setTitle("JNetPipe shell");
// BeanShell objects
final String LOOPEXIT = "loopexit";
/*
* Loops in bsh scripts should always check the state of
* "loopexit" in order to process Ctrl+C:
*
* while(!loopexit) { ... };
*/
JConsole console = new JConsole() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
try {
if (e.getKeyCode() == KeyEvent.VK_C
&& ((e.getModifiers() & InputEvent.CTRL_MASK) > 0)) {
// ctrl+c, set loopexit
interpreter.set(LOOPEXIT, true);
} else {
// Any other key: clear loopflag
interpreter.set(LOOPEXIT, false);
}
} catch (EvalError e1) {
e1.printStackTrace();
}
}
};
interpreter = new Interpreter(console);
try {
// The PipeController will be accessible as "netpipe"
interpreter.set("netpipe", pipe);
interpreter.set(LOOPEXIT, false);
} catch (EvalError e) {
e.printStackTrace();
}
NameCompletionTable nct = new NameCompletionTable();
nct.add(interpreter.getNameSpace());
console.setNameCompletion(nct);
// Build the frame
JScrollPane pane = new JScrollPane(console);
pane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.add(pane);
final Thread thread = new Thread(interpreter, "BeanShell");
thread.setDaemon(true);
thread.start();
frame.pack();
frame.setVisible(true);
// load env
interpreter.setShowResults(true);
try {
interpreter.eval("importCommands(\"commands\");");
} catch (EvalError e) {
e.printStackTrace();
}
}
});
}
} |
package com.stackallocated.imageupload;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.AndroidHttpClient;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.JsonReader;
import android.util.Log;
import com.stackallocated.util.ImageUtils;
import com.stackallocated.util.ProgressHttpEntityWrapper;
import com.stackallocated.util.ProgressListener;
public class UploadService extends Service {
private final static String TAG = "UploadService";
private Handler handler;
private final static int UPLOAD_IMAGE = 1;
private class JsonUploadResponse {
public String status = null;
public String url = null;
HashMap<String, String> errors = new HashMap<>();
}
private class UploadServiceHandler extends Handler {
final NotificationManager nm;
final Resources res;
final PendingIntent historypending;
final SharedPreferences prefs;
final static int UPLOAD_PROGRESS_NOTIFICATION = 1;
final static int UPLOAD_COMPLETE_NOTIFICATION = 2;
public UploadServiceHandler(Looper looper) {
super(looper);
res = getResources();
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Intent historyintent = new Intent(getApplicationContext(), HistoryActivity.class);
historypending = PendingIntent.getActivity(getApplicationContext(), 0, historyintent, 0);
}
JsonUploadResponse parseJsonResponse(InputStream input) throws IOException {
JsonUploadResponse response = new JsonUploadResponse();
InputStreamReader inputreader = new InputStreamReader(input);
BufferedReader bufreader = new BufferedReader(inputreader);
JsonReader reader = new JsonReader(bufreader);
reader.setLenient(true);
reader.beginObject();
while (reader.hasNext()) {
String field = reader.nextName();
switch (field) {
case "status": {
response.status = reader.nextString();
Log.v(TAG, "Got status " + response.status);
break;
}
case "public_url": {
response.url = reader.nextString();
Log.v(TAG, "Got URL " + response.url);
break;
}
case "errors": {
reader.beginArray();
while (reader.hasNext()) {
reader.beginObject();
String error = null, message = null;
while (reader.hasNext()) {
switch (reader.nextName()) {
case "error":
error = reader.nextString();
break;
case "message":
message = reader.nextString();
break;
}
}
if (error != null && message != null) {
Log.v(TAG, "Got error '" + error + "': '" + message + "'");
response.errors.put(error, message);
}
reader.endObject();
}
reader.endArray();
break;
}
}
}
reader.endObject();
reader.close();
return response;
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPLOAD_IMAGE: {
Uri uri = (Uri)msg.obj;
handleUploadImage(uri);
Log.i(TAG, "Finished handling of '" + uri + "'");
break;
}
// If the message type is wrong, panic and kill everything.
default:
Log.e(TAG, "Got message '" + msg.what + "' that wasn't UPLOAD_IMAGE!");
stopSelf();
return;
}
int startId = msg.arg1;
stopSelfResult(startId);
}
private void handleUploadImage(Uri uri) {
final Notification.Builder notification = makeUploadProgressNotification(uri.toString());
try {
// Here, we need to:
// a) get the HTTP endpoint / credentials
// b) open the image
// c) display a progress notification
// d) open an HTTP connection
// e) stream the image through the connection
// e) retrieve the resulting URL
// f) display a final notification with the URL
final AssetFileDescriptor desc = getContentResolver().openAssetFileDescriptor(uri, "r");
final long imageLen = desc.getLength();
Log.v(TAG, "Image length is " + imageLen);
String credentials = Uri.encode(prefs.getString(SettingsActivity.KEY_UPLOAD_USERNAME, "")) + ":" +
Uri.encode(prefs.getString(SettingsActivity.KEY_UPLOAD_PASSWORD, ""));
String authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HttpEntity entity = MultipartEntityBuilder.create()
.addBinaryBody("upload", desc.createInputStream(), ContentType.DEFAULT_BINARY, uri.getLastPathSegment())
.build();
HttpEntity wrapper = new ProgressHttpEntityWrapper(entity, new ProgressListener() {
@Override
public void progress(long bytes) {
int percent = (int)((100 * bytes) / imageLen);
if (percent > 100) {
percent = 100;
}
notification.setProgress(100, percent, false);
nm.notify(UPLOAD_PROGRESS_NOTIFICATION, notification.build());
Log.v(TAG, "Total is " + bytes + " of " + imageLen);
}
});
HttpClient client = AndroidHttpClient.newInstance(res.getString(R.string.http_user_agent));
HttpPost post = new HttpPost(prefs.getString(SettingsActivity.KEY_UPLOAD_URL, ""));
post.setHeader("Authorization", authHeader);
post.setEntity(wrapper);
HttpResponse response = client.execute(post);
Log.e(TAG, "Response: " + response.getStatusLine());
Log.e(TAG, "Len: " + response.getEntity().getContentLength());
// XXX should handle 404, 401, and things that aren't either 400 or 200 here before parsing JSON
switch (response.getStatusLine().getStatusCode()) {
case 401:
break;
case 404:
break;
case 400:
break;
}
JsonUploadResponse json = parseJsonResponse(response.getEntity().getContent());
if ("ok".equals(json.status) && json.url != null) {
Bitmap original = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), uri);
// Create successful upload notification.
showUploadSuccessfulNotification(notification, json.url, original);
// Store successful upload in the database.
HistoryDatabase db = HistoryDatabase.getInstance(getApplicationContext());
Bitmap thumbnail = ImageUtils.makeThumbnail(original, 128);
db.insertImage(json.url, System.currentTimeMillis(), thumbnail);
} else {
// Create upload failure notification.
// Should do something better with the errors from the JSON here.
showUploadFailureNotification(notification, uri.toString(), uri.toString());
}
desc.close();
} catch (Exception e) {
showUploadFailureNotification(notification, uri.toString(), e.getLocalizedMessage());
Log.e(TAG, "Something went wrong in the upload!");
e.printStackTrace();
}
}
private void showUploadFailureNotification(final Notification.Builder notification, String tag, String msg) {
stopProgressNotification(notification);
notification.setContentTitle(res.getString(R.string.uploader_notification_failure))
.setContentText(msg);
nm.notify(tag, UPLOAD_COMPLETE_NOTIFICATION, notification.build());
}
private void showUploadSuccessfulNotification(final Notification.Builder notification, String url, Bitmap bitmap) {
Intent copyintent = new Intent(getApplicationContext(), ClipboardURLReceiver.class);
copyintent.setAction(url);
PendingIntent copypending = PendingIntent.getBroadcast(getApplicationContext(), 0, copyintent, 0);
Bitmap bigthumbnail = ImageUtils.makeThumbnail(bitmap, 512);
stopProgressNotification(notification);
notification.setContentTitle(res.getString(R.string.uploader_notification_successful))
.setContentText(url)
.setContentIntent(historypending)
.setAutoCancel(true)
.setStyle(new Notification.BigPictureStyle().bigPicture(bigthumbnail))
.addAction(R.drawable.ic_action_copy_dark,
res.getString(R.string.action_copy_url),
copypending);
nm.notify(url, UPLOAD_COMPLETE_NOTIFICATION, notification.build());
}
// Builds a notification that is a progress bar.
// This will be replaced with the final error or success notification at the end.
private Notification.Builder makeUploadProgressNotification(String string) {
final Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(res.getString(R.string.uploader_notification_uploading))
.setContentText(string)
.setProgress(100, 0, false)
.setOngoing(true);
startForeground(UPLOAD_PROGRESS_NOTIFICATION, builder.build());
return builder;
}
private void stopProgressNotification(Notification.Builder builder) {
builder.setOngoing(false)
.setProgress(0, 0, false);
}
}
@Override
public void onCreate() {
Log.i(TAG, "Starting upload service");
HandlerThread thread = new HandlerThread("UploadServiceThread", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
handler = new UploadServiceHandler(thread.getLooper());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
Message msg = handler.obtainMessage(UPLOAD_IMAGE, imageUri);
msg.arg1 = startId;
if (!handler.sendMessage(msg)) {
Log.w(TAG, "Couldn't send message '" + msg + "' to handler");
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
Log.i(TAG, "Stopping upload service");
}
// Have to override this, even though we don't use it.
@Override
public IBinder onBind(Intent intent) {
return null;
}
} |
package com.untamedears.citadel.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name="faction_member", uniqueConstraints={
@UniqueConstraint(columnNames={"faction_name", "member_name"})})
public class FactionMember {
@Id private String factionName;
@Id private String memberName;
public FactionMember(){}
public FactionMember(String memberName, String factionName){
this.memberName = memberName;
this.factionName = factionName;
}
public String getMemberName(){
return this.memberName;
}
public void setMemberName(String memberName){
this.memberName = memberName;
}
public String getFactionName(){
return this.factionName;
}
public void setFactionName(String factionName){
this.factionName = factionName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FactionMember)) return false;
FactionMember that = (FactionMember) o;
return factionName.equals(that.factionName) && memberName.equals(that.memberName);
}
@Override
public int hashCode() {
int result = factionName.hashCode();
result = 31 * result + memberName.hashCode();
return result;
}
} |
package com.vaadin.terminal.gwt.client;
import java.util.List;
import java.util.Set;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.Style.FontWeight;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.UmbrellaException;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventPreview;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ui.VOverlay;
/**
* A helper console for client side development. The debug console can also be
* used to resolve layout issues and to inspect the communication between
* browser and the server.
*
* <p>
* This implementation is used vaadin is in debug mode (see manual) and
* developer appends "?debug" query parameter to url. Debug information can also
* be shown on browsers internal console only, by appending "?debug=quiet" query
* parameter.
* <p>
* This implementation can be overridden with GWT deferred binding.
*
*/
public final class VDebugConsole extends VOverlay implements Console {
private static final String POS_COOKIE_NAME = "VDebugConsolePos";
Element caption = DOM.createDiv();
private Panel panel;
private Button clear = new Button("Clear console");
private Button restart = new Button("Restart app");
private Button forceLayout = new Button("Force layout");
private Button analyzeLayout = new Button("Analyze layouts");
private Button savePosition = new Button("Save pos");
private HorizontalPanel actions;
private boolean collapsed = false;
private boolean resizing;
private int startX;
private int startY;
private int initialW;
private int initialH;
private boolean moving = false;
private int origTop;
private int origLeft;
private static final String help = "Drag=move, shift-drag=resize, doubleclick=min/max."
+ "Use debug=quiet to log only to browser console.";
public VDebugConsole() {
super(false, false);
}
private EventPreview dragpreview = new EventPreview() {
public boolean onEventPreview(Event event) {
onBrowserEvent(event);
return false;
}
};
private boolean quietMode;
@Override
public void onBrowserEvent(Event event) {
super.onBrowserEvent(event);
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (DOM.eventGetShiftKey(event)) {
resizing = true;
DOM.setCapture(getElement());
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
initialW = VDebugConsole.this.getOffsetWidth();
initialH = VDebugConsole.this.getOffsetHeight();
DOM.eventCancelBubble(event, true);
DOM.eventPreventDefault(event);
DOM.addEventPreview(dragpreview);
} else if (DOM.eventGetTarget(event) == caption) {
moving = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origTop = getAbsoluteTop();
origLeft = getAbsoluteLeft();
DOM.eventCancelBubble(event, true);
DOM.eventPreventDefault(event);
DOM.addEventPreview(dragpreview);
}
break;
case Event.ONMOUSEMOVE:
if (resizing) {
int deltaX = startX - DOM.eventGetScreenX(event);
int detalY = startY - DOM.eventGetScreenY(event);
int w = initialW - deltaX;
if (w < 30) {
w = 30;
}
int h = initialH - detalY;
if (h < 40) {
h = 40;
}
VDebugConsole.this.setPixelSize(w, h);
DOM.eventCancelBubble(event, true);
DOM.eventPreventDefault(event);
} else if (moving) {
int deltaX = startX - DOM.eventGetScreenX(event);
int detalY = startY - DOM.eventGetScreenY(event);
int left = origLeft - deltaX;
if (left < 0) {
left = 0;
}
int top = origTop - detalY;
if (top < 0) {
top = 0;
}
VDebugConsole.this.setPopupPosition(left, top);
DOM.eventCancelBubble(event, true);
DOM.eventPreventDefault(event);
}
break;
case Event.ONLOSECAPTURE:
case Event.ONMOUSEUP:
if (resizing) {
DOM.releaseCapture(getElement());
resizing = false;
} else if (moving) {
DOM.releaseCapture(getElement());
moving = false;
}
DOM.removeEventPreview(dragpreview);
break;
case Event.ONDBLCLICK:
if (DOM.eventGetTarget(event) == caption) {
if (collapsed) {
panel.setVisible(true);
setToDefaultSizeAndPos();
} else {
panel.setVisible(false);
setPixelSize(120, 20);
setPopupPosition(Window.getClientWidth() - 125,
Window.getClientHeight() - 25);
}
collapsed = !collapsed;
}
break;
default:
break;
}
}
private void setToDefaultSizeAndPos() {
String cookie = Cookies.getCookie(POS_COOKIE_NAME);
int width, height, top, left;
if (cookie != null) {
String[] split = cookie.split(",");
left = Integer.parseInt(split[0]);
top = Integer.parseInt(split[1]);
width = Integer.parseInt(split[2]);
height = Integer.parseInt(split[3]);
} else {
width = 400;
height = 150;
top = Window.getClientHeight() - 160;
left = Window.getClientWidth() - 410;
}
setPixelSize(width, height);
setPopupPosition(left, top);
}
@Override
public void setPixelSize(int width, int height) {
if (height < 20) {
height = 20;
}
if (width < 2) {
width = 2;
}
panel.setHeight((height - 20) + "px");
panel.setWidth((width - 2) + "px");
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Console#log(java.lang.String)
*/
public void log(String msg) {
if (msg == null) {
msg = "null";
}
logToDebugWindow(msg, false);
GWT.log(msg);
consoleLog(msg);
}
/**
* Logs the given message to the debug window.
*
* @param msg
* The message to log. Must not be null.
*/
private void logToDebugWindow(String msg, boolean error) {
if (error) {
panel.add(createErrorHtml(msg));
} else {
panel.add(new HTML(msg));
}
}
private HTML createErrorHtml(String msg) {
HTML html = new HTML(msg);
html.getElement().getStyle().setColor("#f00");
html.getElement().getStyle().setFontWeight(FontWeight.BOLD);
return html;
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Console#error(java.lang.String)
*/
public void error(String msg) {
if (msg == null) {
msg = "null";
}
logToDebugWindow(msg, true);
GWT.log(msg);
consoleErr(msg);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Console#printObject(java.lang.
* Object)
*/
public void printObject(Object msg) {
String str;
if (msg == null) {
str = "null";
} else {
str = msg.toString();
}
panel.add((new Label(str)));
consoleLog(str);
}
/*
* (non-Javadoc)
*
* @see com.vaadin.terminal.gwt.client.Console#dirUIDL(com.vaadin
* .terminal.gwt.client.UIDL)
*/
public void dirUIDL(UIDL u, ApplicationConfiguration conf) {
if (panel.isAttached()) {
panel.add(new VUIDLBrowser(u, conf));
}
consoleDir(u);
// consoleLog(u.getChildrenAsXML());
}
private static native void consoleDir(UIDL u)
/*-{
if($wnd.console && $wnd.console.log) {
if($wnd.console.dir) {
$wnd.console.dir(u);
} else {
$wnd.console.log(u);
}
}
}-*/;
private static native void consoleLog(String msg)
/*-{
if($wnd.console && $wnd.console.log) {
$wnd.console.log(msg);
}
}-*/;
private static native void consoleErr(String msg)
/*-{
if($wnd.console) {
if ($wnd.console.error)
$wnd.console.error(msg);
else if ($wnd.console.log)
$wnd.console.log(msg);
}
}-*/;
public void printLayoutProblems(ValueMap meta, ApplicationConnection ac,
Set<Paintable> zeroHeightComponents,
Set<Paintable> zeroWidthComponents) {
JsArray<ValueMap> valueMapArray = meta
.getJSValueMapArray("invalidLayouts");
int size = valueMapArray.length();
panel.add(new HTML("<div>************************</di>"
+ "<h4>Layouts analyzed on server, total top level problems: "
+ size + " </h4>"));
if (size > 0) {
Tree tree = new Tree();
// Position relative does not work here in IE7
DOM.setStyleAttribute(tree.getElement(), "position", "");
TreeItem root = new TreeItem("Root problems");
for (int i = 0; i < size; i++) {
printLayoutError(valueMapArray.get(i), root, ac);
}
panel.add(tree);
tree.addItem(root);
}
if (zeroHeightComponents.size() > 0 || zeroWidthComponents.size() > 0) {
panel.add(new HTML("<h4> Client side notifications</h4>"
+ " <em>The following relative sized components were "
+ "rendered to a zero size container on the client side."
+ " Note that these are not necessarily invalid "
+ "states, but reported here as they might be.</em>"));
if (zeroHeightComponents.size() > 0) {
panel.add(new HTML(
"<p><strong>Vertically zero size:</strong><p>"));
printClientSideDetectedIssues(zeroHeightComponents, ac);
}
if (zeroWidthComponents.size() > 0) {
panel.add(new HTML(
"<p><strong>Horizontally zero size:</strong><p>"));
printClientSideDetectedIssues(zeroWidthComponents, ac);
}
}
log("************************");
}
private void printClientSideDetectedIssues(
Set<Paintable> zeroHeightComponents, ApplicationConnection ac) {
for (final Paintable paintable : zeroHeightComponents) {
final Container layout = Util.getLayout((Widget) paintable);
VerticalPanel errorDetails = new VerticalPanel();
errorDetails.add(new Label("" + Util.getSimpleName(paintable)
+ " inside " + Util.getSimpleName(layout)));
final CheckBox emphasisInUi = new CheckBox(
"Emphasize components parent in UI (the actual component is not visible)");
emphasisInUi.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (paintable != null) {
Element element2 = ((Widget) layout).getElement();
Widget.setStyleName(element2, "invalidlayout",
emphasisInUi.getValue());
}
}
});
errorDetails.add(emphasisInUi);
panel.add(errorDetails);
}
}
private void printLayoutError(ValueMap valueMap, TreeItem parent,
final ApplicationConnection ac) {
final String pid = valueMap.getString("id");
final Paintable paintable = ac.getPaintable(pid);
TreeItem errorNode = new TreeItem();
VerticalPanel errorDetails = new VerticalPanel();
errorDetails.add(new Label(Util.getSimpleName(paintable) + " id: "
+ pid));
if (valueMap.containsKey("heightMsg")) {
errorDetails.add(new Label("Height problem: "
+ valueMap.getString("heightMsg")));
}
if (valueMap.containsKey("widthMsg")) {
errorDetails.add(new Label("Width problem: "
+ valueMap.getString("widthMsg")));
}
final CheckBox emphasisInUi = new CheckBox("Emphasize component in UI");
emphasisInUi.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (paintable != null) {
Element element2 = ((Widget) paintable).getElement();
Widget.setStyleName(element2, "invalidlayout",
emphasisInUi.getValue());
}
}
});
errorDetails.add(emphasisInUi);
errorNode.setWidget(errorDetails);
if (valueMap.containsKey("subErrors")) {
HTML l = new HTML(
"<em>Expand this node to show problems that may be dependent on this problem.</em>");
errorDetails.add(l);
JsArray<ValueMap> suberrors = valueMap
.getJSValueMapArray("subErrors");
for (int i = 0; i < suberrors.length(); i++) {
ValueMap value = suberrors.get(i);
printLayoutError(value, errorNode, ac);
}
}
parent.addItem(errorNode);
}
public void log(Throwable e) {
if (e instanceof UmbrellaException) {
UmbrellaException ue = (UmbrellaException) e;
for (Throwable t : ue.getCauses()) {
log(t);
}
return;
}
log(Util.getSimpleName(e) + ": " + e.getMessage());
GWT.log(e.getMessage(), e);
}
public void error(Throwable e) {
if (e instanceof UmbrellaException) {
UmbrellaException ue = (UmbrellaException) e;
for (Throwable t : ue.getCauses()) {
error(t);
}
return;
}
error(Util.getSimpleName(e) + ": " + e.getMessage());
GWT.log(e.getMessage(), e);
}
public void init() {
panel = new FlowPanel();
if (!quietMode) {
DOM.appendChild(getContainerElement(), caption);
setWidget(panel);
caption.setClassName("v-debug-console-caption");
setStyleName("v-debug-console");
DOM.setStyleAttribute(getElement(), "zIndex", 20000 + "");
DOM.setStyleAttribute(getElement(), "overflow", "hidden");
sinkEvents(Event.ONDBLCLICK);
sinkEvents(Event.MOUSEEVENTS);
panel.setStyleName("v-debug-console-content");
caption.setInnerHTML("Debug window");
caption.setTitle(help);
show();
setToDefaultSizeAndPos();
actions = new HorizontalPanel();
actions.add(clear);
actions.add(restart);
actions.add(forceLayout);
actions.add(analyzeLayout);
actions.add(savePosition);
savePosition
.setTitle("Saves the position and size of debug console to a cookie");
panel.add(actions);
panel.add(new HTML("<i>" + help + "</i>"));
clear.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
int width = panel.getOffsetWidth();
int height = panel.getOffsetHeight();
panel = new FlowPanel();
panel.setPixelSize(width, height);
panel.setStyleName("v-debug-console-content");
panel.add(actions);
setWidget(panel);
}
});
restart.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String queryString = Window.Location.getQueryString();
if (queryString != null
&& queryString.contains("restartApplications")) {
Window.Location.reload();
} else {
String url = Location.getHref();
String separator = "?";
if (url.contains("?")) {
separator = "&";
}
if (!url.contains("restartApplication")) {
url += separator;
url += "restartApplication";
}
if (!"".equals(Location.getHash())) {
String hash = Location.getHash();
url = url.replace(hash, "") + hash;
}
Window.Location.replace(url);
}
}
});
forceLayout.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// TODO for each client in appconf force layout
// VDebugConsole.this.client.forceLayout();
}
});
analyzeLayout.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
List<ApplicationConnection> runningApplications = ApplicationConfiguration
.getRunningApplications();
for (ApplicationConnection applicationConnection : runningApplications) {
applicationConnection.analyzeLayouts();
}
}
});
analyzeLayout
.setTitle("Analyzes currently rendered view and "
+ "reports possible common problems in usage of relative sizes."
+ "Will cause server visit/rendering of whole screen and loss of"
+ " all non committed variables form client side.");
savePosition.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
String pos = getAbsoluteLeft() + "," + getAbsoluteTop()
+ "," + getOffsetWidth() + "," + getOffsetHeight();
Cookies.setCookie(POS_COOKIE_NAME, pos);
}
});
}
log("Widget set is built on version: "
+ ApplicationConfiguration.VERSION);
logToDebugWindow("<div class=\"v-theme-version v-theme-version-"
+ ApplicationConfiguration.VERSION.replaceAll("\\.", "_")
+ "\">Warning: widgetset version "
+ ApplicationConfiguration.VERSION
+ " does not seem to match theme version </div>", true);
}
public void setQuietMode(boolean quietDebugMode) {
quietMode = quietDebugMode;
}
} |
package de.smits_net.games.framework.board;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
/**
* Base class for the game board. This class starts the game thread.
*
* @author Thomas Smits
*/
public abstract class BoardBase extends JPanel implements ActionListener, Runnable {
/** Debug information */
private static final boolean DEBUG = true;
/** Conversion factor from nano to milliseconds */
public static final long NANOSECONDS_PER_MILLISECOND = 1000000L;
/** Conversion factor from nano to seconds */
public static final long NANOSECONDS_PER_SECOND = NANOSECONDS_PER_MILLISECOND * 1000L;
/** Number of updates without sleep before a yield is triggered */
private static final int NO_DELAYS_PER_YIELD = 16;
/** Maximum number of frames skipped in the output */
private static final int MAX_FRAME_SKIPS = 5;
/* Time between two debug updates */
private static final long DEBUG_FREQUENCY = NANOSECONDS_PER_SECOND / 4;
/** Indicator that the game is still running */
protected boolean gameRunning = true;
/** Width of the board */
protected int width;
/** Height of the board */
protected int height;
/** Time for each iteration (frame) in nano seconds */
protected long delay;
/** The thread */
protected Thread thread;
/** Canvas the game is drawn on */
private Image image;
/** Color of the background of the board */
private Color backgroundColor;
/** Frame per second counter (only used if debugging is on) */
private long fps;
/** Timestamp of the last update of the debug line */
private long lastDebugUpdate;
/**
* Create a new board.
*
* @param delay delay between two frames in milliseconds
* @param width width of the board in pixel
* @param height height of the board in pixel
* @param color background color of the board
*/
public BoardBase(int delay, int width, int height, Color color) {
this.width = width;
this.height = height;
this.delay = delay * NANOSECONDS_PER_MILLISECOND;
this.backgroundColor = color;
setFocusable(true);
setBackground(color);
setPreferredSize(new Dimension(width, height));
}
/**
* @see javax.swing.JComponent#getWidth()
*/
@Override
public int getWidth() {
return width;
}
/**
* @see javax.swing.JComponent#getHeight()
*/
@Override
public int getHeight() {
return height;
}
/**
* Stops the game.
*/
public void stopGame() {
gameRunning = false;
}
/**
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public final void actionPerformed(ActionEvent e) {
}
/**
* The game loop for the game logic. This method will be called
* periodically be the framework to execute the game. All game
* actions must be triggered from this loop.
*
* @return true if the game should continue, otherwise false
*/
public abstract boolean updateGame();
/**
* The graphics output of the game. This method is called
* periodically by the framework to draw the game graphics.
*/
public abstract void drawGame(Graphics g);
/**
* Prepare the graphics context and then call the render methods.
*/
private void triggerRendering() {
// we apply double buffering. This means that we do not draw on
// the screen directly but into an image that is eventually
// blitted to screen in onw step. Therefore, we need an image
// as the target of our drawing operations.
if (image == null) {
image = createImage(width, height);
if (image == null) {
return;
}
}
Graphics g = image.getGraphics();
// clear the background
g.setColor(backgroundColor);
g.fillRect(0, 0, width, height);
// Let subclass draw its background
drawBackground(g);
// Draw game
if (gameRunning) {
drawGame(g);
}
else {
drawGameOver(g);
}
if (DEBUG) {
g.setColor(Color.RED);
g.drawString(String.format("FPS: %d", fps), 0, height - 5);
}
g.dispose();
}
/**
* Paints the screen.
*/
private void paintScreen() {
try {
Graphics g = this.getGraphics();
if ((g != null) && (image != null)) {
g.drawImage(image, 0, 0, null);
g.dispose();
}
Toolkit.getDefaultToolkit().sync();
}
catch (Exception e) {
System.err.println("Graphics error: " + e);
}
}
/**
* Draw a text centered on the screen.
*
* @param g the graphics context
* @param msg the message to be shown
*/
protected void centerText(Graphics g, String msg) {
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics fm = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (width - fm.stringWidth(msg)) / 2,
height / 2);
}
/**
* Writes a text at the given position.
*
* @param g graphics context
* @param x x position of the text
* @param y y position of the text
* @param msg the message to be drawn
*/
protected void writeText(Graphics g, int x, int y, String msg) {
g.setColor(Color.WHITE);
g.drawString(msg, x, y);
}
/**
* Draw game over message.
*
* @param g the graphics context
*/
protected abstract void drawGameOver(Graphics g);
/**
* Draw the background.
*
* @param g the graphics context
*/
protected abstract void drawBackground(Graphics g);
/**
* @see javax.swing.JComponent#addNotify()
*/
@Override
public void addNotify() {
super.addNotify();
thread = new Thread(this);
thread.start();
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
// Updates that were not fast enough and therefore caused a
// missed sleep
int numberOfDelays = 0;
// Time we slipped over the expected FPS
long excess = 0L;
// The approach used here is taken from the book
// Killer Game Programming in JavaTM by Andrew Davison
while (gameRunning) {
// time before game actions
long beforeTime = System.nanoTime();
// correction of sleep time
long sleepCorrection = 0L;
// execute the game actions
gameRunning = updateGame();
triggerRendering();
paintScreen();
// time after game actions
long afterTime = System.nanoTime();
// time passed during game actions
long timeDiff = afterTime - beforeTime;
// sleep long enough to reach the desired delays between updates
long sleepDuration = (delay - timeDiff - sleepCorrection);
if (sleepDuration < 0) {
sleepCorrection = 0L;
excess -= sleepDuration;
if (++numberOfDelays >= NO_DELAYS_PER_YIELD) {
Thread.yield();
numberOfDelays = 0;
}
}
else {
try {
Thread.sleep(sleepDuration / NANOSECONDS_PER_MILLISECOND);
} catch (InterruptedException e) {
break;
}
// sleep may be inaccurate, therefore calculate sleep's skew
sleepCorrection = System.nanoTime() - afterTime - sleepDuration;
}
int skips = 0;
// Rendering takes too much time, therefore update the game without
// rendering the screen. The display will lack FPS but the game
// logic will proceed with the right speed
while ((excess > delay) && (skips < MAX_FRAME_SKIPS)) {
excess -= delay;
gameRunning = updateGame();
skips++;
}
if (DEBUG) {
if (System.nanoTime() - lastDebugUpdate > DEBUG_FREQUENCY) {
fps = NANOSECONDS_PER_SECOND / (System.nanoTime() - beforeTime);
lastDebugUpdate = System.nanoTime();
}
}
}
}
} |
package org.jivesoftware.smack;
import java.util.logging.Logger;
import org.jivesoftware.smack.util.DNSUtil;
import org.jivesoftware.smack.util.dns.DNSJavaResolver;
import org.xbill.DNS.ResolverConfig;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
public class SmackAndroid {
private static final Logger LOGGER = Logger.getLogger(SmackAndroid.class.getName());
private static SmackAndroid sSmackAndroid = null;
private BroadcastReceiver mConnectivityChangedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
LOGGER.fine("ConnectivityChange received, calling ResolverConfig.refresh()");
ResolverConfig.refresh();
}
};
private static boolean receiverRegistered = false;
private Context mCtx;
private SmackAndroid(Context ctx) {
mCtx = ctx;
DNSUtil.setDNSResolver(DNSJavaResolver.getInstance());
}
/**
* Init Smack for Android. Make sure to call
* SmackAndroid.onDestroy() in all the exit code paths of your
* application.
*/
public static synchronized SmackAndroid init(Context ctx) {
if (sSmackAndroid == null) {
sSmackAndroid = new SmackAndroid(ctx);
}
sSmackAndroid.maybeRegisterReceiver();
return sSmackAndroid;
}
/**
* Cleanup all components initialized by init(). Make sure to call
* this method in all the exit code paths of your application.
*/
public synchronized void onDestroy() {
LOGGER.fine("onDestroy: receiverRegistered=" + receiverRegistered);
if (receiverRegistered) {
mCtx.unregisterReceiver(mConnectivityChangedReceiver);
receiverRegistered = false;
}
}
private void maybeRegisterReceiver() {
LOGGER.fine("maybeRegisterReceiver: receiverRegistered=" + receiverRegistered);
if (!receiverRegistered) {
mCtx.registerReceiver(mConnectivityChangedReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
receiverRegistered = true;
}
}
} |
package org.jgroups.protocols;
import org.jgroups.*;
import org.jgroups.annotations.GuardedBy;
import org.jgroups.stack.Protocol;
import org.jgroups.util.BoundedList;
import org.jgroups.util.Streamable;
import org.jgroups.util.Util;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Simple flow control protocol based on a credit system. Each sender has a number of credits (bytes
* to send). When the credits have been exhausted, the sender blocks. Each receiver also keeps track of
* how many credits it has received from a sender. When credits for a sender fall below a threshold,
* the receiver sends more credits to the sender. Works for both unicast and multicast messages.
* <p/>
* Note that this protocol must be located towards the top of the stack, or all down_threads from JChannel to this
* protocol must be set to false ! This is in order to block JChannel.send()/JChannel.down().
* <br/>This is the second simplified implementation of the same model. The algorithm is sketched out in
* doc/FlowControl.txt
* <br/>
* Changes (Brian) April 2006:
* <ol>
* <li>Receivers now send credits to a sender when more than min_credits have been received (rather than when min_credits
* are left)
* <li>Receivers don't send the full credits (max_credits), but rather tha actual number of bytes received
* <ol/>
* @author Bela Ban
* @version $Id: FC.java,v 1.83 2007/05/07 09:55:23 belaban Exp $
*/
public class FC extends Protocol {
/**
* Map<Address,Long>: keys are members, values are credits left. For each send, the
* number of credits is decremented by the message size. A HashMap rather than a ConcurrentHashMap is
* currently used as there might be null values
*/
@GuardedBy("sent_lock")
final Map<Address, Long> sent=new HashMap<Address, Long>(11);
// final Map sent=new ConcurrentHashMap(11);
/**
* Map<Address,Long>: keys are members, values are credits left (in bytes).
* For each receive, the credits for the sender are decremented by the size of the received message.
* When the credits are 0, we refill and send a CREDIT message to the sender. Sender blocks until CREDIT
* is received after reaching <tt>min_credits</tt> credits.
*/
@GuardedBy("received_lock")
final Map<Address, Long> received=new ConcurrentHashMap<Address, Long>(11);
/**
* List of members from whom we expect credits
*/
@GuardedBy("sent_lock")
final Set<Address> creditors=new HashSet<Address>(11);
/** Peers who have asked for credit that we didn't have */
final Set<Address> pending_requesters=new HashSet<Address>(11);
/**
* Max number of bytes to send per receiver until an ack must
* be received before continuing sending
*/
private long max_credits=500000;
private Long max_credits_constant=new Long(max_credits);
/**
* Max time (in milliseconds) to block. If credit hasn't been received after max_block_time, we send
* a REPLENISHMENT request to the members from which we expect credits. A value <= 0 means to
* wait forever.
*/
private long max_block_time=5000;
/**
* If credits fall below this limit, we send more credits to the sender. (We also send when
* credits are exhausted (0 credits left))
*/
private double min_threshold=0.25;
/**
* Computed as <tt>max_credits</tt> times <tt>min_theshold</tt>. If explicitly set, this will
* override the above computation
*/
private long min_credits=0;
/**
* Whether FC is still running, this is set to false when the protocol terminates (on stop())
*/
private boolean running=true;
/**
* Determines whether or not to block on down(). Set when not enough credit is available to send a message
* to all or a single member
*/
// @GuardedBy("sent_lock")
// private boolean insufficient_credit=false;
/**
* the lowest credits of any destination (sent_msgs)
*/
@GuardedBy("sent_lock")
private long lowest_credit=max_credits;
/** Lock protecting sent credits table and some other vars (creditors for example) */
final Lock sent_lock=new ReentrantLock();
/** Lock protecting received credits table */
final Lock received_lock=new ReentrantLock();
/** Mutex to block on down() */
final Condition credits_available=sent_lock.newCondition();
/**
* Whether an up thread that comes back down should be allowed to
* bypass blocking if all credits are exhausted. Avoids JGRP-465.
* Set to false by default in 2.5 because we have OOB messages for credit replenishments - this flag should not be set
* to true if the concurrent stack is used
*/
private boolean ignore_synchronous_response=false;
/**
* Thread that carries messages through up() and shouldn't be blocked
* in down() if ignore_synchronous_response==true. JGRP-465.
*/
private Thread ignore_thread;
static final String name="FC";
/** Last time a credit request was sent. Used to prevent credit request storms */
@GuardedBy("sent_lock")
private long last_credit_request=0;
private int num_blockings=0;
private int num_credit_requests_received=0, num_credit_requests_sent=0;
private int num_credit_responses_sent=0, num_credit_responses_received=0;
private long total_time_blocking=0;
final BoundedList last_blockings=new BoundedList(50);
final static FcHeader REPLENISH_HDR=new FcHeader(FcHeader.REPLENISH);
final static FcHeader CREDIT_REQUEST_HDR=new FcHeader(FcHeader.CREDIT_REQUEST);
public final String getName() {
return name;
}
public void resetStats() {
super.resetStats();
num_blockings=0;
num_credit_responses_sent=num_credit_responses_received=num_credit_requests_received=num_credit_requests_sent=0;
total_time_blocking=0;
last_blockings.removeAll();
}
public long getMaxCredits() {
return max_credits;
}
public void setMaxCredits(long max_credits) {
this.max_credits=max_credits;
max_credits_constant=new Long(this.max_credits);
}
public double getMinThreshold() {
return min_threshold;
}
public void setMinThreshold(double min_threshold) {
this.min_threshold=min_threshold;
}
public long getMinCredits() {
return min_credits;
}
public void setMinCredits(long min_credits) {
this.min_credits=min_credits;
}
public int getNumberOfBlockings() {
return num_blockings;
}
public long getMaxBlockTime() {
return max_block_time;
}
public void setMaxBlockTime(long t) {
max_block_time=t;
}
public long getTotalTimeBlocked() {
return total_time_blocking;
}
public double getAverageTimeBlocked() {
return num_blockings == 0? 0.0 : total_time_blocking / (double)num_blockings;
}
public int getNumberOfCreditRequestsReceived() {
return num_credit_requests_received;
}
public int getNumberOfCreditRequestsSent() {
return num_credit_requests_sent;
}
public int getNumberOfCreditResponsesReceived() {
return num_credit_responses_received;
}
public int getNumberOfCreditResponsesSent() {
return num_credit_responses_sent;
}
public String printSenderCredits() {
return printMap(sent);
}
public String printReceiverCredits() {
return printMap(received);
}
public String printCredits() {
StringBuilder sb=new StringBuilder();
sb.append("senders:\n").append(printMap(sent)).append("\n\nreceivers:\n").append(printMap(received));
return sb.toString();
}
public Map<String, Object> dumpStats() {
Map<String, Object> retval=super.dumpStats();
if(retval == null)
retval=new HashMap<String, Object>();
retval.put("senders", printMap(sent));
retval.put("receivers", printMap(received));
retval.put("num_blockings", new Integer(this.num_blockings));
retval.put("avg_time_blocked", new Double(getAverageTimeBlocked()));
retval.put("num_replenishments", new Integer(this.num_credit_responses_received));
retval.put("total_time_blocked", new Long(total_time_blocking));
retval.put("num_credit_requests", new Long(num_credit_requests_sent));
return retval;
}
public String showLastBlockingTimes() {
return last_blockings.toString();
}
/**
* Allows to unblock a blocked sender from an external program, e.g. JMX
*/
public void unblock() {
sent_lock.lock();
try {
if(log.isTraceEnabled())
log.trace("unblocking the sender and replenishing all members, creditors are " + creditors);
for(Map.Entry<Address, Long> entry: sent.entrySet()) {
entry.setValue(max_credits_constant);
}
lowest_credit=computeLowestCredit(sent);
creditors.clear();
credits_available.signalAll();
}
finally {
sent_lock.unlock();
}
}
public boolean setProperties(Properties props) {
String str;
boolean min_credits_set=false;
super.setProperties(props);
str=props.getProperty("max_credits");
if(str != null) {
max_credits=Long.parseLong(str);
props.remove("max_credits");
}
str=props.getProperty("min_threshold");
if(str != null) {
min_threshold=Double.parseDouble(str);
props.remove("min_threshold");
}
str=props.getProperty("min_credits");
if(str != null) {
min_credits=Long.parseLong(str);
props.remove("min_credits");
min_credits_set=true;
}
if(!min_credits_set)
min_credits=(long)((double)max_credits * min_threshold);
str=props.getProperty("max_block_time");
if(str != null) {
max_block_time=Long.parseLong(str);
props.remove("max_block_time");
}
Util.checkBufferSize("FC.max_credits", max_credits);
str=props.getProperty("ignore_synchronous_response");
if(str != null) {
ignore_synchronous_response=Boolean.valueOf(str).booleanValue();
props.remove("ignore_synchronous_response");
}
if(!props.isEmpty()) {
log.error("the following properties are not recognized: " + props);
return false;
}
max_credits_constant=new Long(max_credits);
return true;
}
public void start() throws Exception {
super.start();
sent_lock.lock();
try {
running=true;
lowest_credit=max_credits;
}
finally {
sent_lock.unlock();
}
}
public void stop() {
super.stop();
sent_lock.lock();
try {
running=false;
ignore_thread=null;
credits_available.signalAll(); // notify all threads waiting on the mutex that we are done
}
finally {
sent_lock.unlock();
}
}
public Object down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
return handleDownMessage(evt);
}
return down_prot.down(evt); // this could potentially use the lower protocol's thread which may block
}
public Object up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
// JGRP-465. We only deal with msgs to avoid having to use a concurrent collection; ignore views,
// suspicions, etc which can come up on unusual threads.
if(ignore_thread == null && ignore_synchronous_response)
ignore_thread=Thread.currentThread();
Message msg=(Message)evt.getArg();
FcHeader hdr=(FcHeader)msg.getHeader(name);
if(hdr != null) {
switch(hdr.type) {
case FcHeader.REPLENISH:
num_credit_responses_received++;
handleCredit(msg.getSrc(), (Number)msg.getObject());
break;
case FcHeader.CREDIT_REQUEST:
num_credit_requests_received++;
Address sender=msg.getSrc();
Long sent_credits=(Long)msg.getObject();
handleCreditRequest(received, received_lock, sender, sent_credits);
break;
default:
log.error("header type " + hdr.type + " not known");
break;
}
return null; // don't pass message up
}
else {
Address sender=msg.getSrc();
long new_credits=adjustCredit(received, received_lock, sender, msg.getLength());
try {
return up_prot.up(evt);
}
finally {
if(new_credits > 0) {
if(log.isTraceEnabled()) log.trace("sending " + new_credits + " credits to " + sender);
sendCredit(sender, new_credits);
}
}
}
case Event.VIEW_CHANGE:
handleViewChange(((View)evt.getArg()).getMembers());
break;
}
return up_prot.up(evt);
}
private Object handleDownMessage(Event evt) {
Message msg=(Message)evt.getArg();
int length=msg.getLength();
Address dest=msg.getDest();
sent_lock.lock();
try {
if(length > lowest_credit) { // then block and loop asking for credits until enough credits are available
if(ignore_synchronous_response && ignore_thread == Thread.currentThread()) { // JGRP-465
if(log.isTraceEnabled())
log.trace("bypassing blocking to avoid deadlocking " + Thread.currentThread());
}
else {
determineCreditors(dest, length);
long start_blocking=System.currentTimeMillis();
num_blockings++; // we count overall blockings, not blockings for *all* threads
if(log.isTraceEnabled())
log.trace("Starting blocking. lowest_credit=" + lowest_credit + "; msg length =" + length);
while(length > lowest_credit && running) {
try {
credits_available.await(max_block_time, TimeUnit.MILLISECONDS);
if(length <= lowest_credit || !running)
break;
long wait_time=System.currentTimeMillis() - last_credit_request;
if(wait_time >= max_block_time) {
// we have to set this var now, because we release the lock below (for sending a
// credit request), so all blocked threads would send a credit request, leading to
// a credit request storm
last_credit_request=System.currentTimeMillis();
// we need to send the credit requests down *without* holding the sent_lock, otherwise we might
Map<Address,Long> sent_copy=new HashMap<Address,Long>(sent);
sent_copy.keySet().retainAll(creditors);
sent_lock.unlock();
try {
// System.out.println(new Date() + " --> credit request");
for(Map.Entry<Address,Long> entry: sent_copy.entrySet()) {
sendCreditRequest(entry.getKey(), entry.getValue());
}
}
finally {
sent_lock.lock();
}
}
}
catch(InterruptedException e) {
// set the interrupted flag again, so the caller's thread can handle the interrupt as well
Thread.currentThread().interrupt();
}
}
// if(!running) // don't send the message if not running anymore
// return null;
long block_time=System.currentTimeMillis() - start_blocking;
if(log.isTraceEnabled())
log.trace("total time blocked: " + block_time + " ms");
total_time_blocking+=block_time;
last_blockings.add(new Long(block_time));
}
}
long tmp=decrementCredit(sent, dest, length);
if(tmp != -1)
lowest_credit=Math.min(tmp, lowest_credit);
}
finally {
sent_lock.unlock();
}
// send message - either after regular processing, or after blocking (when enough credits available again)
return down_prot.down(evt);
}
/**
* Checks whether one member (unicast msg) or all members (multicast msg) have enough credits. Add those
* that don't to the creditors list. Called with sent_lock held
* @param dest
* @param length
*/
private void determineCreditors(Address dest, int length) {
boolean multicast=dest == null || dest.isMulticastAddress();
Address mbr;
Long credits;
if(multicast) {
for(Map.Entry<Address,Long> entry: sent.entrySet()) {
mbr=entry.getKey();
credits=entry.getValue();
if(credits.longValue() <= length)
creditors.add(mbr);
}
}
else {
credits=sent.get(dest);
if(credits != null && credits.longValue() <= length)
creditors.add(dest);
}
}
/**
* Decrements credits from a single member, or all members in sent_msgs, depending on whether it is a multicast
* or unicast message. No need to acquire mutex (must already be held when this method is called)
* @param dest
* @param credits
* @return The lowest number of credits left, or -1 if a unicast member was not found
*/
private long decrementCredit(Map<Address, Long> m, Address dest, long credits) {
boolean multicast=dest == null || dest.isMulticastAddress();
long lowest=max_credits, new_credit;
Long val;
if(multicast) {
if(m.isEmpty())
return -1;
for(Map.Entry<Address, Long> entry: m.entrySet()) {
val=entry.getValue();
new_credit=val - credits;
entry.setValue(new_credit);
lowest=Math.min(new_credit, lowest);
}
return lowest;
}
else {
val=m.get(dest);
if(val != null) {
lowest=val.longValue();
lowest-=credits;
m.put(dest, lowest);
return lowest;
}
}
return -1;
}
private void handleCredit(Address sender, Number increase) {
if(sender == null) return;
StringBuilder sb=null;
sent_lock.lock();
try {
Long old_credit=sent.get(sender);
Long new_credit=Math.min(max_credits, old_credit.longValue() + increase.longValue());
if(log.isTraceEnabled()) {
sb=new StringBuilder();
sb.append("received credit from ").append(sender).append(", old credit was ").append(old_credit)
.append(", new credits are ").append(new_credit).append(".\nCreditors before are: ").append(creditors);
}
sent.put(sender, new_credit);
lowest_credit=computeLowestCredit(sent);
// boolean was_empty=true;
if(!creditors.isEmpty()) { // we are blocked because we expect credit from one or more members
// was_empty=false;
creditors.remove(sender);
if(log.isTraceEnabled()) {
sb.append("\nCreditors after removal of ").append(sender).append(" are: ").append(creditors);
log.trace(sb);
}
}
if(creditors.isEmpty()) {// && !was_empty) {
credits_available.signalAll();
}
}
finally {
sent_lock.unlock();
}
}
private static long computeLowestCredit(Map<Address, Long> m) {
Collection<Long> credits=m.values(); // List of Longs (credits)
Long retval=Collections.min(credits);
return retval.longValue();
}
/**
* Check whether sender has enough credits left. If not, send him some more
* @param map The hashmap to use
* @param lock The lock which can be used to lock map
* @param sender The address of the sender
* @param length The number of bytes received by this message. We don't care about the size of the headers for
* the purpose of flow control
* @return long Number of credits to be sent. Greater than 0 if credits needs to be sent, 0 otherwise
*/
private long adjustCredit(Map<Address,Long> map, final Lock lock, Address sender, int length) {
if(sender == null) {
if(log.isErrorEnabled()) log.error("src is null");
return 0;
}
if(length == 0)
return 0; // no effect
lock.lock();
try {
long remaining_cred=decrementCredit(map, sender, length);
long credit_response=max_credits - remaining_cred;
if(credit_response >= min_credits) {
map.put(sender, max_credits_constant);
return credit_response; // this will trigger sending of new credits as we have received more than min_credits bytes from src
}
}
finally {
lock.unlock();
}
return 0;
}
/**
* @param map The map to modify
* @param lock The lock to lock map
* @param sender The sender who requests credits
* @param left_credits Number of bytes that the sender has left to send messages to us
*/
private void handleCreditRequest(Map<Address,Long> map, Lock lock, Address sender, Long left_credits) {
if(sender == null) return;
long credit_response=0;
lock.lock();
try {
Long old_credit=map.get(sender);
if(old_credit != null) {
credit_response=Math.min(max_credits, max_credits - old_credit.longValue());
}
if(credit_response > 0) {
if(log.isTraceEnabled())
log.trace("received credit request from " + sender + ": sending " + credit_response + " credits");
map.put(sender, max_credits_constant);
pending_requesters.remove(sender);
}
else {
if(pending_requesters.contains(sender)) {
// a sender might have negative credits, e.g. -20000. If we subtracted -20000 from max_credits,
// we'd end up with max_credits + 20000, and send too many credits back. So if the sender's
// credits is negative, we simply send max_credits back
long credits_left=Math.max(0, left_credits.longValue());
credit_response=max_credits - credits_left;
// credit_response = max_credits;
map.put(sender, max_credits_constant);
pending_requesters.remove(sender);
if(log.isWarnEnabled())
log.warn("Received two credit requests from " + sender +
" without any intervening messages; sending " + credit_response + " credits");
}
else {
pending_requesters.add(sender);
if(log.isTraceEnabled())
log.trace("received credit request from " + sender + " but have no credits available");
}
}
}
finally {
lock.unlock();
}
if(credit_response > 0)
sendCredit(sender, credit_response);
}
private void sendCredit(Address dest, long credit) {
Number number;
if(credit < Integer.MAX_VALUE)
number=new Integer((int)credit);
else
number=new Long(credit);
Message msg=new Message(dest, null, number);
msg.setFlag(Message.OOB);
msg.putHeader(name, REPLENISH_HDR);
down_prot.down(new Event(Event.MSG, msg));
num_credit_responses_sent++;
}
/**
* We cannot send this request as OOB messages, as the credit request needs to queue up behind the regular messages;
* if a receiver cannot process the regular messages, that is a sign that the sender should be throttled !
* @param dest The member to which we send the credit request
* @param credits_left The number of bytes (of credits) left for dest
*/
private void sendCreditRequest(final Address dest, Long credits_left) {
if(log.isTraceEnabled())
log.trace("sending credit request to " + dest);
Message msg=new Message(dest, null, credits_left);
msg.putHeader(name, CREDIT_REQUEST_HDR);
down_prot.down(new Event(Event.MSG, msg));
num_credit_requests_sent++;
}
private void handleViewChange(Vector mbrs) {
Address addr;
if(mbrs == null) return;
if(log.isTraceEnabled()) log.trace("new membership: " + mbrs);
sent_lock.lock();
received_lock.lock();
try {
// add members not in membership to received and sent hashmap (with full credits)
for(int i=0; i < mbrs.size(); i++) {
addr=(Address)mbrs.elementAt(i);
if(!received.containsKey(addr))
received.put(addr, max_credits_constant);
if(!sent.containsKey(addr))
sent.put(addr, max_credits_constant);
}
// remove members that left
for(Iterator it=received.keySet().iterator(); it.hasNext();) {
addr=(Address)it.next();
if(!mbrs.contains(addr))
it.remove();
}
// remove members that left
for(Iterator it=sent.keySet().iterator(); it.hasNext();) {
addr=(Address)it.next();
if(!mbrs.contains(addr))
it.remove(); // modified the underlying map
}
// remove all creditors which are not in the new view
for(Address creditor: creditors) {
if(!mbrs.contains(creditor))
creditors.remove(creditor);
}
if(log.isTraceEnabled()) log.trace("creditors are " + creditors);
if(creditors.isEmpty()) {
lowest_credit=computeLowestCredit(sent);
credits_available.signalAll();
}
}
finally {
sent_lock.unlock();
received_lock.unlock();
}
}
private static String printMap(Map<Address,Long> m) {
StringBuilder sb=new StringBuilder();
for(Map.Entry<Address,Long> entry: m.entrySet()) {
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
public static class FcHeader extends Header implements Streamable {
public static final byte REPLENISH=1;
public static final byte CREDIT_REQUEST=2; // the sender of the message is the requester
byte type=REPLENISH;
public FcHeader() {
}
public FcHeader(byte type) {
this.type=type;
}
public int size() {
return Global.BYTE_SIZE;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeByte(type);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type=in.readByte();
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeByte(type);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
type=in.readByte();
}
public String toString() {
switch(type) {
case REPLENISH:
return "REPLENISH";
case CREDIT_REQUEST:
return "CREDIT_REQUEST";
default:
return "<invalid type>";
}
}
}
} |
// $Id: FC.java,v 1.49 2005/10/28 07:38:31 belaban Exp $
package org.jgroups.protocols;
import EDU.oswego.cs.dl.util.concurrent.ConcurrentReaderHashMap;
import org.jgroups.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.BoundedList;
import org.jgroups.util.Streamable;
import java.io.*;
import java.util.*;
/**
* Simple flow control protocol based on a credit system. Each sender has a number of credits (bytes
* to send). When the credits have been exhausted, the sender blocks. Each receiver also keeps track of
* how many credits it has received from a sender. When credits for a sender fall below a threshold,
* the receiver sends more credits to the sender. Works for both unicast and multicast messages.
* <p>
* Note that this protocol must be located towards the top of the stack, or all down_threads from JChannel to this
* protocol must be set to false ! This is in order to block JChannel.send()/JChannel.down().
* <br/>This is the second simplified implementation of the same model. The algorithm is sketched out in
* doc/FlowControl.txt
* @author Bela Ban
* @version $Revision: 1.49 $
*/
public class FC extends Protocol {
/** HashMap<Address,Long>: keys are members, values are credits left. For each send, the
* number of credits is decremented by the message size */
final Map sent=new HashMap(11);
// final Map sent=new ConcurrentHashMap(11);
/** HashMap<Address,Long>: keys are members, values are credits left (in bytes).
* For each receive, the credits for the sender are decremented by the size of the received message.
* When the credits are 0, we refill and send a CREDIT message to the sender. Sender blocks until CREDIT
* is received after reaching <tt>min_credits</tt> credits. */
final Map received=new ConcurrentReaderHashMap(11);
// final Map received=new ConcurrentHashMap(11);
/** List of members from whom we expect credits */
final List creditors=new ArrayList(11);
/** Max number of bytes to send per receiver until an ack must
* be received before continuing sending */
private long max_credits=50000;
private Long max_credits_constant;
/** Max time (in milliseconds) to block. If credit hasn't been received after max_block_time, we send
* a REPLENISHMENT request to the members from which we expect credits. A value <= 0 means to
* wait forever.
*/
private long max_block_time=5000;
/** If credits fall below this limit, we send more credits to the sender. (We also send when
* credits are exhausted (0 credits left)) */
private double min_threshold=0.25;
/** Computed as <tt>max_credits</tt> times <tt>min_theshold</tt>. If explicitly set, this will
* override the above computation */
private long min_credits=0;
/** Whether FC is still running, this is set to false when the protocol terminates (on stop()) */
private boolean running=true;
/** Determines whether or not to block on down(). Set when not enough credit is available to send a message
* to all or a single member */
private boolean insufficient_credit=false;
/** the lowest credits of any destination (sent_msgs) */
private long lowest_credit=max_credits;
/** Mutex to block on down() */
final Object mutex=new Object();
static final String name="FC";
private long start_blocking=0, stop_blocking=0;
private int num_blockings=0;
private int num_credit_requests_received=0, num_credit_requests_sent=0;
private int num_credit_responses_sent=0, num_credit_responses_received=0;
private long total_time_blocking=0;
final BoundedList last_blockings=new BoundedList(50);
final static FcHeader REPLENISH_HDR=new FcHeader(FcHeader.REPLENISH);
final static FcHeader CREDIT_REQUEST_HDR=new FcHeader(FcHeader.CREDIT_REQUEST);
public final String getName() {
return name;
}
public void resetStats() {
super.resetStats();
num_blockings=0;
num_credit_responses_sent=num_credit_responses_received=num_credit_requests_received=num_credit_requests_sent=0;
total_time_blocking=0;
last_blockings.removeAll();
}
public long getMaxCredits() {
return max_credits;
}
public void setMaxCredits(long max_credits) {
this.max_credits=max_credits;
max_credits_constant=new Long(this.max_credits);
}
public double getMinThreshold() {
return min_threshold;
}
public void setMinThreshold(double min_threshold) {
this.min_threshold=min_threshold;
}
public long getMinCredits() {
return min_credits;
}
public void setMinCredits(long min_credits) {
this.min_credits=min_credits;
}
public boolean isBlocked() {
return insufficient_credit;
}
public int getNumberOfBlockings() {
return num_blockings;
}
public long getMaxBlockTime() {
return max_block_time;
}
public void setMaxBlockTime(long t) {
max_block_time=t;
}
public long getTotalTimeBlocked() {
return total_time_blocking;
}
public double getAverageTimeBlocked() {
return num_blockings == 0? 0.0 : total_time_blocking / (double)num_blockings;
}
public int getNumberOfCreditRequestsReceived() {
return num_credit_requests_received;
}
public int getNumberOfCreditRequestsSent() {
return num_credit_requests_sent;
}
public int getNumberOfCreditResponsesReceived() {
return num_credit_responses_received;
}
public int getNumberOfCreditResponsesSent() {
return num_credit_responses_sent;
}
public String printSenderCredits() {
return printMap(sent);
}
public String printReceiverCredits() {
return printMap(received);
}
public String printCredits() {
StringBuffer sb=new StringBuffer();
sb.append("senders:\n").append(printMap(sent)).append("\n\nreceivers:\n").append(printMap(received));
return sb.toString();
}
public Map dumpStats() {
Map retval=super.dumpStats();
if(retval == null)
retval=new HashMap();
retval.put("senders", printMap(sent));
retval.put("receivers", printMap(received));
retval.put("num_blockings", new Integer(this.num_blockings));
retval.put("avg_time_blocked", new Double(getAverageTimeBlocked()));
retval.put("num_replenishments", new Integer(this.num_credit_responses_received));
retval.put("total_time_blocked", new Long(total_time_blocking));
return retval;
}
public String showLastBlockingTimes() {
return last_blockings.toString();
}
/** Allows to unblock a blocked sender from an external program, e.g. JMX */
public void unblock() {
synchronized(mutex) {
if(trace)
log.trace("unblocking the sender and replenishing all members, creditors are " + creditors);
Map.Entry entry;
for(Iterator it=sent.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
entry.setValue(max_credits_constant);
}
lowest_credit=computeLowestCredit(sent);
creditors.clear();
insufficient_credit=false;
mutex.notifyAll();
}
}
public boolean setProperties(Properties props) {
String str;
boolean min_credits_set=false;
super.setProperties(props);
str=props.getProperty("max_credits");
if(str != null) {
max_credits=Long.parseLong(str);
props.remove("max_credits");
}
str=props.getProperty("min_threshold");
if(str != null) {
min_threshold=Double.parseDouble(str);
props.remove("min_threshold");
}
str=props.getProperty("min_credits");
if(str != null) {
min_credits=Long.parseLong(str);
props.remove("min_credits");
min_credits_set=true;
}
if(!min_credits_set)
min_credits=(long)((double)max_credits * min_threshold);
str=props.getProperty("max_block_time");
if(str != null) {
max_block_time=Long.parseLong(str);
props.remove("max_block_time");
}
if(props.size() > 0) {
log.error("FC.setProperties(): the following properties are not recognized: " + props);
return false;
}
max_credits_constant=new Long(max_credits);
return true;
}
public void start() throws Exception {
super.start();
synchronized(mutex) {
running=true;
insufficient_credit=false;
lowest_credit=max_credits;
}
}
public void stop() {
super.stop();
synchronized(mutex) {
running=false;
mutex.notifyAll();
}
}
/**
* We need to receive view changes concurrent to messages on the down events: a message might blocks, e.g.
* because we don't have enough credits to send to member P. However, if member P crashed, we need to unblock !
* @param evt
*/
protected void receiveDownEvent(Event evt) {
if(evt.getType() == Event.VIEW_CHANGE) {
View v=(View)evt.getArg();
Vector mbrs=v.getMembers();
handleViewChange(mbrs);
}
super.receiveDownEvent(evt);
}
public void down(Event evt) {
switch(evt.getType()) {
case Event.MSG:
handleDownMessage(evt);
return;
}
passDown(evt); // this could potentially use the lower protocol's thread which may block
}
public void up(Event evt) {
switch(evt.getType()) {
case Event.MSG:
Message msg=(Message)evt.getArg();
FcHeader hdr=(FcHeader)msg.removeHeader(name);
if(hdr != null) {
switch(hdr.type) {
case FcHeader.REPLENISH:
num_credit_responses_received++;
handleCredit(msg.getSrc());
break;
case FcHeader.CREDIT_REQUEST:
num_credit_requests_received++;
Address sender=msg.getSrc();
if(trace)
log.trace("received credit request from " + sender + ": sending credits");
received.put(sender, max_credits_constant);
sendCredit(sender);
break;
default:
log.error("header type " + hdr.type + " not known");
break;
}
return; // don't pass message up
}
else {
adjustCredit(msg);
}
break;
case Event.VIEW_CHANGE:
handleViewChange(((View)evt.getArg()).getMembers());
break;
}
passUp(evt);
}
private void handleDownMessage(Event evt) {
Message msg=(Message)evt.getArg();
int length=msg.getLength();
Address dest=msg.getDest();
synchronized(mutex) {
if(lowest_credit <= length) {
determineCreditors(dest, length);
insufficient_credit=true;
num_blockings++;
start_blocking=System.currentTimeMillis();
while(insufficient_credit && running) {
try {mutex.wait(max_block_time);} catch(InterruptedException e) {}
if(insufficient_credit && running) {
if(trace)
log.trace("timeout occurred waiting for credits; sending credit request to " + creditors);
for(int i=0; i < creditors.size(); i++) {
sendCreditRequest((Address)creditors.get(i));
}
}
}
stop_blocking=System.currentTimeMillis();
long block_time=stop_blocking - start_blocking;
if(trace)
log.trace("total time blocked: " + block_time + " ms");
total_time_blocking+=block_time;
last_blockings.add(new Long(block_time));
}
else {
long tmp=decrementCredit(sent, dest, length);
lowest_credit=Math.min(tmp, lowest_credit);
}
}
// send message - either after regular processing, or after blocking (when enough credits available again)
passDown(evt);
}
/**
* Checks whether one member (unicast msg) or all members (multicast msg) have enough credits. Add those
* that don't to the creditors list
* @param dest
* @param length
*/
private void determineCreditors(Address dest, int length) {
boolean multicast=dest == null || dest.isMulticastAddress();
Address mbr;
Long credits;
if(multicast) {
Map.Entry entry;
for(Iterator it=sent.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
mbr=(Address)entry.getKey();
credits=(Long)entry.getValue();
if(credits.longValue() <= length) {
if(!creditors.contains(mbr))
creditors.add(mbr);
}
}
}
else {
credits=(Long)sent.get(dest);
if(credits != null && credits.longValue() <= length) {
if(!creditors.contains(dest))
creditors.add(dest);
}
}
}
/**
* Decrements credits from a single member, or all members in sent_msgs, depending on whether it is a multicast
* or unicast message. No need to acquire mutex (must already be held when this method is called)
* @param dest
* @param credits
* @return The lowest number of credits left, or -1 if a unicast member was not found
*/
private long decrementCredit(Map m, Address dest, long credits) {
boolean multicast=dest == null || dest.isMulticastAddress();
long lowest=max_credits, tmp;
Long val;
if(multicast) {
if(m.size() == 0)
return -1;
Map.Entry entry;
for(Iterator it=m.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
val=(Long)entry.getValue();
tmp=val.longValue();
tmp-=credits;
entry.setValue(new Long(tmp));
lowest=Math.min(tmp, lowest);
}
return lowest;
}
else {
val=(Long)m.get(dest);
if(val != null) {
lowest=val.longValue();
lowest-=credits;
m.put(dest, new Long(lowest));
return lowest;
}
}
return -1;
}
private void handleCredit(Address sender) {
if(sender == null) return;
StringBuffer sb=null;
synchronized(mutex) {
if(trace) {
Long old_credit=(Long)sent.get(sender);
sb=new StringBuffer();
sb.append("received credit from ").append(sender).append(", old credit was ").
append(old_credit).append(", new credits are ").append(max_credits).
append(".\nCreditors before are: ").append(creditors);
}
sent.put(sender, max_credits_constant);
lowest_credit=computeLowestCredit(sent);
if(creditors.size() > 0) { // we are blocked because we expect credit from one or more members
creditors.remove(sender);
if(trace) {
sb.append("\nCreditors after removal of ").append(sender).append(" are: ").append(creditors);
log.trace(sb.toString());
}
}
if(insufficient_credit && lowest_credit > 0 && creditors.size() == 0) {
insufficient_credit=false;
mutex.notifyAll();
}
}
}
private long computeLowestCredit(Map m) {
Collection credits=m.values(); // List of Longs (credits)
Long retval=(Long)Collections.min(credits);
return retval.longValue();
}
/**
* Check whether sender has enough credits left. If not, send him some more
* @param msg
*/
private void adjustCredit(Message msg) {
Address src=msg.getSrc();
long length=msg.getLength(); // we don't care about headers for the purpose of flow control
if(src == null) {
if(log.isErrorEnabled()) log.error("src is null");
return;
}
if(length == 0)
return; // no effect
if(decrementCredit(received, src, length) <= min_credits) {
received.put(src, max_credits_constant);
if(trace) log.trace("sending replenishment message to " + src);
sendCredit(src);
}
}
private void sendCredit(Address dest) {
Message msg=new Message(dest, null, null);
msg.putHeader(name, REPLENISH_HDR);
passDown(new Event(Event.MSG, msg));
num_credit_responses_sent++;
}
private void sendCreditRequest(final Address dest) {
Message msg=new Message(dest, null, null);
msg.putHeader(name, CREDIT_REQUEST_HDR);
passDown(new Event(Event.MSG, msg));
num_credit_requests_sent++;
}
private void handleViewChange(Vector mbrs) {
Address addr;
if(mbrs == null) return;
if(trace) log.trace("new membership: " + mbrs);
synchronized(mutex) {
// add members not in membership to received and sent hashmap (with full credits)
for(int i=0; i < mbrs.size(); i++) {
addr=(Address) mbrs.elementAt(i);
if(!received.containsKey(addr))
received.put(addr, max_credits_constant);
if(!sent.containsKey(addr))
sent.put(addr, max_credits_constant);
}
// remove members that left
for(Iterator it=received.keySet().iterator(); it.hasNext();) {
addr=(Address) it.next();
if(!mbrs.contains(addr))
it.remove();
}
// remove members that left
for(Iterator it=sent.keySet().iterator(); it.hasNext();) {
addr=(Address)it.next();
if(!mbrs.contains(addr))
it.remove(); // modified the underlying map
}
// remove all creditors which are not in the new view
for(int i=0; i < creditors.size(); i++) {
Address creditor=(Address)creditors.get(i);
if(!mbrs.contains(creditor))
creditors.remove(creditor);
}
if(trace) log.trace("creditors are " + creditors);
if(insufficient_credit && lowest_credit > 0 && creditors.size() == 0) {
insufficient_credit=false;
mutex.notifyAll();
}
}
}
private static String printMap(Map m) {
Map.Entry entry;
StringBuffer sb=new StringBuffer();
for(Iterator it=m.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
public static class FcHeader extends Header implements Streamable {
public static final byte REPLENISH = 1;
public static final byte CREDIT_REQUEST = 2; // the sender of the message is the requester
byte type = REPLENISH;
public FcHeader() {
}
public FcHeader(byte type) {
this.type=type;
}
public long size() {
return Global.BYTE_SIZE;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeByte(type);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
type=in.readByte();
}
public void writeTo(DataOutputStream out) throws IOException {
out.writeByte(type);
}
public void readFrom(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
type=in.readByte();
}
public String toString() {
switch(type) {
case REPLENISH: return "REPLENISH";
case CREDIT_REQUEST: return "CREDIT_REQUEST";
default: return "<invalid type>";
}
}
}
} |
package dr.evomodel.coalescent;
import dr.evolution.coalescent.DemographicFunction;
import dr.evolution.coalescent.TreeIntervals;
import dr.evolution.coalescent.IntervalType;
import dr.evolution.tree.Tree;
import java.util.Arrays;
/**
* @author Joseph Heled
*/
public class VDdemographicFunction extends DemographicFunction.Abstract {
private double[] values;
private double[] times;
private double[] intervals;
private double[][] ttimes;
private double[] alltimes;
private boolean[] dirtyTrees;
boolean dirty;
private VariableDemographicModel.Type type;
TreeIntervals[] ti;
public VDdemographicFunction(Tree[] trees, VariableDemographicModel.Type type,
double[] indicatorParameter, double[] popSizeParameter, boolean logSpace,
boolean mid) {
super(trees[0].getUnits());
this.type = type;
ti = new TreeIntervals[trees.length];
dirtyTrees = new boolean[trees.length];
Arrays.fill(dirtyTrees, true);
ttimes = new double[ti.length][];
int tot = 0;
for(int k = 0; k < ti.length; ++k) {
ttimes[k] = new double[trees[k].getTaxonCount()-1];
tot += ttimes[k].length;
}
alltimes = new double[tot];
setDirty();
setup(trees, indicatorParameter, popSizeParameter, logSpace, mid);
}
/**
* Reduce memory footprint of object. After a call to freeze only population/intensity
* are allowed.
*/
public void freeze() {
ttimes = null;
alltimes = null;
dirtyTrees = null;
ti = null;
}
public VDdemographicFunction(VDdemographicFunction demoFunction) {
super(demoFunction.getUnits());
type = demoFunction.type;
this.ti = demoFunction.ti.clone();
this.values = demoFunction.values.clone();
this.times = demoFunction.times.clone();
this.intervals = demoFunction.intervals.clone();
this.ttimes = demoFunction.ttimes.clone();
for(int k = 0; k < ttimes.length; ++k) {
ttimes[k] = ttimes[k].clone();
}
this.alltimes = demoFunction.alltimes.clone();
this.dirtyTrees = demoFunction.dirtyTrees.clone();
this.dirty = demoFunction.dirty;
}
public int numberOfChanges() {
return values.length - 1;
}
public void treeChanged(int nt) {
dirtyTrees[nt] = true;
setDirty();
}
public void setDirty() {
dirty = true;
}
private boolean setTreeTimes(int nt, Tree[] trees) {
if( dirtyTrees[nt] ) {
/*double[] doubles = null;
if( ! dirtyTrees[nt] ) {
doubles = ttimes[nt].clone();
}*/
ti[nt] = new TreeIntervals(trees[nt]);
TreeIntervals nti = ti[nt];
// make sure we get each coalescent event individually
nti.setMultifurcationLimit(0);
// code probably incorrect for serial samples
final int nLineages = nti.getIntervalCount();
assert nLineages >= ttimes[nt].length: nLineages + " " + ttimes[nt].length;
int iCount = 0;
for(int k = 0; k < ttimes[nt].length; ++k) {
double timeToCoal = nti.getInterval(iCount);
while( nti.getIntervalType(iCount) != IntervalType.COALESCENT ) {
++iCount;
timeToCoal += nti.getInterval(iCount);
}
int linAtStart = nti.getLineageCount(iCount);
++iCount;
assert ! (iCount == nLineages && linAtStart != 2);
int linAtEnd = (iCount == nLineages) ? 1 : nti.getLineageCount(iCount);
while( linAtStart <= linAtEnd ) {
++iCount;
timeToCoal += nti.getInterval(iCount);
linAtStart = linAtEnd;
++iCount;
linAtEnd = nti.getLineageCount(iCount);
}
ttimes[nt][k] = timeToCoal + (k == 0 ? 0 : ttimes[nt][k-1]);
}
/*if( doubles != null ) {
if( ! Arrays.equals(doubles, ttimes[nt]) ) {
System.out.println(Arrays.toString(doubles) + " != " + Arrays.toString(ttimes[nt])
+ Arrays.toString(dirtyTrees) + " " + dirtyTrees);
}
}*/
dirtyTrees[nt] = false;
// System.out.print(nt + " " + Arrays.toString(dirtyTrees) + " " + dirtyTrees);
return true;
}
return false;
}
void setup(Tree[] trees, double[] indicatorParameter, double[] popSizes, boolean logSpace, boolean mid) {
// boolean was = dirty;
if( dirty ) {
boolean any = false;
for(int nt = 0; nt < ti.length; ++nt) {
if( setTreeTimes(nt, trees) ) {
any = true;
}
}
final int nd = indicatorParameter.length;
assert nd == alltimes.length + (type == VariableDemographicModel.Type.STEPWISE ? -1 : 0);
if( any ) {
// now we want to merge times together
int[] inds = new int[ttimes.length];
for(int k = 0; k < alltimes.length; ++k) {
int j = 0;
while( inds[j] == ttimes[j].length ) {
++j;
}
for(int l = j+1; l < inds.length; ++l) {
if( inds[l] < ttimes[l].length ) {
if( ttimes[l][inds[l]] < ttimes[j][inds[j]] ) {
j = l;
}
}
}
alltimes[k] = ttimes[j][inds[j]];
inds[j] ++;
}
}
// assumes lowest node has time 0. this is probably problematic when we come
// to deal with multiple trees
int tot = 1;
for(int k = 0; k < nd; ++k) {
if( indicatorParameter[k] > 0 ) {
++tot;
}
}
times = new double[tot+1];
values = new double[tot];
intervals = new double[tot -1];
times[0] = 0.0;
times[tot] = Double.POSITIVE_INFINITY;
values[0] = logSpace ? Math.exp(popSizes[0]) : popSizes[0];
int n = 0;
for(int k = 0; k < nd && n+1 < tot; ++k) {
if( indicatorParameter[k] > 0 ) {
times[n+1] = mid ? ((alltimes[k] + (k > 0 ? alltimes[k-1] : 0))/2) : alltimes[k];
values[n+1] = logSpace ? Math.exp(popSizes[k+1]) : popSizes[k+1];
intervals[n] = times[n+1] - times[n];
++n;
}
}
dirty = false;
}
/*System.out.println("after setup " + (was ? "(dirty)" : "") + " , alltimes " + Arrays.toString(alltimes)
+ " times " + Arrays.toString(times) + " values " + Arrays.toString(values) +
" inds " + Arrays.toString(indicatorParameter.getParameterValues())) ;*/
}
private int getIntervalIndexStep(final double t) {
int j = 0;
// ugly hack,
// when doubles are added in a different order and compared later, they can be a tiny bit off. With a
// stepwise model this creates a "one off" situation here, which is unpleasent.
// use float comarison here to avoid it
final float tf = (float)t;
while( tf > (float)times[j+1] ) ++j;
return j;
}
private int getIntervalIndexLin(final double t) {
int j = 0;
while( t > times[j+1] ) ++j;
return j;
}
public double getDemographic(double t) {
double p;
switch( type ) {
case STEPWISE:
{
final int j = getIntervalIndexStep(t);
p = values[j];
break;
}
case LINEAR:
{
final int j = getIntervalIndexLin(t);
if( j == values.length - 1 ) {
p = values[j];
break;
}
final double a = (t - times[j]) / (intervals[j]);
p = a * values[j+1] + (1-a) * values[j];
break;
}
default: throw new IllegalArgumentException("");
}
return p;
}
public double getIntensity(double t) {
return getIntegral(0, t);
}
public double getInverseIntensity(double x) {
assert false;
return 0;
}
private double intensityLinInterval(double start, double end, int index) {
final double dx = end - start;
final double popStart = values[index];
final double popDiff = (index < values.length - 1 ) ? values[index + 1] - popStart : 0.0;
if( popDiff == 0.0 ) {
return dx / popStart;
}
final double time0 = times[index];
final double interval = intervals[index];
assert (float)start <= (float)(time0 + interval) && start >= time0 && (float)end <= (float)(time0 + interval) && end >= time0;
// final double pop0 = popStart + ((start - time0) / interval) * popDiff;
// final double pop1 = popStart + ((end - time0) / interval) * popDiff;
// do same as above more effeciently
// final double r = popDiff / interval;
// final double x = popStart - time0 * r;
// final double pop0 = x + start * r;
// final double pop1 = x + end * r;
//better numerical stability but not perfect
double p1minusp0 = ((end-start)/interval) * popDiff;
double v = interval * (popStart / popDiff);
final double p1overp0 = (v + (end- time0)) / (v + (start- time0));
if( p1minusp0 == 0.0 || p1overp0 <= 0 ) {
// either dx == 0 or is very small (numerical inaccuracy)
final double pop0 = popStart + ((start - time0) / interval) * popDiff;
return dx/pop0;
}
return dx * Math.log(p1overp0) / p1minusp0;
// return dx * Math.log(pop1/pop0) / (pop1 - pop0);*/
}
private double intensityLinInterval(int index) {
final double interval = intervals[index];
final double pop0 = values[index];
final double pop1 = values[index+1];
if( pop0 == pop1 ) {
return interval / pop0;
}
return interval * Math.log(pop1/pop0) / (pop1 - pop0);
}
public double getIntegral(double start, double finish) {
double intensity = 0.0;
switch( type ) {
case STEPWISE:
{
final int first = getIntervalIndexStep(start);
final int last = getIntervalIndexStep(finish);
final double popStart = values[first];
if( first == last ) {
intensity = (finish - start) / popStart;
} else {
intensity = (times[first+1] - start) / popStart;
for(int k = first + 1; k < last; ++k) {
intensity += intervals[k]/values[k];
}
intensity += (finish - times[last]) / values[last];
}
break;
}
case LINEAR:
{
final int first = getIntervalIndexLin(start);
final int last = getIntervalIndexLin(finish);
if( first == last ) {
intensity += intensityLinInterval(start, finish, first);
} else {
// from first to end of interval
intensity += intensityLinInterval(start, times[first+1], first);
// intervals until (not including) last
for(int k = first + 1; k < last; ++k) {
intensity += intensityLinInterval(k);
}
// last interval
intensity += intensityLinInterval(times[last], finish, last);
}
break;
}
}
return intensity;
}
public int getNumArguments() {
assert false;
return 0;
}
public String getArgumentName(int n) {
assert false;
return null;
}
public double getArgument(int n) {
assert false;
return 0;
}
public void setArgument(int n, double value) {
assert false;
}
public double getLowerBound(int n) {
return 0.0;
}
public double getUpperBound(int n) {
return Double.POSITIVE_INFINITY;
}
public DemographicFunction getCopy() {
return null;
}
// not sure why we need this here
public double value(double x) {
return 1.0 / getDemographic(x);
}
public TreeIntervals getTreeIntervals(int nt) {
return ti[nt];
}
public double[] allTimePoints() {
return alltimes;
}
} |
package org.jgroups.protocols;
import EDU.oswego.cs.dl.util.concurrent.BoundedLinkedQueue;
import org.jgroups.*;
import org.jgroups.stack.Protocol;
import org.jgroups.util.*;
import org.jgroups.util.List;
import org.jgroups.util.Queue;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.text.NumberFormat;
/**
* Generic transport - specific implementations should extend this abstract class.
* Features which are provided to the subclasses include
* <ul>
* <li>version checking
* <li>marshalling and unmarshalling
* <li>message bundling (handling single messages, and message lists)
* <li>incoming packet handler
* <li>loopback
* </ul>
* A subclass has to override
* <ul>
* <li>{@link #sendToAllMembers(byte[], int, int)}
* <li>{@link #sendToSingleMember(org.jgroups.Address, byte[], int, int)}
* <li>{@link #init()}
* <li>{@link #start()}: subclasses <em>must</em> call super.start() <em>after</em> they initialize themselves
* (e.g., created their sockets).
* <li>{@link #stop()}: subclasses <em>must</em> call super.stop() after they deinitialized themselves
* <li>{@link #destroy()}
* </ul>
* The create() or start() method has to create a local address.<br>
* The {@link #receive(Address, Address, byte[], int, int)} method must
* be called by subclasses when a unicast or multicast message has been received.
* @author Bela Ban
* @version $Id: TP.java,v 1.58 2006/01/18 15:24:15 belaban Exp $
*/
public abstract class TP extends Protocol {
/** The address (host and port) of this member */
Address local_addr=null;
/** The name of the group to which this member is connected */
String channel_name=null;
/** The interface (NIC) which should be used by this transport */
InetAddress bind_addr=null;
/** Overrides bind_addr and -Dbind.address: let's the OS return the local host address */
boolean use_local_host=false;
/** If true, the transport should use all available interfaces to receive multicast messages
* @deprecated Use {@link receive_on_all_interfaces} instead */
boolean bind_to_all_interfaces=false;
/** If true, the transport should use all available interfaces to receive multicast messages */
boolean receive_on_all_interfaces=false;
/** List<NetworkInterface> of interfaces to receive multicasts on. The multicast receive socket will listen
* on all of these interfaces. This is a comma-separated list of IP addresses or interface names. E.g.
* "192.168.5.1,eth1,127.0.0.1". Duplicates are discarded; we only bind to an interface once.
* If this property is set, it override receive_on_all_interfaces.
*/
java.util.List receive_interfaces=null;
/** If true, the transport should use all available interfaces to send multicast messages. This means
* the same multicast message is sent N times, so use with care */
boolean send_on_all_interfaces=false;
/** List<NetworkInterface> of interfaces to send multicasts on. The multicast send socket will send the
* same multicast message on all of these interfaces. This is a comma-separated list of IP addresses or
* interface names. E.g. "192.168.5.1,eth1,127.0.0.1". Duplicates are discarded.
* If this property is set, it override send_on_all_interfaces.
*/
java.util.List send_interfaces=null;
/** The port to which the transport binds. 0 means to bind to any (ephemeral) port */
int bind_port=0;
int port_range=1; // 27-6-2003 bgooren, Only try one port by default
/** The members of this group (updated when a member joins or leaves) */
final Vector members=new Vector(11);
View view=null;
/** Pre-allocated byte stream. Used for marshalling messages. Will grow as needed */
final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(1024);
final ExposedBufferedOutputStream buf_out_stream=new ExposedBufferedOutputStream(out_stream, 1024);
final ExposedDataOutputStream dos=new ExposedDataOutputStream(buf_out_stream);
final ExposedByteArrayInputStream in_stream=new ExposedByteArrayInputStream(new byte[]{'0'});
final ExposedBufferedInputStream buf_in_stream=new ExposedBufferedInputStream(in_stream);
final DataInputStream dis=new DataInputStream(buf_in_stream);
/** If true, messages sent to self are treated specially: unicast messages are
* looped back immediately, multicast messages get a local copy first and -
* when the real copy arrives - it will be discarded. Useful for Window
* media (non)sense */
boolean loopback=false;
/** Discard packets with a different version. Usually minor version differences are okay. Setting this property
* to true means that we expect the exact same version on all incoming packets */
boolean discard_incompatible_packets=false;
/** Sometimes receivers are overloaded (they have to handle de-serialization etc).
* Packet handler is a separate thread taking care of de-serialization, receiver
* thread(s) simply put packet in queue and return immediately. Setting this to
* true adds one more thread */
boolean use_incoming_packet_handler=false;
/** Used by packet handler to store incoming DatagramPackets */
Queue incoming_packet_queue=null;
/** Dequeues DatagramPackets from packet_queue, unmarshalls them and
* calls <tt>handleIncomingUdpPacket()</tt> */
IncomingPacketHandler incoming_packet_handler=null;
/** Used by packet handler to store incoming Messages */
Queue incoming_msg_queue=null;
IncomingMessageHandler incoming_msg_handler;
/** Packets to be sent are stored in outgoing_queue and sent by a separate thread. Enabling this
* value uses an additional thread */
boolean use_outgoing_packet_handler=false;
/** Used by packet handler to store outgoing DatagramPackets */
BoundedLinkedQueue outgoing_queue=null;
/** max number of elements in the bounded outgoing_queue */
int outgoing_queue_max_size=2000;
OutgoingPacketHandler outgoing_packet_handler=null;
/** If set it will be added to <tt>local_addr</tt>. Used to implement
* for example transport independent addresses */
byte[] additional_data=null;
/** Maximum number of bytes for messages to be queued until they are sent. This value needs to be smaller
than the largest datagram packet size in case of UDP */
int max_bundle_size=AUTOCONF.senseMaxFragSizeStatic();
/** Max number of milliseconds until queued messages are sent. Messages are sent when max_bundle_size or
* max_bundle_timeout has been exceeded (whichever occurs faster)
*/
long max_bundle_timeout=20;
/** Enabled bundling of smaller messages into bigger ones */
boolean enable_bundling=false;
private Bundler bundler=null;
TimeScheduler timer=null;
private DiagnosticsHandler diag_handler=null;
boolean enable_diagnostics=true;
String diagnostics_addr="224.0.0.75";
int diagnostics_port=7500;
/** HashMap<Address, Address>. Keys=senders, values=destinations. For each incoming message M with sender S, adds
* an entry with key=S and value= sender's IP address and port.
*/
HashMap addr_translation_table=new HashMap();
boolean use_addr_translation=false;
TpHeader header;
final String name=getName();
static final byte LIST = 1; // we have a list of messages rather than a single message when set
static final byte MULTICAST = 2; // message is a multicast (versus a unicast) message when set
long num_msgs_sent=0, num_msgs_received=0, num_bytes_sent=0, num_bytes_received=0;
static NumberFormat f;
static {
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
}
/**
* Creates the TP protocol, and initializes the
* state variables, does however not start any sockets or threads.
*/
protected TP() {
}
/**
* debug only
*/
public String toString() {
return name + "(local address: " + local_addr + ')';
}
public void resetStats() {
num_msgs_sent=num_msgs_received=num_bytes_sent=num_bytes_received=0;
}
public long getNumMessagesSent() {return num_msgs_sent;}
public long getNumMessagesReceived() {return num_msgs_received;}
public long getNumBytesSent() {return num_bytes_sent;}
public long getNumBytesReceived() {return num_bytes_received;}
public String getBindAddress() {return bind_addr != null? bind_addr.toString() : "null";}
public void setBindAddress(String bind_addr) throws UnknownHostException {
this.bind_addr=InetAddress.getByName(bind_addr);
}
/** @deprecated Use {@link #isReceiveOnAllInterfaces()} instead */
public boolean getBindToAllInterfaces() {return receive_on_all_interfaces;}
public void setBindToAllInterfaces(boolean flag) {this.receive_on_all_interfaces=flag;}
public boolean isReceiveOnAllInterfaces() {return receive_on_all_interfaces;}
public java.util.List getReceiveInterfaces() {return receive_interfaces;}
public boolean isSendOnAllInterfaces() {return send_on_all_interfaces;}
public java.util.List getSendInterfaces() {return send_interfaces;}
public boolean isDiscardIncompatiblePackets() {return discard_incompatible_packets;}
public void setDiscardIncompatiblePackets(boolean flag) {discard_incompatible_packets=flag;}
public boolean isEnableBundling() {return enable_bundling;}
public void setEnableBundling(boolean flag) {enable_bundling=flag;}
public int getMaxBundleSize() {return max_bundle_size;}
public void setMaxBundleSize(int size) {max_bundle_size=size;}
public long getMaxBundleTimeout() {return max_bundle_timeout;}
public void setMaxBundleTimeout(long timeout) {max_bundle_timeout=timeout;}
public int getOutgoingQueueSize() {return outgoing_queue != null? outgoing_queue.size() : 0;}
public int getIncomingQueueSize() {return incoming_packet_queue != null? incoming_packet_queue.size() : 0;}
public Address getLocalAddress() {return local_addr;}
public String getChannelName() {return channel_name;}
public boolean isLoopback() {return loopback;}
public void setLoopback(boolean b) {loopback=b;}
public boolean isUseIncomingPacketHandler() {return use_incoming_packet_handler;}
public boolean isUseOutgoingPacketHandler() {return use_outgoing_packet_handler;}
public int getOutgoingQueueMaxSize() {return outgoing_queue != null? outgoing_queue_max_size : 0;}
public void setOutgoingQueueMaxSize(int new_size) {
if(outgoing_queue != null) {
outgoing_queue.setCapacity(new_size);
outgoing_queue_max_size=new_size;
}
}
public Map dumpStats() {
Map retval=super.dumpStats();
if(retval == null)
retval=new HashMap();
retval.put("num_msgs_sent", new Long(num_msgs_sent));
retval.put("num_msgs_received", new Long(num_msgs_received));
retval.put("num_bytes_sent", new Long(num_bytes_sent));
retval.put("num_bytes_received", new Long(num_bytes_received));
return retval;
}
/**
* Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N
* messages, one for each member
* @param data The data to be sent. This is not a copy, so don't modify it
* @param offset
* @param length
* @throws Exception
*/
public abstract void sendToAllMembers(byte[] data, int offset, int length) throws Exception;
/**
* Send to all members in the group. UDP would use an IP multicast message, whereas TCP would send N
* messages, one for each member
* @param dest Must be a non-null unicast address
* @param data The data to be sent. This is not a copy, so don't modify it
* @param offset
* @param length
* @throws Exception
*/
public abstract void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception;
public abstract String getInfo();
public abstract void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast);
public abstract void postUnmarshallingList(Message msg, Address dest, boolean multicast);
private StringBuffer _getInfo() {
StringBuffer sb=new StringBuffer();
sb.append(local_addr).append(" (").append(channel_name).append(") ").append("\n");
sb.append("local_addr=").append(local_addr).append("\n");
sb.append("group_name=").append(channel_name).append("\n");
sb.append("Version=").append(Version.description).append(", cvs=\"").append(Version.cvs).append("\"\n");
sb.append("view: ").append(view).append('\n');
sb.append(getInfo());
return sb;
}
private void handleDiagnosticProbe(SocketAddress sender, DatagramSocket sock, String request) {
try {
StringTokenizer tok=new StringTokenizer(request);
String req=tok.nextToken();
StringBuffer info=new StringBuffer("n/a");
if(req.trim().toLowerCase().startsWith("query")) {
ArrayList l=new ArrayList(tok.countTokens());
while(tok.hasMoreTokens())
l.add(tok.nextToken().trim().toLowerCase());
info=_getInfo();
if(l.contains("jmx")) {
Channel ch=stack.getChannel();
if(ch != null) {
Map m=ch.dumpStats();
StringBuffer sb=new StringBuffer();
sb.append("stats:\n");
for(Iterator it=m.entrySet().iterator(); it.hasNext();) {
sb.append(it.next()).append("\n");
}
info.append(sb);
}
}
if(l.contains("props")) {
String p=stack.printProtocolSpecAsXML();
info.append("\nprops:\n").append(p);
}
}
byte[] diag_rsp=info.toString().getBytes();
if(log.isDebugEnabled())
log.debug("sending diag response to " + sender);
sendResponse(sock, sender, diag_rsp);
}
catch(Throwable t) {
if(log.isErrorEnabled())
log.error("failed sending diag rsp to " + sender, t);
}
}
private static void sendResponse(DatagramSocket sock, SocketAddress sender, byte[] buf) throws IOException {
DatagramPacket p=new DatagramPacket(buf, 0, buf.length, sender);
sock.send(p);
}
public void init() throws Exception {
super.init();
if(bind_addr != null) {
Map m=new HashMap(1);
m.put("bind_addr", bind_addr);
passUp(new Event(Event.CONFIG, m));
}
}
/**
* Creates the unicast and multicast sockets and starts the unicast and multicast receiver threads
*/
public void start() throws Exception {
timer=stack.timer;
if(timer == null)
throw new Exception("timer is null");
if(enable_diagnostics) {
diag_handler=new DiagnosticsHandler();
diag_handler.start();
}
if(use_incoming_packet_handler) {
incoming_packet_queue=new Queue();
incoming_packet_handler=new IncomingPacketHandler();
incoming_packet_handler.start();
}
if(loopback) {
incoming_msg_queue=new Queue();
incoming_msg_handler=new IncomingMessageHandler();
incoming_msg_handler.start();
}
if(use_outgoing_packet_handler) {
outgoing_queue=new BoundedLinkedQueue(outgoing_queue_max_size);
outgoing_packet_handler=new OutgoingPacketHandler();
outgoing_packet_handler.start();
}
if(enable_bundling) {
bundler=new Bundler();
}
passUp(new Event(Event.SET_LOCAL_ADDRESS, local_addr));
}
public void stop() {
if(diag_handler != null) {
diag_handler.stop();
diag_handler=null;
}
// 1. Stop the outgoing packet handler thread
if(outgoing_packet_handler != null)
outgoing_packet_handler.stop();
// 2. Stop the incoming packet handler thread
if(incoming_packet_handler != null)
incoming_packet_handler.stop();
// 3. Finally stop the incoming message handler
if(incoming_msg_handler != null)
incoming_msg_handler.stop();
}
/**
* Setup the Protocol instance according to the configuration string
* @return true if no other properties are left.
* false if the properties still have data in them, ie ,
* properties are left over and not handled by the protocol stack
*/
public boolean setProperties(Properties props) {
String str;
String tmp = null;
super.setProperties(props);
try {
tmp=System.getProperty("bind.address");
if(Util.isBindAddressPropertyIgnored()) {
tmp=null;
}
}
catch (SecurityException ex){
}
if(tmp != null)
str=tmp;
else
str=props.getProperty("bind_addr");
if(str != null) {
try {
bind_addr=InetAddress.getByName(str);
}
catch(UnknownHostException unknown) {
if(log.isFatalEnabled()) log.fatal("(bind_addr): host " + str + " not known");
return false;
}
props.remove("bind_addr");
}
str=props.getProperty("use_local_host");
if(str != null) {
use_local_host=new Boolean(str).booleanValue();
props.remove("use_local_host");
}
str=props.getProperty("bind_to_all_interfaces");
if(str != null) {
receive_on_all_interfaces=new Boolean(str).booleanValue();
props.remove("bind_to_all_interfaces");
log.warn("bind_to_all_interfaces has been deprecated; use receive_on_all_interfaces instead");
}
str=props.getProperty("receive_on_all_interfaces");
if(str != null) {
receive_on_all_interfaces=new Boolean(str).booleanValue();
props.remove("receive_on_all_interfaces");
}
str=props.getProperty("receive_interfaces");
if(str != null) {
try {
receive_interfaces=parseInterfaceList(str);
props.remove("receive_interfaces");
}
catch(Exception e) {
log.error("error determining interfaces (" + str + ")", e);
return false;
}
}
str=props.getProperty("send_on_all_interfaces");
if(str != null) {
send_on_all_interfaces=new Boolean(str).booleanValue();
props.remove("send_on_all_interfaces");
}
str=props.getProperty("send_interfaces");
if(str != null) {
try {
send_interfaces=parseInterfaceList(str);
props.remove("send_interfaces");
}
catch(Exception e) {
log.error("error determining interfaces (" + str + ")", e);
return false;
}
}
str=props.getProperty("bind_port");
if(str != null) {
bind_port=Integer.parseInt(str);
props.remove("bind_port");
}
str=props.getProperty("port_range");
if(str != null) {
port_range=Integer.parseInt(str);
props.remove("port_range");
}
str=props.getProperty("loopback");
if(str != null) {
loopback=Boolean.valueOf(str).booleanValue();
props.remove("loopback");
}
str=props.getProperty("discard_incompatible_packets");
if(str != null) {
discard_incompatible_packets=Boolean.valueOf(str).booleanValue();
props.remove("discard_incompatible_packets");
}
// this is deprecated, just left for compatibility (use use_incoming_packet_handler)
str=props.getProperty("use_packet_handler");
if(str != null) {
use_incoming_packet_handler=Boolean.valueOf(str).booleanValue();
props.remove("use_packet_handler");
if(warn) log.warn("'use_packet_handler' is deprecated; use 'use_incoming_packet_handler' instead");
}
str=props.getProperty("use_incoming_packet_handler");
if(str != null) {
use_incoming_packet_handler=Boolean.valueOf(str).booleanValue();
props.remove("use_incoming_packet_handler");
}
str=props.getProperty("use_outgoing_packet_handler");
if(str != null) {
use_outgoing_packet_handler=Boolean.valueOf(str).booleanValue();
props.remove("use_outgoing_packet_handler");
}
str=props.getProperty("outgoing_queue_max_size");
if(str != null) {
outgoing_queue_max_size=Integer.parseInt(str);
props.remove("outgoing_queue_max_size");
if(outgoing_queue_max_size <= 0) {
if(log.isWarnEnabled())
log.warn("outgoing_queue_max_size of " + outgoing_queue_max_size + " is invalid, setting it to 1");
outgoing_queue_max_size=1;
}
}
str=props.getProperty("max_bundle_size");
if(str != null) {
int bundle_size=Integer.parseInt(str);
if(bundle_size > max_bundle_size) {
if(log.isErrorEnabled()) log.error("max_bundle_size (" + bundle_size +
") is greater than largest TP fragmentation size (" + max_bundle_size + ')');
return false;
}
if(bundle_size <= 0) {
if(log.isErrorEnabled()) log.error("max_bundle_size (" + bundle_size + ") is <= 0");
return false;
}
max_bundle_size=bundle_size;
props.remove("max_bundle_size");
}
str=props.getProperty("max_bundle_timeout");
if(str != null) {
max_bundle_timeout=Long.parseLong(str);
if(max_bundle_timeout <= 0) {
if(log.isErrorEnabled()) log.error("max_bundle_timeout of " + max_bundle_timeout + " is invalid");
return false;
}
props.remove("max_bundle_timeout");
}
str=props.getProperty("enable_bundling");
if(str != null) {
enable_bundling=Boolean.valueOf(str).booleanValue();
props.remove("enable_bundling");
}
str=props.getProperty("use_addr_translation");
if(str != null) {
use_addr_translation=Boolean.valueOf(str).booleanValue();
props.remove("use_addr_translation");
}
str=props.getProperty("enable_diagnostics");
if(str != null) {
enable_diagnostics=Boolean.valueOf(str).booleanValue();
props.remove("enable_diagnostics");
}
str=props.getProperty("diagnostics_addr");
if(str != null) {
diagnostics_addr=str;
props.remove("diagnostics_addr");
}
str=props.getProperty("diagnostics_port");
if(str != null) {
diagnostics_port=Integer.parseInt(str);
props.remove("diagnostics_port");
}
if(enable_bundling) {
//if (use_outgoing_packet_handler == false)
// if(warn) log.warn("enable_bundling is true; setting use_outgoing_packet_handler=true");
// use_outgoing_packet_handler=true;
}
return true;
}
/**
* This prevents the up-handler thread to be created, which essentially is superfluous:
* messages are received from the network rather than from a layer below.
* DON'T REMOVE !
*/
public void startUpHandler() {
}
/**
* handle the UP event.
* @param evt - the event being send from the stack
*/
public void up(Event evt) {
switch(evt.getType()) {
case Event.CONFIG:
passUp(evt);
if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
return;
}
passUp(evt);
}
/**
* Caller by the layer above this layer. Usually we just put this Message
* into the send queue and let one or more worker threads handle it. A worker thread
* then removes the Message from the send queue, performs a conversion and adds the
* modified Message to the send queue of the layer below it, by calling down()).
*/
public void down(Event evt) {
if(evt.getType() != Event.MSG) { // unless it is a message handle it and respond
handleDownEvent(evt);
return;
}
Message msg=(Message)evt.getArg();
if(header != null) {
// added patch by Roland Kurmann (March 20 2003)
// msg.putHeader(name, new TpHeader(channel_name));
msg.putHeader(name, header);
}
// Because we don't call Protocol.passDown(), we notify the observer directly (e.g. PerfObserver).
// This way, we still have performance numbers for TP
if(observer != null)
observer.passDown(evt);
setSourceAddress(msg); // very important !! listToBuffer() will fail with a null src address !!
if(trace) {
StringBuffer sb=new StringBuffer("sending msg to ").append(msg.getDest()).
append(" (src=").append(msg.getSrc()).append("), headers are ").append(msg.getHeaders());
log.trace(sb.toString());
}
// Don't send if destination is local address. Instead, switch dst and src and put in up_queue.
// If multicast message, loopback a copy directly to us (but still multicast). Once we receive this,
// we will discard our own multicast message
Address dest=msg.getDest();
boolean multicast=dest == null || dest.isMulticastAddress();
if(loopback && (multicast || dest.equals(local_addr))) {
Message copy=msg.copy();
// copy.removeHeader(name); // we don't remove the header
copy.setSrc(local_addr);
// copy.setDest(dest);
if(trace) log.trace(new StringBuffer("looping back message ").append(copy));
try {
incoming_msg_queue.add(copy);
}
catch(QueueClosedException e) {
// log.error("failed adding looped back message to incoming_msg_queue", e);
}
if(!multicast)
return;
}
try {
if(use_outgoing_packet_handler)
outgoing_queue.put(msg);
else
send(msg, dest, multicast);
}
catch(QueueClosedException closed_ex) {
}
catch(InterruptedException interruptedEx) {
}
catch(Throwable e) {
if(log.isErrorEnabled()) log.error("failed sending message", e);
}
}
/**
* If the sender is null, set our own address. We cannot just go ahead and set the address
* anyway, as we might be sending a message on behalf of someone else ! E.gin case of
* retransmission, when the original sender has crashed, or in a FLUSH protocol when we
* have to return all unstable messages with the FLUSH_OK response.
*/
private void setSourceAddress(Message msg) {
if(msg.getSrc() == null)
msg.setSrc(local_addr);
}
/**
* Subclasses must call this method when a unicast or multicast message has been received.
* Declared final so subclasses cannot override this method.
*
* @param dest
* @param sender
* @param data
* @param offset
* @param length
*/
protected final void receive(Address dest, Address sender, byte[] data, int offset, int length) {
if(data == null) return;
// if(length == 4) { // received a diagnostics probe
// if(data[offset] == 'd' && data[offset+1] == 'i' && data[offset+2] == 'a' && data[offset+3] == 'g') {
// handleDiagnosticProbe(sender);
// return;
boolean mcast=dest == null || dest.isMulticastAddress();
if(trace){
StringBuffer sb=new StringBuffer("received (");
sb.append(mcast? "mcast)" : "ucast) ").append(length).append(" bytes from ").append(sender);
log.trace(sb.toString());
}
try {
if(use_incoming_packet_handler) {
byte[] tmp=new byte[length];
System.arraycopy(data, offset, tmp, 0, length);
incoming_packet_queue.add(new IncomingQueueEntry(dest, sender, tmp, offset, length));
}
else
handleIncomingPacket(dest, sender, data, offset, length);
}
catch(Throwable t) {
if(log.isErrorEnabled())
log.error(new StringBuffer("failed handling data from ").append(sender), t);
}
}
/**
* Processes a packet read from either the multicast or unicast socket. Needs to be synchronized because
* mcast or unicast socket reads can be concurrent.
* Correction (bela April 19 2005): we access no instance variables, all vars are allocated on the stack, so
* this method should be reentrant: removed 'synchronized' keyword
*/
private void handleIncomingPacket(Address dest, Address sender, byte[] data, int offset, int length) {
Message msg=null;
List l=null; // used if bundling is enabled
short version;
boolean is_message_list, multicast;
byte flags;
try {
synchronized(in_stream) {
in_stream.setData(data, offset, length);
buf_in_stream.reset(length);
version=dis.readShort();
if(Version.compareTo(version) == false) {
if(warn) {
StringBuffer sb=new StringBuffer();
sb.append("packet from ").append(sender).append(" has different version (").append(version);
sb.append(") from ours (").append(Version.printVersion()).append("). ");
if(discard_incompatible_packets)
sb.append("Packet is discarded");
else
sb.append("This may cause problems");
log.warn(sb);
}
if(discard_incompatible_packets)
return;
}
flags=dis.readByte();
is_message_list=(flags & LIST) == LIST;
multicast=(flags & MULTICAST) == MULTICAST;
if(is_message_list)
l=bufferToList(dis, dest, multicast);
else
msg=bufferToMessage(dis, dest, sender, multicast);
}
LinkedList msgs=new LinkedList();
if(is_message_list) {
for(Enumeration en=l.elements(); en.hasMoreElements();)
msgs.add(en.nextElement());
}
else
msgs.add(msg);
Address src;
for(Iterator it=msgs.iterator(); it.hasNext();) {
msg=(Message)it.next();
src=msg.getSrc();
if(loopback) {
if(multicast && src != null && local_addr.equals(src)) { // discard own loopback multicast packets
it.remove();
}
}
else
handleIncomingMessage(msg);
}
if(incoming_msg_queue != null && msgs.size() > 0)
incoming_msg_queue.addAll(msgs);
}
catch(QueueClosedException closed_ex) {
; // swallow exception
}
catch(Throwable t) {
if(log.isErrorEnabled())
log.error("failed unmarshalling message", t);
}
}
private void handleIncomingMessage(Message msg) {
Event evt;
TpHeader hdr;
if(stats) {
num_msgs_received++;
num_bytes_received+=msg.getLength();
}
evt=new Event(Event.MSG, msg);
if(trace) {
StringBuffer sb=new StringBuffer("message is ").append(msg).append(", headers are ").append(msg.getHeaders());
log.trace(sb);
}
/* Because Protocol.up() is never called by this bottommost layer, we call up() directly in the observer.
* This allows e.g. PerfObserver to get the time of reception of a message */
if(observer != null)
observer.up(evt, up_queue.size());
hdr=(TpHeader)msg.getHeader(name); // replaced removeHeader() with getHeader()
if(hdr != null) {
/* Discard all messages destined for a channel with a different name */
String ch_name=hdr.channel_name;
// Discard if message's group name is not the same as our group name unless the
// message is a diagnosis message (special group name DIAG_GROUP)
if(ch_name != null && channel_name != null && !channel_name.equals(ch_name) &&
!ch_name.equals(Util.DIAG_GROUP)) {
if(warn)
log.warn(new StringBuffer("discarded message from different group \"").append(ch_name).
append("\" (our group is \"").append(channel_name).append("\"). Sender was").append(msg.getSrc()));
return;
}
}
else {
if(trace)
log.trace(new StringBuffer("message does not have a transport header, msg is ").append(msg).
append(", headers are ").append(msg.getHeaders()).append(", will be discarded"));
return;
}
passUp(evt);
}
/** Internal method to serialize and send a message. This method is not reentrant */
private void send(Message msg, Address dest, boolean multicast) throws Exception {
if(enable_bundling) {
bundler.send(msg, dest);
return;
}
// Needs to be synchronized because we can have possible concurrent access, e.g.
// Discovery uses a separate thread to send out discovery messages
// We would *not* need to sync between send(), OutgoingPacketHandler and BundlingOutgoingPacketHandler,
// because only *one* of them is enabled
Buffer buf;
synchronized(out_stream) {
buf=messageToBuffer(msg, multicast);
doSend(buf, dest, multicast);
}
}
private void doSend(Buffer buf, Address dest, boolean multicast) throws Exception {
if(stats) {
num_msgs_sent++;
num_bytes_sent+=buf.getLength();
}
if(multicast) {
sendToAllMembers(buf.getBuf(), buf.getOffset(), buf.getLength());
}
else {
sendToSingleMember(dest, buf.getBuf(), buf.getOffset(), buf.getLength());
}
}
/**
* This method needs to be synchronized on out_stream when it is called
* @param msg
* @return
* @throws java.io.IOException
*/
private Buffer messageToBuffer(Message msg, boolean multicast) throws Exception {
Buffer retval;
byte flags=0;
out_stream.reset();
buf_out_stream.reset(out_stream.getCapacity());
dos.reset();
dos.writeShort(Version.version); // write the version
if(multicast)
flags+=MULTICAST;
dos.writeByte(flags);
// preMarshalling(msg, dest, src); // allows for optimization by subclass
msg.writeTo(dos);
// postMarshalling(msg, dest, src); // allows for optimization by subclass
dos.flush();
retval=new Buffer(out_stream.getRawBuffer(), 0, out_stream.size());
return retval;
}
private Message bufferToMessage(DataInputStream instream, Address dest, Address sender, boolean multicast) throws Exception {
Message msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(instream);
postUnmarshalling(msg, dest, sender, multicast); // allows for optimization by subclass
return msg;
}
private Buffer listToBuffer(List l, boolean multicast) throws Exception {
Buffer retval;
Address src;
Message msg;
byte flags=0;
int len=l != null? l.size() : 0;
boolean src_written=false;
out_stream.reset();
buf_out_stream.reset(out_stream.getCapacity());
dos.reset();
dos.writeShort(Version.version);
flags+=LIST;
if(multicast)
flags+=MULTICAST;
dos.writeByte(flags);
dos.writeInt(len);
for(Enumeration en=l.elements(); en.hasMoreElements();) {
msg=(Message)en.nextElement();
src=msg.getSrc();
if(!src_written) {
Util.writeAddress(src, dos);
src_written=true;
}
// msg.setSrc(null);
msg.writeTo(dos);
// msg.setSrc(src);
}
dos.flush();
retval=new Buffer(out_stream.getRawBuffer(), 0, out_stream.size());
return retval;
}
private List bufferToList(DataInputStream instream, Address dest, boolean multicast) throws Exception {
List l=new List();
DataInputStream in=null;
int len;
Message msg;
Address src;
try {
len=instream.readInt();
src=Util.readAddress(instream);
for(int i=0; i < len; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(instream);
postUnmarshallingList(msg, dest, multicast);
msg.setSrc(src);
l.add(msg);
}
return l;
}
finally {
Util.closeInputStream(in);
}
}
/**
*
* @param s
* @return List<NetworkInterface>
*/
private java.util.List parseInterfaceList(String s) throws Exception {
java.util.List interfaces=new ArrayList(10);
if(s == null)
return null;
StringTokenizer tok=new StringTokenizer(s, ",");
String interface_name;
NetworkInterface intf;
while(tok.hasMoreTokens()) {
interface_name=tok.nextToken();
// try by name first (e.g. (eth0")
intf=NetworkInterface.getByName(interface_name);
// next try by IP address or symbolic name
if(intf == null)
intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));
if(intf == null)
throw new Exception("interface " + interface_name + " not found");
if(interfaces.contains(intf)) {
log.warn("did not add interface " + interface_name + " (already present in " + print(interfaces) + ")");
}
else {
interfaces.add(intf);
}
}
return interfaces;
}
private static String print(java.util.List interfaces) {
StringBuffer sb=new StringBuffer();
boolean first=true;
NetworkInterface intf;
for(Iterator it=interfaces.iterator(); it.hasNext();) {
intf=(NetworkInterface)it.next();
if(first) {
first=false;
}
else {
sb.append(", ");
}
sb.append(intf.getName());
}
return sb.toString();
}
protected void handleDownEvent(Event evt) {
switch(evt.getType()) {
case Event.TMP_VIEW:
case Event.VIEW_CHANGE:
synchronized(members) {
view=(View)evt.getArg();
members.clear();
Vector tmpvec=view.getMembers();
members.addAll(tmpvec);
}
break;
case Event.GET_LOCAL_ADDRESS: // return local address -> Event(SET_LOCAL_ADDRESS, local)
passUp(new Event(Event.SET_LOCAL_ADDRESS, local_addr));
break;
case Event.CONNECT:
channel_name=(String)evt.getArg();
header=new TpHeader(channel_name);
// removed March 18 2003 (bela), not needed (handled by GMS)
// changed July 2 2003 (bela): we discard CONNECT_OK at the GMS level anyway, this might
// be needed if we run without GMS though
passUp(new Event(Event.CONNECT_OK));
break;
case Event.DISCONNECT:
passUp(new Event(Event.DISCONNECT_OK));
break;
case Event.CONFIG:
if(log.isDebugEnabled()) log.debug("received CONFIG event: " + evt.getArg());
handleConfigEvent((HashMap)evt.getArg());
break;
}
}
protected void handleConfigEvent(HashMap map) {
if(map == null) return;
if(map.containsKey("additional_data"))
additional_data=(byte[])map.get("additional_data");
}
static class IncomingQueueEntry {
Address dest=null;
Address sender=null;
byte[] buf;
int offset, length;
IncomingQueueEntry(Address dest, Address sender, byte[] buf, int offset, int length) {
this.dest=dest;
this.sender=sender;
this.buf=buf;
this.offset=offset;
this.length=length;
}
}
/**
* This thread fetches byte buffers from the packet_queue, converts them into messages and passes them up
* to the higher layer (done in handleIncomingUdpPacket()).
*/
class IncomingPacketHandler implements Runnable {
Thread t=null;
void start() {
if(t == null || !t.isAlive()) {
t=new Thread(this, "IncomingPacketHandler");
t.setDaemon(true);
t.start();
}
}
void stop() {
incoming_packet_queue.close(true); // should terminate the packet_handler thread too
t=null;
}
public void run() {
IncomingQueueEntry entry;
while(!incoming_packet_queue.closed() && Thread.currentThread().equals(t)) {
try {
entry=(IncomingQueueEntry)incoming_packet_queue.remove();
handleIncomingPacket(entry.dest, entry.sender, entry.buf, entry.offset, entry.length);
}
catch(QueueClosedException closed_ex) {
break;
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("error processing incoming packet", ex);
}
}
if(trace) log.trace("incoming packet handler terminating");
}
}
class IncomingMessageHandler implements Runnable {
Thread t;
int i=0;
public void start() {
if(t == null || !t.isAlive()) {
t=new Thread(this, "IncomingMessageHandler");
t.setDaemon(true);
t.start();
}
}
public void stop() {
incoming_msg_queue.close(true);
t=null;
}
public void run() {
Message msg;
while(!incoming_msg_queue.closed() && Thread.currentThread().equals(t)) {
try {
msg=(Message)incoming_msg_queue.remove();
handleIncomingMessage(msg);
}
catch(QueueClosedException closed_ex) {
break;
}
catch(Throwable ex) {
if(log.isErrorEnabled())
log.error("error processing incoming message", ex);
}
}
if(trace) log.trace("incoming message handler terminating");
}
}
/**
* This thread fetches byte buffers from the outgoing_packet_queue, converts them into messages and sends them
* using the unicast or multicast socket
*/
class OutgoingPacketHandler implements Runnable {
Thread t=null;
byte[] buf;
DatagramPacket packet;
void start() {
if(t == null || !t.isAlive()) {
t=new Thread(this, "OutgoingPacketHandler");
t.setDaemon(true);
t.start();
}
}
void stop() {
Thread tmp=t;
t=null;
if(tmp != null) {
tmp.interrupt();
}
}
public void run() {
Message msg;
while(t != null && Thread.currentThread().equals(t)) {
try {
msg=(Message)outgoing_queue.take();
handleMessage(msg);
}
catch(QueueClosedException closed_ex) {
break;
}
catch(InterruptedException interruptedEx) {
}
catch(Throwable th) {
if(log.isErrorEnabled()) log.error("exception sending packet", th);
}
msg=null; // let's give the garbage collector a hand... this is probably useless though
}
if(trace) log.trace("outgoing message handler terminating");
}
protected void handleMessage(Message msg) throws Throwable {
Address dest=msg.getDest();
send(msg, dest, dest == null || dest.isMulticastAddress());
}
}
/**
* Bundles smaller messages into bigger ones. Collects messages in a list until
* messages of a total of <tt>max_bundle_size bytes</tt> have accumulated, or until
* <tt>max_bundle_timeout</tt> milliseconds have elapsed, whichever is first. Messages
* are unbundled at the receiver.
*/
private class BundlingOutgoingPacketHandler extends OutgoingPacketHandler {
/** HashMap<Address, List<Message>>. Keys are destinations, values are lists of Messages */
final HashMap msgs=new HashMap(11);
long count=0; // current number of bytes accumulated
int num_msgs=0;
long start=0;
long wait_time=0; // wait for removing messages from the queue
private void init() {
wait_time=start=count=0;
}
void start() {
init();
super.start();
t.setName("BundlingOutgoingPacketHandler");
}
void stop() {
// bundleAndSend();
super.stop();
}
public void run() {
Message msg;
long length;
while(t != null && Thread.currentThread().equals(t)) {
try {
msg=(Message)outgoing_queue.poll(wait_time);
if(msg == null)
throw new TimeoutException();
length=msg.size();
checkLength(length);
if(start == 0)
start=System.currentTimeMillis();
if(count + length >= max_bundle_size) {
bundleAndSend();
count=0;
start=System.currentTimeMillis();
}
addMessage(msg);
count+=length;
wait_time=max_bundle_timeout - (System.currentTimeMillis() - start);
if(wait_time <= 0) {
bundleAndSend();
init();
}
}
catch(QueueClosedException queue_closed_ex) {
bundleAndSend();
break;
}
catch(TimeoutException timeout_ex) {
bundleAndSend();
init();
}
catch(Throwable ex) {
log.error("failure in bundling", ex);
}
}
if(trace) log.trace("BundlingOutgoingPacketHandler thread terminated");
}
private void checkLength(long len) throws Exception {
if(len > max_bundle_size)
throw new Exception("message size (" + len + ") is greater than max bundling size (" + max_bundle_size +
"). Set the fragmentation/bundle size in FRAG and TP correctly");
}
private void addMessage(Message msg) { // no sync needed, never called by multiple threads concurrently
List tmp;
Address dst=msg.getDest();
tmp=(List)msgs.get(dst);
if(tmp == null) {
tmp=new List();
msgs.put(dst, tmp);
}
tmp.add(msg);
num_msgs++;
}
private void bundleAndSend() {
Map.Entry entry;
Address dst;
Buffer buffer;
List l;
long stop_time=System.currentTimeMillis();
if(msgs.size() == 0)
return;
try {
if(trace) {
StringBuffer sb=new StringBuffer("sending ").append(num_msgs).append(" msgs (");
sb.append(count).append(" bytes, ").append(stop_time-start).append("ms)");
sb.append(" to ").append(msgs.size()).append(" destination(s)");
if(msgs.size() > 1) sb.append(" (dests=").append(msgs.keySet()).append(")");
log.trace(sb.toString());
}
boolean multicast;
for(Iterator it=msgs.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
l=(List)entry.getValue();
if(l.size() == 0)
continue;
dst=(Address)entry.getKey();
multicast=dst == null || dst.isMulticastAddress();
synchronized(out_stream) {
try {
buffer=listToBuffer(l, multicast);
doSend(buffer, dst, multicast);
}
catch(Throwable e) {
if(log.isErrorEnabled()) log.error("exception sending msg", e);
}
}
}
}
finally {
msgs.clear();
num_msgs=0;
}
}
}
private class Bundler {
/** HashMap<Address, List<Message>>. Keys are destinations, values are lists of Messages */
final HashMap msgs=new HashMap(36);
long count=0; // current number of bytes accumulated
int num_msgs=0;
long start=0;
BundlingTimer bundling_timer=null;
private synchronized void send(Message msg, Address dest) throws Exception {
long length=msg.size();
checkLength(length);
if(start == 0)
start=System.currentTimeMillis();
if(count + length >= max_bundle_size) {
cancelTimer();
bundleAndSend(); // clears msgs and resets num_msgs
}
addMessage(msg, dest);
count+=length;
startTimer(); // start timer if not running
}
/** Never called concurrently with cancelTimer - no need for synchronization */
private void startTimer() {
if(bundling_timer == null || bundling_timer.cancelled()) {
bundling_timer=new BundlingTimer();
timer.add(bundling_timer);
}
}
/** Never called concurrently with startTimer() - no need for synchronization */
private void cancelTimer() {
if(bundling_timer != null) {
bundling_timer.cancel();
bundling_timer=null;
}
}
private void addMessage(Message msg, Address dest) { // no sync needed, never called by multiple threads concurrently
List tmp;
synchronized(msgs) {
tmp=(List)msgs.get(dest);
if(tmp == null) {
tmp=new List();
msgs.put(dest, tmp);
}
tmp.add(msg);
num_msgs++;
}
}
private void bundleAndSend() {
Map.Entry entry;
Address dst;
Buffer buffer;
List l;
synchronized(msgs) {
if(msgs.size() == 0)
return;
try {
if(trace) {
long stop=System.currentTimeMillis();
double percentage=100.0 / max_bundle_size * count;
StringBuffer sb=new StringBuffer("sending ").append(num_msgs).append(" msgs (");
sb.append(count).append(" bytes (" + f.format(percentage) + "% of max_bundle_size), collected in "+
+ (stop-start) + "ms) to ").append(msgs.size()).
append(" destination(s)");
if(msgs.size() > 1) sb.append(" (dests=").append(msgs.keySet()).append(")");
log.trace(sb.toString());
}
boolean multicast;
for(Iterator it=msgs.entrySet().iterator(); it.hasNext();) {
entry=(Map.Entry)it.next();
l=(List)entry.getValue();
if(l.size() == 0)
continue;
dst=(Address)entry.getKey();
multicast=dst == null || dst.isMulticastAddress();
synchronized(out_stream) {
try {
buffer=listToBuffer(l, multicast);
doSend(buffer, dst, multicast);
}
catch(Throwable e) {
if(log.isErrorEnabled()) log.error("exception sending msg", e);
}
}
}
}
finally {
msgs.clear();
num_msgs=0;
start=0;
count=0;
}
}
}
private void checkLength(long len) throws Exception {
if(len > max_bundle_size)
throw new Exception("message size (" + len + ") is greater than max bundling size (" + max_bundle_size +
"). Set the fragmentation/bundle size in FRAG and TP correctly");
}
private class BundlingTimer implements TimeScheduler.Task {
boolean cancelled=false;
void cancel() {
cancelled=true;
}
public boolean cancelled() {
return cancelled;
}
public long nextInterval() {
return max_bundle_timeout;
}
public void run() {
bundleAndSend();
cancelled=true;
}
}
}
private class DiagnosticsHandler implements Runnable {
Thread t=null;
MulticastSocket diag_sock=null;
DiagnosticsHandler() {
}
void start() throws IOException {
diag_sock=new MulticastSocket(diagnostics_port);
java.util.List interfaces=Util.getAllAvailableInterfaces();
bindToInterfaces(interfaces, diag_sock);
if(t == null || !t.isAlive()) {
t=new Thread(this, "DiagnosticsHandler");
t.setDaemon(true);
t.start();
}
}
void stop() {
if(diag_sock != null)
diag_sock.close();
t=null;
}
public void run() {
byte[] buf=new byte[1500]; // MTU on most LANs
DatagramPacket packet;
while(!diag_sock.isClosed() && Thread.currentThread().equals(t)) {
packet=new DatagramPacket(buf, 0, buf.length);
try {
diag_sock.receive(packet);
handleDiagnosticProbe(packet.getSocketAddress(), diag_sock,
new String(packet.getData(), packet.getOffset(), packet.getLength()));
}
catch(IOException e) {
}
}
}
private void bindToInterfaces(java.util.List interfaces, MulticastSocket s) {
SocketAddress group_addr=new InetSocketAddress(diagnostics_addr, diagnostics_port);
for(Iterator it=interfaces.iterator(); it.hasNext();) {
NetworkInterface i=(NetworkInterface)it.next();
try {
if (i.getInetAddresses().hasMoreElements()) { // fix for VM crash - suggested by JJalenak@netopia.com
s.joinGroup(group_addr, i);
if(trace)
log.trace("joined " + group_addr + " on " + i.getName());
}
}
catch(IOException e) {
log.warn("failed to join " + group_addr + " on " + i.getName() + ": " + e);
}
}
}
}
} |
package edu.syr.pcpratts.rootbeer.runtime;
import com.sun.java.swing.plaf.windows.WindowsTreeUI;
import edu.syr.pcpratts.rootbeer.runtime.memory.Memory;
import edu.syr.pcpratts.rootbeer.runtime.remap.GpuAtomicLong;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.TreeMap;
public abstract class Serializer {
public Memory mMem;
public Memory mTextureMem;
private static final Map<Object, Long> mWriteToGpuCache;
private static final Map<Long, Object> mReverseWriteToGpuCache;
private static final Map<Long, Object> mReadFromGpuCache;
private static Map<Long, Integer> m_classRefToTypeNumber;
private ReadOnlyAnalyzer m_Analyzer;
static {
mWriteToGpuCache = new IdentityHashMap<Object, Long>();
mReverseWriteToGpuCache = new HashMap<Long, Object>();
mReadFromGpuCache = new HashMap<Long, Object>();
m_classRefToTypeNumber = new HashMap<Long, Integer>();
}
public Serializer(Memory mem, Memory texture_mem){
mMem = mem;
mTextureMem = texture_mem;
mReadFromGpuCache.clear();
mWriteToGpuCache.clear();
mReverseWriteToGpuCache.clear();
m_classRefToTypeNumber.clear();
}
public void setAnalyzer(ReadOnlyAnalyzer analyzer){
m_Analyzer = analyzer;
}
public void writeStaticsToHeap(){
doWriteStaticsToHeap();
}
public long writeToHeap(Object o){
return writeToHeap(o, true);
}
private static class WriteCacheResult {
public long m_Ref;
public boolean m_NeedToWrite;
public WriteCacheResult(long ref, boolean need_to_write){
m_Ref = ref;
m_NeedToWrite = need_to_write;
}
}
public void addClassRef(long ref, int class_number){
m_classRefToTypeNumber.put(ref, class_number);
}
public int[] getClassRefArray(){
int max_type = 0;
for(int num : m_classRefToTypeNumber.values()){
if(num > max_type){
max_type = num;
}
}
int[] ret = new int[max_type+1];
for(long value : m_classRefToTypeNumber.keySet()){
int pos = m_classRefToTypeNumber.get(value);
ret[pos] = (int) (value >> 4);
}
return ret;
}
private static synchronized WriteCacheResult checkWriteCache(Object o, int size, boolean read_only, Memory mem){
if(mWriteToGpuCache.containsKey(o)){
long ref = mWriteToGpuCache.get(o);
return new WriteCacheResult(ref, false);
}
long ref = mem.mallocWithSize(size);
mWriteToGpuCache.put(o, ref);
mReverseWriteToGpuCache.put(ref, o);
return new WriteCacheResult(ref, true);
}
public Object writeCacheFetch(long ref){
synchronized(mWriteToGpuCache){
if(mReverseWriteToGpuCache.containsKey(ref)){
return mReverseWriteToGpuCache.get(ref);
}
return null;
}
}
public long writeToHeap(Object o, boolean write_data){
if(o == null)
return -1;
int size = doGetSize(o);
boolean read_only = false;
WriteCacheResult result;
result = checkWriteCache(o, size, read_only, mMem);
if(result.m_NeedToWrite == false)
return result.m_Ref;
doWriteToHeap(o, write_data, result.m_Ref, read_only);
return result.m_Ref;
}
protected Object checkCache(long address, Object item){
synchronized(mReadFromGpuCache){
if(mReadFromGpuCache.containsKey(address)){
return mReadFromGpuCache.get(address);
} else {
mReadFromGpuCache.put(address, item);
return item;
}
}
}
public Object readFromHeap(Object o, boolean read_data, long address){
synchronized(mReadFromGpuCache){
if(mReadFromGpuCache.containsKey(address)){
Object ret = mReadFromGpuCache.get(address);
return ret;
}
}
long null_ptr_check = address >> 4;
if(null_ptr_check == -1){
return null;
}
Object ret = doReadFromHeap(o, read_data, address);
return checkCache(address, ret);
}
public void readStaticsFromHeap(){
doReadStaticsFromHeap();
}
public Object readField(Object base, String name){
Class cls = base.getClass();
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
Object ret = f.get(base);
return ret;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public Object readStaticField(Class cls, String name){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
Object ret = f.get(null);
return ret;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeField(Object base, String name, Object value){
Class cls = base.getClass();
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.set(base, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticField(Class cls, String name, Object value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.set(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticByteField(Class cls, String name, byte value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setByte(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticBooleanField(Class cls, String name, boolean value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setBoolean(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticCharField(Class cls, String name, char value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setChar(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticShortField(Class cls, String name, short value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setShort(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticIntField(Class cls, String name, int value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setInt(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticLongField(Class cls, String name, long value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setLong(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticFloatField(Class cls, String name, float value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setFloat(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public void writeStaticDoubleField(Class cls, String name, double value){
while(true){
try {
Field f = cls.getDeclaredField(name);
f.setAccessible(true);
f.setDouble(null, value);
return;
} catch(Exception ex){
cls = cls.getSuperclass();
}
}
}
public abstract void doWriteToHeap(Object o, boolean write_data, long ref, boolean read_only);
public abstract void doWriteStaticsToHeap();
public abstract Object doReadFromHeap(Object o, boolean read_data, long ref);
public abstract void doReadStaticsFromHeap();
public abstract int doGetSize(Object o);
} |
package org.mapyrus;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.mapyrus.font.AdobeFontMetricsManager;
import org.mapyrus.font.PostScriptFont;
import org.mapyrus.font.StringDimension;
import org.mapyrus.font.TrueTypeFont;
import org.mapyrus.io.ASCII85Writer;
import org.mapyrus.io.WildcardFile;
/**
* Abstraction of a graphics format. Provides methods to create new
* output files and then draw to them, independent of the graphics
* format.
*/
public class OutputFormat
{
/*
* Type of output currently being generated.
*/
private static final int INTERNAL_IMAGE = 1;
private static final int IMAGE_FILE = 2;
/*
* PostScript output can be created as either moveto-lineto-stroke
* commands to draw shapes on page or as an single image covering
* the whole page containing all drawn shapes.
*/
private static final int POSTSCRIPT_GEOMETRY = 3;
private static final int POSTSCRIPT_IMAGE = 4;
/*
* Type of justification for labels on page, as used
* in a word processor and in HTML tags.
*/
public static final int JUSTIFY_LEFT = 1;
public static final int JUSTIFY_CENTER = 2;
public static final int JUSTIFY_RIGHT = 4;
public static final int JUSTIFY_TOP = 8;
public static final int JUSTIFY_MIDDLE = 16;
public static final int JUSTIFY_BOTTOM = 32;
/*
* File or image that drawing commands are
* writing to.
*/
private int mOutputType;
private String mFormatName;
private BufferedImage mImage;
private String mFilename;
private PrintWriter mWriter;
private OutputStream mOutputStream;
private Graphics2D mGraphics2D;
private boolean mIsPipedOutput;
private boolean mIsStandardOutput;
private Process mOutputProcess;
/*
* Frequently used fonts.
*/
private FontCache mFontCache;
/*
* List of font definitions included in this PostScript file and list of fonts
* used in this file but not defined.
*/
private HashSet mSuppliedFontResources;
private HashSet mNeededFontResources;
/*
* Fonts which are to be re-encoded to ISOLatin1 in PostScript file.
* This is normally done so that extended symbols (such as degree symbol)
* can be used.
*/
private HashSet mEncodeAsISOLatin1;
/*
* Adobe Font Metrics files containing character width information for all fonts.
*/
private AdobeFontMetricsManager mAdobeFontMetrics;
private ArrayList mAfmFiles;
/*
* List of TrueType fonts to load using Java Font.createFont() method.
*/
private HashMap mTTFFonts;
/*
* Page dimensions and resolution.
*/
private double mPageWidth;
private double mPageHeight;
private double mResolution;
/*
* Indentation for PostScript commands.
*/
private int mPostScriptIndent;
/*
* Justification for labels as fraction of string height and width
* to move string in X and Y direction to achieve correct justification.
*/
private double mJustificationShiftX;
private double mJustificationShiftY;
/*
* Rotation of current font in radians, with 0 horizontal,
* measured counter-clockwise.
*/
private double mFontRotation;
/*
* If non-zero, gives linewidth to use for drawing outlines of
* each character of labels.
*/
private double mFontOutlineWidth;
private Font mBaseFont;
/*
* Mask containing protected areas of the page.
*/
private PageMask mPageMask;
/**
* Write PostScript file header, including document structuring conventions (DSC).
* @param width width of page in mm.
* @param height height of page in mm.
* @param resolution resolution of page in DPI.
* @param turnPage flag true when page is to be rotated 90 degrees.
* @param fontList list of PostScript fonts to include in header.
* @param backgroundColor background color for page, or null if no background.
*/
private void writePostScriptHeader(double width, double height,
int resolution, boolean turnPage, ArrayList fontList, Color backgroundColor)
throws IOException, MapyrusException
{
long widthInPoints = Math.round(width / Constants.MM_PER_INCH *
Constants.POINTS_PER_INCH);
long heightInPoints = Math.round(height / Constants.MM_PER_INCH *
Constants.POINTS_PER_INCH);
mWriter.print("%!PS-Adobe-3.0");
if (mFormatName.equals("eps") || mFormatName.equals("epsimage"))
mWriter.print(" EPSF-3.0");
mWriter.println("");
if (turnPage)
mWriter.println("%%BoundingBox: 0 0 " + heightInPoints + " " + widthInPoints);
else
mWriter.println("%%BoundingBox: 0 0 " + widthInPoints + " " + heightInPoints);
mWriter.println("%%DocumentData: Clean7Bit");
mWriter.println("%%LanguageLevel: 2");
mWriter.println("%%Creator: (" + Constants.PROGRAM_NAME +
" " + Constants.getVersion() + ")");
mWriter.println("%%OperatorMessage: (Mapyrus Output...)");
Date now = new Date();
mWriter.println("%%CreationDate: (" + now.toString() + ")");
String username = System.getProperty("user.name");
if (username != null)
mWriter.println("%%For: (" + username + ")");
/*
* List fonts included in this PostScript file.
*/
mWriter.println("%%DocumentRequiredResources: (atend)");
if (fontList.size() > 0)
{
mWriter.print("%%DocumentSuppliedResources: font");
Iterator it = fontList.iterator();
while (it.hasNext())
{
PostScriptFont psFont = (PostScriptFont)(it.next());
mWriter.print(" " + psFont.getName());
mSuppliedFontResources.add(psFont.getName());
}
mWriter.println("");
}
mWriter.println("%%EndComments");
mWriter.println("");
mWriter.println("% Resolution " + resolution + " DPI");
/*
* Inline font definitions.
*/
mWriter.println("%%BeginSetup");
Iterator it = fontList.iterator();
while (it.hasNext())
{
PostScriptFont psFont = (PostScriptFont)(it.next());
mWriter.println("%%BeginResource: font " + psFont.getName());
String fontDefinition = psFont.getFontDefinition();
mWriter.println(fontDefinition);
mWriter.println("%%EndResource");
}
mWriter.println("%%EndSetup");
/*
* Set color and linestyle to reasonable default values.
* Taken from 'initgraphics' operator example in PostScript Language
* Reference Manual.
*/
mWriter.println("1 setlinewidth 0 setlinecap 0 setlinejoin");
mWriter.println("[] 0 setdash 0 setgray 10 setmiterlimit");
if (turnPage)
{
/*
* Turn page 90 degrees so that a landscape orientation page appears
* on a portrait page.
*/
mWriter.println("% Turn page 90 degrees.");
mWriter.println("90 rotate 0 " + heightInPoints + " neg translate");
}
/*
* Prevent anything being displayed outside bounding box we've just defined.
*/
mWriter.println("0 0 " + widthInPoints + " " + heightInPoints + " rectclip");
/*
* Set background color for page.
*/
if (backgroundColor != null)
{
float c[] = backgroundColor.getRGBColorComponents(null);
mWriter.println("gsave");
mWriter.println(c[0] + " " + c[1] + " " + c[2] + " setrgbcolor");
mWriter.println("0 0 " + widthInPoints + " " + heightInPoints + " rectfill");
mWriter.println("grestore");
}
/*
* Set plotting units to millimetres.
*/
mWriter.println(Constants.POINTS_PER_INCH + " " + Constants.MM_PER_INCH +
" div dup scale");
/*
* Define shorter names for most commonly used operations.
* Bind all operators names to improve performance (see 3.11 of
* PostScript Language Reference Manual).
*/
mWriter.println("/m { moveto } bind def /l { lineto } bind def");
mWriter.println("/s { stroke } bind def /f { fill } bind def");
mWriter.println("/j { /fjy exch def /fjx exch def } bind def");
/*
* Define font and dictionary entries for font size and justification.
* Don't bind these as font loading operators may be overridden in interpreter.
*/
mWriter.println("/font {");
mWriter.println("/foutline exch def");
mWriter.println("/frot exch radtodeg def");
mWriter.println("/fsize exch def findfont fsize scalefont setfont } def");
mWriter.println("/radtodeg { 180 mul 3.1415629 div } bind def");
/*
* Draw text string, after setting correct position, rotation,
* justifying it horizontally and vertically for current font size
* and shifting it down a number of lines if it is part of a multi-line
* string.
*
* Line number (starting at 0) and string to show are passed to this procedure.
*/
mWriter.println("/t { gsave currentpoint translate frot rotate");
mWriter.println("dup stringwidth pop fjx mul");
mWriter.println("3 -1 roll neg fjy add fsize mul");
mWriter.println("rmoveto foutline 0 gt");
mWriter.println("{false charpath foutline 0 0 2 sl stroke} {show} ifelse");
mWriter.println("grestore newpath } bind def");
mWriter.println("/rgb { setrgbcolor } bind def");
mWriter.println("/sl { setmiterlimit setlinejoin setlinecap");
mWriter.println("setlinewidth } bind def");
/*
* Use new dictionary in saved state so that variables we define
* do not overwrite variables in parent state.
*/
mWriter.println("/gs { gsave 4 dict begin } bind def");
mWriter.println("/gr { end grestore } bind def");
mWriter.println("");
}
/**
* Sets correct rendering hints and transformation
* for buffered image we will plot to.
* @param resolution resolution for page in DPI.
* @param backgroundColor background color for page, or null if no background.
* @param lineAliasing flag true if lines should be drawn with anti-aliasing.
* @param labelAliasing flag true if labels should be drawn with anti-aliasing.
*/
private void setupBufferedImage(double resolution, Color backgroundColor,
boolean lineAntiAliasing, boolean labelAntiAliasing)
{
double scale;
scale = resolution / Constants.MM_PER_INCH;
/*
* Set background of entire image to desired color.
*/
if (backgroundColor != null)
{
Color originalColor = mGraphics2D.getColor();
mGraphics2D.setColor(backgroundColor);
mGraphics2D.fillRect(0, 0, mImage.getWidth(), mImage.getHeight());
mGraphics2D.setColor(originalColor);
}
/*
* Set transform with origin in lower-left corner and
* Y axis increasing upwards.
*/
mGraphics2D.translate(0, mImage.getHeight());
mGraphics2D.scale(scale, -scale);
/*
* Set anti-aliasing for labels and lines if the user wants it.
*/
if (lineAntiAliasing)
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON));
}
else
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF));
}
if (labelAntiAliasing)
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON));
}
else
{
mGraphics2D.addRenderingHints(new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_OFF));
}
}
/**
* Indicates whether an image format is supported or not.
* @param formatName
* @return true if creation of images in given format is supported.
*/
private boolean isSupportedImageFormat(String formatName)
{
boolean found = false;
String knownFormats[] = ImageIO.getWriterFormatNames();
for (int i = 0; i < knownFormats.length && found == false; i++)
{
if (formatName.equalsIgnoreCase(knownFormats[i]))
{
found = true;
}
}
return(found);
}
/**
* Return PostScript commands to re-encode a font in ISOLatin1 encoding.
* @param fontName name of font to re-encode.
* @return string containing PostScript commands to re-encode font.
*/
private String isoLatinEncode(String fontName)
{
/*
* Re-encoding commands taken from section 5.6.1 of Adobe PostScript
* Language Reference Manual (2nd Edition).
*/
return("/" + fontName + " findfont" + Constants.LINE_SEPARATOR +
"dup length dict begin" + Constants.LINE_SEPARATOR +
"{1 index /FID ne {def} {pop pop} ifelse} forall" + Constants.LINE_SEPARATOR +
"/Encoding ISOLatin1Encoding def" + Constants.LINE_SEPARATOR +
"currentdict" + Constants.LINE_SEPARATOR +
"end" + Constants.LINE_SEPARATOR +
"/" + fontName + " exch definefont pop");
}
private void setOutput(String filename, double width, double height, String extras)
throws IOException, MapyrusException
{
/*
* Parse list of additional options given by caller.
*/
ArrayList fontList = new ArrayList();
mEncodeAsISOLatin1 = new HashSet();
mTTFFonts = new HashMap();
mAfmFiles = new ArrayList();
int resolution;
boolean turnPage = false;
Color backgroundColor = null;
boolean labelAntiAliasing = true;
boolean lineAntiAliasing = false;
if (mOutputType == POSTSCRIPT_GEOMETRY)
resolution = 300;
else
resolution = Constants.getScreenResolution();
/*
* Reading all font metrics information takes some time.
* Wait until we really need it before loading it.
*/
mAdobeFontMetrics = null;
StringTokenizer st = new StringTokenizer(extras);
while (st.hasMoreTokens())
{
String token = st.nextToken();
if (token.startsWith("pfafiles="))
{
/*
* Build list of font filenames user wants
* to include in this PostScript file.
*/
StringTokenizer st2 = new StringTokenizer(token.substring(9), ",");
while (st2.hasMoreTokens())
{
String pfaFilename = st2.nextToken();
if (pfaFilename.length() > 0)
{
/*
* Accept wildcards in filenames.
*/
WildcardFile wildcard = new WildcardFile(pfaFilename);
Iterator it = wildcard.getMatchingFiles().iterator();
while (it.hasNext())
fontList.add(new PostScriptFont((String)it.next()));
}
}
}
if (token.startsWith("afmfiles="))
{
StringTokenizer st2 = new StringTokenizer(token.substring(9), ",");
while (st2.hasMoreTokens())
{
String afmFilename = st2.nextToken();
if (afmFilename.length() > 0)
{
/*
* Accept wildcards in filenames.
*/
WildcardFile wildcard = new WildcardFile(afmFilename);
Iterator it = wildcard.getMatchingFiles().iterator();
while (it.hasNext())
{
mAfmFiles.add(it.next());
}
}
}
}
else if (token.startsWith("isolatinfonts="))
{
/*
* Build list of fonts to encode in ISOLatin1.
*/
StringTokenizer st2 = new StringTokenizer(token.substring(14), ",");
while (st2.hasMoreTokens())
{
String fontName = st2.nextToken();
if (fontName.length() > 0)
mEncodeAsISOLatin1.add(fontName);
}
}
else if (token.startsWith("resolution="))
{
String r = token.substring(11);
try
{
resolution = Integer.parseInt(r);
}
catch (NumberFormatException e)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) +
": " + r);
}
if (resolution < 1)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_PAGE_RESOLUTION) +
": " + r);
}
}
else if (token.startsWith("ttffiles="))
{
/*
* Build list of TrueType font filenames user wants
* to open with Java methods.
*/
StringTokenizer st2 = new StringTokenizer(token.substring(9), ",");
while (st2.hasMoreTokens())
{
String ttfFilename = st2.nextToken();
/*
* Accept wildcards in filenames.
*/
if (ttfFilename.length() > 0)
{
WildcardFile wildcard = new WildcardFile(ttfFilename);
Iterator it = wildcard.getMatchingFiles().iterator();
while (it.hasNext())
{
String s = (String)it.next();
TrueTypeFont ttf = new TrueTypeFont(s);
mTTFFonts.put(ttf.getName(), ttf);
}
}
}
}
else if (token.startsWith("turnpage="))
{
String flag = token.substring(9);
turnPage = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("labelantialiasing="))
{
String flag = token.substring(18);
labelAntiAliasing = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("lineantialiasing="))
{
String flag = token.substring(17);
lineAntiAliasing = flag.equalsIgnoreCase("true");
}
else if (token.startsWith("background="))
{
String colorName = token.substring(11);
backgroundColor = ColorDatabase.getColor(colorName, 255);
if (backgroundColor == null)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.COLOR_NOT_FOUND) +
": " + colorName);
}
}
}
/*
* Setup file we are writing to.
*/
if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE)
{
mWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(mOutputStream)));
mSuppliedFontResources = new HashSet();
writePostScriptHeader(width, height, resolution, turnPage, fontList, backgroundColor);
mPostScriptIndent = 0;
mNeededFontResources = new HashSet();
}
if (mOutputType != POSTSCRIPT_GEOMETRY)
{
/*
* Create image to draw into.
*/
if (mOutputType == IMAGE_FILE || mOutputType == POSTSCRIPT_IMAGE)
{
/*
* Create a BufferedImage to draw into. We'll save it to a file
* when user has finished drawing to it.
*/
int widthInPixels = (int)Math.round(width / Constants.MM_PER_INCH * resolution);
int heightInPixels = (int)Math.round(height / Constants.MM_PER_INCH * resolution);
int imageType;
/*
* Create images with transparency for all formats except
* JPEG (which does not support it).
*/
if (mFormatName.equals("jpg") || mFormatName.equals("jpeg"))
imageType = BufferedImage.TYPE_3BYTE_BGR;
else
imageType = BufferedImage.TYPE_INT_ARGB;
mImage = new BufferedImage(widthInPixels, heightInPixels,
imageType);
}
else if (mOutputType == INTERNAL_IMAGE)
{
/*
* Calculate width of page, based on image and resolution given
* by user.
*/
width = mImage.getWidth() / (resolution / Constants.MM_PER_INCH);
height = mImage.getHeight() / (resolution / Constants.MM_PER_INCH);
}
mGraphics2D = (Graphics2D)(mImage.getGraphics());
setupBufferedImage(resolution, backgroundColor, lineAntiAliasing, labelAntiAliasing);
}
mFilename = filename;
mPageWidth = width;
mPageHeight = height;
mResolution = Constants.MM_PER_INCH / resolution;
mFontCache = new FontCache();
mJustificationShiftX = mJustificationShiftY = 0.0;
mFontOutlineWidth = 0.0;
/*
* Set impossible current font rotation so first font
* accessed will be loaded.
*/
mFontRotation = Double.MAX_VALUE;
/*
* Do not allocate page mask until needed to save memory.
*/
mPageMask = null;
}
/**
* Creates new graphics file, ready for drawing to.
* @param filename name of image file output will be saved to.
* If filename begins with '|' character then output is piped as
* input to that command.
* @param format is the graphics format to use.
* @param width is the page width (in mm).
* @param height is the page height (in mm).
* @param extras contains extra settings for this output.
* @param stdoutStream standard output stream for program.
*/
public OutputFormat(String filename, String format,
double width, double height, String extras,
PrintStream stdoutStream)
throws IOException, MapyrusException
{
mFormatName = format.toLowerCase();
/*
* Check that Java can write this image format to a file.
*/
if (mFormatName.equals("ps") ||
mFormatName.equals("postscript") ||
mFormatName.equals("application/postscript"))
{
mFormatName = "ps";
mOutputType = POSTSCRIPT_GEOMETRY;
}
else if (mFormatName.equals("eps"))
{
mOutputType = POSTSCRIPT_GEOMETRY;
}
else if (mFormatName.equals("epsimage"))
{
mOutputType = POSTSCRIPT_IMAGE;
}
else
{
if (mFormatName.startsWith("image/"))
mFormatName = mFormatName.substring(6);
if (!isSupportedImageFormat(mFormatName))
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.INVALID_OUTPUT) +
": " + format);
}
mOutputType = IMAGE_FILE;
}
/*
* Should we pipe the output to another program
* instead of writing a file?
*/
mIsPipedOutput = filename.startsWith("|");
/*
* Are we writing to standard output instead of to a file?
*/
mIsStandardOutput = filename.equals("-");
if (mIsPipedOutput)
{
String pipeCommand = filename.substring(1).trim();
mOutputProcess = Runtime.getRuntime().exec(pipeCommand);
mOutputStream = mOutputProcess.getOutputStream();
}
else
{
if (mIsStandardOutput)
mOutputStream = stdoutStream;
else
mOutputStream = new FileOutputStream(filename);
}
setOutput(filename, width, height, extras);
}
/**
* Sets image for drawing into.
* @param image is buffered image to draw into.
* @param extras contains extra settings for this output.
*/
public OutputFormat(BufferedImage image, String extras)
throws IOException, MapyrusException
{
mOutputType = INTERNAL_IMAGE;
mImage = image;
mFormatName = "png";
setOutput("", 0, 0, extras);
}
/**
* Return page width.
* @return width in millimetres.
*/
public double getPageWidth()
{
return(mPageWidth);
}
/**
* Return page height.
* @return height in millimetres.
*/
public double getPageHeight()
{
return(mPageHeight);
}
/**
* Return file format of page.
* @return file format of page in lowercase.
*/
public String getPageFormat()
{
return(mFormatName);
}
/**
* Return resolution of page as a distance measurement.
* @return distance in millimetres between centres of adjacent pixels.
*/
public double getResolution()
{
return(mResolution);
}
/**
* Returns height and width of a string, drawn to current page.
* @param s string to calculate width for.
* @param fontName name of font to calculate dimensions for.
* @param fontSize size of characters in millimetres.
* @return height and width of string in millimetres.
*/
public StringDimension getStringDimension(String s, String fontName, double fontSize)
throws IOException, MapyrusException
{
StringDimension retval = new StringDimension();
BufferedReader stringReader = new BufferedReader(new StringReader(s));
double width = 0, height = 0;
String token;
double tokenWidth;
/*
* Break multi-line strings into separate lines so we
* can find the width of the longest line.
*/
while ((token = stringReader.readLine()) != null)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Load Font Metrics information only when it is needed.
*/
if (mAdobeFontMetrics == null)
mAdobeFontMetrics = new AdobeFontMetricsManager(mAfmFiles, mEncodeAsISOLatin1);
double pointSize = fontSize / Constants.MM_PER_INCH * Constants.POINTS_PER_INCH;
tokenWidth = mAdobeFontMetrics.getStringWidth(fontName, pointSize, token);
tokenWidth = tokenWidth / Constants.POINTS_PER_INCH * Constants.MM_PER_INCH;
if (tokenWidth > width)
width = tokenWidth;
height += fontSize;
}
else
{
/*
* Use Java2D calculation for bounding box of string displayed with
* horizontal font.
*/
FontRenderContext frc = mGraphics2D.getFontRenderContext();
Rectangle2D bounds = mBaseFont.getStringBounds(token, frc);
tokenWidth = bounds.getWidth();
if (tokenWidth > width)
width = tokenWidth;
height += bounds.getHeight();
}
}
retval.setSize(width, height);
return(retval);
}
/**
* Return mask for this page.
* @return page mask.
*/
public PageMask getPageMask()
{
if (mPageMask == null)
{
mPageMask = new PageMask((int)Math.round(mPageWidth),
(int)Math.round(mPageHeight));
}
return(mPageMask);
}
/*
* Write a line to PostScript file. Line is indented to show
* saving and restoring of state more clearly.
*/
private void writePostScriptLine(String line)
{
for (int i = 0; i < mPostScriptIndent; i++)
{
mWriter.print(' ');
}
mWriter.println(line);
}
/**
* Write image to PostScript file.
* @param image image to write.
* @param x center position on page for image.
* @param y center position on page for image.
* @param width width of image in millimetres.
* @param height height of image in millimetres.
* @param rotation rotation angle for image.
*/
private void writePostScriptImage(Image image, double x, double y,
double width, double height, double rotation)
throws IOException, MapyrusException
{
/*
* Grab pixels of icon.
*/
int j;
int pixelWidth, pixelHeight;
int []pixels = null;
try
{
pixelWidth = image.getWidth(null);
pixelHeight = image.getHeight(null);
pixels = new int[pixelWidth * pixelHeight];
PixelGrabber grabber = new PixelGrabber(image, 0, 0,
pixelWidth, pixelHeight, pixels, 0, pixelWidth);
grabber.grabPixels();
}
catch (InterruptedException e)
{
throw new MapyrusException(e.getMessage());
}
catch (NullPointerException e)
{
throw new OutOfMemoryError("Failed loading image.");
}
/*
* Check if image is a single color.
* Draw single color images with transparent background
* using PostScript 'imagemask' operator.
* Draw other images as RGB images using 'image' operator.
*/
Color singleColor = getSingleImageColor(pixels);
/*
* Write PostScript image directionary entry to draw image.
* Taken from Adobe PostScript Language Reference Manual
* (2nd Edition), p. 234.
*/
writePostScriptLine("gs");
writePostScriptLine("/DeviceRGB setcolorspace");
writePostScriptLine(x + " " + y + " translate");
writePostScriptLine(rotation + " radtodeg rotate");
writePostScriptLine(width + " " + height + " scale");
/*
* Image is centred at each point.
* Shift image left and down half it's size so that it is displayed centred.
*/
writePostScriptLine("-0.5 -0.5 translate");
/*
* Set color for drawing single color images.
*/
if (singleColor != null)
{
float []c = singleColor.getColorComponents(null);
writePostScriptLine(c[0] + " " + c[1] + " " + c[2] + " rgb");
}
writePostScriptLine("<<");
writePostScriptLine("/ImageType 1");
writePostScriptLine("/Width " + pixelWidth);
writePostScriptLine("/Height " + pixelHeight);
if (singleColor != null)
{
writePostScriptLine("/BitsPerComponent 1");
writePostScriptLine("/Decode [0 1]");
}
else
{
writePostScriptLine("/BitsPerComponent 8");
writePostScriptLine("/Decode [0 1 0 1 0 1]");
}
writePostScriptLine("/ImageMatrix [" + pixelWidth + " 0 0 " +
-pixelHeight + " 0 " + pixelHeight + "]");
writePostScriptLine("/DataSource currentfile /ASCII85Decode filter");
writePostScriptLine(">>");
if (singleColor != null)
writePostScriptLine("imagemask");
else
writePostScriptLine("image");
/*
* Write ASCII85 encoded string containing all pixel values.
*/
ASCII85Writer ascii85 = new ASCII85Writer(mWriter);
int byteValue = 0;
int bitCounter = 0;
for (j = 0; j < pixels.length; j++)
{
int pixel = pixels[j];
if (singleColor != null)
{
/*
* Pixel is set in PostScript image if it is transparent.
*/
int nextBit = ((pixel >> 24) == 0) ? 1 : 0;
/*
* Store next pixel value as a single bit in a byte.
* If we've completed a byte or reached the end of a row
* then write byte out and begin next byte.
*/
nextBit <<= (7 - bitCounter);
byteValue |= nextBit;
bitCounter++;
if (bitCounter == 8 || (j + 1) % pixelWidth == 0)
{
ascii85.write(byteValue);
byteValue = bitCounter = 0;
}
}
else
{
/*
* Ignore transparency, we want only red, green, blue components
* of pixel.
*/
int blue = (pixel & 0xff);
int green = ((pixel >> 8) & 0xff);
int red = ((pixel >> 16) & 0xff);
ascii85.write(red);
ascii85.write(green);
ascii85.write(blue);
}
}
ascii85.close();
/*
* Write ASCII85 end-of-data marker.
*/
writePostScriptLine("~>");
writePostScriptLine("gr");
}
/**
* Save state, protecting color, linestyle, transform of output.
* This state can be restored later with restoreState().
*/
public void saveState()
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
writePostScriptLine("gs");
mPostScriptIndent++;
}
}
/**
* Restore state saved with saveState().
* @return true if saved state was successfully restored.
* Only PostScript format can be successfully restored, caller
* will have to reset values for other formats.
*/
public boolean restoreState()
{
boolean retval;
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
mPostScriptIndent
writePostScriptLine("gr");
retval = true;
}
else
{
/*
* Can't restore state when drawing to an image. Caller
* must set everything to correct values again.
*/
retval = false;
}
return(retval);
}
/**
* Writes trailing and buffered information, then closes output file.
*/
public void closeOutputFormat() throws IOException, MapyrusException
{
if (mOutputType == POSTSCRIPT_GEOMETRY || mOutputType == POSTSCRIPT_IMAGE)
{
if (mOutputType == POSTSCRIPT_IMAGE)
{
/*
* Write image file containing page.
*/
writePostScriptImage(mImage, mPageWidth / 2, mPageHeight / 2,
mPageWidth, mPageHeight, 0);
}
/*
* Finish off PostScript file.
*/
if (mFormatName.equals("ps"))
{
/*
* showpage is not included in Encapsulated PostScript files.
*/
mWriter.println("showpage");
}
mWriter.println("%%Trailer");
/*
* Included list of fonts we used in this file but did
* not include in the header.
*/
mWriter.println("%%DocumentNeededResources:");
Iterator it = mNeededFontResources.iterator();
while (it.hasNext())
{
String fontName = (String)(it.next());
if (!mSuppliedFontResources.contains(fontName))
mWriter.println("%%+ font " + fontName);
}
mWriter.println("%%EOF");
if (mIsStandardOutput)
mWriter.flush();
else
mWriter.close();
if (mWriter.checkError())
{
throw new MapyrusException(mFilename +
": " + MapyrusMessages.get(MapyrusMessages.ERROR_PS));
}
}
else if (mOutputType == IMAGE_FILE)
{
/*
* Write image buffer to file.
*/
ImageIO.write(mImage, mFormatName, mOutputStream);
if (mIsStandardOutput)
mOutputStream.flush();
else
mOutputStream.close();
}
mImage = null;
mGraphics2D = null;
if (mOutputType != INTERNAL_IMAGE)
{
/*
* If we are piping output to another program then wait for
* that program to finish. Then check that it succeeded.
*/
if (mIsPipedOutput)
{
int retval = 0;
try
{
retval = mOutputProcess.waitFor();
}
catch (InterruptedException e)
{
throw new MapyrusException(mFilename + ": " + e.getMessage());
}
if (retval != 0)
{
throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.PROCESS_ERROR) +
": " + retval + ": " + mFilename);
}
}
}
}
/**
* Set font for labelling in output format.
* @param fontName is name of font as defined in java.awt.Font class.
* @param fontSize is size for labelling in millimetres.
* @param fontRotation is rotation angle for font, in degrees,
* measured counter-clockwise.
* @param outlineWidth if non-zero, labels will drawn as character outlines
* with this width.
*/
public void setFontAttribute(String fontName, double fontSize, double fontRotation, double outlineWidth)
throws IOException, MapyrusException
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
if (mEncodeAsISOLatin1.contains(fontName))
{
/*
* Re-encode font from StandardEncoding to ISOLatin1Encoding
* before it is used.
*/
writePostScriptLine(isoLatinEncode(fontName));
mEncodeAsISOLatin1.remove(fontName);
}
/*
* Set font and size for labelling.
*/
writePostScriptLine("/" + fontName + " " +
fontSize + " " +
fontRotation + " " +
outlineWidth + " font");
mNeededFontResources.add(fontName);
}
else
{
/*
* Split font name into font and style.
*/
int style = Font.PLAIN;
if (fontName.endsWith("-Bold"))
{
style = Font.BOLD;
fontName = fontName.substring(0, fontName.length() - 5);
}
else if (fontName.endsWith("-Italic"))
{
style = Font.ITALIC;
fontName = fontName.substring(0, fontName.length() - 7);
}
else if (fontName.endsWith("-BoldItalic"))
{
style = Font.BOLD|Font.ITALIC;
fontName = fontName.substring(0, fontName.length() - 11);
}
/*
* Continually opening and deriving fonts is probably expensive.
* Check that new font is actually different to current font
* before defining it.
*/
Font currentFont = mGraphics2D.getFont();
int newSize = (int)Math.round(fontSize);
if (newSize != currentFont.getSize() ||
style != currentFont.getStyle() ||
(!fontName.equals(currentFont.getFontName())) ||
fontRotation != mFontRotation)
{
/*
* We need a base font that is not rotated for calculating
* string widths for justifying text.
* Get base font from cache, or create it if we don't find it there.
*/
mBaseFont = mFontCache.get(fontName, style, newSize, 0);
if (mBaseFont == null)
{
/*
* If this is a font for which user provided a TTF file then
* use that, else expect the operating system to be able to
* open the font.
*/
TrueTypeFont ttf = (TrueTypeFont)mTTFFonts.get(fontName);
if (ttf != null)
mBaseFont = ttf.getFont().deriveFont(style, (float)newSize);
else
mBaseFont = new Font(fontName, style, newSize);
mFontCache.put(fontName, style, newSize, 0, mBaseFont);
}
/*
* The real font used for labelling must be mirrored in Y axis
* (to reverse the transform we use on Graphics2D objects) and
* rotated to the angle the user wants.
*
* Look it up in cache too.
*/
Font font = mFontCache.get(fontName, style, -newSize, fontRotation);
if (font == null)
{
AffineTransform fontTransform;
fontTransform = AffineTransform.getRotateInstance(fontRotation);
fontTransform.scale(1, -1);
font = mBaseFont.deriveFont(fontTransform);
mFontCache.put(fontName, style, -newSize, fontRotation, font);
}
mGraphics2D.setFont(font);
}
}
/*
* Font rotation and outlining not easily held in a Graphics2D
* object so keep track of it's current value ourselves.
*/
mFontRotation = fontRotation;
mFontOutlineWidth = outlineWidth;
}
/**
* Set label justification in output format.
* @param justify is label justification value, combination of JUSTIFY_* bit flags.
*/
public void setJustifyAttribute(int justify)
{
/*
* Calculate fraction of string height and width to move text to get required
* justification.
*/
if ((justify & JUSTIFY_LEFT) != 0)
mJustificationShiftX = 0.0;
else if ((justify & JUSTIFY_CENTER) != 0)
mJustificationShiftX = -0.5;
else
mJustificationShiftX = -1.0;
if ((justify & JUSTIFY_BOTTOM) != 0)
mJustificationShiftY = 0.0;
else if ((justify & JUSTIFY_MIDDLE) != 0)
mJustificationShiftY = -0.5;
else
mJustificationShiftY = -1.0;
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Define dictionary entries for justification settings for PostScript
* procedure to use for aligning text correctly itself.
*/
writePostScriptLine(mJustificationShiftX + " " + mJustificationShiftY + " j");
}
}
/**
* Set color in output format.
* @param color is color to draw in.
*/
public void setColorAttribute(Color color)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
float c[] = color.getRGBColorComponents(null);
writePostScriptLine(c[0] + " " + c[1] + " " + c[2] + " rgb");
}
else
{
mGraphics2D.setColor(color);
}
}
/**
* Set linestyle in output format.
* @param linestyle is Java2D line width, cap and join style, dash pattern.
*/
public void setLinestyleAttribute(BasicStroke linestyle)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Convert BasicStroke end cap and line join values to PostScript.
*/
int cap = linestyle.getEndCap();
if (cap == BasicStroke.CAP_BUTT)
cap = 0;
else if (cap == BasicStroke.CAP_ROUND)
cap = 1;
else /* SQUARE */
cap = 2;
int join = linestyle.getLineJoin();
if (join == BasicStroke.JOIN_MITER)
join = 0;
else if (join == BasicStroke.JOIN_ROUND)
join = 1;
else /* BEVEL */
join = 2;
writePostScriptLine(linestyle.getLineWidth() + " " +
cap + " " + join + " " +
linestyle.getMiterLimit() + " sl");
/*
* If there a dash pattern then set that too.
*/
float dashes[] = linestyle.getDashArray();
if (dashes != null)
{
StringBuffer s = new StringBuffer("[");
for (int i = 0; i < dashes.length; i++)
{
if (i > 0)
s.append(" ");
s.append(dashes[i]);
}
s.append("] ");
s.append(linestyle.getDashPhase());
s.append(" setdash");
writePostScriptLine(s.toString());
}
else
{
/*
* Remove any dashed line previously defined.
*/
writePostScriptLine("[] 0 setdash");
}
}
else
{
mGraphics2D.setStroke(linestyle);
}
}
/**
* Set clip path for output format.
* @param clipPaths are polygons to clip against, or null if there are no clip polygons.
*/
public void setClipAttribute(ArrayList clipPaths)
{
if (mOutputType != POSTSCRIPT_GEOMETRY)
{
mGraphics2D.setClip(null);
if (clipPaths != null)
{
for (int i = 0; i < clipPaths.size(); i++)
{
GeometricPath clipPath = (GeometricPath)(clipPaths.get(i));
mGraphics2D.clip(clipPath.getShape());
}
}
}
}
/*
* Walk through path, converting it to PostScript.
*/
private void writePostScriptShape(Shape shape)
{
PathIterator pi = shape.getPathIterator(null);
float coords[] = new float[6];
float lastX = 0.0f, lastY = 0.0f;
float distSquared;
float resolutionSquared = (float)(mResolution * mResolution);
int segmentType;
while (!pi.isDone())
{
segmentType = pi.currentSegment(coords);
switch (segmentType)
{
case PathIterator.SEG_MOVETO:
lastX = coords[0];
lastY = coords[1];
writePostScriptLine(lastX + " " + lastY + " m");
break;
case PathIterator.SEG_LINETO:
distSquared = (lastX - coords[0]) * (lastX - coords[0]) + (lastY - coords[1]) * (lastY - coords[1]);
if (distSquared >= resolutionSquared)
{
/*
* Skip segments that are less than one unit of resolution in length.
*/
lastX = coords[0];
lastY = coords[1];
writePostScriptLine(lastX + " " + lastY + " l");
}
break;
case PathIterator.SEG_CLOSE:
writePostScriptLine("closepath");
break;
case PathIterator.SEG_CUBICTO:
writePostScriptLine(coords[0] + " " +
coords[1] + " " +
coords[2] + " " +
coords[3] + " " +
coords[4] + " " +
coords[5] + " " +
"curveto");
lastX = coords[4];
lastY = coords[5];
break;
}
pi.next();
}
}
/**
* Determines single color used in an image.
* @param pixels RGB pixel values for image.
* @return single non-transparent color used in an image, or null if
* image has many colors.
*/
private Color getSingleImageColor(int []pixels)
{
Color singleColor = Color.BLACK;
boolean foundDifferentColors = false;
boolean foundFirstColor = false;
int i = 0;
/*
* Check if all pixels are the same color, or transparent.
*/
while ((!foundDifferentColors) && i < pixels.length)
{
if ((pixels[i] & 0xff000000) != 0)
{
/*
* Pixel is not transparent.
*/
if (!foundFirstColor)
{
foundFirstColor = true;
singleColor = new Color(pixels[i] & 0xffffff);
}
else
{
foundDifferentColors = (pixels[i] != singleColor.getRGB());
}
}
i++;
}
if (foundDifferentColors)
singleColor = null;
return(singleColor);
}
/**
* Draw icon at points on page.
* @param pointList is list of Point2D objects at which to draw icon.
* @param icon image to draw.
* @param size is size of icon in millimeters, or zero for screen size.
* @param rotation rotation angle for icon.
* @param scaling scale factor for icon.
*/
public void drawIcon(ArrayList pointList, ImageIcon icon, double size,
double rotation, double scaling)
throws IOException, MapyrusException
{
int pixelWidth = icon.getIconWidth();
int pixelHeight = icon.getIconHeight();
Point2D pt;
int i, j;
double x, y, mmWidth, mmHeight;
/*
* If size not given then make icon about as large as it would appear
* on the screen in an image viewer, with one image pixel in one screen
* pixel.
*/
if (size <= 0.0)
{
size = Math.max(pixelWidth, pixelHeight) * (Constants.MM_PER_INCH /
Constants.getScreenResolution());
}
size *= scaling;
/*
* Calculate width and height for non-square images.
*/
if (pixelWidth > pixelHeight)
{
mmWidth = size;
mmHeight = size * ((double)pixelHeight / pixelWidth);
}
else
{
mmHeight = size;
mmWidth = size * ((double)pixelWidth / pixelHeight);
}
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Draw icon at each position in list.
*/
Image image = icon.getImage();
for (i = 0; i < pointList.size(); i++)
{
pt = (Point2D)(pointList.get(i));
x = pt.getX();
y = pt.getY();
/*
* Skip points that are outside page.
*/
if (x + mmWidth >= 0 && x - mmWidth <= mPageWidth &&
y + mmHeight >= 0.0 && y - mmHeight <= mPageHeight)
{
writePostScriptImage(image, x, y, mmWidth, mmHeight, rotation);
}
}
}
else
{
for (i = 0; i < pointList.size(); i++)
{
pt = (Point2D)(pointList.get(i));
x = pt.getX();
y = pt.getY();
AffineTransform affine = AffineTransform.getTranslateInstance(x, y);
/*
* Scale transformation so that units are in pixels.
*/
double mmPerPixel = Constants.MM_PER_INCH / Constants.getScreenResolution();
affine.scale(mmPerPixel, mmPerPixel * -1);
/*
* Rotate clockwise around point (x, y).
*/
affine.rotate(-rotation);
/*
* Scale image to requested size.
*/
double xScale = (mmWidth / mmPerPixel) / pixelWidth;
double yScale = (mmHeight / mmPerPixel) / pixelHeight;
affine.scale(xScale, yScale);
/*
* Shift origin so that middle of image is at point (x, y).
*/
affine.translate(-pixelWidth / 2.0, -pixelHeight / 2.0);
try
{
/*
* Sun JVM throws NullPointerException if image is
* too big to fit in memory.
*/
Image image = icon.getImage();
mGraphics2D.drawImage(image, affine, null);
}
catch (NullPointerException e)
{
throw new OutOfMemoryError("Failed loading icon.");
}
}
}
}
/**
* Draw currently defined path to output page.
*/
public void stroke(Shape shape)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight))
{
writePostScriptShape(shape);
writePostScriptLine("s");
}
}
else
{
/*
* Draw path into image.
*/
mGraphics2D.draw(shape);
}
}
/**
* Fill currently defined path on output page.
*/
public void fill(Shape shape)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight))
{
writePostScriptShape(shape);
writePostScriptLine("f");
}
}
else
{
/*
* Fill path in image.
*/
mGraphics2D.fill(shape);
}
}
/**
* Set clip region to inside of currently defined path on output page.
*/
public void clip(Shape shape)
{
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
/*
* Set clip path now, then it stays in effect until previous
* state is restored.
*/
if (shape.intersects(0.0, 0.0, mPageWidth, mPageHeight))
{
writePostScriptShape(shape);
}
else
{
/*
* Clip region is outside page. Clip to simple rectangle
* outside page instead so that nothing is shown.
*/
writePostScriptShape(new Rectangle2D.Float(-1.0f, -1.0f, 0.1f, 0.1f));
}
writePostScriptLine("clip newpath");
}
}
/**
* Convert a string to PostScript format, escaping special characters and
* write it to PostScript file.
* @param s is string to convert and write.
*/
private void writePostScriptString(String s)
{
char c;
StringBuffer buffer = new StringBuffer("(");
for (int i = 0; i < s.length(); i++)
{
/*
* Wrap strings that get too long.
*/
if (buffer.length() > 72)
{
buffer.append('\\');
mWriter.println(buffer.toString());
buffer.setLength(0);
}
/*
* Convert backslashes to '\\' and other special characters to octal code.
*/
c = s.charAt(i);
if (c == '\\')
{
buffer.append("\\\\");
}
else if (c == '(' || c == ')' || c == '%' || c < ' ' || c > 'z')
{
int extendedChar = c;
int b1 = extendedChar / (8 * 8);
extendedChar -= b1 * (8 * 8);
int b2 = extendedChar / 8;
extendedChar -= b2 * 8;
int b3 = extendedChar;
buffer.append('\\');
buffer.append(b1);
buffer.append(b2);
buffer.append(b3);
}
else
{
buffer.append(c);
}
}
buffer.append(")");
mWriter.println(buffer.toString());
}
/**
* Draw label positioned at (or along) currently defined path.
* @param pointList is list of Point2D objects at which to draw label.
* @param label is string to draw on path.
*/
public void label(ArrayList pointList, String label)
{
Point2D pt, startPt;
double x, y;
String nextLine;
StringTokenizer st;
int lineNumber;
AffineTransform affine;
FontRenderContext frc = null;
Stroke originalStroke = null;
if (mOutputType != POSTSCRIPT_GEOMETRY)
{
frc = mGraphics2D.getFontRenderContext();
if (mFontOutlineWidth > 0)
{
/*
* Save existing linestyle and create new one for drawing outlines of each letter.
*/
originalStroke = mGraphics2D.getStroke();
BasicStroke outlineStroke = new BasicStroke((float)mFontOutlineWidth,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 2.0f);
mGraphics2D.setStroke(outlineStroke);
}
}
/*
* Draw label at each position in list.
*/
for (int i = 0; i < pointList.size(); i++)
{
pt = (Point2D)(pointList.get(i));
x = pt.getX();
y = pt.getY();
/*
* Draw each line of label below the one above.
*/
st = new StringTokenizer(label, Constants.LINE_SEPARATOR);
lineNumber = 0;
while (st.hasMoreTokens())
{
nextLine = st.nextToken();
if (mOutputType == POSTSCRIPT_GEOMETRY)
{
writePostScriptLine(x + " " + y + " m");
/*
* Pass counter and line to PostScript procedure for
* drawing each line of the label.
*/
writePostScriptLine(Integer.toString(lineNumber));
writePostScriptString(nextLine);
writePostScriptLine("t");
}
else
{
/*
* Reposition label from original point so it has correct justification.
*/
if (mJustificationShiftX != 0.0 || mJustificationShiftY != 0.0 || lineNumber > 0)
{
Rectangle2D bounds = mBaseFont.getStringBounds(nextLine, frc);
affine = AffineTransform.getTranslateInstance(x, y);
affine.rotate(mFontRotation);
startPt = new Point2D.Double(bounds.getWidth() * mJustificationShiftX,
bounds.getHeight() * (mJustificationShiftY - lineNumber));
affine.transform(startPt, startPt);
}
else
{
startPt = pt;
}
float fx = (float)startPt.getX();
float fy = (float)startPt.getY();
if (mFontOutlineWidth > 0)
{
/*
* Draw only outline of letters in label as lines.
*/
GlyphVector glyphs = mGraphics2D.getFont().createGlyphVector(frc, nextLine);
Shape outline = glyphs.getOutline(fx, fy);
mGraphics2D.draw(outline);
}
else
{
/*
* Draw plain label.
*/
mGraphics2D.drawString(nextLine, fx, fy);
}
}
lineNumber++;
}
}
if (originalStroke != null)
{
/*
* Restore line style.
*/
mGraphics2D.setStroke(originalStroke);
}
}
} |
package edu.ucla.cens.awserver.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.List;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.PreparedStatementCreator;
import edu.ucla.cens.awserver.datatransfer.AwRequest;
import edu.ucla.cens.awserver.domain.DataPacket;
import edu.ucla.cens.awserver.domain.MobilityModeFeaturesDataPacket;
import edu.ucla.cens.awserver.domain.MobilityModeOnlyDataPacket;
/**
* DAO for handling persistence of uploaded mobility mode_only data.
*
* @author selsky
*/
public class MobilityUploadDao extends AbstractUploadDao {
private static Logger _logger = Logger.getLogger(MobilityUploadDao.class);
private final String _insertMobilityModeOnlySql = "insert into mobility_mode_only_entry" +
" (user_id, utc_time_stamp, utc_epoch_millis, phone_timezone, latitude," +
" longitude, mode) values (?,?,?,?,?,?,?) ";
private final String _insertMobilityModeFeaturesSql = "insert into mobility_mode_features_entry" +
" (user_id, utc_time_stamp, utc_epoch_millis, phone_timezone, latitude," +
" longitude, mode, speed, variance, average, fft)" +
" values (?,?,?,?,?,?,?,?,?,?,?)";
public MobilityUploadDao(DataSource datasource) {
super(datasource);
}
public void execute(AwRequest awRequest) {
_logger.info("beginning to persist mobility messages");
List<DataPacket> dataPackets = (List<DataPacket>) awRequest.getAttribute("dataPackets");
if(null == dataPackets) {
throw new IllegalArgumentException("no DataPackets found in the AwRequest");
}
int userId = awRequest.getUser().getId();
int index = -1;
for(DataPacket dataPacket : dataPackets) {
try {
index++;
int numberOfRowsUpdated = 0;
boolean modeFeatures = false;
if(dataPacket instanceof MobilityModeFeaturesDataPacket) { // the order of these instanceofs is important because
// a MobilityModeFeaturesDataPacket is a
// MobilityModeOnlyDataPacket -- need to check for the
// superclass first -- maybe move away from instanceof?
modeFeatures = true;
numberOfRowsUpdated = insertMobilityModeFeatures((MobilityModeFeaturesDataPacket)dataPacket, userId);
} else if (dataPacket instanceof MobilityModeOnlyDataPacket){
numberOfRowsUpdated = insertMobilityModeOnly((MobilityModeOnlyDataPacket)dataPacket, userId);
} else { // this is a logical error because this class should never be called with non-mobility packets
throw new IllegalArgumentException("invalid data packet found: " + dataPacket.getClass());
}
if(1 != numberOfRowsUpdated) {
throw new DataAccessException("inserted multiple rows even though one row was intended. sql: "
+ (modeFeatures ? _insertMobilityModeFeaturesSql : _insertMobilityModeOnlySql));
}
} catch (DataIntegrityViolationException dive) {
if(isDuplicate(dive)) {
_logger.info("found a duplicate mobility message");
handleDuplicate(awRequest, index);
} else {
// some other integrity violation occurred - bad!! All of the data to be inserted must be validated
// before this DAO runs so there is either missing validation or somehow an auto_incremented key
// has been duplicated
throw new DataAccessException(dive);
}
} catch (org.springframework.dao.DataAccessException dae) { // some other database problem happened that prevented
// the SQL from completing normally
throw new DataAccessException(dae);
}
}
_logger.info("completed mobility message persistence");
}
/**
* The insert is auto_committed, or rather nothing is done in this method to commit the insert so if auto_commit is ever
* turned off in the db, this code has to change.
*/
private int insertMobilityModeOnly(final MobilityModeOnlyDataPacket dataPacket, final int userId) {
return getJdbcTemplate().update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(_insertMobilityModeOnlySql);
ps.setInt(1, userId);
ps.setTimestamp(2, Timestamp.valueOf(dataPacket.getUtcDate()));
ps.setLong(3, dataPacket.getUtcTime());
ps.setString(4, dataPacket.getTimezone());
if(dataPacket.getLatitude().isNaN()) {
ps.setNull(5, Types.DOUBLE);
} else {
ps.setDouble(5, dataPacket.getLatitude());
}
if(dataPacket.getLatitude().isNaN()) {
ps.setNull(6, Types.DOUBLE);
} else {
ps.setDouble(6, dataPacket.getLongitude());
}
ps.setString(7, dataPacket.getMode());
return ps;
}
}
);
}
/**
* The insert is auto_committed, or rather nothing is done in this method to commit the insert so if auto_commit is ever
* turned off in the db, this code has to change.
*/
private int insertMobilityModeFeatures(final MobilityModeFeaturesDataPacket dataPacket, final int userId) {
return getJdbcTemplate().update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(_insertMobilityModeFeaturesSql);
ps.setInt(1, userId);
ps.setTimestamp(2, Timestamp.valueOf(dataPacket.getUtcDate()));
ps.setLong(3, dataPacket.getUtcTime());
ps.setString(4, dataPacket.getTimezone());
ps.setDouble(5, dataPacket.getLatitude().equals(Double.NaN) ? null : dataPacket.getLatitude());
ps.setDouble(6, dataPacket.getLongitude().equals(Double.NaN) ? null : dataPacket.getLongitude());
ps.setString(7, dataPacket.getMode());
ps.setDouble(8, dataPacket.getSpeed());
ps.setDouble(9, dataPacket.getVariance());
ps.setDouble(10, dataPacket.getAverage());
ps.setString(11, dataPacket.getFftArray());
return ps;
}
}
);
}
} |
package org.marc4j;
import org.marc4j.converter.CharConverter;
import org.marc4j.marc.*;
import org.marc4j.util.Normalizer;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.*;
public class MarcXmlWriter implements MarcWriter {
protected static final String CONTROL_FIELD = "controlfield";
protected static final String DATA_FIELD = "datafield";
protected static final String SUBFIELD = "subfield";
protected static final String COLLECTION = "collection";
protected static final String RECORD = "record";
protected static final String LEADER = "leader";
private boolean indent = false;
private TransformerHandler handler = null;
private Writer writer = null;
/**
* Character encoding. Default is UTF-8.
*/
private String encoding = "UTF8";
private CharConverter converter = null;
private boolean normalize = false;
/**
* Constructs an instance with the specified output stream.
*
* The default character encoding for UTF-8 is used.
*
* @throws MarcException
*/
public MarcXmlWriter(OutputStream out) {
this(out, false);
}
/**
* Constructs an instance with the specified output stream and indentation.
*
* The default character encoding for UTF-8 is used.
*
* @throws MarcException
*/
public MarcXmlWriter(OutputStream out, boolean indent) {
this(out, "UTF8", indent);
}
/**
* Constructs an instance with the specified output stream and character
* encoding.
*
* @throws MarcException
*/
public MarcXmlWriter(OutputStream out, String encoding) {
this(out, encoding, false);
}
/**
* Constructs an instance with the specified output stream, character
* encoding and indentation.
*
* @throws MarcException
*/
public MarcXmlWriter(OutputStream out, String encoding, boolean indent) {
this.encoding = encoding;
if (out == null) {
throw new NullPointerException("null OutputStream");
}
if (this.encoding == null) {
throw new NullPointerException("null encoding");
}
try {
setIndent(indent);
writer = new OutputStreamWriter(out, encoding);
writer = new BufferedWriter(writer);
setHandler(new StreamResult(writer), null);
} catch (UnsupportedEncodingException e) {
throw new MarcException(e.getMessage(), e);
}
writeStartDocument();
}
/**
* Constructs an instance with the specified result.
*
* @param result
* @throws SAXException
*/
public MarcXmlWriter(Result result) {
if (result == null)
throw new NullPointerException("null Result");
setHandler(result, null);
writeStartDocument();
}
/**
* Constructs an instance with the specified stylesheet location and result.
*
* @param result
* @throws SAXException
*/
public MarcXmlWriter(Result result, String stylesheetUrl) {
this(result, new StreamSource(stylesheetUrl));
}
/**
* Constructs an instance with the specified stylesheet source and result.
*
* @param result
* @throws SAXException
*/
public MarcXmlWriter(Result result, Source stylesheet) {
if (stylesheet == null)
throw new NullPointerException("null Source");
if (result == null)
throw new NullPointerException("null Result");
setHandler(result, stylesheet);
writeStartDocument();
}
public void close() {
writeEndDocument();
try {
writer.write("\n");
writer.close();
} catch (IOException e) {
throw new MarcException(e.getMessage(), e);
}
}
/**
* Returns the character converter.
*
* @return CharConverter the character converter
*/
public CharConverter getConverter() {
return converter;
}
/**
* Sets the character converter.
*
* @param converter
* the character converter
*/
public void setConverter(CharConverter converter) {
this.converter = converter;
}
/**
* If set to true this writer will perform Unicode normalization on data
* elements using normalization form C (NFC). The default is false.
*
* The implementation used is ICU4J 2.6. This version is based on Unicode
* 4.0.
*
* @param normalize
* true if this writer performs Unicode normalization, false
* otherwise
*/
public void setUnicodeNormalization(boolean normalize) {
this.normalize = normalize;
}
/**
* Returns true if this writer will perform Unicode normalization, false
* otherwise.
*
* @return boolean - true if this writer performs Unicode normalization,
* false otherwise.
*/
public boolean getUnicodeNormalization() {
return normalize;
}
protected void setHandler(Result result, Source stylesheet)
throws MarcException {
try {
TransformerFactory factory = TransformerFactory.newInstance();
if (!factory.getFeature(SAXTransformerFactory.FEATURE))
throw new UnsupportedOperationException(
"SAXTransformerFactory is not supported");
SAXTransformerFactory saxFactory = (SAXTransformerFactory) factory;
if (stylesheet == null)
handler = saxFactory.newTransformerHandler();
else
handler = saxFactory.newTransformerHandler(stylesheet);
handler.getTransformer()
.setOutputProperty(OutputKeys.METHOD, "xml");
handler.setResult(result);
} catch (Exception e) {
throw new MarcException(e.getMessage(), e);
}
}
/**
* Writes the root start tag to the result.
*
* @throws SAXException
*/
protected void writeStartDocument() {
try {
AttributesImpl atts = new AttributesImpl();
handler.startDocument();
handler.startElement(Constants.MARCXML_NS_URI, COLLECTION, COLLECTION, atts);
} catch (SAXException e) {
throw new MarcException(
"SAX error occured while writing start document", e);
}
}
/**
* Writes the root end tag to the result.
*
* @throws SAXException
*/
protected void writeEndDocument() {
try {
if (indent)
handler.ignorableWhitespace("\n".toCharArray(), 0, 1);
handler
.endElement(Constants.MARCXML_NS_URI, COLLECTION,
COLLECTION);
handler.endPrefixMapping("");
handler.endDocument();
} catch (SAXException e) {
throw new MarcException(
"SAX error occured while writing end document", e);
}
}
/**
* Writes a Record object to the result.
*
* @param record -
* the <code>Record</code> object
* @throws SAXException
*/
public void write(Record record) {
try {
toXml(record);
} catch (SAXException e) {
throw new MarcException("SAX error occured while writing record", e);
}
}
/**
* Returns true if indentation is active, false otherwise.
*
* @return boolean
*/
public boolean hasIndent() {
return indent;
}
/**
* Activates or deactivates indentation. Default value is false.
*
* @param indent
*/
public void setIndent(boolean indent) {
this.indent = indent;
}
protected void toXml(Record record) throws SAXException
{
char temp[];
AttributesImpl atts = new AttributesImpl();
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 3);
handler.startElement(Constants.MARCXML_NS_URI, RECORD, RECORD, atts);
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 5);
handler.startElement(Constants.MARCXML_NS_URI, LEADER, LEADER, atts);
Leader leader = record.getLeader();
temp = leader.toString().toCharArray();
handler.characters(temp, 0, temp.length);
handler.endElement(Constants.MARCXML_NS_URI, LEADER, LEADER);
for (ControlField field : record.getControlFields())
{
atts = new AttributesImpl();
atts.addAttribute("", "tag", "tag", "CDATA", field.getTag());
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 5);
handler.startElement(Constants.MARCXML_NS_URI, CONTROL_FIELD, CONTROL_FIELD, atts);
temp = getDataElement(field.getData());
handler.characters(temp, 0, temp.length);
handler.endElement(Constants.MARCXML_NS_URI, CONTROL_FIELD, CONTROL_FIELD);
}
for (DataField field : record.getDataFields())
{
atts = new AttributesImpl();
atts.addAttribute("", "tag", "tag", "CDATA", field.getTag());
atts.addAttribute("", "ind1", "ind1", "CDATA", String.valueOf(field.getIndicator1()));
atts.addAttribute("", "ind2", "ind2", "CDATA", String.valueOf(field.getIndicator2()));
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 5);
handler.startElement(Constants.MARCXML_NS_URI, DATA_FIELD, DATA_FIELD, atts);
for (Subfield subfield : field.getSubfields())
{
atts = new AttributesImpl();
atts.addAttribute("", "code", "code", "CDATA", String.valueOf(subfield.getCode()));
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 7);
handler.startElement(Constants.MARCXML_NS_URI, SUBFIELD, SUBFIELD, atts);
temp = getDataElement(subfield.getData());
handler.characters(temp, 0, temp.length);
handler.endElement(Constants.MARCXML_NS_URI, SUBFIELD, SUBFIELD);
}
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 5);
handler.endElement(Constants.MARCXML_NS_URI, DATA_FIELD, DATA_FIELD);
}
if (indent)
handler.ignorableWhitespace("\n ".toCharArray(), 0, 3);
handler.endElement(Constants.MARCXML_NS_URI, RECORD, RECORD);
}
protected char[] getDataElement(String data)
{
String dataElement = null;
if (converter == null)
dataElement = data;
else
dataElement = converter.convert(data);
if (normalize)
dataElement = Normalizer.normalize(dataElement, Normalizer.NFC);
return dataElement.toCharArray();
}
} |
package edu.washington.escience.myria.util;
import java.util.Objects;
import com.google.common.base.Preconditions;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import edu.washington.escience.myria.storage.ReadableColumn;
import edu.washington.escience.myria.storage.ReadableTable;
/**
* A utility class for hashing tuples and parts of tuples.
*/
public final class HashUtils {
/** Utility classes have no constructors. */
private HashUtils() {}
private static final int[] SEEDS = {
243, 402653189, 24593, 786433, 3145739, 12289, 49157, 6151, 98317, 1572869,
};
/** The hash functions. */
private static final HashFunction[] HASH_FUNCTIONS = {
Hashing.murmur3_128(SEEDS[0]),
Hashing.murmur3_128(SEEDS[1]),
Hashing.murmur3_128(SEEDS[2]),
Hashing.murmur3_128(SEEDS[3]),
Hashing.murmur3_128(SEEDS[4]),
Hashing.murmur3_128(SEEDS[5]),
Hashing.murmur3_128(SEEDS[6]),
Hashing.murmur3_128(SEEDS[7]),
Hashing.murmur3_128(SEEDS[8]),
Hashing.murmur3_128(SEEDS[9])
};
/**
* Size of the hash function pool.
*/
public static final int NUM_OF_HASHFUNCTIONS = 10;
private static HashCode getHashCode(
final ReadableTable table, final int[] hashColumns, final int row, final int seedIndex) {
Objects.requireNonNull(table, "table");
Objects.requireNonNull(hashColumns, "hashColumns");
Hasher hasher = HASH_FUNCTIONS[seedIndex].newHasher();
for (int column : hashColumns) {
addValue(hasher, table, column, row);
}
return hasher.hash();
}
private static HashCode getHashCode(final ReadableTable table, final int row) {
return getHashCode(table, MyriaUtils.range(table.numColumns()), row, 0);
}
/**
* Compute the hash code of all the values in the specified row, in column order.
*
* @param table the table containing the values
* @param row the row to be hashed
* @return the hash code of all the values in the specified row, in column order
*/
public static int hashRow(final ReadableTable table, final int row) {
return getHashCode(table, row).asInt();
}
/**
* Compute the hash code of all the values in the specified row, in column order.
*
* @param table the table containing the values
* @param row the row to be hashed
* @return the hash code of all the values in the specified row, in column order
*/
public static long hashRowLong(final ReadableTable table, final int row) {
return getHashCode(table, row).asLong();
}
/**
* Compute the hash code of all the values in the specified row, in column order.
*
* @param table the table containing the values
* @param row the row to be hashed
* @return the hash code of all the values in the specified row, in column order
*/
public static byte[] hashRowBytes(final ReadableTable table, final int row) {
return getHashCode(table, row).asBytes();
}
/**
* Compute the hash code of the value in the specified column and row of the given table.
*
* @param table the table containing the values to be hashed
* @param column the column containing the value to be hashed
* @param row the row containing the value to be hashed
* @return the hash code of the specified value
*/
public static int hashValue(final ReadableTable table, final int column, final int row) {
return hashValue(table, column, row, 0);
}
/**
* Compute the hash code of the value in the specified column and row of the given table with specific hashcode.
*
* @param table the table containing the values to be hashed
* @param column the column containing the value to be hashed
* @param row the row containing the value to be hashed
* @param seedIndex the index of the chosen hash function
* @return hash code of the specified seed
*/
public static int hashValue(
final ReadableTable table, final int column, final int row, final int seedIndex) {
Preconditions.checkPositionIndex(seedIndex, NUM_OF_HASHFUNCTIONS);
Hasher hasher = HASH_FUNCTIONS[seedIndex].newHasher();
addValue(hasher, table, column, row);
return hasher.hash().asInt();
}
/**
* Compute the hash code of the specified columns in the specified row of the given table.
*
* @param table the table containing the values to be hashed
* @param hashColumns the columns to be hashed. Order matters
* @param row the row containing the values to be hashed
* @return the hash code of the specified columns in the specified row of the given table
*/
public static int hashSubRow(final ReadableTable table, final int[] hashColumns, final int row) {
return hashSubRow(table, hashColumns, row, 0);
}
/**
* Compute the hash code of the specified columns in the specified row of the given table.
*
* @param table the table containing the values to be hashed
* @param hashColumns the columns to be hashed. Order matters
* @param row the row containing the values to be hashed
* @param seedIndex the index of the chosen hash function
* @return the hash code of the specified columns in the specified row of the given table
*/
public static int hashSubRow(
final ReadableTable table, final int[] hashColumns, final int row, final int seedIndex) {
return getHashCode(table, hashColumns, row, seedIndex).asInt();
}
/**
* Compute the hash code of the value in the specified column and row of the given table.
*
* @param table the table containing the values to be hashed
* @param column the column containing the value to be hashed
* @param row the row containing the value to be hashed
* @return the hash code of the specified value
*/
public static long hashValueLong(final ReadableTable table, final int column, final int row) {
return hashValueLong(table, column, row, 0);
}
/**
* Compute the hash code of the value in the specified column and row of the given table with specific hashcode.
*
* @param table the table containing the values to be hashed
* @param column the column containing the value to be hashed
* @param row the row containing the value to be hashed
* @param seedIndex the index of the chosen hash function
* @return hash code of the specified seed
*/
public static long hashValueLong(
final ReadableTable table, final int column, final int row, final int seedIndex) {
Preconditions.checkPositionIndex(seedIndex, NUM_OF_HASHFUNCTIONS);
Hasher hasher = HASH_FUNCTIONS[seedIndex].newHasher();
addValue(hasher, table, column, row);
return hasher.hash().asLong();
}
/**
* Compute the hash code of the specified columns in the specified row of the given table.
*
* @param table the table containing the values to be hashed
* @param hashColumns the columns to be hashed. Order matters
* @param row the row containing the values to be hashed
* @return the hash code of the specified columns in the specified row of the given table
*/
public static long hashSubRowLong(
final ReadableTable table, final int[] hashColumns, final int row) {
return hashSubRowLong(table, hashColumns, row, 0);
}
/**
* Compute the hash code of the specified columns in the specified row of the given table.
*
* @param table the table containing the values to be hashed
* @param hashColumns the columns to be hashed. Order matters
* @param row the row containing the values to be hashed
* @param seedIndex the index of the chosen hash function
* @return the hash code of the specified columns in the specified row of the given table
*/
public static long hashSubRowLong(
final ReadableTable table, final int[] hashColumns, final int row, final int seedIndex) {
return getHashCode(table, hashColumns, row, seedIndex).asLong();
}
/**
* Add the value at the specified row and column to the specified hasher.
*
* @param hasher the hasher
* @param table the table containing the value
* @param column the column containing the value
* @param row the row containing the value
* @return the hasher
*/
private static Hasher addValue(
final Hasher hasher, final ReadableTable table, final int column, final int row) {
return addValue(hasher, table.asColumn(column), row);
}
/**
* Add the value at the specified row and column to the specified hasher.
*
* @param hasher the hasher
* @param column the column containing the value
* @param row the row containing the value
* @return the hasher
*/
private static Hasher addValue(final Hasher hasher, final ReadableColumn column, final int row) {
switch (column.getType()) {
case BOOLEAN_TYPE:
return hasher.putBoolean(column.getBoolean(row));
case DATETIME_TYPE:
return hasher.putObject(column.getDateTime(row), TypeFunnel.INSTANCE);
case DOUBLE_TYPE:
return hasher.putDouble(column.getDouble(row));
case FLOAT_TYPE:
return hasher.putFloat(column.getFloat(row));
case INT_TYPE:
return hasher.putInt(column.getInt(row));
case LONG_TYPE:
return hasher.putLong(column.getLong(row));
case STRING_TYPE:
return hasher.putObject(column.getString(row), TypeFunnel.INSTANCE);
default:
throw new UnsupportedOperationException(
"Hashing a column of type " + column.getType() + " is unsupported");
}
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.redkale.util;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;
import java.nio.charset.*;
import java.time.*;
import java.util.*;
import java.util.function.*;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.*;
public final class Utility {
private static final int zoneRawOffset = TimeZone.getDefault().getRawOffset();
private static final String format = "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final sun.misc.Unsafe UNSAFE;
private static final long strvaloffset;
private static final long sbvaloffset;
private static final javax.net.ssl.SSLContext DEFAULTSSL_CONTEXT;
private static final javax.net.ssl.HostnameVerifier defaultVerifier = (s, ss) -> true;
static {
sun.misc.Unsafe usafe = null;
long fd1 = 0L;
long fd2 = 0L;
try {
Field f = String.class.getDeclaredField("value");
if (f.getType() == char[].class) { //JDK9char[]
Field safeField = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
safeField.setAccessible(true);
usafe = (sun.misc.Unsafe) safeField.get(null);
fd1 = usafe.objectFieldOffset(f);
fd2 = usafe.objectFieldOffset(StringBuilder.class.getSuperclass().getDeclaredField("value"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
UNSAFE = usafe;
strvaloffset = fd1;
sbvaloffset = fd2;
try {
DEFAULTSSL_CONTEXT = javax.net.ssl.SSLContext.getInstance("SSL");
DEFAULTSSL_CONTEXT.init(null, new javax.net.ssl.TrustManager[]{new javax.net.ssl.X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException {
}
}}, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Utility() {
}
/**
* key:valueMapitems,
* JDK9 Map.of
*
* @param items
*
* @return Map
*/
public static Map<String, String> ofMap(String... items) {
HashMap<String, String> map = new LinkedHashMap<>();
int len = items.length / 2;
for (int i = 0; i < len; i++) {
map.put(items[i * 2], items[i * 2 + 1]);
}
return map;
}
/**
* key:valueMapitems,
* JDK9 Map.of
*
* @param <K>
* @param <V>
* @param items
*
* @return Map
*/
public static <K, V> Map<K, V> ofMap(Object... items) {
HashMap<K, V> map = new LinkedHashMap<>();
int len = items.length / 2;
for (int i = 0; i < len; i++) {
map.put((K) items[i * 2], (V) items[i * 2 + 1]);
}
return map;
}
/**
* MapMap
*
* @param <K>
* @param <V>
* @param maps Map
*
* @return Map
*/
public static <K, V> Map<K, V> merge(Map<K, V>... maps) {
Map<K, V> map = null;
for (Map<K, V> m : maps) {
if (map == null) {
map = m;
} else if (m != null) {
map.putAll(m);
}
}
return map;
}
/**
* Set
*
* @param <T>
* @param items
*
* @return Set
*/
public static <T> Set<T> ofSet(T... items) {
Set<T> set = new LinkedHashSet<>();
for (T item : items) set.add(item);
return set;
}
/**
* List
*
* @param <T>
* @param items
*
* @return List
*/
public static <T> List<T> ofList(T... items) {
List<T> list = new ArrayList<>();
for (T item : items) list.add(item);
return list;
}
/**
* "-"UUID
*
* @return "-"UUID
*/
public static String uuid() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
*
*
* @param <T>
* @param array
* @param objs
*
* @return
*/
public static <T> T[] unshift(final T[] array, final T... objs) {
if (array == null || array.length == 0) return objs;
final T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + objs.length);
System.arraycopy(objs, 0, news, 0, objs.length);
System.arraycopy(array, 0, news, objs.length, array.length);
return news;
}
/**
*
*
* @param <T>
* @param array
* @param objs
*
* @return
*/
public static <T> T[] unshift(final T[] array, final Collection<T> objs) {
if (objs == null || objs.isEmpty()) return array;
if (array == null) {
T one = null;
for (T t : objs) {
if (t != null) one = t;
break;
}
if (one == null) return array;
T[] news = (T[]) Array.newInstance(one.getClass(), objs.size());
return objs.toArray(news);
}
T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + objs.size());
int index = -1;
for (T t : objs) {
news[(++index)] = t;
}
System.arraycopy(array, 0, news, objs.size(), array.length);
return news;
}
/**
* int
*
* @param array
*
* @return int
*/
public static int max(final int... array) {
if (array == null || array.length == 0) throw new NullPointerException("array is null or empty");
int max = array[0];
for (int i : array) {
if (i > max) i = max;
}
return max;
}
/**
* long
*
* @param array
*
* @return long
*/
public static long max(final long... array) {
if (array == null || array.length == 0) throw new NullPointerException("array is null or empty");
long max = array[0];
for (long i : array) {
if (i > max) i = max;
}
return max;
}
/**
* int
*
* @param array
*
* @return int
*/
public static long min(final int... array) {
if (array == null || array.length == 0) throw new NullPointerException("array is null or empty");
int min = array[0];
for (int i : array) {
if (i < min) i = min;
}
return min;
}
/**
* long
*
* @param array
*
* @return long
*/
public static long min(final long... array) {
if (array == null || array.length == 0) throw new NullPointerException("array is null or empty");
long min = array[0];
for (long i : array) {
if (i < min) i = min;
}
return min;
}
/**
* int
*
* @param array
* @param delimiter
*
* @return String
*/
public static String joining(final int[] array, final String delimiter) {
if (array == null || array.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (int i : array) {
if (sb.length() > 0) sb.append(delimiter);
sb.append(i);
}
return sb.toString();
}
/**
* long
*
* @param array
* @param delimiter
*
* @return String
*/
public static String joining(final long[] array, final String delimiter) {
if (array == null || array.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (long i : array) {
if (sb.length() > 0) sb.append(delimiter);
sb.append(i);
}
return sb.toString();
}
/**
*
*
* @param <T>
* @param array
* @param delimiter
*
* @return String
*/
public static <T> String joining(final T[] array, final String delimiter) {
if (array == null || array.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (T i : array) {
if (sb.length() > 0) sb.append(delimiter);
sb.append(i);
}
return sb.toString();
}
/**
* intint
*
* @param array
* @param objs
*
* @return
*/
public static int[] append(final int[] array, final int... objs) {
if (array == null || array.length == 0) return objs;
if (objs == null || objs.length == 0) return array;
final int[] news = new int[array.length + objs.length];
System.arraycopy(array, 0, news, 0, array.length);
System.arraycopy(objs, 0, news, array.length, objs.length);
return news;
}
/**
* longlong
*
* @param array
* @param objs
*
* @return
*/
public static long[] append(final long[] array, final long... objs) {
if (array == null || array.length == 0) return objs;
if (objs == null || objs.length == 0) return array;
final long[] news = new long[array.length + objs.length];
System.arraycopy(array, 0, news, 0, array.length);
System.arraycopy(objs, 0, news, array.length, objs.length);
return news;
}
/**
*
*
* @param <T>
* @param array
* @param objs
*
* @return
*/
public static <T> T[] append(final T[] array, final T... objs) {
if (array == null || array.length == 0) return objs;
if (objs == null || objs.length == 0) return array;
final T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + objs.length);
System.arraycopy(array, 0, news, 0, array.length);
System.arraycopy(objs, 0, news, array.length, objs.length);
return news;
}
/**
*
*
* @param <T>
* @param array
* @param objs
*
* @return
*/
public static <T> T[] append(final T[] array, final Collection<T> objs) {
if (objs == null || objs.isEmpty()) return array;
if (array == null) {
T one = null;
for (T t : objs) {
if (t != null) one = t;
break;
}
if (one == null) return array;
T[] news = (T[]) Array.newInstance(one.getClass(), objs.size());
return objs.toArray(news);
}
T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length + objs.size());
System.arraycopy(array, 0, news, 0, array.length);
int index = -1;
for (T t : objs) {
news[array.length + (++index)] = t;
}
return news;
}
/**
*
*
* @param <T>
* @param array
* @param item
*
* @return
*/
public static <T> T[] remove(final T[] array, final T item) {
return remove(array, (i) -> item.equals(item));
}
/**
*
*
* @param <T>
* @param array
* @param filter Predicate
*
* @return
*/
public static <T> T[] remove(final T[] array, final Predicate filter) {
if (array == null || array.length == 0 || filter == null) return array;
final T[] news = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length);
int index = 0;
for (int i = 0; i < news.length; i++) {
if (!filter.test(array[i])) {
news[index++] = array[i];
}
}
if (index == array.length) return array;
final T[] rs = (T[]) Array.newInstance(array.getClass().getComponentType(), index);
System.arraycopy(news, 0, rs, 0, index);
return rs;
}
/**
* true
*
* @param string
* @param values
*
* @return boolean
*/
public static boolean contains(String string, char... values) {
if (string == null) return false;
for (char ch : Utility.charArray(string)) {
for (char ch2 : values) {
if (ch == ch2) return true;
}
}
return false;
}
/**
*
*
* @param columns
* @param cols
*
* @return
*/
public static String[] exclude(final String[] columns, final String... cols) {
if (columns == null || columns.length == 0 || cols == null || cols.length == 0) return columns;
int count = 0;
for (String column : columns) {
boolean flag = false;
for (String col : cols) {
if (column != null && column.equals(col)) {
flag = true;
break;
}
}
if (flag) count++;
}
if (count == 0) return columns;
if (count == columns.length) return new String[0];
final String[] newcols = new String[columns.length - count];
count = 0;
for (String column : columns) {
boolean flag = false;
for (String col : cols) {
if (column != null && column.equals(col)) {
flag = true;
break;
}
}
if (!flag) newcols[count++] = column;
}
return newcols;
}
/**
* buffer, stringbuffer
*
* @param string
* @param buffer ByteBuffer
*
* @return
*/
public static String toString(String string, ByteBuffer buffer) {
if (buffer == null || !buffer.hasRemaining()) return string;
int pos = buffer.position();
int limit = buffer.limit();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
buffer.position(pos);
buffer.limit(limit);
if (string == null) return new String(bytes, UTF_8);
return string + new String(bytes, UTF_8);
}
/**
* buffer, stringbuffer
*
* @param string
* @param buffer ByteBuffer
*
*/
public static void println(String string, ByteBuffer buffer) {
if (buffer == null || !buffer.hasRemaining()) return;
int pos = buffer.position();
int limit = buffer.limit();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
buffer.position(pos);
buffer.limit(limit);
println(string, bytes);
}
/**
* , string
*
* @param string
* @param bytes
*
*/
public static void println(String string, byte... bytes) {
if (bytes == null) return;
StringBuilder sb = new StringBuilder();
if (string != null) sb.append(string);
sb.append(bytes.length).append(".[");
boolean last = false;
for (byte b : bytes) {
if (last) sb.append(',');
int v = b & 0xff;
sb.append("0x");
if (v < 16) sb.append('0');
sb.append(Integer.toHexString(v));
last = true;
}
sb.append(']');
(System.out).println(sb);
}
/**
* IPv4 null
*
* @return IPv4
*/
public static InetAddress localInetAddress() {
InetAddress back = null;
try {
Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
while (nifs.hasMoreElements()) {
NetworkInterface nif = nifs.nextElement();
if (!nif.isUp()) continue;
Enumeration<InetAddress> eis = nif.getInetAddresses();
while (eis.hasMoreElements()) {
InetAddress ia = eis.nextElement();
if (ia.isLoopbackAddress()) back = ia;
if (ia.isSiteLocalAddress()) return ia;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return back;
}
/**
* CompletionHandler
*
* @param <V>
* @param <A>
* @param success
* @param fail
*
* @return CompletionHandler
*/
public static <V, A> CompletionHandler<V, A> createAsyncHandler(final BiConsumer<V, A> success, final BiConsumer<Throwable, A> fail) {
return new CompletionHandler<V, A>() {
@Override
public void completed(V result, A attachment) {
if (success != null) success.accept(result, attachment);
}
@Override
public void failed(Throwable exc, A attachment) {
if (fail != null) fail.accept(exc, attachment);
}
};
}
/**
* CompletionHandler
*
* @param <A>
* @param success
* @param fail
*
* @return CompletionHandler
*/
public static <A> CompletionHandler<Void, A> createAsyncHandler(final Consumer<A> success, final BiConsumer<Throwable, A> fail) {
return new CompletionHandler<Void, A>() {
@Override
public void completed(Void result, A attachment) {
if (success != null) success.accept(attachment);
}
@Override
public void failed(Throwable exc, A attachment) {
if (fail != null) fail.accept(exc, attachment);
}
};
}
/**
* CompletionHandler
*
* @param <V>
* @param success
* @param fail
*
* @return CompletionHandler
*/
public static <V> CompletionHandler<V, Void> createAsyncHandler(final Consumer<V> success, final Consumer<Throwable> fail) {
return new CompletionHandler<V, Void>() {
@Override
public void completed(V result, Void attachment) {
if (success != null) success.accept(result);
}
@Override
public void failed(Throwable exc, Void attachment) {
if (fail != null) fail.accept(exc);
}
};
}
/**
* yyyy-MM-dd HH:mm:ss
*
* @return yyyy-MM-dd HH:mm:ss
*/
public static String now() {
return String.format(format, System.currentTimeMillis());
}
/**
* yyyy-MM-dd HH:mm:ss
*
* @param time
*
* @return yyyy-MM-dd HH:mm:ss
*/
public static String formatTime(long time) {
return String.format(format, time);
}
/**
* 93680
*
* @param time
*
* @return 36
*/
public static String format36time(long time) {
String time36 = Long.toString(time, 36);
return time36.length() < 9 ? ("0" + time36) : time36;
}
/**
*
*
* @return
*/
public static long midnight() {
return midnight(System.currentTimeMillis());
}
/**
*
*
* @param time
*
* @return
*/
public static long midnight(long time) {
return (time + zoneRawOffset) / 86400000 * 86400000 - zoneRawOffset;
}
/**
* 20151231int
*
* @return 20151231int
*/
public static int today() {
java.time.LocalDate today = java.time.LocalDate.now();
return today.getYear() * 10000 + today.getMonthValue() * 100 + today.getDayOfMonth();
}
/**
* 20151230int
*
* @return 20151230int
*/
public static int yesterday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -1);
return cal.get(Calendar.YEAR) * 10000 + (cal.get(Calendar.MONTH) + 1) * 100 + cal.get(Calendar.DAY_OF_MONTH);
}
/**
* 20160202int
*
* @param time
*
* @return
*/
public static int yyyyMMdd(long time) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
return cal.get(Calendar.YEAR) * 10000 + (cal.get(Calendar.MONTH) + 1) * 100 + cal.get(Calendar.DAY_OF_MONTH);
}
/**
*
*
* @param time
*
* @return
*/
public static long monday(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate();
ld = ld.minusDays(ld.getDayOfWeek().getValue() - 1);
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
/**
*
*
* @param time
*
* @return
*/
public static long sunday(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate();
ld = ld.plusDays(7 - ld.getDayOfWeek().getValue());
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
/**
* 1
*
* @param time
*
* @return
*/
public static long monthFirstDay(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate().withDayOfMonth(1);
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
/**
*
*
* @param time
*
* @return
*/
public static long monthLastDay(long time) {
ZoneId zid = ZoneId.systemDefault();
Instant instant = Instant.ofEpochMilli(time);
LocalDate ld = instant.atZone(zid).toLocalDate();
ld = ld.withDayOfMonth(ld.lengthOfMonth());
return ld.atStartOfDay(zid).toInstant().toEpochMilli();
}
/**
* 16
*
* @param bytes
*
* @return 16
*/
public static String binToHexString(byte[] bytes) {
return new String(binToHex(bytes));
}
/**
* 16
*
* @param bytes
*
* @return 16
*/
public static char[] binToHex(byte[] bytes) {
return binToHex(bytes, 0, bytes.length);
}
/**
* 16
*
* @param bytes
* @param offset
* @param len
*
* @return 16
*/
public static String binToHexString(byte[] bytes, int offset, int len) {
return new String(binToHex(bytes, offset, len));
}
/**
* 16
*
* @param bytes
* @param offset
* @param len
*
* @return 16
*/
public static char[] binToHex(byte[] bytes, int offset, int len) {
final char[] sb = new char[len * 2];
final int end = offset + len;
int index = 0;
final char[] hexs = hex;
for (int i = offset; i < end; i++) {
byte b = bytes[i];
sb[index++] = (hexs[((b >> 4) & 0xF)]);
sb[index++] = hexs[((b) & 0xF)];
}
return sb;
}
/**
* 16
*
* @param src 16
*
* @return
*/
public static byte[] hexToBin(CharSequence src) {
return hexToBin(src, 0, src.length());
}
/**
*
* 16
*
* @param src 16
* @param offset
* @param len
*
* @return
*/
public static byte[] hexToBin(CharSequence src, int offset, int len) {
final int size = (len + 1) / 2;
final byte[] bytes = new byte[size];
String digits = "0123456789abcdef";
for (int i = 0; i < size; i++) {
int ch1 = src.charAt(offset + i * 2);
if ('A' <= ch1 && 'F' >= ch1) ch1 = ch1 - 'A' + 'a';
int ch2 = src.charAt(offset + i * 2 + 1);
if ('A' <= ch2 && 'F' >= ch2) ch2 = ch2 - 'A' + 'a';
int pos1 = digits.indexOf(ch1);
if (pos1 < 0) throw new NumberFormatException();
int pos2 = digits.indexOf(ch2);
if (pos2 < 0) throw new NumberFormatException();
bytes[i] = (byte) (pos1 * 0x10 + pos2);
}
return bytes;
}
/**
*
* 16
*
* @param str 16
*
* @return
*/
public static byte[] hexToBin(String str) {
return hexToBin(charArray(str));
}
/**
*
* 16
*
* @param src 16
*
* @return
*/
public static byte[] hexToBin(char[] src) {
return hexToBin(src, 0, src.length);
}
/**
* 16
*
* @param src 16
* @param offset
* @param len
*
* @return
*/
public static byte[] hexToBin(char[] src, int offset, int len) {
final int size = (len + 1) / 2;
final byte[] bytes = new byte[size];
String digits = "0123456789abcdef";
for (int i = 0; i < size; i++) {
int ch1 = src[offset + i * 2];
if ('A' <= ch1 && 'F' >= ch1) ch1 = ch1 - 'A' + 'a';
int ch2 = src[offset + i * 2 + 1];
if ('A' <= ch2 && 'F' >= ch2) ch2 = ch2 - 'A' + 'a';
int pos1 = digits.indexOf(ch1);
if (pos1 < 0) throw new NumberFormatException();
int pos2 = digits.indexOf(ch2);
if (pos2 < 0) throw new NumberFormatException();
bytes[i] = (byte) (pos1 * 0x10 + pos2);
}
return bytes;
}
/**
* UTF-8byte[]char[]
*
* @param array byte[]
*
* @return char[]
*/
public static char[] decodeUTF8(final byte[] array) {
return decodeUTF8(array, 0, array.length);
}
public static char[] decodeUTF8(final byte[] array, final int start, final int len) {
byte b;
int size = len;
final byte[] bytes = array;
final int limit = start + len;
for (int i = start; i < limit; i++) {
b = bytes[i];
if ((b >> 5) == -2) {
size
} else if ((b >> 4) == -2) {
size -= 2;
}
}
final char[] text = new char[size];
size = 0;
for (int i = start; i < limit;) {
b = bytes[i++];
if (b >= 0) {
text[size++] = (char) b;
} else if ((b >> 5) == -2) {
text[size++] = (char) (((b << 6) ^ bytes[i++]) ^ (((byte) 0xC0 << 6) ^ ((byte) 0x80)));
} else if ((b >> 4) == -2) {
text[size++] = (char) ((b << 12) ^ (bytes[i++] << 6) ^ (bytes[i++] ^ (((byte) 0xE0 << 12) ^ ((byte) 0x80 << 6) ^ ((byte) 0x80))));
}
}
return text;
}
public static byte[] encodeUTF8(final String value) {
if (value == null) return new byte[0];
if (UNSAFE == null) return encodeUTF8(value.toCharArray());
return encodeUTF8((char[]) UNSAFE.getObject(value, strvaloffset));
}
public static byte[] encodeUTF8(final char[] array) {
return encodeUTF8(array, 0, array.length);
}
public static byte[] encodeUTF8(final char[] text, final int start, final int len) {
char c;
int size = 0;
final char[] chars = text;
final int limit = start + len;
for (int i = start; i < limit; i++) {
c = chars[i];
if (c < 0x80) {
size++;
} else if (c < 0x800) {
size += 2;
} else {
size += 3;
}
}
final byte[] bytes = new byte[size];
size = 0;
for (int i = start; i < limit; i++) {
c = chars[i];
if (c < 0x80) {
bytes[size++] = (byte) c;
} else if (c < 0x800) {
bytes[size++] = (byte) (0xc0 | (c >> 6));
bytes[size++] = (byte) (0x80 | (c & 0x3f));
} else {
bytes[size++] = (byte) (0xe0 | ((c >> 12)));
bytes[size++] = (byte) (0x80 | ((c >> 6) & 0x3f));
bytes[size++] = (byte) (0x80 | (c & 0x3f));
}
}
return bytes;
}
public static char[] charArray(String value) {
if (value == null) return null;
if (UNSAFE == null) return value.toCharArray();
return (char[]) UNSAFE.getObject(value, strvaloffset);
}
public static char[] charArray(StringBuilder value) {
if (value == null) return null;
if (UNSAFE == null) return value.toString().toCharArray();
return (char[]) UNSAFE.getObject(value, sbvaloffset);
}
public static ByteBuffer encodeUTF8(final ByteBuffer buffer, final char[] array) {
return encodeUTF8(buffer, array, 0, array.length);
}
public static ByteBuffer encodeUTF8(final ByteBuffer buffer, int bytesLength, final char[] array) {
return encodeUTF8(buffer, bytesLength, array, 0, array.length);
}
public static int encodeUTF8Length(String value) {
if (value == null) return -1;
if (UNSAFE == null) return encodeUTF8Length(value.toCharArray());
return encodeUTF8Length((char[]) UNSAFE.getObject(value, strvaloffset));
}
public static int encodeUTF8Length(final char[] text) {
return encodeUTF8Length(text, 0, text.length);
}
public static int encodeUTF8Length(final char[] text, final int start, final int len) {
char c;
int size = 0;
final char[] chars = text;
final int limit = start + len;
for (int i = start; i < limit; i++) {
c = chars[i];
size += (c < 0x80 ? 1 : (c < 0x800 ? 2 : 3));
}
return size;
}
/**
* long
*
* @param high
* @param low
*
* @return long
*/
public static long merge(int high, int low) {
return (0L + high) << 32 | low;
}
public static ByteBuffer encodeUTF8(final ByteBuffer buffer, final char[] text, final int start, final int len) {
return encodeUTF8(buffer, encodeUTF8Length(text, start, len), text, start, len);
}
public static ByteBuffer encodeUTF8(final ByteBuffer buffer, int bytesLength, final char[] text, final int start, final int len) {
char c;
char[] chars = text;
final int limit = start + len;
int remain = buffer.remaining();
final ByteBuffer buffer2 = remain >= bytesLength ? null : ByteBuffer.allocate(bytesLength - remain + 3); //bufferbyte
ByteBuffer buf = buffer;
for (int i = start; i < limit; i++) {
c = chars[i];
if (c < 0x80) {
if (buf.remaining() < 1) buf = buffer2;
buf.put((byte) c);
} else if (c < 0x800) {
if (buf.remaining() < 2) buf = buffer2;
buf.put((byte) (0xc0 | (c >> 6)));
buf.put((byte) (0x80 | (c & 0x3f)));
} else {
if (buf.remaining() < 3) buf = buffer2;
buf.put((byte) (0xe0 | ((c >> 12))));
buf.put((byte) (0x80 | ((c >> 6) & 0x3f)));
buf.put((byte) (0x80 | (c & 0x3f)));
}
}
if (buffer2 != null) buffer2.flip();
return buffer2;
}
public static String getTypeDescriptor(java.lang.reflect.Type type) {
if (type == null) return null;
if (type instanceof Class) {
Class d = (Class) type;
final StringBuilder sb = new StringBuilder();
while (true) {
if (d.isPrimitive()) {
char car;
if (d == Integer.TYPE) {
car = 'I';
} else if (d == Void.TYPE) {
car = 'V';
} else if (d == Boolean.TYPE) {
car = 'Z';
} else if (d == Byte.TYPE) {
car = 'B';
} else if (d == Character.TYPE) {
car = 'C';
} else if (d == Short.TYPE) {
car = 'S';
} else if (d == Double.TYPE) {
car = 'D';
} else if (d == Float.TYPE) {
car = 'F';
} else /* if (d == Long.TYPE) */ {
car = 'J';
}
return sb.append(car).toString();
} else if (d.isArray()) {
sb.append('[');
d = d.getComponentType();
} else {
sb.append('L');
String name = d.getName();
int len = name.length();
for (int i = 0; i < len; ++i) {
char car = name.charAt(i);
sb.append(car == '.' ? '/' : car);
}
return sb.append(';').toString();
}
}
}
if (type instanceof ParameterizedType) {// : Map<String, Serializable>
ParameterizedType pt = (ParameterizedType) type;
final StringBuilder sb = new StringBuilder();
String raw = getTypeDescriptor(pt.getRawType());
sb.append(raw.substring(0, raw.length() - 1)).append('<');
for (java.lang.reflect.Type item : pt.getActualTypeArguments()) {
sb.append(getTypeDescriptor(item));
}
return sb.append(">;").toString();
}
if (type instanceof WildcardType) { // : <? extends Serializable>
final WildcardType wt = (WildcardType) type;
final StringBuilder sb = new StringBuilder();
java.lang.reflect.Type[] us = wt.getUpperBounds();
java.lang.reflect.Type[] ls = wt.getLowerBounds();
if (ls.length < 1) {
if (us.length == 1 && us[0] == Object.class) {
sb.append('*');
} else {
for (java.lang.reflect.Type f : us) {
sb.append('+');
sb.append(getTypeDescriptor(f));
}
}
}
for (java.lang.reflect.Type f : ls) {
sb.append('-');
sb.append(getTypeDescriptor(f));
}
return sb.toString();
}
//TypeVariable
return null;
}
public static javax.net.ssl.SSLContext getDefaultSSLContext() {
return DEFAULTSSL_CONTEXT;
}
public static javax.net.ssl.HostnameVerifier getDefaultHostnameVerifier() {
return defaultVerifier;
}
public static Socket createDefaultSSLSocket(InetSocketAddress address) throws IOException {
return createDefaultSSLSocket(address.getAddress(), address.getPort());
}
public static Socket createDefaultSSLSocket(InetAddress host, int port) throws IOException {
Socket socket = DEFAULTSSL_CONTEXT.getSocketFactory().createSocket(host, port);
return socket;
}
public static String postHttpContent(String url) throws IOException {
return remoteHttpContent(null, "POST", url, 0, null, null).toString("UTF-8");
}
public static String postHttpContent(String url, int timeout) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, null, null).toString("UTF-8");
}
public static String postHttpContent(String url, String body) throws IOException {
return remoteHttpContent(null, "POST", url, 0, null, body).toString("UTF-8");
}
public static String postHttpContent(String url, int timeout, String body) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, null, body).toString("UTF-8");
}
public static String postHttpContent(String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "POST", url, 0, headers, body).toString("UTF-8");
}
public static String postHttpContent(String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, headers, body).toString("UTF-8");
}
public static String postHttpContent(SSLContext ctx, String url) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, null, null).toString("UTF-8");
}
public static String postHttpContent(SSLContext ctx, String url, int timeout) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, null, null).toString("UTF-8");
}
public static String postHttpContent(SSLContext ctx, String url, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, null, body).toString("UTF-8");
}
public static String postHttpContent(SSLContext ctx, String url, int timeout, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, null, body).toString("UTF-8");
}
public static String postHttpContent(SSLContext ctx, String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, headers, body).toString("UTF-8");
}
public static String postHttpContent(SSLContext ctx, String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, headers, body).toString("UTF-8");
}
public static String postHttpContent(String url, Charset charset) throws IOException {
return remoteHttpContent(null, "POST", url, 0, null, null).toString(charset.name());
}
public static String postHttpContent(String url, int timeout, Charset charset) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, null, null).toString(charset.name());
}
public static String postHttpContent(String url, Charset charset, String body) throws IOException {
return remoteHttpContent(null, "POST", url, 0, null, body).toString(charset.name());
}
public static String postHttpContent(String url, int timeout, Charset charset, String body) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, null, body).toString(charset.name());
}
public static String postHttpContent(String url, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "POST", url, 0, headers, body).toString(charset.name());
}
public static String postHttpContent(String url, int timeout, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, headers, body).toString(charset.name());
}
public static String postHttpContent(SSLContext ctx, String url, Charset charset) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, null, null).toString(charset.name());
}
public static String postHttpContent(SSLContext ctx, String url, int timeout, Charset charset) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, null, null).toString(charset.name());
}
public static String postHttpContent(SSLContext ctx, String url, Charset charset, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, null, body).toString(charset.name());
}
public static String postHttpContent(SSLContext ctx, String url, int timeout, Charset charset, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, null, body).toString(charset.name());
}
public static String postHttpContent(SSLContext ctx, String url, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, headers, body).toString(charset.name());
}
public static String postHttpContent(SSLContext ctx, String url, int timeout, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, headers, body).toString(charset.name());
}
public static byte[] postHttpBytesContent(String url) throws IOException {
return remoteHttpContent(null, "POST", url, 0, null, null).toByteArray();
}
public static byte[] postHttpBytesContent(String url, int timeout) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, null, null).toByteArray();
}
public static byte[] postHttpBytesContent(SSLContext ctx, String url) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, null, null).toByteArray();
}
public static byte[] postHttpBytesContent(SSLContext ctx, String url, int timeout) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, null, null).toByteArray();
}
public static byte[] postHttpBytesContent(String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "POST", url, 0, headers, body).toByteArray();
}
public static byte[] postHttpBytesContent(String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "POST", url, timeout, headers, body).toByteArray();
}
public static byte[] postHttpBytesContent(SSLContext ctx, String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, 0, headers, body).toByteArray();
}
public static byte[] postHttpBytesContent(SSLContext ctx, String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "POST", url, timeout, headers, body).toByteArray();
}
public static String getHttpContent(String url) throws IOException {
return remoteHttpContent(null, "GET", url, 0, null, null).toString("UTF-8");
}
public static String getHttpContent(String url, int timeout) throws IOException {
return remoteHttpContent(null, "GET", url, timeout, null, null).toString("UTF-8");
}
public static String getHttpContent(SSLContext ctx, String url) throws IOException {
return remoteHttpContent(ctx, "GET", url, 0, null, null).toString("UTF-8");
}
public static String getHttpContent(SSLContext ctx, String url, int timeout) throws IOException {
return remoteHttpContent(ctx, "GET", url, timeout, null, null).toString("UTF-8");
}
public static String getHttpContent(SSLContext ctx, String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "GET", url, 0, headers, body).toString("UTF-8");
}
public static String getHttpContent(SSLContext ctx, String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "GET", url, timeout, headers, body).toString("UTF-8");
}
public static String getHttpContent(String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "GET", url, 0, headers, body).toString("UTF-8");
}
public static String getHttpContent(String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "GET", url, timeout, headers, body).toString("UTF-8");
}
public static String getHttpContent(String url, Charset charset) throws IOException {
return remoteHttpContent(null, "GET", url, 0, null, null).toString(charset.name());
}
public static String getHttpContent(String url, int timeout, Charset charset) throws IOException {
return remoteHttpContent(null, "GET", url, timeout, null, null).toString(charset.name());
}
public static String getHttpContent(SSLContext ctx, String url, Charset charset) throws IOException {
return remoteHttpContent(ctx, "GET", url, 0, null, null).toString(charset.name());
}
public static String getHttpContent(SSLContext ctx, String url, int timeout, Charset charset) throws IOException {
return remoteHttpContent(ctx, "GET", url, timeout, null, null).toString(charset.name());
}
public static String getHttpContent(SSLContext ctx, String url, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "GET", url, 0, headers, body).toString(charset.name());
}
public static String getHttpContent(SSLContext ctx, String url, int timeout, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "GET", url, timeout, headers, body).toString(charset.name());
}
public static String getHttpContent(String url, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "GET", url, 0, headers, body).toString(charset.name());
}
public static String getHttpContent(String url, int timeout, Charset charset, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "GET", url, timeout, headers, body).toString(charset.name());
}
public static byte[] getHttpBytesContent(String url) throws IOException {
return remoteHttpContent(null, "GET", url, 0, null, null).toByteArray();
}
public static byte[] getHttpBytesContent(String url, int timeout) throws IOException {
return remoteHttpContent(null, "GET", url, timeout, null, null).toByteArray();
}
public static byte[] getHttpBytesContent(SSLContext ctx, String url) throws IOException {
return remoteHttpContent(ctx, "GET", url, 0, null, null).toByteArray();
}
public static byte[] getHttpBytesContent(SSLContext ctx, String url, int timeout) throws IOException {
return remoteHttpContent(ctx, "GET", url, timeout, null, null).toByteArray();
}
public static byte[] getHttpBytesContent(String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "GET", url, 0, headers, body).toByteArray();
}
public static byte[] getHttpBytesContent(String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, "GET", url, timeout, headers, body).toByteArray();
}
public static byte[] getHttpBytesContent(SSLContext ctx, String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "GET", url, 0, headers, body).toByteArray();
}
public static byte[] getHttpBytesContent(SSLContext ctx, String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(ctx, "GET", url, timeout, headers, body).toByteArray();
}
public static ByteArrayOutputStream remoteHttpContent(String method, String url, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, method, url, 0, headers, body);
}
public static ByteArrayOutputStream remoteHttpContent(String method, String url, int timeout, Map<String, String> headers, String body) throws IOException {
return remoteHttpContent(null, method, url, timeout, headers, body);
}
public static ByteArrayOutputStream remoteHttpContent(SSLContext ctx, String method, String url, int timeout, Map<String, String> headers, String body) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(timeout > 0 ? timeout : 3000);
conn.setReadTimeout(timeout > 0 ? timeout : 3000);
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsconn = ((HttpsURLConnection) conn);
httpsconn.setSSLSocketFactory((ctx == null ? DEFAULTSSL_CONTEXT : ctx).getSocketFactory());
httpsconn.setHostnameVerifier(defaultVerifier);
}
conn.setRequestMethod(method);
if (headers != null) {
for (Map.Entry<String, String> en : headers.entrySet()) { //forEachJDK 6
conn.setRequestProperty(en.getKey(), en.getValue());
}
}
if (body != null) {
conn.setDoInput(true);
conn.setDoOutput(true);
conn.getOutputStream().write(body.getBytes(UTF_8));
}
conn.connect();
int rs = conn.getResponseCode();
if (rs == 301 || rs == 302) {
String newurl = conn.getHeaderField("Location");
conn.disconnect();
return remoteHttpContent(ctx, method, newurl, timeout, headers, body);
}
InputStream in = (rs < 400 || rs == 404) && rs != 405 ? conn.getInputStream() : conn.getErrorStream();
if ("gzip".equalsIgnoreCase(conn.getContentEncoding())) in = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] bytes = new byte[1024];
int pos;
while ((pos = in.read(bytes)) != -1) {
out.write(bytes, 0, pos);
}
conn.disconnect();
return out;
}
public static String read(InputStream in) throws IOException {
return read(in, "UTF-8");
}
public static String readThenClose(InputStream in) throws IOException {
return read(in, "UTF-8", true);
}
public static String read(InputStream in, String charsetName) throws IOException {
return read(in, charsetName, false);
}
private static String read(InputStream in, String charsetName, boolean close) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] bytes = new byte[1024];
int pos;
while ((pos = in.read(bytes)) != -1) {
out.write(bytes, 0, pos);
}
if (close) in.close();
return charsetName == null ? out.toString() : out.toString(charsetName);
}
public static ByteArrayOutputStream readStream(InputStream in) throws IOException {
return readStream(in, false);
}
public static ByteArrayOutputStream readStreamThenClose(InputStream in) throws IOException {
return readStream(in, true);
}
private static ByteArrayOutputStream readStream(InputStream in, boolean close) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] bytes = new byte[1024];
int pos;
while ((pos = in.read(bytes)) != -1) {
out.write(bytes, 0, pos);
}
if (close) in.close();
return out;
}
public static byte[] readBytes(InputStream in) throws IOException {
return readStream(in).toByteArray();
}
public static byte[] readBytesThenClose(InputStream in) throws IOException {
return readStreamThenClose(in).toByteArray();
}
} |
package factory.youbot;
import factory.common.Constants;
import jade.core.Agent;
import jade.core.AID;
import jade.core.behaviours.*;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
public class YouBot extends Agent implements Constants {
private String status;
private AID[] stationAgents;
protected void setup() {
System.out.println("Hello! youBot "+getAID().getName()+" is ready.");
//get initialization arguments
Object[] args = getArguments();
if (args != null && args.length > 0) {
String argument0 = (String) args[0];
// Initiate youBot Query for Work every 10seconds
addBehaviour(new TickerBehaviour(this, 10000) {
protected void onTick() {
System.out.println("Querying for Work");
// Update the list of seller agents
DFAgentDescription template = new DFAgentDescription();
ServiceDescription sd = new ServiceDescription();
sd.setType("order_assembling");
template.addServices(sd);
try {
DFAgentDescription[] result = DFService.search(myAgent, template);
System.out.println("Found the following stationAgents");
stationAgents = new AID[result.length];
for (int i = 0; i < result.length; ++i) {
stationAgents[i] = result[i].getName();
System.out.println(stationAgents[i].getName());
}
}
catch (FIPAException fe) {
fe.printStackTrace();
}
// Perform the request
myAgent.addBehaviour(new RequestPerformer());
}
} );
}
}
protected void takeDown() {
// Printout a dismissal message
System.out.println("youBotAgent "+getAID().getName()+" terminating.");
}
/**
Inner class RequestPerformer.
This is the behaviour used by youBot agents to request stationAgents
for work
*/
private class RequestPerformer extends Behaviour {
private AID commitedStation; // The Station to which the youBot commits working for
private int longestQueue; // The longest received Station Queue
private int repliesCnt = 0; // The counter of replies from station agents
private MessageTemplate mt; // The template to receive replies
private int step = 0;
public void action() {
switch (step) {
case 0:
// Send the cfp to all stations
ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
for (int i = 0; i < stationAgents.length; ++i) {
cfp.addReceiver(stationAgents[i]);
}
cfp.setContent("need something to do..");
cfp.setConversationId(CONV_ID_PICKUP);
cfp.setReplyWith("cfp"+System.currentTimeMillis()); // Unique value
myAgent.send(cfp);
// Prepare the template to get proposals
mt = MessageTemplate.and(MessageTemplate.MatchConversationId(CONV_ID_PICKUP),
MessageTemplate.MatchInReplyTo(cfp.getReplyWith()));
step = 1;
break;
case 1:
// Receive TransportationTask replies from Stations
ACLMessage reply = myAgent.receive(mt);
if (reply != null) {
// Reply received
// This is a transportation task offer because specified in mt - template
int queue = Integer.parseInt(reply.getContent());
if (commitedStation == null || queue < longestQueue) {
// This is the best offer at present
longestQueue = queue;
commitedStation = reply.getSender();
}
}
repliesCnt++;
if (repliesCnt >= stationAgents.length) {
// We received all replies
step = 2;
}
else {
block();
}
break;
case 2:
// inform the commited Station about commitment
ACLMessage commitment = new ACLMessage(ACLMessage.ACCEPT_PROPOSAL);
commitment.addReceiver(commitedStation);
//optional todo - add content
//commitment.setContent();
commitment.setConversationId(CONV_ID_PICKUP);
commitment.setReplyWith("commitment"+System.currentTimeMillis());
myAgent.send(commitment);
// Prepare the template to get the commitment-message reply
mt = MessageTemplate.and(MessageTemplate.MatchConversationId(CONV_ID_PICKUP),
MessageTemplate.MatchInReplyTo(commitment.getReplyWith()));
step = 3;
break;
case 3:
// Receive the commitment reply
reply = myAgent.receive(mt);
if (reply != null) {
// commitment reply received
if (reply.getPerformative() == ACLMessage.INFORM) {
// we can execute transportation
//sleep 5s for virtualizing transport-time
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Object item = reply.getContentObject();
} catch (UnreadableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("couldn receive Stations Object");
}
status = "loaded";
System.out.println("successfully commited to work for agent "+reply.getSender().getName() + " starting to work now.");
System.out.println("Queue = "+longestQueue);
//myAgent.doDelete();
}
else {
System.out.println("Attempt to commit to working failed.");
}
step = 4;
}
else {
block();
}
break;
}
}
public boolean done() {
if (step == 2 && commitedStation == null) {
System.out.println("Attempt failed: no work available.");
}
return ((step == 2 && commitedStation == null) || step == 4);
}
// End of inner class RequestPerformer
}
} |
package edu.wustl.xipHost.application;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import edu.wustl.xipHost.avt2ext.iterator.IterationTarget;
/**
* @author Jaroslaw Krych
*
*/
public class ApplicationBar extends JPanel implements ActionListener {
final static Logger logger = Logger.getLogger(ApplicationBar.class);
public ApplicationBar() {
setLayout(new FlowLayout(FlowLayout.LEADING));
}
public void setApplications(List<Application> applications){
removeAll();
for(int i = 0; i < applications.size(); i++){
Application app = applications.get(i);
addApplicationIcon(app);
}
}
public void addApplicationIcon(Application app){
ImageIcon iconFile;
if(app.getIconFile() == null){
iconFile = null;
}else{
iconFile = new ImageIcon(app.getIconFile().getPath());
}
final AppButton btn = new AppButton(app.getName(), iconFile);
btn.setPreferredSize(new Dimension(150, 25));
//btn.setOpaque(true);
btn.setApplicationUUID(app.getID());
btn.setForeground(Color.BLACK);
btn.addActionListener(this);
btn.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Runnable doWorkRunnable = new Runnable() {
public void run() {
add(btn);
repaint();
}
};
SwingUtilities.invokeLater(doWorkRunnable);
}
public class AppButton extends JButton{
public AppButton(String text, Icon icon){
super(text, icon);
}
UUID appUUID;
public void setApplicationUUID(UUID uuid){
appUUID = uuid;
}
public UUID getApplicationUUID(){
return appUUID;
}
}
public static void main(String[] args) {
List<Application> applications = new ArrayList<Application>();
File exePath = new File("./src-tests/edu/wustl/xipHost/application/test.bat");
Application test1 = new Application("Test1", exePath, "WashU", "1.0", null, "analytical", true, "files", 1, IterationTarget.SERIES);
Application test2 = new Application("Test2", exePath, "WashU", "1.0", null, "analytical", true, "files", 1, IterationTarget.SERIES);
Application test3 = new Application("Test3", exePath, "WashU", "1.0", null, "analytical", true, "files", 1, IterationTarget.SERIES);
applications.add(test1);
applications.add(test2);
applications.add(test3);
JFrame frame = new JFrame();
ApplicationBar panel = new ApplicationBar();
panel.setApplications(applications);
frame.getContentPane().add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = frame.getPreferredSize();
frame.setBounds((screenSize.width - windowSize.width) / 2, (screenSize.height - windowSize.height) /2, windowSize.width, windowSize.height);
frame.pack();
}
@Override
public void actionPerformed(ActionEvent e) {
//select current tab
//check if selectedDataSearchresult is not null
//check if DICOM and DICOM and SEG are selected.
//setSelectedDataSearchResult on application
AppButton btn = (AppButton)e.getSource();
fireLaunchApplication(btn);
}
ApplicationListener listener;
public void addApplicationListener(ApplicationListener l){
listener = l;
}
void fireLaunchApplication(AppButton btn){
ApplicationEvent event = new ApplicationEvent(btn);
listener.launchApplication(event);
}
} |
package me.teaisaweso.client;
import java.util.Collection;
import junit.framework.Assert;
import junit.framework.TestCase;
import me.teaisaweso.client.graphmanagers.GraphManager2d;
import me.teaisaweso.client.graphmanagers.GraphManager2dFactory;
import me.teaisaweso.shared.Graph;
import me.teaisaweso.shared.Vertex;
import me.teaisaweso.shared.VertexDirection;
/**
* NOTE: this class relies on the GraphManager2d factory working, if it isn't
* you should probably assume that this test is totally broken
*/
public class GraphManager2dTest extends TestCase {
private GraphManager2d mManager;
private boolean mCalled = false;
private Runnable mCheckCalled = new Runnable() {
@Override
public void run() {
GraphManager2dTest.this.mCalled = true;
}
};
/**
* runs test setup, creates a graphmanager instance
*/
public void setUp() {
mManager = GraphManager2dFactory.getInstance().makeDefaultGraphManager();
mCalled = false;
}
public void tearDown() {
mManager = null;
mCalled = false;
}
/**
* tests that adding vertices works
*/
public void testAddVertex_single() {
mManager.addVertex(new Vertex("hi"), 0, -3, 10);
Graph underlying = mManager.getUnderlyingGraph();
Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("hi")));
Collection<VertexDrawable> drawables = mManager.getVertexDrawables();
Assert.assertEquals(1, drawables.size());
VertexDrawable[] vds = drawables.toArray(new VertexDrawable[] { new VertexDrawable(0, 0, 0,
0, "") });
Assert.assertEquals(0, vds[0].getCenterX());
Assert.assertEquals(-5, vds[0].getLeft());
Assert.assertEquals(-3, vds[0].getCenterY());
Assert.assertEquals(-8, vds[0].getTop());
Assert.assertEquals(10, vds[0].getWidth());
Assert.assertEquals(10, vds[0].getHeight());
Assert.assertEquals("hi", vds[0].getLabel());
}
public void testAddEdge_singleBothDir() {
mManager.addVertex(new Vertex("cake"), 0, -1, 0);
mManager.addVertex(new Vertex("faces"), 100, 17, 0);
mManager.addEdge(new Vertex("faces"), new Vertex("cake"), VertexDirection.both);
EdgeDrawable e = mManager.getEdgeDrawables().toArray(new EdgeDrawable[0])[0];
Assert.assertEquals(0, e.getStartX());
Assert.assertEquals(-1, e.getStartY());
Assert.assertEquals(100, e.getEndX());
Assert.assertEquals(17, e.getEndY());
}
public void testAddVertex_multiple() {
mManager.addVertex(new Vertex("bees"), 100, 17, 2);
mManager.addVertex(new Vertex("cheese"), 0, 0, 2);
Graph underlying = mManager.getUnderlyingGraph();
Assert.assertEquals(2, underlying.getVertices().size());
Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("bees")));
Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("cheese")));
VertexDrawable[] vds = mManager.getVertexDrawables().toArray(new VertexDrawable[] {});
Assert.assertEquals(2, vds.length);
}
public void testInvalidate_addEdge() {
mManager.addRedrawCallback(mCheckCalled);
mManager.addEdge(new Vertex("a"), new Vertex("b"), VertexDirection.fromTo);
Assert.assertEquals(true, mCalled);
}
public void testInvalidate_addVertex() {
mManager.addRedrawCallback(mCheckCalled);
mManager.addVertex(new Vertex("bees"), 0, 0, 10);
Assert.assertEquals(true, mCalled);
}
public void testInvalidate_removeVertex() {
mManager.addVertex(new Vertex("faces"), 0, 0, 10);
mManager.addRedrawCallback(mCheckCalled);
mManager.removeVertex(new Vertex("faces"));
Assert.assertEquals(true, mCalled);
}
public void testInvalidate_removeAllEdges() {
mManager.addVertex(new Vertex("faces"), 0, 0, 10);
mManager.addVertex(new Vertex("bees"), 0, 0, 10);
mManager.addEdge(new Vertex("bees"), new Vertex("faces"), VertexDirection.both);
mManager.addRedrawCallback(mCheckCalled);
mManager.removeAllEdges(new Vertex("faces"), new Vertex("bees"));
Assert.assertEquals(true, mCalled);
}
} |
package net.sf.farrago.ddl;
import java.util.*;
import java.util.logging.*;
import javax.jmi.reflect.*;
import net.sf.farrago.catalog.*;
import net.sf.farrago.cwm.core.*;
import net.sf.farrago.cwm.relational.*;
import net.sf.farrago.cwm.relational.enumerations.*;
import net.sf.farrago.fem.med.*;
import net.sf.farrago.fem.security.*;
import net.sf.farrago.fem.sql2003.*;
import net.sf.farrago.fennel.*;
import net.sf.farrago.namespace.util.*;
import net.sf.farrago.query.*;
import net.sf.farrago.resource.*;
import net.sf.farrago.session.*;
import net.sf.farrago.trace.*;
import net.sf.farrago.type.*;
import net.sf.farrago.util.*;
import org.eigenbase.enki.mdr.*;
import org.eigenbase.jmi.*;
import org.eigenbase.reltype.*;
import org.eigenbase.sql.*;
import org.eigenbase.sql.parser.*;
import org.eigenbase.sql.type.*;
import org.eigenbase.sql.validate.*;
import org.eigenbase.util.*;
import org.jgrapht.*;
import org.jgrapht.alg.*;
import org.jgrapht.graph.*;
import org.netbeans.api.mdr.events.*;
public class DdlValidator
extends FarragoCompoundAllocation
implements FarragoSessionDdlValidator,
MDRPreChangeListener
{
private static final Logger tracer = FarragoTrace.getDdlValidatorTracer();
private static enum ValidatedOp
{
CREATION, MODIFICATION, DELETION, TRUNCATION
}
private final FarragoSessionStmtValidator stmtValidator;
/**
* Queue of excns detected during plannedChange.
*/
private DeferredException enqueuedValidationExcn;
/**
* Map (from RefAssociation.Class to FarragoSessionDdlDropRule) of
* associations for which special handling is required during DROP.
*/
private MultiMap<Class<? extends Object>, FarragoSessionDdlDropRule>
dropRules;
/**
* Map from catalog object to SqlParserPos for beginning of definition.
*/
private final Map<Object, SqlParserPos> parserContextMap;
/**
* Map from catalog object to SqlParserPos for offset of body.
*/
private final Map<RefObject, SqlParserPos> parserOffsetMap;
/**
* Map from catalog object to associated SQL definition (not all objects
* have these).
*/
private final Map<RefObject, SqlNode> sqlMap;
/**
* Map containing scheduled validation actions. The key is the MofId of the
* object scheduled for validation; the value is a simple object containing
* a ValidatedOp and the object's RefClass.
*/
private Map<String, SchedulingDetail> schedulingMap;
/**
* Map of objects in transition between schedulingMap and validatedMap.
* Content format is same as for schedulingMap.
*/
private Map<String, SchedulingDetail> transitMap;
/**
* Map of object validations which have already taken place. The key is the
* RefObject itself; the value is the action type.
*/
private Map<RefObject, ValidatedOp> validatedMap;
/**
* Set of objects which a DROP CASCADE has encountered but not yet
* processed.
*/
private Set<RefObject> deleteQueue;
/**
* Thread binding to prevent cross-talk.
*/
private Thread activeThread;
/**
* DDL statement being validated.
*/
private FarragoSessionDdlStmt ddlStmt;
/**
* List of handlers to be invoked.
*/
protected List<DdlHandler> actionHandlers;
/**
* Object to be replaced if CREATE OR REPLACE
*/
private CwmModelElement replacementTarget;
/**
* Set of objects to be revalidated (CREATE OR REPLACE)
*/
private Set<CwmModelElement> revalidateQueue;
private String timestamp;
private final ReflectiveVisitDispatcher<DdlHandler, CwmModelElement>
dispatcher =
ReflectUtil.createDispatcher(DdlHandler.class, CwmModelElement.class);
private FemAuthId systemUserAuthId;
private FemAuthId currentUserAuthId;
/**
* Creates a new validator. The validator will listen for repository change
* events and schedule appropriate validation actions on the affected
* objects. Validation is deferred until validate() is called.
*
* @param stmtValidator generic stmt validator
*/
public DdlValidator(FarragoSessionStmtValidator stmtValidator)
{
this.stmtValidator = stmtValidator;
stmtValidator.addAllocation(this);
// NOTE jvs 25-Jan-2004: Use LinkedHashXXX, since order
// matters for these.
schedulingMap =
new LinkedHashMap<String, SchedulingDetail>();
validatedMap = new LinkedHashMap<RefObject, ValidatedOp>();
deleteQueue = new LinkedHashSet<RefObject>();
parserContextMap = new HashMap<Object, SqlParserPos>();
parserOffsetMap = new HashMap<RefObject, SqlParserPos>();
sqlMap = new HashMap<RefObject, SqlNode>();
revalidateQueue = new HashSet<CwmModelElement>();
// NOTE: dropRules are populated implicitly as action handlers
// are set up below.
dropRules =
new MultiMap<Class<? extends Object>, FarragoSessionDdlDropRule>();
// Build up list of action handlers.
actionHandlers = new ArrayList<DdlHandler>();
// First, install action handlers for all installed model
// extensions.
for (
FarragoSessionModelExtension ext
: stmtValidator.getSession().getModelExtensions())
{
ext.defineDdlHandlers(this, actionHandlers);
}
// Then, install action handlers specific to this personality.
stmtValidator.getSession().getPersonality().defineDdlHandlers(
this,
actionHandlers);
startListening();
}
// implement FarragoSessionDdlValidator
public FarragoSessionStmtValidator getStmtValidator()
{
return stmtValidator;
}
// implement FarragoSessionDdlValidator
public FarragoRepos getRepos()
{
return stmtValidator.getRepos();
}
// implement FarragoSessionDdlValidator
public FennelDbHandle getFennelDbHandle()
{
return stmtValidator.getFennelDbHandle();
}
// implement FarragoSessionDdlValidator
public FarragoTypeFactory getTypeFactory()
{
return stmtValidator.getTypeFactory();
}
// implement FarragoSessionDdlValidator
public FarragoSessionIndexMap getIndexMap()
{
return stmtValidator.getIndexMap();
}
// implement FarragoSessionDdlValidator
public FarragoDataWrapperCache getDataWrapperCache()
{
return stmtValidator.getDataWrapperCache();
}
// implement FarragoSessionDdlValidator
public FarragoSession newReentrantSession()
{
return getInvokingSession().cloneSession(
stmtValidator.getSessionVariables());
}
// implement FarragoSessionDdlValidator
public FarragoSession getInvokingSession()
{
return stmtValidator.getSession();
}
// implement FarragoSessionDdlValidator
public void releaseReentrantSession(FarragoSession session)
{
session.closeAllocation();
}
// implement FarragoSessionDdlValidator
public FarragoSessionParser getParser()
{
return stmtValidator.getParser();
}
// implement FarragoSessionDdlValidator
public boolean isDeletedObject(RefObject refObject)
{
return testObjectStatus(refObject, ValidatedOp.DELETION);
}
// implement FarragoSessionDdlValidator
public boolean isCreatedObject(RefObject refObject)
{
return testObjectStatus(refObject, ValidatedOp.CREATION);
}
private boolean testObjectStatus(
RefObject refObject,
ValidatedOp status)
{
return (getObjectStatusFromMap(schedulingMap, refObject) == status)
|| (validatedMap.get(refObject) == status)
|| ((transitMap != null)
&& (getObjectStatusFromMap(transitMap, refObject) == status));
}
private ValidatedOp getObjectStatusFromMap(
Map<String, SchedulingDetail> map, RefObject refObject)
{
SchedulingDetail detail = map.get(refObject.refMofId());
if (detail == null) {
return null;
}
return detail.validatedOp;
}
// implement FarragoSessionDdlValidator
public boolean isDropRestrict()
{
return ddlStmt.isDropRestricted();
}
/**
* Determines whether a catalog object has had its visibility set yet. NOTE:
* this should remain private and only be called prior to executeStorage().
*
* @param modelElement object in question
*
* @return true if refObject isn't visible yet
*/
private boolean isNewObject(CwmModelElement modelElement)
{
return modelElement.getVisibility() != VisibilityKindEnum.VK_PUBLIC;
}
// implement FarragoSessionDdlValidator
public String getParserPosString(RefObject obj)
{
SqlParserPos parserContext = getParserPos(obj);
if (parserContext == null) {
return null;
}
return parserContext.toString();
}
private SqlParserPos getParserPos(RefObject obj)
{
return parserContextMap.get(obj);
}
// implement FarragoSessionDdlValidator
public String setParserOffset(
RefObject obj,
SqlParserPos pos,
String body)
{
int n = 0;
char c;
int column = pos.getColumnNum();
int line = pos.getLineNum();
while (n < body.length()
&& Character.isWhitespace((c = body.charAt(n)))) {
++n;
if (c == '\n'
|| (c == '\r'
&& (n == 0 || body.charAt(n - 1) != '\n')))
{
++line;
column = 1;
} else {
++column;
}
}
pos =
new SqlParserPos(
line, column, pos.getEndLineNum(), pos.getEndColumnNum());
parserOffsetMap.put(obj, pos);
return body.substring(n);
}
// implement FarragoSessionDdlValidator
public SqlParserPos getParserOffset(RefObject obj)
{
return parserOffsetMap.get(obj);
}
// implement FarragoSessionDdlValidator
public void setSqlDefinition(
RefObject obj,
SqlNode sqlNode)
{
sqlMap.put(obj, sqlNode);
}
// implement FarragoSessionDdlValidator
public SqlNode getSqlDefinition(RefObject obj)
{
SqlNode sqlNode = sqlMap.get(obj);
SqlParserPos parserContext = getParserPos(obj);
if (parserContext != null) {
stmtValidator.setParserPosition(parserContext);
}
return sqlNode;
}
// implement FarragoSessionDdlValidator
public void setSchemaObjectName(
CwmModelElement schemaElement,
SqlIdentifier qualifiedName)
{
SqlIdentifier schemaName;
assert (qualifiedName.names.length > 0);
assert (qualifiedName.names.length < 4);
if (qualifiedName.names.length == 3) {
schemaElement.setName(qualifiedName.names[2]);
schemaName =
new SqlIdentifier(
new String[] {
qualifiedName.names[0], qualifiedName.names[1]
},
SqlParserPos.ZERO);
} else if (qualifiedName.names.length == 2) {
schemaElement.setName(qualifiedName.names[1]);
schemaName =
new SqlIdentifier(qualifiedName.names[0], SqlParserPos.ZERO);
} else {
schemaElement.setName(qualifiedName.names[0]);
if (stmtValidator.getSessionVariables().schemaName == null) {
throw FarragoResource.instance().ValidatorNoDefaultSchema.ex();
}
schemaName =
new SqlIdentifier(
stmtValidator.getSessionVariables().schemaName,
SqlParserPos.ZERO);
}
CwmSchema schema = stmtValidator.findSchema(schemaName);
schema.getOwnedElement().add(schemaElement);
}
// implement MDRChangeListener
public void change(MDRChangeEvent event)
{
// don't care
}
// implement MDRPreChangeListener
public void changeCancelled(MDRChangeEvent event)
{
// don't care
}
// override FarragoCompoundAllocation
public void closeAllocation()
{
stopListening();
super.closeAllocation();
}
/**
* Tests if DDL statement is CREATE OR REPLACE.
*
* @return true if statement is CREATE OR REPLACE
*/
public boolean isReplace()
{
if (ddlStmt instanceof DdlCreateStmt) {
return (((DdlCreateStmt) ddlStmt).getReplaceOptions().isReplace());
}
return false;
}
/**
* Returns RENAME TO argument of CREATE OR REPLACE.
*
* @return new name of object, or null if this is not a CREATE OR REPLACE or
* RENAME TO.
*/
private SqlIdentifier getNewName()
{
if (ddlStmt instanceof DdlCreateStmt) {
return (((DdlCreateStmt) ddlStmt).getReplaceOptions().getNewName());
}
return null;
}
/**
* Tests if DDL statement is CREATE OR REPLACE and the target object (to be
* replaced) is of the specified type.
*
* @param object Object type to test for
*
* @return true if CREATE OR REPLACE and replacing an object of this type
*/
public boolean isReplacingType(CwmModelElement object)
{
if (ddlStmt instanceof DdlCreateStmt) {
DdlCreateStmt createStmt = (DdlCreateStmt) ddlStmt;
if (createStmt.getReplaceOptions().isReplace()) {
CwmModelElement e = createStmt.getModelElement();
if (e != null) {
String newClassName =
object.refClass().refMetaObject().refGetValue(
"name").toString();
String targetClassName =
e.refClass().refMetaObject().refGetValue(
"name").toString();
return newClassName.equals(targetClassName);
}
}
}
return false;
}
/**
* Delete the existing object of a CREATE OR REPLACE statement, saving its
* dependencies for later revalidation.
*/
public void deleteReplacementTarget(CwmModelElement newElement)
{
if (replacementTarget != null) {
Set<CwmModelElement> deps = getDependencies(replacementTarget);
// also revalidate dependencies of children (owned by rootElement)
if (replacementTarget instanceof CwmNamespace) {
Collection<CwmModelElement> children =
((CwmNamespace) replacementTarget).getOwnedElement();
if (children != null) {
for (CwmModelElement e : children) {
deps.addAll(getDependencies(e));
}
}
} else if (replacementTarget instanceof FemLabel) {
deps.addAll(((FemLabel) replacementTarget).getAlias());
try {
// remove stats associated with the replaced label
FarragoCatalogUtil.removeObsoleteStatistics(
(FemLabel) replacementTarget,
getRepos());
} catch (Exception ex) {
throw Util.newInternal(
ex,
"error removing replaced label's statistics: " +
ex.getMessage());
}
}
scheduleRevalidation(deps);
SqlIdentifier newName = getNewName();
if (newName != null) {
newElement.setName(newName.getSimple());
}
stopListening();
// special cases - FemBaseColumnSet, FemDataServer, FemLabel
for (CwmModelElement e : deps) {
if (e instanceof FemBaseColumnSet) {
// must reset server to newElement
((FemBaseColumnSet) e).setServer(
(FemDataServer) newElement);
} else if (e instanceof FemDataServer) {
((FemDataServer) e).setWrapper((FemDataWrapper) newElement);
} else if (e instanceof FemLabel) {
((FemLabel) e).setParentLabel((FemLabel) newElement);
}
}
// preserve owned elements
List<CwmModelElement> ownedElements = null;
if (replacementTarget instanceof CwmNamespace) {
ownedElements = new ArrayList<CwmModelElement>();
Collection<CwmModelElement> c =
((CwmNamespace) replacementTarget).getOwnedElement();
ownedElements.addAll(c);
// remove ownership to avoid cascade delete
c.clear();
}
replaceDependencies(replacementTarget, newElement);
startListening();
replacementTarget.refDelete();
while (!deleteQueue.isEmpty()) {
RefObject refObj = deleteQueue.iterator().next();
deleteQueue.remove(refObj);
if (!schedulingMap.containsKey(refObj.refMofId())) {
if (tracer.isLoggable(Level.FINE)) {
tracer.fine("probe deleting " + refObj);
}
refObj.refDelete();
}
}
// restore owned elements
if (ownedElements != null) {
Collection<CwmModelElement> c =
((CwmNamespace) newElement).getOwnedElement();
c.addAll(ownedElements);
}
}
}
// implement FarragoSessionDdlValidator
public void executeStorage()
{
// catalog updates which occur during execution should not result in
// further validation
stopListening();
List<RefObject> deletionList = new ArrayList<RefObject>();
for (
Map.Entry<RefObject, ValidatedOp> mapEntry
: validatedMap.entrySet())
{
RefObject obj = mapEntry.getKey();
ValidatedOp action = mapEntry.getValue();
if (action != ValidatedOp.DELETION) {
if (obj instanceof CwmStructuralFeature) {
// Set some mandatory but irrelevant attributes.
CwmStructuralFeature feature = (CwmStructuralFeature) obj;
feature.setChangeability(ChangeableKindEnum.CK_CHANGEABLE);
}
} else {
RefFeatured container = obj.refImmediateComposite();
if (container != null) {
ValidatedOp containerAction = validatedMap.get(container);
if (containerAction == ValidatedOp.DELETION) {
// container is also being deleted; don't try
// deleting this contained object--depending on order,
// the attempt could cause an excn
} else {
// container is not being deleted
deletionList.add(obj);
}
} else {
// top-level object
deletionList.add(obj);
}
}
if (!(obj instanceof CwmModelElement)) {
continue;
}
CwmModelElement element = (CwmModelElement) obj;
if (action == ValidatedOp.CREATION) {
invokeHandler(element, "executeCreation");
} else if (action == ValidatedOp.DELETION) {
invokeHandler(element, "executeDrop");
} else if (action == ValidatedOp.TRUNCATION) {
invokeHandler(element, "executeTruncation");
} else if (action == ValidatedOp.MODIFICATION) {
invokeHandler(element, "executeModification");
} else {
assert (false);
}
}
// Now mark objects as visible and update their timestamps; we defer
// this until here so that storage handlers above can use object
// visibility attribute to distinguish new objects.
for (
Map.Entry<RefObject, ValidatedOp> mapEntry
: validatedMap.entrySet())
{
RefObject obj = mapEntry.getKey();
ValidatedOp action = mapEntry.getValue();
if (!(obj instanceof CwmModelElement)) {
continue;
}
CwmModelElement element = (CwmModelElement) obj;
if (action != ValidatedOp.DELETION) {
updateObjectTimestamp(element);
}
}
// now we can finally consummate any requested deletions, since we're
// all done referencing the objects
Collections.reverse(deletionList);
getRepos().getEnkiMdrRepos().delete(deletionList);
// verify repository integrity post-delete
for (
Map.Entry<RefObject, ValidatedOp> mapEntry
: validatedMap.entrySet())
{
RefObject obj = mapEntry.getKey();
ValidatedOp action = mapEntry.getValue();
if (action != ValidatedOp.DELETION) {
checkJmiConstraints(obj);
}
}
}
private void checkJmiConstraints(RefObject obj)
{
JmiObjUtil.setMandatoryPrimitiveDefaults(obj);
List<FarragoReposIntegrityErr> errs = getRepos().verifyIntegrity(obj);
if (!errs.isEmpty()) {
throw Util.newInternal(
"Repository integrity check failed on object update: "
+ errs.toString());
}
}
private void updateObjectTimestamp(CwmModelElement element)
{
boolean isNew = isNewObject(element);
if (isNew) {
// Retrieve and cache the system and current user FemAuthId
// objects rather than looking them up every time.
if (systemUserAuthId == null) {
systemUserAuthId =
FarragoCatalogUtil.getAuthIdByName(
getRepos(), FarragoCatalogInit.SYSTEM_USER_NAME);
}
String currentUserName =
getInvokingSession().getSessionVariables().currentUserName;
if (currentUserAuthId == null) {
currentUserAuthId =
FarragoCatalogUtil.getAuthIdByName(
getRepos(), currentUserName);
}
// Define a pseudo-grant representing the element's relationship to
// its creator.
FarragoCatalogUtil.newCreationGrant(
getRepos(),
systemUserAuthId,
currentUserAuthId,
element);
}
// We use the visibility attribute to distinguish new objects
// from existing objects. From here on, no longer treat
// this element as new.
element.setVisibility(VisibilityKindEnum.VK_PUBLIC);
if (!(element instanceof FemAnnotatedElement)) {
return;
}
// Update attributes maintained for annotated elements.
FemAnnotatedElement annotatedElement = (FemAnnotatedElement) element;
FarragoCatalogUtil.updateAnnotatedElement(
annotatedElement,
obtainTimestamp(),
isNew);
}
// implement MDRPreChangeListener
public void plannedChange(MDRChangeEvent event)
{
if (tracer.isLoggable(Level.FINE)) {
tracer.fine(event.toString());
}
if (activeThread != Thread.currentThread()) {
// REVIEW: This isn't going to be good enough if we have
// reentrant DDL.
// ignore events from other threads
return;
}
// NOTE: do not throw exceptions from this method, because MDR will
// swallow them! Instead, use enqueueValidationExcn(), and the
// exception will be thrown when validate() is called.
if (event.getType() == InstanceEvent.EVENT_INSTANCE_DELETE) {
RefObject obj = (RefObject) (event.getSource());
scheduleDeletion(obj);
} else if (event instanceof AttributeEvent) {
checkStringLength((AttributeEvent)event);
RefObject obj = (RefObject) (event.getSource());
scheduleModification(obj);
} else if (event instanceof AssociationEvent) {
AssociationEvent associationEvent = (AssociationEvent) event;
if (tracer.isLoggable(Level.FINE)) {
tracer.fine("end name = " + associationEvent.getEndName());
}
boolean touchEnds = true;
DependencySupplier depSupplier =
getRepos().getCorePackage().getDependencySupplier();
RefAssociation refAssoc =
(RefAssociation) associationEvent.getSource();
if (refAssoc.equals(depSupplier)) {
// REVIEW jvs 3-Jun-2008: make a special case for
// the supplier end of dependencies. For example,
// when we create a view which depends on a table,
// there's no need to revalidate the table at
// that time.
touchEnds = false;
}
if (touchEnds) {
scheduleModification(associationEvent.getFixedElement());
if (associationEvent.getOldElement() != null) {
scheduleModification(associationEvent.getNewElement());
}
if (associationEvent.getNewElement() != null) {
scheduleModification(associationEvent.getNewElement());
}
}
if (event.getType() == AssociationEvent.EVENT_ASSOCIATION_REMOVE) {
// MDR's event loses some information, namely which end the
// association is being removed from. event.getEndName() is
// chosen arbitrarily. To work around this, we use our
// knowledge of which side has already been scheduled for
// deleted to infer what we need. (TODO jvs 9-Aug-2008: once
// we've completely migrated off of MDR, enhance enki to
// deliver the full information as part of the event.)
// By default, or if we can't do any better, rely on MDR.
String endName = associationEvent.getEndName();
RefObject droppedEnd = associationEvent.getFixedElement();
RefObject otherEnd = associationEvent.getOldElement();
if (!isDeletedObject(droppedEnd) && isDeletedObject(otherEnd)) {
// Swap ends.
RefObject tmp = droppedEnd;
droppedEnd = otherEnd;
otherEnd = tmp;
JmiAssocEdge assocEdge =
getRepos().getModelGraph().getEdgeForRefAssoc(refAssoc);
if (endName.equals(assocEdge.getSourceEnd().getName())) {
endName = assocEdge.getTargetEnd().getName();
} else {
assert(endName.equals(
assocEdge.getTargetEnd().getName()));
endName = assocEdge.getSourceEnd().getName();
}
}
List<FarragoSessionDdlDropRule> rules =
dropRules.getMulti(refAssoc.getClass());
for (FarragoSessionDdlDropRule rule : rules) {
if ((rule != null)
&& rule.getEndName().equals(endName))
{
fireDropRule(
rule,
droppedEnd,
otherEnd);
}
}
}
} else {
// REVIEW: when I turn this on, I see notifications for
// CreateInstanceEvent, which is supposed to be masked out.
// Probably an MDR bug.
/*
tracer.warning( "Unexpected event "+event.getClass().getName()
+ ", type="+event.getType()); assert(false);
*/
}
}
// implement FarragoSessionDdlValidator
public void validate(FarragoSessionDdlStmt ddlStmt)
{
this.ddlStmt = ddlStmt;
ddlStmt.preValidate(this);
checkValidationExcnQueue();
if (ddlStmt instanceof DdlDropStmt) {
checkInUse(ddlStmt.getModelElement().refMofId());
// Process deletions until a fixpoint is reached, using MDR events
// to implement RESTRICT/CASCADE.
while (!deleteQueue.isEmpty()) {
RefObject refObj = deleteQueue.iterator().next();
checkInUse(refObj.refMofId());
deleteQueue.remove(refObj);
if (!schedulingMap.containsKey(refObj.refMofId())) {
if (tracer.isLoggable(Level.FINE)) {
tracer.fine("probe deleting " + refObj);
}
refObj.refDelete();
}
}
// In order to validate deletion, we need the objects to exist, but
// they've already been deleted. So rollback the deletion now, but
// we still remember the objects encountered above.
rollbackDeletions();
// REVIEW: This may need to get more complicated in the future.
// Like, if deletions triggered modifications to some referencing
// object which needs to have its update validation run AFTER the
// deletion takes place, not before.
}
if (isReplace()) {
replacementTarget = findDuplicate(ddlStmt.getModelElement());
if (replacementTarget != null) {
if (stmtValidator.getDdlLockManager().isObjectInUse(
replacementTarget.refMofId()))
{
throw FarragoResource.instance()
.ValidatorReplacedObjectInUse.ex(
getRepos().getLocalizedObjectName(
null,
replacementTarget.getName(),
replacementTarget.refClass()));
}
// if this is CREATE OR REPLACE and we've encountered an object
// to be replaced, save its dependencies for revalidation and
// delete it.
deleteReplacementTarget(ddlStmt.getModelElement());
}
}
while (!schedulingMap.isEmpty()) {
checkValidationExcnQueue();
// Swap in a new map so new scheduling calls aren't handled until
// the next round.
transitMap = schedulingMap;
schedulingMap =
new LinkedHashMap<String, SchedulingDetail>();
boolean progress = false;
for (
Map.Entry<String, SchedulingDetail> mapEntry
: transitMap.entrySet())
{
SchedulingDetail scheduleDetail = mapEntry.getValue();
RefClass cls = scheduleDetail.refClass;
RefObject obj =
((EnkiMDRepository)getRepos().getMdrRepos()).getByMofId(
mapEntry.getKey(), cls);
if (obj == null) {
continue;
}
ValidatedOp action = scheduleDetail.validatedOp;
// mark this object as already validated so it doesn't slip
// back in by updating itself
validatedMap.put(obj, action);
if (!(obj instanceof CwmModelElement)) {
progress = true;
continue;
}
final CwmModelElement element = (CwmModelElement) obj;
try {
validateAction(element, action);
if (element.getVisibility() == null) {
// mark this new element as validated
element.setVisibility(VisibilityKindEnum.VK_PRIVATE);
}
if ((revalidateQueue != null)
&& revalidateQueue.contains(element)) {
setRevalidationResult(element, null);
}
progress = true;
} catch (FarragoUnvalidatedDependencyException ex) {
// Something hit an unvalidated dependency; we'll have
// to retry this object later.
validatedMap.remove(obj);
schedulingMap.put(obj.refMofId(), scheduleDetail);
} catch (EigenbaseException ex) {
tracer.info(
"Revalidate exception on "
+ ((CwmModelElement) obj).getName() + ": "
+ FarragoUtil.exceptionToString(ex));
setSourceInContext(ex, getParser().getSourceString());
if ((revalidateQueue != null)
&& revalidateQueue.contains(element))
{
setRevalidationResult(element, ex);
} else {
throw ex;
}
}
}
transitMap = null;
if (!progress) {
// Every single object hit a
// FarragoUnvalidatedDependencyException. This implies a
// cycle. TODO: identify the cycle in the exception.
throw FarragoResource.instance().ValidatorSchemaDependencyCycle
.ex();
}
}
if (isReplace()) {
// check for loops in our newly replaced object
if (containsCycle(
ddlStmt.getModelElement()))
{
throw FarragoResource.instance().ValidatorSchemaDependencyCycle
.ex();
}
}
// one last time
checkValidationExcnQueue();
// finally, process any deferred privilege checks
stmtValidator.getPrivilegeChecker().checkAccess();
}
private void setSourceInContext(EigenbaseException e, String sourceString)
{
if (sourceString != null) {
Throwable ex = (Throwable)e;
while (ex != null) {
if (ex instanceof EigenbaseContextException) {
((EigenbaseContextException)ex).setOriginalStatement(sourceString);
break;
}
ex = ex.getCause();
}
}
}
/**
* Handle an exception encountered during validation of dependencies of an
* object replaced via CREATE OR REPLACE (a.k.a. revalidation).
*
* @param element Catalog object causing revalidation exception
* @param ex Revalidation exception
*/
public void setRevalidationResult(
CwmModelElement element,
EigenbaseException ex)
{
if (ex != null) {
throw ex;
}
}
// implement FarragoSessionDdlValidator
public void validateUniqueNames(
CwmModelElement container,
Collection<? extends CwmModelElement> collection,
boolean includeType)
{
// Sort the collection by parser position, since we depend on the
// sort order later and it is NOT guaranteed.
ArrayList<CwmModelElement> sortedCollection =
new ArrayList<CwmModelElement>(collection);
Collections.sort(
sortedCollection,
new RefObjectPositionComparator());
Map<Object, CwmModelElement> nameMap =
new LinkedHashMap<Object, CwmModelElement>();
for (CwmModelElement element : sortedCollection) {
String nameKey = getNameKey(element, includeType);
if (nameKey == null) {
continue;
}
CwmModelElement other = nameMap.get(nameKey);
if (other != null) {
if (isNewObject(other) && isNewObject(element)) {
// clash between two new objects being defined
// simultaneously
// Error message assumes collection is sorted by
// definition order, which we guaranteed earlier.
throw newPositionalError(
element,
FarragoResource.instance().ValidatorDuplicateNames.ex(
getRepos().getLocalizedObjectName(
null,
element.getName(),
element.refClass()),
getRepos().getLocalizedObjectName(container),
getParserPosString(other)));
} else {
CwmModelElement newElement;
CwmModelElement oldElement;
if (isNewObject(other)) {
newElement = other;
oldElement = element;
} else {
// TODO: remove this later when RENAME is supported
assert (isNewObject(element));
newElement = element;
oldElement = other;
}
// new object clashes with existing object
throw newPositionalError(
newElement,
FarragoResource.instance().ValidatorNameInUse.ex(
getRepos().getLocalizedObjectName(
null,
oldElement.getName(),
oldElement.refClass()),
getRepos().getLocalizedObjectName(container)));
}
}
nameMap.put(nameKey, element);
}
}
private String getNameKey(
CwmModelElement element,
boolean includeType)
{
String name = element.getName();
if (name == null) {
return null;
}
if (!includeType) {
return name;
}
Class<?> typeClass;
// TODO jvs 25-Feb-2005: provide a mechanism for generalizing these
// special cases
if (element instanceof CwmNamedColumnSet) {
typeClass = CwmNamedColumnSet.class;
} else if (element instanceof CwmCatalog) {
typeClass = CwmCatalog.class;
} else {
try {
typeClass =
JmiObjUtil.getJavaInterfaceForRefObject(
element.refClass());
}
catch(ClassNotFoundException e) {
throw Util.newInternal(e);
}
}
return typeClass.toString() + ":" + name;
}
// implement FarragoSessionDdlValidator
public <T extends CwmModelElement> CwmDependency createDependency(
CwmNamespace client,
Collection<T> suppliers)
{
String depName = client.getName() + "$DEP";
CwmDependency dependency =
FarragoCatalogUtil.getModelElementByNameAndType(
client.getOwnedElement(),
depName,
CwmDependency.class);
if (dependency == null) {
dependency = getRepos().newCwmDependency();
dependency.setName(depName);
dependency.setKind("GenericDependency");
// NOTE: The client owns the dependency, so their lifetimes are
// coeval. That's why we restrict clients to being namespaces.
client.getOwnedElement().add(dependency);
dependency.getClient().add(client);
}
for (T supplier : suppliers) {
dependency.getSupplier().add(supplier);
}
return dependency;
}
// implement FarragoSessionDdlValidator
public void discardDataWrapper(CwmModelElement wrapper)
{
stmtValidator.getSharedDataWrapperCache().discard(wrapper.refMofId());
}
// implement FarragoSessionDdlValidator
public void setCreatedSchemaContext(FemLocalSchema schema)
{
FarragoSessionVariables sessionVariables =
getStmtValidator().getSessionVariables();
sessionVariables.catalogName = schema.getNamespace().getName();
sessionVariables.schemaName = schema.getName();
// convert from List<FemSqlpathElement> to List<SqlIdentifier>
List<SqlIdentifier> list = new ArrayList<SqlIdentifier>();
for (Object o : schema.getPathElement()) {
FemSqlpathElement element = (FemSqlpathElement) o;
SqlIdentifier id =
new SqlIdentifier(
new String[] {
element.getSearchedSchemaCatalogName(),
element.getSearchedSchemaName()
},
SqlParserPos.ZERO);
list.add(id);
}
sessionVariables.schemaSearchPath = Collections.unmodifiableList(list);
}
// implement FarragoSessionDdlValidator
public EigenbaseException newPositionalError(
RefObject refObj,
SqlValidatorException ex)
{
SqlParserPos parserContext = getParserPos(refObj);
if (parserContext == null) {
return new EigenbaseException(
ex.getMessage(),
ex.getCause());
}
String msg = parserContext.toString();
EigenbaseContextException contextExcn =
FarragoResource.instance().ValidatorPositionContext.ex(msg, ex);
contextExcn.setPosition(
parserContext.getLineNum(),
parserContext.getColumnNum(),
parserContext.getEndLineNum(),
parserContext.getEndColumnNum());
return contextExcn;
}
// implement FarragoSessionDdlValidator
public void defineDropRule(
RefAssociation refAssoc,
FarragoSessionDdlDropRule dropRule)
{
// NOTE: use class object because in some circumstances MDR makes up
// multiple instances of the same association, but doesn't implement
// equals/hashCode correctly.
dropRules.putMulti(
refAssoc.getClass(),
dropRule);
}
private void enqueueValidationExcn(DeferredException excn)
{
if (enqueuedValidationExcn != null) {
// for now, only deal with one at a time
return;
}
enqueuedValidationExcn = excn;
}
private void checkValidationExcnQueue()
{
if (enqueuedValidationExcn != null) {
// rollback any deletions so that exception construction can
// rely on pre-deletion state (e.g. for object identification)
rollbackDeletions();
throw enqueuedValidationExcn.getException();
}
}
private void fireDropRule(
FarragoSessionDdlDropRule rule,
RefObject droppedEnd,
RefObject otherEnd)
{
if ((rule.getSuperInterface() != null)
&& !(rule.getSuperInterface().isInstance(droppedEnd)))
{
return;
}
ReferentialRuleTypeEnum action = rule.getAction();
if (action == ReferentialRuleTypeEnum.IMPORTED_KEY_CASCADE) {
deleteQueue.add(otherEnd);
return;
}
if (!isDropRestrict()) {
deleteQueue.add(otherEnd);
return;
}
// NOTE: We can't construct the exception now since the object is
// deleted. Instead, defer until after rollback.
final String mofId = droppedEnd.refMofId();
enqueueValidationExcn(
new DeferredException() {
EigenbaseException getException()
{
CwmModelElement droppedElement =
(CwmModelElement) getRepos().getMdrRepos().getByMofId(
mofId);
return FarragoResource.instance().ValidatorDropRestrict.ex(
getRepos().getLocalizedObjectName(
droppedElement,
droppedElement.refClass()));
}
});
}
private void mapParserPosition(RefObject obj)
{
SqlParserPos context = getParser().getCurrentPosition();
if (context == null) {
return;
}
parserContextMap.put(obj, context);
}
private void rollbackDeletions()
{
// A savepoint or chained transaction would be smoother, but MDR doesn't
// support those. Instead, have to restart the txn altogether. Take
// advantage of the fact that MDR allows us to retain references across
// txns.
getRepos().endReposTxn(true);
// Restart the session, which is safe because we pass objects across
// the session boundary via MOF ID.
getRepos().endReposSession();
getRepos().beginReposSession();
// TODO: really need a lock to protect us against someone else's DDL
// here, which could invalidate our schedulingMap.
getRepos().beginReposTxn(true);
}
private void scheduleDeletion(RefObject obj)
{
assert (!validatedMap.containsKey(obj));
// delete overrides anything else
schedulingMap.put(
obj.refMofId(),
new SchedulingDetail(
ValidatedOp.DELETION, obj.refClass()));
mapParserPosition(obj);
}
private void scheduleModification(RefObject obj)
{
if (obj == null) {
return;
}
if (validatedMap.containsKey(obj)) {
return;
}
if (schedulingMap.containsKey(obj.refMofId())) {
return;
}
if (!(obj instanceof CwmModelElement)) {
// NOTE jvs 12-June-2005: record it so that we can run
// integrity verification on it during executeStorage()
schedulingMap.put(
obj.refMofId(),
new SchedulingDetail(
ValidatedOp.MODIFICATION, obj.refClass()));
return;
}
CwmModelElement element = (CwmModelElement) obj;
if (isNewObject(element)) {
schedulingMap.put(
obj.refMofId(),
new SchedulingDetail(ValidatedOp.CREATION, obj.refClass()));
} else {
schedulingMap.put(
obj.refMofId(),
new SchedulingDetail(
ValidatedOp.MODIFICATION, obj.refClass()));
}
mapParserPosition(obj);
}
private void checkStringLength(AttributeEvent event)
{
RefObject obj = (RefObject)event.getSource();
final String attrName = event.getAttributeName();
RefClass refClass = obj.refClass();
javax.jmi.model.Attribute attr =
JmiObjUtil.getNamedFeature(
refClass, javax.jmi.model.Attribute.class, attrName, true);
if (attr == null) {
throw Util.newInternal(
"did not find attribute '" + attrName + "'");
}
final int maxLength = JmiObjUtil.getMaxLength(refClass, attr);
if (maxLength == Integer.MAX_VALUE) {
// Marked unlimited or not string type.
return;
}
Object val = event.getNewElement();
if (val == null) {
return;
}
if (val instanceof Collection) {
boolean allPass = true;
for(Object v: (Collection<?>)val) {
if (v == null) {
continue;
}
int length = v.toString().length();
if (length > maxLength) {
allPass = false;
break;
}
}
if (allPass) {
return;
}
} else {
int length = ((String)val).length();
if (length <= maxLength) {
return;
}
}
final String name = getRepos().getLocalizedClassName(refClass);
enqueueValidationExcn(
new DeferredException() {
EigenbaseException getException()
{
return FarragoResource.instance().ValidatorInvalidObjectAttributeDefinition.ex(
name,
attrName,
maxLength);
}
});
}
private void startListening()
{
// MDR pre-change instance creation events are useless, since they don't
// refer to the new instance. Instead, we rely on the fact that it's
// pretty much guaranteed that the new object will have attributes or
// associations set (though someone will probably come up with a
// pathological case eventually).
activeThread = Thread.currentThread();
getRepos().getMdrRepos().addListener(
this,
InstanceEvent.EVENT_INSTANCE_DELETE
| AttributeEvent.EVENTMASK_ATTRIBUTE
| AssociationEvent.EVENTMASK_ASSOCIATION);
}
private void stopListening()
{
if (activeThread != null) {
getRepos().getMdrRepos().removeListener(this);
activeThread = null;
}
}
private boolean validateAction(
CwmModelElement modelElement,
ValidatedOp action)
{
stmtValidator.setParserPosition(null);
if (action == ValidatedOp.CREATION) {
return invokeHandler(modelElement, "validateDefinition");
} else if (action == ValidatedOp.MODIFICATION) {
return invokeHandler(modelElement, "validateModification");
} else if (action == ValidatedOp.DELETION) {
return invokeHandler(modelElement, "validateDrop");
} else if (action == ValidatedOp.TRUNCATION) {
return invokeHandler(modelElement, "validateTruncation");
} else {
throw new AssertionError();
}
}
// called by DdlStmt.postCommit(): dispatches by reflection
void handlePostCommit(CwmModelElement modelElement, String command)
{
invokeHandler(modelElement, "postCommit" + command);
}
private boolean invokeHandler(
CwmModelElement modelElement,
String action)
{
for (DdlHandler handler : actionHandlers) {
boolean handled =
dispatcher.invokeVisitor(
handler,
modelElement,
action);
if (handled) {
return true;
}
}
return false;
}
/**
* Check transitive closure of dependencies of an element for cycles.
*
* @param rootElement Starting element for dependency search
*
* @return true if cycle is found
*/
private boolean containsCycle(
CwmModelElement rootElement)
{
Set<CwmModelElement> visited = new HashSet<CwmModelElement>();
Set<CwmModelElement> queue = new HashSet<CwmModelElement>();
DirectedGraph<CwmModelElement, DefaultEdge> graph =
new DefaultDirectedGraph<CwmModelElement, DefaultEdge>(
DefaultEdge.class);
DependencySupplier depSupplier =
getRepos().getCorePackage().getDependencySupplier();
// First, build the graph
queue.add(rootElement);
while (!queue.isEmpty()) {
CwmModelElement element = queue.iterator().next();
queue.remove(element);
if (visited.contains(element)) {
continue;
}
graph.addVertex(element);
visited.add(element);
Collection<?> deps = depSupplier.getSupplierDependency(element);
if (deps != null) {
for (Object o : deps) {
if (o instanceof CwmDependency) {
CwmDependency dep = (CwmDependency) o;
Collection<CwmModelElement> c = dep.getClient();
for (CwmModelElement e : c) {
queue.add(e);
graph.addVertex(e);
graph.addEdge(element, e);
}
}
}
}
}
// Then, check for cycles (TODO jvs 19-Oct-2006: now that we're using
// JGraphT, we can do better error reporting on names of objects
// participating in the cycle.)
return new CycleDetector<CwmModelElement, DefaultEdge>(
graph).detectCycles();
}
private void scheduleRevalidation(Set<CwmModelElement> elements)
{
for (CwmModelElement e : elements) {
if (!revalidateQueue.contains(e)) {
revalidateQueue.add(e);
// REVIEW jvs 3-Nov-2006: Probably we should
// discriminate revalidation from both
// ValidatedOp.CREATION and ValidatedOp.MODIFICATION.
//REVIEW: unless we regenerate this dependency's SQL
//and reparse, how would we get the SqlParserPos.
//set to a dummy value for now.
this.setParserOffset(
e,
new SqlParserPos(1, 0),
"");
schedulingMap.put(
e.refMofId(),
new SchedulingDetail(ValidatedOp.CREATION, e.refClass()));
}
}
}
// implement FarragoSessionDdlValidator
public Set<CwmModelElement> getDependencies(CwmModelElement rootElement)
{
Set<CwmModelElement> result = new HashSet<CwmModelElement>();
DependencySupplier s =
getRepos().getCorePackage().getDependencySupplier();
for (Object o : s.getSupplierDependency(rootElement)) {
if (o instanceof CwmDependency) {
CwmDependency dep = (CwmDependency) o;
Collection<CwmModelElement> c = dep.getClient();
for (CwmModelElement e : c) {
result.add(e);
}
}
}
return result;
}
public void fixupView(
FemLocalView view,
FarragoSessionAnalyzedSql analyzedSql)
{
// Add CAST( VAR/CHAR/BINARY(0) to VAR/CHAR/BINARY(1) )
List<FemViewColumn> columnList =
Util.cast(view.getFeature(), FemViewColumn.class);
boolean updateSql = false;
if (columnList.size() > 0) {
StringBuilder buf = new StringBuilder("SELECT");
int k = 0;
for (RelDataTypeField field : analyzedSql.resultType.getFields()) {
String targetType = null;
SqlTypeName sqlType = field.getType().getSqlTypeName();
SqlTypeFamily typeFamily =
SqlTypeFamily.getFamilyForSqlType(sqlType);
if ((typeFamily == SqlTypeFamily.CHARACTER)
|| (typeFamily == SqlTypeFamily.BINARY))
{
if (field.getType().getPrecision() == 0) {
// Can't have precision of 0
// Add cast so there is precision of 1
targetType = sqlType.name() + "(1)";
updateSql = true;
}
}
FemViewColumn viewColumn = columnList.get(k);
if (k > 0) {
buf.append(", ");
}
if (targetType == null) {
SqlUtil.eigenbaseDialect.quoteIdentifier(
buf,
field.getName());
} else {
buf.append(" CAST(");
SqlUtil.eigenbaseDialect.quoteIdentifier(
buf,
field.getName());
buf.append(" AS ");
buf.append(targetType);
buf.append(")");
}
buf.append(" AS ");
SqlUtil.eigenbaseDialect.quoteIdentifier(
buf,
viewColumn.getName());
k++;
}
buf.append(" FROM (").append(analyzedSql.canonicalString).append(
")");
if (updateSql) {
analyzedSql.canonicalString = buf.toString();
}
}
}
/**
* Removes dependency associations on oldElement so that it may be deleted
* without cascading side effects. Reassign these dependencies to
* newElement. Assumes MDR change listener isn't active.
*
* @param oldElement Element to remove dependencies from
* @param newElement Element to add dependencies to
*/
private void replaceDependencies(
CwmModelElement oldElement,
CwmModelElement newElement)
{
assert (activeThread == null);
DependencySupplier depSupplier =
getRepos().getCorePackage().getDependencySupplier();
Collection<CwmDependency> supplierDependencies =
new ArrayList<CwmDependency>(
depSupplier.getSupplierDependency(oldElement));
for(CwmDependency dep: supplierDependencies) {
depSupplier.remove(oldElement, dep);
depSupplier.add(newElement, dep);
}
DependencyClient depClient =
getRepos().getCorePackage().getDependencyClient();
Collection<CwmDependency> clientDependencies =
new ArrayList<CwmDependency>(
depClient.getClientDependency(oldElement));
for(CwmDependency dep: clientDependencies) {
depClient.remove(oldElement, dep);
depClient.add(newElement, dep);
}
}
/**
* Searches an element's namespace's owned elements and returns the first
* duplicate found (by name, type).
*
* @param target Target of search
*
* @return CwmModelElement found, or null if not found
*/
private CwmModelElement findDuplicate(CwmModelElement target)
{
String name = target.getName();
RefClass type = target.refClass();
CwmNamespace ns = target.getNamespace();
if (ns != null) {
Collection<?> c = ns.getOwnedElement();
if (c != null) {
for (Object o : c) {
CwmModelElement element = (CwmModelElement) o;
if (element.equals(target)) {
continue;
}
if (!element.getName().equals(name)) {
continue;
}
if (element.refIsInstanceOf(
type.refMetaObject(),
true))
{
return element;
}
}
}
}
return null;
}
// implement FarragoSessionDdlValidator
public String obtainTimestamp()
{
// NOTE jvs 5-Nov-2006: Use a single consistent timestamp for
// all objects involved in the same DDL transaction (FRG-126).
if (timestamp == null) {
timestamp = FarragoCatalogUtil.createTimestamp();
}
return timestamp;
}
public void validateViewColumnList(Collection<?> collection)
{
// intentionally empty
}
/**
* Checks if an object is in use by a running statement. If so, throw a
* deferred exception. Used only in the DROP case. CREATE OR REPLACE throws
* a different exception.
*
* @param mofId Object MOFID being dropped
*/
private void checkInUse(final String mofId)
{
if (stmtValidator.getDdlLockManager().isObjectInUse(mofId)) {
enqueueValidationExcn(
new DeferredException() {
EigenbaseException getException()
{
CwmModelElement droppedElement =
(CwmModelElement) getRepos().getMdrRepos()
.getByMofId(mofId);
throw FarragoResource.instance()
.ValidatorDropObjectInUse.ex(
getRepos().getLocalizedObjectName(
droppedElement,
droppedElement.refClass()));
}
});
}
}
/**
* DeferredException allows an exception's creation to be deferred. This is
* needed since it is not possible to correctly construct an exception in
* certain validation contexts.
*/
private static abstract class DeferredException
{
abstract EigenbaseException getException();
}
/**
* RefObjectPositionComparator compares RefObjects based on their position
* within the owning DdlValidator's {@link #parserContextMap}. Handles
* the case where position information is not available (all comparisons
* return equality) and even the unlikely case where only partial position
* information is available (RefObjects with positions compare before those
* without).
*/
private class RefObjectPositionComparator
implements Comparator<RefObject>
{
public int compare(RefObject o1, RefObject o2)
{
SqlParserPos pos1 = getParserPos(o1);
SqlParserPos pos2 = getParserPos(o2);
if (pos1 == null) {
if (pos2 == null) {
return 0;
}
return 1;
} else if (pos2 == null) {
return -1;
} else {
int c = pos1.getLineNum() - pos2.getLineNum();
if (c != 0) {
return c;
}
c = pos1.getColumnNum() - pos2.getColumnNum();
if (c != 0) {
return c;
}
c = pos1.getEndLineNum() - pos2.getEndLineNum();
if (c != 0) {
return c;
}
return pos1.getEndColumnNum() - pos2.getEndColumnNum();
}
}
}
private static class SchedulingDetail
{
private final ValidatedOp validatedOp;
private final RefClass refClass;
private SchedulingDetail(ValidatedOp validatedOp, RefClass refClass)
{
this.validatedOp = validatedOp;
this.refClass = refClass;
}
}
}
// End DdlValidator.java |
package me.teaisaweso.client;
import java.util.Collection;
import junit.framework.Assert;
import junit.framework.TestCase;
import me.teaisaweso.client.graphmanagers.GraphManager2d;
import me.teaisaweso.client.graphmanagers.GraphManager2dFactory;
import me.teaisaweso.shared.Graph;
import me.teaisaweso.shared.Vertex;
import me.teaisaweso.shared.VertexDirection;
/**
* NOTE: this class relies on the GraphManager2d factory working, if it isn't
* you should probably assume that this test is totally broken
*/
public class GraphManager2dTest extends TestCase {
private GraphManager2d mManager;
private boolean mCalled = false;
private Runnable mCheckCalled = new Runnable() {
@Override
public void run() {
GraphManager2dTest.this.mCalled = true;
}
};
/**
* runs test setup, creates a graphmanager instance
*/
public void setUp() {
mManager = GraphManager2dFactory.getInstance().makeDefaultGraphManager();
mCalled = false;
}
public void tearDown() {
mManager = null;
mCalled = false;
}
/**
* tests that adding vertices works
*/
public void testAddVertex_single() {
mManager.addVertex(new Vertex("hi"), 0, -3, 10);
Graph underlying = mManager.getUnderlyingGraph();
Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("hi")));
Collection<VertexDrawable> drawables = mManager.getVertexDrawables();
Assert.assertEquals(1, drawables.size());
VertexDrawable[] vds = drawables.toArray(new VertexDrawable[] { new VertexDrawable(0, 0, 0,
0, "") });
Assert.assertEquals(0, vds[0].getCenterX());
Assert.assertEquals(-5, vds[0].getLeft());
Assert.assertEquals(-3, vds[0].getCenterY());
Assert.assertEquals(-8, vds[0].getTop());
Assert.assertEquals(10, vds[0].getWidth());
Assert.assertEquals(10, vds[0].getHeight());
Assert.assertEquals("hi", vds[0].getLabel());
}
public void testAddVertex_multiple() {
mManager.addVertex(new Vertex("bees"), 100, 17, 2);
mManager.addVertex(new Vertex("cheese"), 0, 0, 2);
Graph underlying = mManager.getUnderlyingGraph();
Assert.assertEquals(2, underlying.getVertices().size());
Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("bees")));
Assert.assertEquals(true, underlying.getVertices().contains(new Vertex("cheese")));
VertexDrawable[] vds = mManager.getVertexDrawables().toArray(new VertexDrawable[] {});
Assert.assertEquals(2, vds.length);
}
public void testInvalidate_addEdge() {
mManager.addRedrawCallback(mCheckCalled);
mManager.addEdge(new Vertex("a"), new Vertex("b"), VertexDirection.fromTo);
Assert.assertEquals(true, mCalled);
}
public void testInvalidate_addVertex() {
mManager.addRedrawCallback(mCheckCalled);
mManager.addVertex(new Vertex("bees"), 0, 0, 10);
Assert.assertEquals(true, mCalled);
}
public void testInvalidate_removeVertex() {
mManager.addVertex(new Vertex("faces"), 0, 0, 10);
mManager.addRedrawCallback(mCheckCalled);
mManager.removeVertex(new Vertex("faces"));
Assert.assertEquals(true, mCalled);
}
public void testInvalidate_removeAllEdges() {
mManager.addVertex(new Vertex("faces"), 0, 0, 10);
mManager.addVertex(new Vertex("bees"), 0, 0, 10);
mManager.addEdge(new Vertex("bees"), new Vertex("faces"), VertexDirection.both);
mManager.addRedrawCallback(mCheckCalled);
mManager.removeAllEdges(new Vertex("faces"), new Vertex("bees"));
Assert.assertEquals(true, mCalled);
}
} |
package sunmisc;
import java.lang.reflect.Field;
import sun.misc.Unsafe;
public class UnsafeTest {
public int x;
public static void main(String[] args) throws Exception {
//Unsafe unsafe = Unsafe.getUnsafe();
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
//memory(unsafe);
//array(unsafe);
//objArr(unsafe);
cmpInt(unsafe);
System.out.println("OK!");
}
private static void array(Unsafe unsafe) {
System.out.println("arrayBaseOffset");
System.out.println(unsafe.arrayBaseOffset(new int[0].getClass()));
System.out.println(unsafe.arrayBaseOffset(new long[0].getClass()));
System.out.println(unsafe.arrayBaseOffset(new Object[0].getClass()));
System.out.println(unsafe.arrayBaseOffset(new Class<?>[0].getClass()));
System.out.println("arrayIndexScale");
System.out.println(unsafe.arrayIndexScale(new int[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new long[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new Object[0].getClass()));
System.out.println(unsafe.arrayIndexScale(new Class<?>[0].getClass()));
}
private static void objArr(Unsafe unsafe) {
String[] arr = {"one", "two"};
long arrayBaseOffset = unsafe.arrayBaseOffset(arr.getClass());
long arrayIndexScale = unsafe.arrayIndexScale(arr.getClass());
System.out.println(unsafe.getObject(arr, arrayBaseOffset));
System.out.println(unsafe.getObject(arr, arrayBaseOffset + arrayIndexScale));
}
private static void cmpInt(Unsafe unsafe) throws Exception {
int[] arr = {1, 3, 7};
long arrayBaseOffset = unsafe.arrayBaseOffset(arr.getClass());
long arrayIndexScale = unsafe.arrayIndexScale(arr.getClass());
unsafe.compareAndSwapInt(arr, arrayBaseOffset, 1, 8);
if (arr[0] != 8) {
System.out.println("cmpInt(arr) failed!");
}
UnsafeTest obj = new UnsafeTest();
long xOffset = unsafe.objectFieldOffset(UnsafeTest.class.getField("x"));
unsafe.compareAndSwapInt(obj, xOffset, 0, 7);
if (obj.x != 7) {
System.out.println("cmpInt(obj) failed!");
}
}
private static void memory(Unsafe unsafe) {
final long address = unsafe.allocateMemory(8);
unsafe.putAddress(address, address);
if (unsafe.getAddress(address) != address) {
System.out.println("getAddress() failed!");
}
unsafe.putByte(address, (byte)7);
if (unsafe.getByte(address) != 7) {
System.out.println("getByte() failed!");
}
unsafe.putByte(address, (byte)-7);
if (unsafe.getByte(address) != -7) {
System.out.println("getByte() failed!");
}
unsafe.putShort(address, (short)500);
if (unsafe.getShort(address) != 500) {
System.out.println("getShort() failed!");
}
unsafe.putShort(address, (short)-500);
if (unsafe.getShort(address) != -500) {
System.out.println("getShort() failed!");
}
unsafe.putChar(address, 'c');
if (unsafe.getChar(address) != 'c') {
System.out.println("getChar() failed!");
}
unsafe.putInt(address, 65536);
if (unsafe.getInt(address) != 65536) {
System.out.println("getInt() failed!");
}
unsafe.putInt(address, -65536);
if (unsafe.getInt(address) != -65536) {
System.out.println("getInt() failed!");
}
unsafe.putLong(address, 79L);
if (unsafe.getLong(address) != 79L) {
System.out.println("getLong() failed!");
}
unsafe.putLong(address, -79L);
if (unsafe.getLong(address) != -79L) {
System.out.println("getLong() failed!");
}
unsafe.putFloat(address, 3.14f);
if (unsafe.getFloat(address) != 3.14f) {
System.out.println("getFloat() failed!");
}
unsafe.putDouble(address, 2.71828);
if (unsafe.getDouble(address) != 2.71828) {
System.out.println("getDouble() failed");
}
long newAddress = unsafe.reallocateMemory(address, 100);
unsafe.freeMemory(newAddress);
System.out.println("memory testing ok!");
}
} |
package picoded.servlet;
// Java Serlvet requirments
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;
// Net, io, NIO
import java.net.URL;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
//import java.nio.charset.StandardCharsets;
// Exceptions used
import javax.servlet.ServletException;
import java.io.IOException;
// Objects used
import java.util.*;
import java.io.PrintWriter;
// JMTE inner functions add-on
import com.floreysoft.jmte.*;
// Sub modules useds
import picoded.conv.JMTE;
import picoded.JStack.*;
import picoded.JStruct.*;
import picoded.RESTBuilder.*;
import picoded.webTemplateEngines.JSML.*;
import picoded.webTemplateEngines.PagesBuilder.*;
public class BasePage extends JStackPage implements ServletContextListener {
// Static variables
// RESTBuilder related convinence
/// Cached restbuilder object
protected RESTBuilder _restBuilderObj = null;
/// REST API builder
public RESTBuilder restBuilder() {
if (_restBuilderObj != null) {
return _restBuilderObj;
}
_restBuilderObj = new RESTBuilder();
restBuilderSetup(_restBuilderObj);
return _restBuilderObj;
}
/// !To Override
/// to configure the restBuilderSetup steps
public void restBuilderSetup(RESTBuilder rbObj) {
}
// JStack related convinence function
protected AccountTable _accountAuthObj = null;
/// The default setup process of accountAuthTable
public void accountAuthTableSetup() throws JStackException {
// Gets the configuration setup
JConfig jc = JConfig();
// Setup the tables
AccountTable at = accountAuthTable();
// Setup table
at.systemSetup();
// Gets the superuser group
String superGroup = jc.getString("sys.account.superUsers.groupName", "SuperUsers");
String adminUser = jc.getString("sys.account.superUsers.rootUsername", "admin");
String adminPass = jc.getString("sys.account.superUsers.rootPassword", "P@ssw0rd!");
boolean resetPass = jc.getBoolean("sys.account.superUsers.rootPasswordReset", false);
// Gets and setup the objects if needed
AccountObject grpObject = at.getFromName(superGroup);
if (grpObject == null) {
grpObject = at.newObject(superGroup);
}
// Remove password for super group
grpObject.removePassword();
// Setup the default admin
AccountObject userObject = at.getFromName(adminUser);
if (userObject == null) {
userObject = at.newObject(adminUser);
userObject.setPassword(adminPass);
} else if (resetPass) {
userObject.setPassword(adminPass);
}
// Ensure its role
String role = grpObject.getMemberRole(userObject);
if (role == null || !(role.equals("admin"))) {
grpObject.setMember(userObject, "admin");
}
// Apply changes
userObject.saveDelta();
grpObject.saveDelta();
}
public String getSuperUserGroupName() {
return JConfig().getString("sys.account.superUsers.groupName", "SuperUsers");
}
/// The primary accountAuthTable used for user authentication
public AccountTable accountAuthTable() {
if (_accountAuthObj != null) {
return _accountAuthObj;
}
// @TODO cookiePrefix to be loaded from configurable
// @TODO Config loading
// Gets the configuration setup
JConfig jc = JConfig();
String tablePrefix = jc.getString("sys.account.tableConfig.tablePrefix", "picoded_account");
// httpUserAuthObj.loginLifetime = cStack.getInt( "userAuthCookie.loginLifetime", httpUserAuthObj.loginLifetime);
// httpUserAuthObj.loginRenewal = cStack.getInt( "userAuthCookie.loginRenewal", httpUserAuthObj.loginRenewal);
// httpUserAuthObj.rmberMeLifetime = cStack.getInt( "userAuthCookie.rememberMeLifetime", httpUserAuthObj.rmberMeLifetime);
// httpUserAuthObj.isHttpOnly = cStack.getBoolean( "userAuthCookie.isHttpOnly", httpUserAuthObj.isHttpOnly);
// httpUserAuthObj.isSecureOnly = cStack.getBoolean( "userAuthCookie.isSecureOnly", httpUserAuthObj.isSecureOnly);
_accountAuthObj = JStack().getAccountTable(tablePrefix);
_accountAuthObj.setSuperUserGroupName(getSuperUserGroupName());
return _accountAuthObj;
}
/// [Protected] cached current account object
public AccountObject _currentAccount = null;
/// Current account that is logged in
public AccountObject currentAccount() {
if (_currentAccount != null) {
return _currentAccount;
}
_currentAccount = accountAuthTable().getRequestUser(httpRequest, httpResponse);
return _currentAccount;
}
/// Diverts the user if not logged in, and returns true.
/// Else stored the logged in user name, does setup(), and returns false.
public boolean divertInvalidUser(String redirectTo) throws IOException, JStackException {
if (currentAccount() == null) {
httpResponse.sendRedirect(redirectTo); // wherever you wanna redirect this page.
return true;
}
return false;
}
/// Get the user meta from the current user, this can also be called via JMTE
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.html}
/// {currentUserMetaInfo(metaName)}
public String currentAccountMetaInfo(String meta) throws JStackException {
return currentAccount().getString(meta);
}
// Removed?: Use accountAuthTable() instead
// Gets the user meta info from the specific user
// public String accountMetaInfo(String name, String meta) throws JStackException {
// return accountAuthTable().getFromName(name).getString(meta);
// HTML fetch and JMTE templating
protected class currentAccountMetaInfo_nr implements NamedRenderer {
@Override
public RenderFormatInfo getFormatInfo() {
return null;
}
@Override
public String getName() {
return "currentAccountMetaInfo";
}
@Override
public Class<?>[] getSupportedClasses() {
return new Class<?>[] { (new Object()).getClass() };
}
@Override
public String render(Object o, String format, Locale L) {
if (format == null || format.length() <= 0) {
return null;
}
try {
return currentAccountMetaInfo(format);
} catch (JStackException e) {
throw new RuntimeException(e);
}
}
}
/// [Protected] jmte object used
protected JMTE _jmteObj = null;
/// Loads and setup the jmte object with the "contextPath" parameter, htmlPartsFolder directory if needed
/// @returns the jmte object
public JMTE JMTE() {
if (_jmteObj != null) {
return _jmteObj;
}
_jmteObj = new JMTE(getPagesTemplatePath());
JMTE_initialSetup(_jmteObj);
return _jmteObj;
}
/// Initial setup of the JMTE logic, and base data model.
/// this is the function to override for extended classes to add to JMTE base data model
public void JMTE_initialSetup(JMTE setupObj) {
setupObj.baseDataModel.put("ContextPath", getContextPath());
setupObj.baseDataModel.put("ContextURI", getContextURI());
setupObj.registerNamedRenderer(new currentAccountMetaInfo_nr());
}
// PagesBuilder handling
/// [Protected] PagesBuilder object used
protected PagesBuilder _pagesBuilderObj = null;
/// Loads and setup the PagesBuilder object if needed
/// @returns the PagesBuilder object
public PagesBuilder PagesBuilder() {
if (_pagesBuilderObj != null) {
_pagesBuilderObj.setUriRootPrefix(getContextURI());
return _pagesBuilderObj;
}
_pagesBuilderObj = new PagesBuilder(getPagesTemplatePath(), getPagesOutputPath());
_pagesBuilderObj.setJMTE(JMTE());
_pagesBuilderObj.setUriRootPrefix(getContextURI());
return _pagesBuilderObj;
}
// JSML handling
/// [Protected] JSMLFormSet object used
protected JSMLFormSet _formSetObj = null;
/// Loads and setup the JSMLFormSet object if needed
/// @returns the JSMLFormSet object
public JSMLFormSet JSMLFormSet() {
if (_formSetObj != null) {
return _formSetObj;
}
_formSetObj = new JSMLFormSet(getJsmlTemplatePath(), getContextURI());
return _formSetObj;
}
// Servlet context handling
/// BasePage initializeContext to be extended / build on
@Override
public void initializeContext() throws Exception {
accountAuthTableSetup();
}
} |
package parser.strategy.SLR;
import grammar.Grammar;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import parser.strategy.ParseStrategy;
import parser.strategy.SLR.data.LRData;
import parser.strategy.SLR.exceptions.SLRException;
import parser.strategy.SLR.structure.machine.SLRStateMachine;
import parser.strategy.SLR.structure.machine.node.LRItemNode;
import parser.strategy.SLR.structure.parse.stack.LRAbstractStackEntry;
import parser.strategy.SLR.structure.parse.stack.LRLexicalEntry;
import parser.strategy.SLR.structure.parse.stack.LRSyntaxEntry;
import parser.strategy.SLR.structure.table.LRTable;
import parser.strategy.SLR.structure.table.cell.*;
import token.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class SLR extends ParseStrategy {
// Logger
private Logger l = LogManager.getFormatterLogger(getClass());
// Components
private SLRStateMachine stateMachine;
private LRTable table;
// Root of parser
private NonTerminalToken treeRoot;
// Data storage
private LRData lrData;
public SLR(Grammar grammar) {
super(grammar);
// Check if the grammar is correct
validate();
// Initial components
stateMachine = new SLRStateMachine(grammar);
table = new LRTable(stateMachine);
// Print table
l.info("Printing SLR parser table:\n" + table);
}
/**
* Get LR state machine
* @return LR state machine
*/
public SLRStateMachine getStateMachine() {
return stateMachine;
}
@Override
public boolean parse(AbstractToken firstLexicalTokens) {
// Log
l.info("Start parsing input ...");
// Prepare stack
Stack<LRAbstractStackEntry> parserStack = new Stack<>();
// True if error detected
boolean error = false;
// True if the parser is in panic mode
boolean stable = true;
// Int phases
int phases = 1;
// If listener is set then update the number of parse phases
if(parseStrategyListener != null) {
// Required to reset data
parseStrategyListener.init();
phases = parseStrategyListener.getParsePhase();
// If no phase or phase 0 has been specified
if(phases == 0) {
l.error("Exiting parser because no actions has been specified for phase 1");
return false;
}
}
l.info("Total parses: " + phases);
// Prepare lexical token
AbstractToken lexicalToken = null;
// Run multiple times
for(int phase = 1; phase <= phases; phase++) {
// Push initial entry
LRSyntaxEntry initialEntry = new LRSyntaxEntry();
initialEntry.setNode(stateMachine.getNodes().get(0));
initialEntry.setSyntaxToken(SyntaxTokenFactory.createEndOfStackToken());
parserStack.push(initialEntry);
// Reset input token
lexicalToken = firstLexicalTokens;
if(phase == 1) {
// Prepare storage
lrData = new LRData();
// Add all lexical tokens
AbstractToken lexicalTokenIter = firstLexicalTokens;
while(lexicalTokenIter != null) {
LRLexicalEntry lexicalEntry = new LRLexicalEntry();
lexicalEntry.setLexicalToken(lexicalTokenIter);
lrData.getDerivationList().add(lexicalEntry);
lexicalTokenIter = lexicalTokenIter.getNext();
}
// New data entry
lrData.addFineEntry(parserStack, lexicalToken);
}
while (!parserStack.isEmpty()) {
// Get the top entry
LRItemNode topEntry = parserStack.peek().getNode();
// Get action cell
LRAbstractTableCell actionCell = table.getActionCell(topEntry, lexicalToken);
if(actionCell instanceof LRShiftCell) {
LRShiftCell shiftCell = (LRShiftCell) actionCell;
LRLexicalEntry lexicalEntry = new LRLexicalEntry();
lexicalEntry.setLexicalToken(lexicalToken);
lexicalEntry.setNode(shiftCell.getNode());
parserStack.push(lexicalEntry);
lexicalToken = lexicalToken.getNext();
if(phase == 1) {
lrData.addFineEntry(parserStack, lexicalToken);
}
} else if(actionCell instanceof LRReduceCell) {
LRReduceCell reduceCell = (LRReduceCell) actionCell;
// Create parent token
NonTerminalToken parentToken = SyntaxTokenFactory.createNonTerminalToken(reduceCell.getItem().getLHS());
// Prepare production RHS from the popped entries
List<LRAbstractStackEntry> RHSEntries = new ArrayList<>();
// Get rule
List<AbstractSyntaxToken> rule = reduceCell.getItem().getRuleCopy();
for(int i=rule.size()-1; i >= 0; --i) {
if(rule.get(i) instanceof NonTerminalToken) {
LRSyntaxEntry syntaxEntry = (LRSyntaxEntry) parserStack.pop();
RHSEntries.add(syntaxEntry);
parentToken.addChild(syntaxEntry.getSyntaxToken());
} else if(rule.get(i) instanceof TerminalToken) {
LRLexicalEntry lexicalEntry = (LRLexicalEntry) parserStack.pop();
RHSEntries.add(lexicalEntry);
((TerminalToken) rule.get(i)).setLexicalToken(lexicalEntry.getLexicalToken());
parentToken.addChild(rule.get(i));
} else if(rule.get(i) instanceof EpsilonToken) {
parentToken.addChild(rule.get(i));
}
}
// Get the top entry
topEntry = parserStack.peek().getNode();
// Check if LHS is the initial production
if(actionCell instanceof LRAcceptCell) {
parserStack.pop();
treeRoot = parentToken;
if(phase == 1) {
lrData.addFineEntry(parserStack, lexicalToken);
}
} else {
// Push LHS
LRSyntaxEntry syntaxEntry = new LRSyntaxEntry();
syntaxEntry.setSyntaxToken(parentToken);
// Set go to
int goToNode = table.getGoToCell(topEntry, parentToken.getValue());
if (goToNode == LRTable.GO_TO_EMPTY) {
String message = "GOTO[" + topEntry.getId() + "][" + parentToken.getValue() + "] result was not found. Please report this problem.";
l.fatal(message);
throw new RuntimeException(message);
}
syntaxEntry.setNode(stateMachine.getNodes().get(goToNode));
parserStack.push(syntaxEntry);
if(phase == 1) {
lrData.addFineEntry(parserStack, lexicalToken, syntaxEntry, RHSEntries);
}
}
} else {
// Keep popping until finding goto options with entries in the map
// Worst case, the root node will stay in the stack
while(table.getErrorRecoveryMapList().get(topEntry.getId()).isEmpty()) {
parserStack.pop();
topEntry = parserStack.peek().getNode();
}
// Keep scanning until finding a token in the map
while(lexicalToken != null && table.getErrorRecovery(topEntry, lexicalToken) == null) {
lexicalToken = lexicalToken.getNext();
}
if(lexicalToken != null) {
// Create and store the found value
LRSyntaxEntry syntaxEntry = new LRSyntaxEntry();
String nonTerminalSelected = table.getErrorRecovery(topEntry, lexicalToken);
syntaxEntry.setSyntaxToken(SyntaxTokenFactory.createNonTerminalToken(nonTerminalSelected));
syntaxEntry.setNode(stateMachine.getNodes().get(table.getGoToCell(topEntry, nonTerminalSelected)));
parserStack.push(syntaxEntry);
}
if (phase == 1) {
// New data entry
lrData.addErrorEntry(parserStack, lexicalToken, "Error found");
}
error = true;
}
}
}
if(error) {
return false;
}
return true;
}
/**
* Get data
* @return
*/
public LRData getLrData() {
return lrData;
}
/**
* Check if the grammar is LR
* Cond 1: Start non-terminal should have only one production of the form A -> B
* Cond 2: No other production should call the start non-terminal
* TODO Check if action tokens should be allowed in initial production [Cond 1]
*/
public void validate() {
// Cond 1
List<List<AbstractSyntaxToken>> startProductions = grammar.getProductions().get(grammar.getStart());
if(startProductions.size() != 1 || startProductions.get(0).size() != 1 || !(startProductions.get(0).get(0) instanceof NonTerminalToken)) {
String message = "The initial production should be of the form A -> B";
l.error(message);
throw new SLRException(message);
}
// Cond 2
for(List<List<AbstractSyntaxToken>> productionList : grammar.getProductions().values()) {
for(List<AbstractSyntaxToken> production : productionList) {
for(AbstractSyntaxToken syntaxToken : production) {
if(syntaxToken instanceof NonTerminalToken && syntaxToken.getValue().equals(grammar.getStart())) {
String message = "No production should include the starting non-terminal: " + grammar.getStart();
l.error(message);
throw new SLRException(message);
}
}
}
}
}
@Override
public NonTerminalToken getDerivationRoot() {
return treeRoot;
}
} |
package shared;
/**
*
* @author David Lecoconnier david.lecoconnier@gmail.com
* @author Jean-Luc Amitousa-Mankoy jeanluc.amitousa.mankoy@gmail.com
* @version 1.0
*/
public class Constants {
/**
* Socket port for objects transmission
*/
public static int SOCKET_OBJECT_PORT = 2000;
/**
* Socket port for commands transmission
*/
public static int SOCKET_COMMAND_PORT = 2001;
} |
import java.util.Scanner;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class _07DaysBetweenTwoDates {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String strFirst = input.next();
String strSecond = input.next();
System.out.println(daysBetween(strFirst, strSecond));
}
private static long daysBetween(String strFirst, String strSecond) {
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("dd-MM-yyyy");
DateTime firstDate = dateFormat.parseDateTime(strFirst);
LocalDate firstDateLocal = firstDate.toLocalDate();
DateTime secondDate = dateFormat.parseDateTime(strSecond);
LocalDate secondDateLocal = secondDate.toLocalDate();
Days d = Days.daysBetween(firstDate, secondDate);
long daysBetween = d.getDays();
return daysBetween;
}
} |
package com.stanfy.views;
import android.content.Context;
import android.support.v4.widget.StaggeredGridView;
import android.support.v4.widget.StaggeredGridView.LayoutParams;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import com.stanfy.serverapi.response.ResponseData;
public class StateHelper {
/** Element view states. */
public static final int STATE_NORMAL = 0, STATE_EMPTY = 1, STATE_MESSAGE = 2, STATE_LOADING = 3;
/** Default loading. */
private static final StateViewCreator[] DEFAULT_STATES = new StateViewCreator[STATE_LOADING + 1];
static {
DEFAULT_STATES[STATE_LOADING] = new DefaultLoadingStateViewCreator();
final DefaultMessageStateViewCreator messageCreator = new DefaultMessageStateViewCreator();
DEFAULT_STATES[STATE_EMPTY] = messageCreator;
DEFAULT_STATES[STATE_MESSAGE] = messageCreator;
}
public static void setDefaultStateViewCreator(final int state, final StateViewCreator creator) {
DEFAULT_STATES[state] = creator;
}
/** Special views. */
private StateViewCreator[] viewCreators;
protected StateViewCreator[] constructCreatorsArray() {
final StateViewCreator[] result = new StateViewCreator[DEFAULT_STATES.length];
for (int i = 0; i < result.length; i++) {
final StateViewCreator prototype = DEFAULT_STATES[i];
if (prototype != null) {
result[i] = prototype.copy();
}
}
return result;
}
public void setStateViewCreator(final int state, final StateViewCreator creator) {
final StateViewCreator[] viewCreators = getViewCreators();
if (state != STATE_NORMAL && state > 0 && state < viewCreators.length) {
viewCreators[state] = creator;
}
}
private StateViewCreator[] getViewCreators() {
if (viewCreators == null) {
viewCreators = constructCreatorsArray();
}
return viewCreators;
}
public StateViewCreator getStateViewCreator(final int state) {
final StateViewCreator[] viewCreators = getViewCreators();
return state > 0 && state < viewCreators.length ? viewCreators[state] : null;
}
public View getCustomStateView(final int state, final Context context, final Object lastDataObject, final ViewGroup parent) {
final StateViewCreator creator = getStateViewCreator(state);
if (creator == null) { return null; }
final View view = creator.getView(context, lastDataObject, parent);
// do some tricks
if (view.getLayoutParams() != null) {
configureStateViewHeight(parent, view);
configureStateViewWidth(parent, view);
}
return view;
}
public boolean hasState(final int state) { return getStateViewCreator(state) != null; }
protected void configureStateViewHeight(final ViewGroup parent, final View stateView) {
if (stateView.getLayoutParams().height != ViewGroup.LayoutParams.MATCH_PARENT) { return; }
int h = ViewGroup.LayoutParams.MATCH_PARENT;
if (parent instanceof ListView) {
final ListView listView = (ListView) parent;
// check for one child only that wants to be as tall as we are
final int childCount = listView.getChildCount();
final int headersCount = listView.getHeaderViewsCount();
final int dHeight = listView.getDividerHeight();
h = listView.getHeight() - listView.getPaddingTop() - listView.getPaddingBottom();
for (int i = 0; i < headersCount; i++) {
final View header = listView.getChildAt(i);
if (header != null) {
h -= header.getHeight() + dHeight;
}
}
final int footersCount = listView.getFooterViewsCount();
for (int i = 0; i < footersCount; i++) {
final View footer = listView.getChildAt(childCount - footersCount - 1);
if (footer != null) {
h -= footer.getHeight() + dHeight;
}
}
} else {
h = parent.getHeight() - parent.getPaddingTop() - parent.getPaddingBottom();
}
if (h <= 0) { h = ViewGroup.LayoutParams.MATCH_PARENT; }
final ViewGroup.LayoutParams lp = stateView.getLayoutParams();
lp.height = h;
stateView.setLayoutParams(lp);
}
protected void configureStateViewWidth(final ViewGroup parent, final View stateView) {
final ViewGroup.LayoutParams lp = stateView.getLayoutParams();
if (parent instanceof StaggeredGridView) {
final StaggeredGridView.LayoutParams params = (LayoutParams) lp;
params.span = StaggeredGridView.LayoutParams.SPAN_MAX;
} else {
int w = parent.getWidth() - parent.getPaddingLeft() - parent.getPaddingRight();
if (w <= 0) { w = ViewGroup.LayoutParams.MATCH_PARENT; }
lp.width = w;
}
stateView.setLayoutParams(lp);
}
/**
* State view creator.
*/
public abstract static class StateViewCreator implements Cloneable {
/** View instance. */
private View view;
protected abstract View createView(final Context context, final ViewGroup parent);
protected abstract void bindView(final Context context, final View view, final Object lastResponseData, final ViewGroup parent);
View getView(final Context context, final Object lastResponseData, final ViewGroup parent) {
if (view == null) {
view = createView(context, parent);
}
bindView(context, view, lastResponseData, parent);
return view;
}
public StateViewCreator copy() {
try {
return (StateViewCreator)clone();
} catch (final CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
/** Default loading state. */
public static class DefaultLoadingStateViewCreator extends StateViewCreator {
@Override
protected View createView(final Context context, final ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.progress_panel, parent, false);
}
@Override
protected void bindView(final Context context, final View view, final Object lastResponseData, final ViewGroup parent) {
// nothing
}
}
/** Default message state. */
public static class DefaultMessageStateViewCreator extends StateViewCreator {
@Override
protected View createView(final Context context, final ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.message_panel, parent, false);
}
@Override
protected void bindView(final Context context, final View view, final Object lastResponseData, final ViewGroup parent) {
if (lastResponseData instanceof ResponseData) {
((TextView)view).setText(((ResponseData<?>) lastResponseData).getMessage());
}
}
}
} |
package gov.nih.nci.calab.service.remote;
import gov.nih.nci.cagrid.cadsr.service.ServiceConfiguration;
import gov.nih.nci.cagrid.discovery.client.DiscoveryClient;
import gov.nih.nci.cagrid.metadata.MetadataUtils;
import gov.nih.nci.cagrid.metadata.ServiceMetadata;
import gov.nih.nci.calab.dto.remote.GridNodeBean;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import org.apache.axis.message.addressing.EndpointReferenceType;
/**
* Grid service utils for grid node discovery and grid node URL lookup.
* @author pansu
*
*/
public class GridService {
/**
* Temp code to be replaced
*
* @param indexServiceURL
* @param domainModelName
* @return
* @throws Exception
*/
public static Map<String, GridNodeBean> discoverServices(
String indexServiceURL, String domainModelName) throws Exception {
Map<String, GridNodeBean> gridNodeMap = new TreeMap<String, GridNodeBean>();
GridNodeBean nclNode = new GridNodeBean("NCL",
"http://6116-pansu-2.nci.nih.gov:8880/wsrf/services/cagrid/CaNanoLabSvc",
"http://6116-pansu-2.nci.nih.gov:8080/caNanoLabSDK/http/remoteService");
GridNodeBean washUNode = new GridNodeBean("WashU",
"http://6116-zengje-1.nci.nih.gov:8880/wsrf/services/cagrid/CaNanoLabSvc",
"http://6116-zengje-1.nci.nih.gov:8080/caNanoLabSDK/http/remoteService");
gridNodeMap.put("NCL", nclNode);
gridNodeMap.put("WashU", washUNode);
return gridNodeMap;
}
/**
* Query the grid index service by domain model name and return a map of
* GridNodeBeans with keys being the hostnames.
*
* @param indexServiceURL
* @param domainModelName
* @return
* @throws Exception
*/
public static Map<String, GridNodeBean> discoverServicesToKeep(
String indexServiceURL, String domainModelName) throws Exception {
Map<String, GridNodeBean> gridNodeMap = new TreeMap<String, GridNodeBean>();
DiscoveryClient discoveryClient = new DiscoveryClient(indexServiceURL);
EndpointReferenceType[] services = discoveryClient
.discoverDataServicesByDomainModel(domainModelName);
for (EndpointReferenceType service : services) {
String address = service.getAddress().getPath();
ServiceMetadata serviceMetaData = MetadataUtils
.getServiceMetadata(service);
String hostName = serviceMetaData.getHostingResearchCenter()
.getResearchCenter().getDisplayName();
String appServiceURL=ServiceConfiguration.getConfiguration().getCaCOREServiceURL();
GridNodeBean gridNode = new GridNodeBean(hostName, address, appServiceURL);
gridNodeMap.put(hostName, gridNode);
}
return gridNodeMap;
}
/**
* Return an array of GridNodeBean based on grid host names
*
* @param gridNodeMap
* @param gridNodeHosts
* @return
*/
public static GridNodeBean[] getGridNodesFromHostNames(
Map<String, GridNodeBean> gridNodeMap, String[] gridNodeHosts) {
GridNodeBean[] gridNodes = null;
if (gridNodeHosts.length == 0) {
Collection<GridNodeBean> selectedGrids = gridNodeMap.values();
gridNodes=new GridNodeBean[selectedGrids.size()];
selectedGrids.toArray(gridNodes);
} else {
gridNodes=new GridNodeBean[gridNodeHosts.length];
int i = 0;
for (String host : gridNodeHosts) {
gridNodes[i] = gridNodeMap.get(host);
i++;
}
}
return gridNodes;
}} |
package org.neo4j.impl.shell.apps;
import java.rmi.RemoteException;
import java.util.regex.Pattern;
import org.neo4j.api.core.Direction;
import org.neo4j.api.core.Node;
import org.neo4j.api.core.Relationship;
import org.neo4j.impl.shell.NeoApp;
import org.neo4j.util.shell.AppCommandParser;
import org.neo4j.util.shell.OptionValueType;
import org.neo4j.util.shell.Output;
import org.neo4j.util.shell.Session;
import org.neo4j.util.shell.ShellException;
public class Ls extends NeoApp
{
public Ls()
{
this.addValueType( "d", new OptionContext( OptionValueType.MUST,
"Direction filter for relationships: " +
this.directionAlternatives() ) );
this.addValueType( "v", new OptionContext( OptionValueType.NONE,
"Verbose mode" ) );
this.addValueType( "q", new OptionContext( OptionValueType.NONE,
"Quiet mode" ) );
this.addValueType( "p", new OptionContext( OptionValueType.NONE,
"Lists properties" ) );
this.addValueType( "r", new OptionContext( OptionValueType.NONE,
"Lists relationships" ) );
this.addValueType( "f", new OptionContext( OptionValueType.MUST,
"Filters property keys/relationship types (regexp string)" ) );
}
@Override
public String getDescription()
{
return "Lists the current node. Optionally supply node id for " +
"listing a certain node: ls <node-id>";
}
@Override
protected String exec( AppCommandParser parser, Session session, Output out )
throws ShellException, RemoteException
{
boolean verbose = parser.options().containsKey( "v" );
boolean displayValues = verbose || !parser.options().containsKey( "q" );
boolean displayProperties =
verbose || parser.options().containsKey( "p" );
boolean displayRelationships =
verbose || parser.options().containsKey( "r" );
String filter = parser.options().get( "f" );
if ( !displayProperties && !displayRelationships )
{
displayProperties = true;
displayRelationships = true;
}
Node node = null;
if ( parser.arguments().isEmpty() )
{
node = this.getCurrentNode( session );
}
else
{
node = this.getNodeById(
Long.parseLong( parser.arguments().get( 0 ) ) );
}
this.displayProperties( node, out, displayProperties, displayValues,
verbose, filter );
this.displayRelationships( parser, node, out, displayRelationships,
verbose, filter );
return null;
}
private void displayProperties( Node node, Output out,
boolean displayProperties, boolean displayValues, boolean verbose,
String filter ) throws ShellException, RemoteException
{
if ( !displayProperties )
{
return;
}
int longestKey = this.findLongestKey( node );
Pattern propertyKeyPattern = filter == null ? null :
Pattern.compile( filter );
for ( String key : node.getPropertyKeys() )
{
if ( propertyKeyPattern != null &&
!propertyKeyPattern.matcher( key ).matches() )
{
continue;
}
out.print( "*" + key );
if ( displayValues )
{
this.printMany( out, " ", longestKey - key.length() + 1 );
Object value = node.getProperty( key );
out.print( "=[" + value + "]" );
if ( verbose )
{
out.print( " (" + this.getNiceType( value ) + ")" );
}
}
out.println( "" );
}
}
private void displayRelationships( AppCommandParser parser, Node node,
Output out, boolean displayRelationships, boolean verbose,
String filter ) throws ShellException, RemoteException
{
if ( !displayRelationships )
{
return;
}
String directionFilter = parser.options().get( "d" );
Direction direction = this.getDirection( directionFilter );
boolean displayOutgoing = directionFilter == null ||
direction == Direction.OUTGOING;
boolean displayIncoming = directionFilter == null ||
direction == Direction.INCOMING;
Pattern filterPattern = filter == null ? null :
Pattern.compile( filter );
if ( displayOutgoing )
{
for ( Relationship rel :
node.getRelationships( Direction.OUTGOING ) )
{
if ( filterPattern != null && !filterPattern.matcher(
rel.getType().name() ).matches() )
{
continue;
}
StringBuffer buf = new StringBuffer(
getDisplayNameForCurrentNode() );
buf.append( " --[" ).append( rel.getType() );
if ( verbose )
{
buf.append( ", " ).append( rel.getId() );
}
buf.append( "]
buf.append( getDisplayNameForNode( rel.getEndNode() ) );
out.println( buf );
}
}
if ( displayIncoming )
{
for ( Relationship rel :
node.getRelationships( Direction.INCOMING ) )
{
if ( filterPattern != null && !filterPattern.matcher(
rel.getType().name() ).matches() )
{
continue;
}
StringBuffer buf =
new StringBuffer( getDisplayNameForCurrentNode() );
buf.append( " <--[" ).append( rel.getType() );
if ( verbose )
{
buf.append( ", " ).append( rel.getId() );
}
buf.append( "]
buf.append( getDisplayNameForNode( rel.getStartNode() ) );
out.println( buf );
}
}
}
private String getNiceType( Object value )
{
String cls = value.getClass().getName();
return cls.substring(
String.class.getPackage().getName().length() + 1 );
}
private int findLongestKey( Node node )
{
int length = 0;
for ( String key : node.getPropertyKeys() )
{
if ( key.length() > length )
{
length = key.length();
}
}
return length;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.