repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
safris-src/org | lib4j/test/src/main/java/org/lib4j/test/AssertXml.java | 7601 | /* Copyright (c) 2018 lib4j
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.lib4j.test;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.junit.Assert;
import org.junit.ComparisonFailure;
import org.lib4j.xml.dom.DOMStyle;
import org.lib4j.xml.dom.DOMs;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.Comparison;
import org.xmlunit.diff.ComparisonListener;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.diff.DOMDifferenceEngine;
import org.xmlunit.diff.DifferenceEngine;
public class AssertXml {
private XPath newXPath() {
final XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new SimpleNamespaceContext(prefixToNamespaceURI));
return xPath;
}
public static AssertXml compare(final Element controlElement, final Element testElement) {
final Map<String,String> prefixToNamespaceURI = new HashMap<>();
prefixToNamespaceURI.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
final NamedNodeMap attributes = controlElement.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Attr attribute = (Attr)attributes.item(i);
if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI()) && "xmlns".equals(attribute.getPrefix()))
prefixToNamespaceURI.put(attribute.getLocalName(), attribute.getNodeValue());
}
return new AssertXml(prefixToNamespaceURI, controlElement, testElement);
}
private final Map<String,String> prefixToNamespaceURI;
private final Element controlElement;
private final Element testElement;
private AssertXml(final Map<String,String> prefixToNamespaceURI, final Element controlElement, final Element testElement) {
if (!controlElement.getPrefix().equals(testElement.getPrefix()))
throw new IllegalArgumentException("Prefixes of control and test elements must be the same: " + controlElement.getPrefix() + " != " + testElement.getPrefix());
this.prefixToNamespaceURI = prefixToNamespaceURI;
this.controlElement = controlElement;
this.testElement = testElement;
}
public void addAttribute(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (!(node instanceof Element))
throw new UnsupportedOperationException("Only support addition of attributes to elements");
final Element target = (Element)node;
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? node.getNamespaceURI() : node.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
target.setAttributeNS(namespaceURI, name, value);
}
}
public void remove(final Element element, final String ... xpaths) throws XPathExpressionException {
for (final String xpath : xpaths) {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
attribute.getOwnerElement().removeAttributeNode(attribute);
}
else {
node.getParentNode().removeChild(node);
}
}
}
}
public void replace(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
final XPathExpression expression = newXPath().compile(xpath);
final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
final Node node = nodes.item(i);
if (node instanceof Attr) {
final Attr attribute = (Attr)node;
if (name == null) {
attribute.setValue(value);
}
else {
final int colon = name.indexOf(':');
final String namespaceURI = colon == -1 ? attribute.getNamespaceURI() : attribute.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
final Element owner = attribute.getOwnerElement();
owner.removeAttributeNode(attribute);
owner.setAttributeNS(namespaceURI, name, value);
}
}
else {
throw new UnsupportedOperationException("Only support replacement of attribute values");
}
}
}
public void replace(final Element element, final String xpath, final String value) throws XPathExpressionException {
replace(element, xpath, null, value);
}
public void assertEqual() {
final String prefix = controlElement.getPrefix();
final String controlXml = DOMs.domToString(controlElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final String testXml = DOMs.domToString(testElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
final Source controlSource = Input.fromString(controlXml).build();
final Source testSource = Input.fromString(testXml).build();
final DifferenceEngine diffEngine = new DOMDifferenceEngine();
diffEngine.addDifferenceListener(new ComparisonListener() {
@Override
public void comparisonPerformed(final Comparison comparison, final ComparisonResult result) {
final String controlXPath = comparison.getControlDetails().getXPath() == null ? null : comparison.getControlDetails().getXPath().replaceAll("/([^@])", "/" + prefix + ":$1");
if (controlXPath == null || controlXPath.matches("^.*\\/@[:a-z]+$") || controlXPath.contains("text()"))
return;
try {
Assert.assertEquals(controlXml, testXml);
}
catch (final ComparisonFailure e) {
final StackTraceElement[] stackTrace = e.getStackTrace();
int i;
for (i = 3; i < stackTrace.length; i++)
if (!stackTrace[i].getClassName().startsWith("org.xmlunit.diff"))
break;
final StackTraceElement[] filtered = new StackTraceElement[stackTrace.length - ++i];
System.arraycopy(stackTrace, i, filtered, 0, stackTrace.length - i);
e.setStackTrace(filtered);
throw e;
}
Assert.fail(comparison.toString());
}
});
diffEngine.compare(controlSource, testSource);
}
} | mit |
mlk/miniature-queue | core/src/main/java/com/github/mlk/queue/codex/Utf8StringModule.java | 434 | package com.github.mlk.queue.codex;
import com.github.mlk.queue.Queuify;
import com.github.mlk.queue.implementation.Module;
public class Utf8StringModule implements Module {
public static Utf8StringModule utfStrings() {
return new Utf8StringModule();
}
@Override
public void bind(Queuify.Builder builder) {
builder.encoder(new StringEncoder())
.decoder(new StringDecoder());
}
}
| mit |
SebastienGllmt/jenkins | core/src/main/java/hudson/triggers/SCMTrigger.java | 23475 | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Jean-Baptiste Quenot, id:cactusman
* 2015 Kanstantsin Shautsou
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.triggers;
import antlr.ANTLRException;
import com.google.common.base.Preconditions;
import hudson.Extension;
import hudson.Util;
import hudson.console.AnnotatedLargeText;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.AdministrativeMonitor;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Item;
import hudson.model.Run;
import hudson.scm.SCM;
import hudson.scm.SCMDescriptor;
import hudson.util.FlushProofOutputStream;
import hudson.util.FormValidation;
import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory;
import hudson.util.SequentialExecutionQueue;
import hudson.util.StreamTaskListener;
import hudson.util.TimeUnit2;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.model.RunAction2;
import jenkins.scm.SCMDecisionHandler;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.SystemProperties;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.jelly.XMLOutput;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import static java.util.logging.Level.WARNING;
/**
* {@link Trigger} that checks for SCM updates periodically.
*
* You can add UI elements under the SCM section by creating a
* config.jelly or config.groovy in the resources area for
* your class that inherits from SCMTrigger and has the
* @{@link hudson.model.Extension} annotation. The UI should
* be wrapped in an f:section element to denote it.
*
* @author Kohsuke Kawaguchi
*/
public class SCMTrigger extends Trigger<Item> {
private boolean ignorePostCommitHooks;
public SCMTrigger(String scmpoll_spec) throws ANTLRException {
this(scmpoll_spec, false);
}
@DataBoundConstructor
public SCMTrigger(String scmpoll_spec, boolean ignorePostCommitHooks) throws ANTLRException {
super(scmpoll_spec);
this.ignorePostCommitHooks = ignorePostCommitHooks;
}
/**
* This trigger wants to ignore post-commit hooks.
* <p>
* SCM plugins must respect this and not run this trigger for post-commit notifications.
*
* @since 1.493
*/
public boolean isIgnorePostCommitHooks() {
return this.ignorePostCommitHooks;
}
@Override
public void run() {
if (job == null) {
return;
}
run(null);
}
/**
* Run the SCM trigger with additional build actions. Used by SubversionRepositoryStatus
* to trigger a build at a specific revisionn number.
*
* @param additionalActions
* @since 1.375
*/
public void run(Action[] additionalActions) {
if (job == null) {
return;
}
DescriptorImpl d = getDescriptor();
LOGGER.fine("Scheduling a polling for "+job);
if (d.synchronousPolling) {
LOGGER.fine("Running the trigger directly without threading, " +
"as it's already taken care of by Trigger.Cron");
new Runner(additionalActions).run();
} else {
// schedule the polling.
// even if we end up submitting this too many times, that's OK.
// the real exclusion control happens inside Runner.
LOGGER.fine("scheduling the trigger to (asynchronously) run");
d.queue.execute(new Runner(additionalActions));
d.clogCheck();
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Override
public Collection<? extends Action> getProjectActions() {
if (job == null) {
return Collections.emptyList();
}
return Collections.singleton(new SCMAction());
}
/**
* Returns the file that records the last/current polling activity.
*/
public File getLogFile() {
return new File(job.getRootDir(),"scm-polling.log");
}
@Extension @Symbol("scm")
public static class DescriptorImpl extends TriggerDescriptor {
private static ThreadFactory threadFactory() {
return new NamingThreadFactory(Executors.defaultThreadFactory(), "SCMTrigger");
}
/**
* Used to control the execution of the polling tasks.
* <p>
* This executor implementation has a semantics suitable for polling. Namely, no two threads will try to poll the same project
* at once, and multiple polling requests to the same job will be combined into one. Note that because executor isn't aware
* of a potential workspace lock between a build and a polling, we may end up using executor threads unwisely --- they
* may block.
*/
private transient final SequentialExecutionQueue queue = new SequentialExecutionQueue(Executors.newSingleThreadExecutor(threadFactory()));
/**
* Whether the projects should be polled all in one go in the order of dependencies. The default behavior is
* that each project polls for changes independently.
*/
public boolean synchronousPolling = false;
/**
* Max number of threads for SCM polling.
* 0 for unbounded.
*/
private int maximumThreads;
public DescriptorImpl() {
load();
resizeThreadPool();
}
public boolean isApplicable(Item item) {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(item) != null;
}
public ExecutorService getExecutor() {
return queue.getExecutors();
}
/**
* Returns true if the SCM polling thread queue has too many jobs
* than it can handle.
*/
public boolean isClogged() {
return queue.isStarving(STARVATION_THRESHOLD);
}
/**
* Checks if the queue is clogged, and if so,
* activate {@link AdministrativeMonitorImpl}.
*/
public void clogCheck() {
AdministrativeMonitor.all().get(AdministrativeMonitorImpl.class).on = isClogged();
}
/**
* Gets the snapshot of {@link Runner}s that are performing polling.
*/
public List<Runner> getRunners() {
return Util.filter(queue.getInProgress(),Runner.class);
}
// originally List<SCMedItem> but known to be used only for logging, in which case the instances are not actually cast to SCMedItem anyway
public List<SCMTriggerItem> getItemsBeingPolled() {
List<SCMTriggerItem> r = new ArrayList<SCMTriggerItem>();
for (Runner i : getRunners())
r.add(i.getTarget());
return r;
}
public String getDisplayName() {
return Messages.SCMTrigger_DisplayName();
}
/**
* Gets the number of concurrent threads used for polling.
*
* @return
* 0 if unlimited.
*/
public int getPollingThreadCount() {
return maximumThreads;
}
/**
* Sets the number of concurrent threads used for SCM polling and resizes the thread pool accordingly
* @param n number of concurrent threads, zero or less means unlimited, maximum is 100
*/
public void setPollingThreadCount(int n) {
// fool proof
if(n<0) n=0;
if(n>100) n=100;
maximumThreads = n;
resizeThreadPool();
}
@Restricted(NoExternalUse.class)
public boolean isPollingThreadCountOptionVisible() {
// unless you have a fair number of projects, this option is likely pointless.
// so let's hide this option for new users to avoid confusing them
// unless it was already changed
// TODO switch to check for SCMTriggerItem
return Jenkins.getInstance().getAllItems(AbstractProject.class).size() > 10
|| getPollingThreadCount() != 0;
}
/**
* Update the {@link ExecutorService} instance.
*/
/*package*/ synchronized void resizeThreadPool() {
queue.setExecutors(
(maximumThreads==0 ? Executors.newCachedThreadPool(threadFactory()) : Executors.newFixedThreadPool(maximumThreads, threadFactory())));
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
String t = json.optString("pollingThreadCount",null);
if(t==null || t.length()==0)
setPollingThreadCount(0);
else
setPollingThreadCount(Integer.parseInt(t));
// Save configuration
save();
return true;
}
public FormValidation doCheckPollingThreadCount(@QueryParameter String value) {
if (value != null && "".equals(value.trim()))
return FormValidation.ok();
return FormValidation.validateNonNegativeInteger(value);
}
}
@Extension
public static final class AdministrativeMonitorImpl extends AdministrativeMonitor {
private boolean on;
public boolean isActivated() {
return on;
}
}
/**
* Associated with {@link Run} to show the polling log
* that triggered that build.
*
* @since 1.376
*/
public static class BuildAction implements RunAction2 {
private transient /*final*/ Run<?,?> run;
@Deprecated
public transient /*final*/ AbstractBuild build;
/**
* @since 1.568
*/
public BuildAction(Run<?,?> run) {
this.run = run;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
@Deprecated
public BuildAction(AbstractBuild build) {
this((Run) build);
}
/**
* @since 1.568
*/
public Run<?,?> getRun() {
return run;
}
/**
* Polling log that triggered the build.
*/
public File getPollingLogFile() {
return new File(run.getRootDir(),"polling.log");
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
return Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "pollingLog";
}
/**
* Sends out the raw polling log output.
*/
public void doPollingLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
// Prevent jelly from flushing stream so Content-Length header can be added afterwards
FlushProofOutputStream out = new FlushProofOutputStream(rsp.getCompressedOutputStream(req));
try {
getPollingLogText().writeLogTo(0, out);
} finally {
IOUtils.closeQuietly(out);
}
}
public AnnotatedLargeText getPollingLogText() {
return new AnnotatedLargeText<BuildAction>(getPollingLogFile(), Charset.defaultCharset(), true, this);
}
/**
* Used from <tt>polling.jelly</tt> to write annotated polling log to the given output.
*/
public void writePollingLogTo(long offset, XMLOutput out) throws IOException {
// TODO: resurrect compressed log file support
getPollingLogText().writeHtmlTo(offset, out.asWriter());
}
@Override public void onAttached(Run<?, ?> r) {
// unnecessary, existing constructor does this
}
@Override public void onLoad(Run<?, ?> r) {
run = r;
build = run instanceof AbstractBuild ? (AbstractBuild) run : null;
}
}
/**
* Action object for job. Used to display the last polling log.
*/
public final class SCMAction implements Action {
public AbstractProject<?,?> getOwner() {
Item item = getItem();
return item instanceof AbstractProject ? ((AbstractProject) item) : null;
}
/**
* @since 1.568
*/
public Item getItem() {
return job().asItem();
}
public String getIconFileName() {
return "clipboard.png";
}
public String getDisplayName() {
Set<SCMDescriptor<?>> descriptors = new HashSet<SCMDescriptor<?>>();
for (SCM scm : job().getSCMs()) {
descriptors.add(scm.getDescriptor());
}
return descriptors.size() == 1 ? Messages.SCMTrigger_getDisplayName(descriptors.iterator().next().getDisplayName()) : Messages.SCMTrigger_BuildAction_DisplayName();
}
public String getUrlName() {
return "scmPollLog";
}
public String getLog() throws IOException {
return Util.loadFile(getLogFile());
}
/**
* Writes the annotated log to the given output.
* @since 1.350
*/
public void writeLogTo(XMLOutput out) throws IOException {
new AnnotatedLargeText<SCMAction>(getLogFile(),Charset.defaultCharset(),true,this).writeHtmlTo(0,out.asWriter());
}
}
private static final Logger LOGGER = Logger.getLogger(SCMTrigger.class.getName());
/**
* {@link Runnable} that actually performs polling.
*/
public class Runner implements Runnable {
/**
* When did the polling start?
*/
private volatile long startTime;
private Action[] additionalActions;
public Runner() {
this(null);
}
public Runner(Action[] actions) {
Preconditions.checkNotNull(job, "Runner can't be instantiated when job is null");
if (actions == null) {
additionalActions = new Action[0];
} else {
additionalActions = actions;
}
}
/**
* Where the log file is written.
*/
public File getLogFile() {
return SCMTrigger.this.getLogFile();
}
/**
* For which {@link Item} are we polling?
* @since 1.568
*/
public SCMTriggerItem getTarget() {
return job();
}
/**
* When was this polling started?
*/
public long getStartTime() {
return startTime;
}
/**
* Human readable string of when this polling is started.
*/
public String getDuration() {
return Util.getTimeSpanString(System.currentTimeMillis()-startTime);
}
private boolean runPolling() {
try {
// to make sure that the log file contains up-to-date text,
// don't do buffering.
StreamTaskListener listener = new StreamTaskListener(getLogFile());
try {
PrintStream logger = listener.getLogger();
long start = System.currentTimeMillis();
logger.println("Started on "+ DateFormat.getDateTimeInstance().format(new Date()));
boolean result = job().poll(listener).hasChanges();
logger.println("Done. Took "+ Util.getTimeSpanString(System.currentTimeMillis()-start));
if(result)
logger.println("Changes found");
else
logger.println("No changes");
return result;
} catch (Error | RuntimeException e) {
e.printStackTrace(listener.error("Failed to record SCM polling for "+job));
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
throw e;
} finally {
listener.close();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"Failed to record SCM polling for "+job,e);
return false;
}
}
public void run() {
if (job == null) {
return;
}
// we can pre-emtively check the SCMDecisionHandler instances here
// note that job().poll(listener) should also check this
SCMDecisionHandler veto = SCMDecisionHandler.firstShouldPollVeto(job);
if (veto != null) {
try (StreamTaskListener listener = new StreamTaskListener(getLogFile())) {
listener.getLogger().println(
"Skipping polling on " + DateFormat.getDateTimeInstance().format(new Date())
+ " due to veto from " + veto);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to record SCM polling for " + job, e);
}
LOGGER.log(Level.FINE, "Skipping polling for {0} due to veto from {1}",
new Object[]{job.getFullDisplayName(), veto}
);
return;
}
String threadName = Thread.currentThread().getName();
Thread.currentThread().setName("SCM polling for "+job);
try {
startTime = System.currentTimeMillis();
if(runPolling()) {
SCMTriggerItem p = job();
String name = " #"+p.getNextBuildNumber();
SCMTriggerCause cause;
try {
cause = new SCMTriggerCause(getLogFile());
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse the polling log",e);
cause = new SCMTriggerCause();
}
Action[] queueActions = new Action[additionalActions.length + 1];
queueActions[0] = new CauseAction(cause);
System.arraycopy(additionalActions, 0, queueActions, 1, additionalActions.length);
if (p.scheduleBuild2(p.getQuietPeriod(), queueActions) != null) {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Triggering "+name);
} else {
LOGGER.info("SCM changes detected in "+ job.getFullDisplayName()+". Job is already in the queue");
}
}
} finally {
Thread.currentThread().setName(threadName);
}
}
// as per the requirement of SequentialExecutionQueue, value equality is necessary
@Override
public boolean equals(Object that) {
return that instanceof Runner && job == ((Runner) that)._job();
}
private Item _job() {return job;}
@Override
public int hashCode() {
return job.hashCode();
}
}
@SuppressWarnings("deprecation")
private SCMTriggerItem job() {
return SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(job);
}
public static class SCMTriggerCause extends Cause {
/**
* Only used while ths cause is in the queue.
* Once attached to the build, we'll move this into a file to reduce the memory footprint.
*/
private String pollingLog;
private transient Run run;
public SCMTriggerCause(File logFile) throws IOException {
// TODO: charset of this log file?
this(FileUtils.readFileToString(logFile));
}
public SCMTriggerCause(String pollingLog) {
this.pollingLog = pollingLog;
}
/**
* @deprecated
* Use {@link SCMTrigger.SCMTriggerCause#SCMTriggerCause(String)}.
*/
@Deprecated
public SCMTriggerCause() {
this("");
}
@Override
public void onLoad(Run run) {
this.run = run;
}
@Override
public void onAddedTo(Run build) {
this.run = build;
try {
BuildAction a = new BuildAction(build);
FileUtils.writeStringToFile(a.getPollingLogFile(),pollingLog);
build.replaceAction(a);
} catch (IOException e) {
LOGGER.log(WARNING,"Failed to persist the polling log",e);
}
pollingLog = null;
}
@Override
public String getShortDescription() {
return Messages.SCMTrigger_SCMTriggerCause_ShortDescription();
}
@Restricted(DoNotUse.class)
public Run getRun() {
return this.run;
}
@Override
public boolean equals(Object o) {
return o instanceof SCMTriggerCause;
}
@Override
public int hashCode() {
return 3;
}
}
/**
* How long is too long for a polling activity to be in the queue?
*/
public static long STARVATION_THRESHOLD = SystemProperties.getLong(SCMTrigger.class.getName()+".starvationThreshold", TimeUnit2.HOURS.toMillis(1));
}
| mit |
Pante/Karus-Commons | commons/src/test/java/com/karuslabs/commons/command/synchronization/SynchronizationTest.java | 3282 | /*
* The MIT License
*
* Copyright 2019 Karus Labs.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.karuslabs.commons.command.synchronization;
import java.util.List;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerCommandSendEvent;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class SynchronizationTest {
Synchronizer synchronizer = mock(Synchronizer.class);
BukkitScheduler scheduler = mock(BukkitScheduler.class);
Synchronization synchronization = new Synchronization(synchronizer, scheduler, null);
PlayerCommandSendEvent event = mock(PlayerCommandSendEvent.class);
@Test
void add() {
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_duplicate() {
synchronization.events.add(event);
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertFalse(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void add_running() {
synchronization.running = true;
synchronization.add(event);
assertTrue(synchronization.events.contains(event));
assertTrue(synchronization.running);
verify(scheduler, times(0)).scheduleSyncDelayedTask(null, synchronization);
}
@Test
void run() {
when(event.getPlayer()).thenReturn(mock(Player.class));
when(event.getCommands()).thenReturn(List.of("a"));
synchronization.add(event);
synchronization.run();
verify(synchronizer).synchronize(any(Player.class), any(List.class));
assertTrue(synchronization.events.isEmpty());
assertFalse(synchronization.running);
}
}
| mit |
joansmith/ontrack | ontrack-core/src/main/java/net/ontrack/core/security/ProjectAuthorization.java | 258 | package net.ontrack.core.security;
import lombok.Data;
import net.ontrack.core.model.AccountSummary;
@Data
public class ProjectAuthorization {
private final int project;
private final AccountSummary account;
private final ProjectRole role;
}
| mit |
OlegSvyryd/animalsRepo | SampleProjectPet/src/test/java/com/softserve/app/repository/PetRepositoryStubTest.java | 1751 | package com.softserve.app.repository;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import com.softserve.app.model.Pet;
@RunWith(MockitoJUnitRunner.class)
public class PetRepositoryStubTest {
@Mock PetRepository stubM;
@Mock Pet petM;
@Test
public void testFindAllPetsWithMockStub() {
List<Pet> pets = stubM.findAllPets();
assertNotNull(pets);
}
@Test
public void testFindAllPetsWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
List<Pet> pets = (ArrayList<Pet>) stub.findAllPets();
assertNotNull(pets);
}
@Test
public void testFindPetWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet = stub.findPet("101");
System.out.println(pet);
assertNotNull(pet);
}
@Test
public void testFindPetWithMockStub() {
when(stubM.findPet("10").getType()).thenReturn("dog");
assertEquals("dog", stubM.findPet("0").getType());
}
@Test(expected=RuntimeException.class)
public void testFindPetWithBadRequestWithRealStub() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet = stub.findPet("0");
}
@Test
public void testCreate() {
PetRepositoryStub stub = new PetRepositoryStub();
Pet pet5 = new Pet();
pet5.setId("5");
pet5.setType("Dog");
System.out.println(pet5.getType());
stub.create(pet5);
System.out.println(stub.findPet("5").getType());
assertNotNull(stub.findPet("5").getType());
}
}
| mit |
AltisourceLabs/ecloudmanager | tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/ResourceBurstType.java | 2598 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
/**
* <p>Java class for ResourceBurstType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ResourceBurstType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Actions" type="{}ArrayOfActionType" minOccurs="0"/>
* <element name="Status" type="{}ResourceBurstStatus" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ResourceBurstType", propOrder = {
"actions",
"status"
})
public class ResourceBurstType {
@XmlElementRef(name = "Actions", type = JAXBElement.class, required = false)
protected JAXBElement<ArrayOfActionType> actions;
@XmlElement(name = "Status")
@XmlSchemaType(name = "string")
protected ResourceBurstStatus status;
/**
* Gets the value of the actions property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public JAXBElement<ArrayOfActionType> getActions() {
return actions;
}
/**
* Sets the value of the actions property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link ArrayOfActionType }{@code >}
*
*/
public void setActions(JAXBElement<ArrayOfActionType> value) {
this.actions = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link ResourceBurstStatus }
*
*/
public ResourceBurstStatus getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link ResourceBurstStatus }
*
*/
public void setStatus(ResourceBurstStatus value) {
this.status = value;
}
}
| mit |
ominidi/ominidi-web | src/main/java/org/ominidi/api/controller/FeedController.java | 1506 | package org.ominidi.api.controller;
import org.ominidi.api.exception.ConnectionException;
import org.ominidi.api.exception.NotFoundException;
import org.ominidi.api.model.Errors;
import org.ominidi.domain.model.Feed;
import org.ominidi.domain.model.Post;
import org.ominidi.facebook.service.PageFeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1")
public class FeedController {
private PageFeedService pageFeedService;
@Autowired
public FeedController(PageFeedService pageFeedService) {
this.pageFeedService = pageFeedService;
}
@GetMapping(value = "/feed", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Feed<Post> getFeed(@RequestParam(value = "u", required = false) Optional<String> feedUrl) {
Optional<Feed<Post>> result = feedUrl.isPresent()
? pageFeedService.getFeed(feedUrl.get())
: pageFeedService.getFeed();
return result.orElseThrow(() -> new ConnectionException(Errors.CONNECTION_PROBLEM));
}
@GetMapping(value = "/post/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Post getPost(@PathVariable(value = "id") String id) {
return pageFeedService.getPostById(id).orElseThrow(() -> new NotFoundException(Errors.postNotFound(id)));
}
}
| mit |
Sarwat/GeoSpark | core/src/test/java/org/datasyslab/geospark/utils/RDDSampleUtilsTest.java | 2880 | /*
* FILE: RDDSampleUtilsTest
* Copyright (c) 2015 - 2018 GeoSpark Development Team
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.datasyslab.geospark.utils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class RDDSampleUtilsTest
{
/**
* Test get sample numbers.
*/
@Test
public void testGetSampleNumbers()
{
assertEquals(10, RDDSampleUtils.getSampleNumbers(2, 10, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(2, 100, -1));
assertEquals(10, RDDSampleUtils.getSampleNumbers(5, 1000, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(5, 10000, -1));
assertEquals(100, RDDSampleUtils.getSampleNumbers(5, 10001, -1));
assertEquals(1000, RDDSampleUtils.getSampleNumbers(5, 100011, -1));
assertEquals(99, RDDSampleUtils.getSampleNumbers(6, 100011, 99));
assertEquals(999, RDDSampleUtils.getSampleNumbers(20, 999, -1));
assertEquals(40, RDDSampleUtils.getSampleNumbers(20, 1000, -1));
}
/**
* Test too many partitions.
*/
@Test
public void testTooManyPartitions()
{
assertFailure(505, 999);
assertFailure(505, 1000);
assertFailure(10, 1000, 2100);
}
private void assertFailure(int numPartitions, long totalNumberOfRecords)
{
assertFailure(numPartitions, totalNumberOfRecords, -1);
}
private void assertFailure(int numPartitions, long totalNumberOfRecords, int givenSampleNumber)
{
try {
RDDSampleUtils.getSampleNumbers(numPartitions, totalNumberOfRecords, givenSampleNumber);
fail("Expected IllegalArgumentException");
}
catch (IllegalArgumentException e) {
// expected
}
}
} | mit |
gencer/Twig-Eclipse-Plugin | com.dubture.twig.core/src/com/dubture/twig/core/model/IFunction.java | 91 | package com.dubture.twig.core.model;
public interface IFunction extends ITwigCallable {
}
| mit |
svgorbunov/Mariculture | src/main/java/maritech/nei/MTNEIConfig.java | 676 | package maritech.nei;
import mariculture.core.lib.Modules;
import mariculture.factory.Factory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import codechicken.nei.api.API;
import codechicken.nei.api.IConfigureNEI;
public class MTNEIConfig implements IConfigureNEI {
@Override
public void loadConfig() {
if (Modules.isActive(Modules.factory)) {
API.hideItem(new ItemStack(Factory.customRFBlock, 1, OreDictionary.WILDCARD_VALUE));
}
}
@Override
public String getName() {
return "MariTech NEI";
}
@Override
public String getVersion() {
return "1.0";
}
}
| mit |
tpe-lecture/repo-27 | 06_ausnahmen/02_finally/src/tpe/exceptions/trycatchfinally/GameBoard.java | 955 | package tpe.exceptions.trycatchfinally;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import de.smits_net.games.framework.board.Board;
/**
* Spielfeld.
*/
public class GameBoard extends Board {
/** Sprite, das durch das Bild läuft. */
private Professor sprite;
/**
* Erzeugt ein neues Board.
*/
public GameBoard() {
// neues Spielfeld anlegen
super(10, new Dimension(400, 400), Color.BLACK);
// Sprite initialisieren
sprite = new Professor(this, new Point(300, 200));
}
/**
* Spielfeld neu zeichnen. Wird vom Framework aufgerufen.
*/
@Override
public void drawGame(Graphics g) {
sprite.draw(g, this);
}
/**
* Spielsituation updaten. Wird vom Framework aufgerufen.
*/
@Override
public boolean updateGame() {
sprite.move();
return sprite.isVisible();
}
}
| mit |
pplatek/furnace | container-tests/src/test/java/test/org/jboss/forge/furnace/lifecycle/PreShutdownEventTest.java | 2843 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package test.org.jboss.forge.furnace.lifecycle;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.arquillian.archive.AddonArchive;
import org.jboss.forge.arquillian.services.LocalServices;
import org.jboss.forge.furnace.Furnace;
import org.jboss.forge.furnace.addons.Addon;
import org.jboss.forge.furnace.addons.AddonId;
import org.jboss.forge.furnace.addons.AddonRegistry;
import org.jboss.forge.furnace.repositories.AddonDependencyEntry;
import org.jboss.forge.furnace.repositories.MutableAddonRepository;
import org.jboss.forge.furnace.util.Addons;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import test.org.jboss.forge.furnace.mocks.MockImpl1;
import test.org.jboss.forge.furnace.mocks.MockInterface;
@RunWith(Arquillian.class)
public class PreShutdownEventTest
{
@Deployment(order = 2)
public static AddonArchive getDeployment()
{
AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addAsAddonDependencies(
AddonDependencyEntry.create("dep1")
);
archive.addAsLocalServices(PreShutdownEventTest.class);
return archive;
}
@Deployment(name = "dep2,2", testable = false, order = 1)
public static AddonArchive getDeployment2()
{
AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addAsLocalServices(MockImpl1.class)
.addClasses(MockImpl1.class, MockInterface.class)
.addBeansXML();
return archive;
}
@Deployment(name = "dep1,1", testable = false, order = 0)
public static AddonArchive getDeployment1()
{
AddonArchive archive = ShrinkWrap.create(AddonArchive.class)
.addClass(RecordingEventManager.class)
.addAsLocalServices(RecordingEventManager.class);
return archive;
}
@Test(timeout = 5000)
public void testPreShutdownIsCalled() throws Exception
{
Furnace furnace = LocalServices.getFurnace(getClass().getClassLoader());
AddonRegistry registry = furnace.getAddonRegistry();
Addon dep2 = registry.getAddon(AddonId.from("dep2", "2"));
RecordingEventManager manager = registry.getServices(RecordingEventManager.class).get();
Assert.assertEquals(3, manager.getPostStartupCount());
MutableAddonRepository repository = (MutableAddonRepository) furnace.getRepositories().get(0);
repository.disable(dep2.getId());
Addons.waitUntilStopped(dep2);
Assert.assertEquals(1, manager.getPreShutdownCount());
}
}
| epl-1.0 |
marinmitev/smarthome | bundles/io/org.eclipse.smarthome.io.rest.core/src/main/java/org/eclipse/smarthome/io/rest/core/link/ItemChannelLinkResource.java | 5631 | /**
* Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.io.rest.core.link;
import java.util.ArrayList;
import java.util.Collection;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.link.AbstractLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLink;
import org.eclipse.smarthome.core.thing.link.ItemChannelLinkRegistry;
import org.eclipse.smarthome.core.thing.link.ThingLinkManager;
import org.eclipse.smarthome.core.thing.link.dto.AbstractLinkDTO;
import org.eclipse.smarthome.core.thing.link.dto.ItemChannelLinkDTO;
import org.eclipse.smarthome.io.rest.JSONResponse;
import org.eclipse.smarthome.io.rest.RESTResource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/**
* This class acts as a REST resource for links.
*
* @author Dennis Nobel - Initial contribution
* @author Yordan Zhelev - Added Swagger annotations
* @author Kai Kreuzer - Removed Thing links and added auto link url
*/
@Path(ItemChannelLinkResource.PATH_LINKS)
@Api(value = ItemChannelLinkResource.PATH_LINKS)
public class ItemChannelLinkResource implements RESTResource {
/** The URI path to this resource */
public static final String PATH_LINKS = "links";
private ItemChannelLinkRegistry itemChannelLinkRegistry;
private ThingLinkManager thingLinkManager;
@Context
UriInfo uriInfo;
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets all available links.", response = ItemChannelLinkDTO.class, responseContainer = "Collection")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response getAll() {
Collection<ItemChannelLink> channelLinks = itemChannelLinkRegistry.getAll();
return Response.ok(toBeans(channelLinks)).build();
}
@GET
@Path("/auto")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Tells whether automatic link mode is active or not", response = Boolean.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK") })
public Response isAutomatic() {
return Response.ok(thingLinkManager.isAutoLinksEnabled()).build();
}
@PUT
@Path("/{itemName}/{channelUID}")
@ApiOperation(value = "Links item to a channel.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 400, message = "Item already linked to the channel.") })
public Response link(@PathParam("itemName") @ApiParam(value = "itemName") String itemName,
@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) {
itemChannelLinkRegistry.add(new ItemChannelLink(itemName, new ChannelUID(channelUid)));
return Response.ok().build();
}
@DELETE
@Path("/{itemName}/{channelUID}")
@ApiOperation(value = "Unlinks item from a channel.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK"),
@ApiResponse(code = 404, message = "Link not found."),
@ApiResponse(code = 405, message = "Link not editable.") })
public Response unlink(@PathParam("itemName") @ApiParam(value = "itemName") String itemName,
@PathParam("channelUID") @ApiParam(value = "channelUID") String channelUid) {
String linkId = AbstractLink.getIDFor(itemName, new ChannelUID(channelUid));
if (itemChannelLinkRegistry.get(linkId) == null) {
String message = "Link " + linkId + " does not exist!";
return JSONResponse.createResponse(Status.NOT_FOUND, null, message);
}
ItemChannelLink result = itemChannelLinkRegistry
.remove(AbstractLink.getIDFor(itemName, new ChannelUID(channelUid)));
if (result != null) {
return Response.ok().build();
} else {
return JSONResponse.createErrorResponse(Status.METHOD_NOT_ALLOWED, "Channel is read-only.");
}
}
protected void setThingLinkManager(ThingLinkManager thingLinkManager) {
this.thingLinkManager = thingLinkManager;
}
protected void unsetThingLinkManager(ThingLinkManager thingLinkManager) {
this.thingLinkManager = null;
}
protected void setItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = itemChannelLinkRegistry;
}
protected void unsetItemChannelLinkRegistry(ItemChannelLinkRegistry itemChannelLinkRegistry) {
this.itemChannelLinkRegistry = null;
}
private Collection<AbstractLinkDTO> toBeans(Iterable<ItemChannelLink> links) {
Collection<AbstractLinkDTO> beans = new ArrayList<>();
for (AbstractLink link : links) {
ItemChannelLinkDTO bean = new ItemChannelLinkDTO(link.getItemName(), link.getUID().toString());
beans.add(bean);
}
return beans;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.social_fat.commonTest.LibertyOP/fat/src/com/ibm/ws/security/social/fat/LibertyOP/LibertyOP_BasicTests_oauth_usingSocialConfig.java | 3772 | /*******************************************************************************
* Copyright (c) 2017, 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.social.fat.LibertyOP;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import com.ibm.websphere.simplicity.log.Log;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.RSCommonTestTools;
import com.ibm.ws.security.social.fat.LibertyOP.CommonTests.LibertyOPRepeatActions;
import com.ibm.ws.security.social.fat.commonTests.Social_BasicTests;
import com.ibm.ws.security.social.fat.utils.SocialConstants;
import com.ibm.ws.security.social.fat.utils.SocialTestSettings;
import componenttest.custom.junit.runner.FATRunner;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
import componenttest.rules.repeater.RepeatTests;
import componenttest.topology.impl.LibertyServerWrapper;
@RunWith(FATRunner.class)
@LibertyServerWrapper
@Mode(TestMode.FULL)
public class LibertyOP_BasicTests_oauth_usingSocialConfig extends Social_BasicTests {
public static Class<?> thisClass = LibertyOP_BasicTests_oauth_usingSocialConfig.class;
public static RSCommonTestTools rsTools = new RSCommonTestTools();
@ClassRule
public static RepeatTests r = RepeatTests.with(LibertyOPRepeatActions.usingUserInfo()).andWith(LibertyOPRepeatActions.usingIntrospect());
@BeforeClass
public static void setUp() throws Exception {
classOverrideValidationEndpointValue = FATSuite.UserApiEndpoint;
List<String> startMsgs = new ArrayList<String>();
startMsgs.add("CWWKT0016I.*" + SocialConstants.SOCIAL_DEFAULT_CONTEXT_ROOT);
List<String> extraApps = new ArrayList<String>();
extraApps.add(SocialConstants.HELLOWORLD_SERVLET);
// TODO fix
List<String> opStartMsgs = new ArrayList<String>();
// opStartMsgs.add("CWWKS1600I.*" + SocialConstants.OIDCCONFIGMEDIATOR_APP);
opStartMsgs.add("CWWKS1631I.*");
// TODO fix
List<String> opExtraApps = new ArrayList<String>();
opExtraApps.add(SocialConstants.OP_SAMPLE_APP);
String[] propagationTokenTypes = rsTools.chooseTokenSettings(SocialConstants.OIDC_OP);
String tokenType = propagationTokenTypes[0];
String certType = propagationTokenTypes[1];
Log.info(thisClass, "setupBeforeTest", "inited tokenType to: " + tokenType);
socialSettings = new SocialTestSettings();
testSettings = socialSettings;
testOPServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.op", "op_server_orig.xml", SocialConstants.OIDC_OP, null, SocialConstants.DO_NOT_USE_DERBY, opStartMsgs, null, SocialConstants.OIDC_OP, true, true, tokenType, certType);
genericTestServer = commonSetUp(SocialConstants.SERVER_NAME + ".LibertyOP.social", "server_LibertyOP_basicTests_oauth_usingSocialConfig.xml", SocialConstants.GENERIC_SERVER, extraApps, SocialConstants.DO_NOT_USE_DERBY, startMsgs);
setActionsForProvider(SocialConstants.LIBERTYOP_PROVIDER, SocialConstants.OAUTH_OP);
setGenericVSSpeicificProviderFlags(GenericConfig, "server_LibertyOP_basicTests_oauth_usingSocialConfig");
socialSettings = updateLibertyOPSettings(socialSettings);
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.jbatch.jsl.model/src/com/ibm/jbatch/jsl/model/v2/Batchlet.java | 4330 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vIBM 2.2.3-11/28/2011 06:21 AM(foreman)-
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.06.11 at 05:49:00 PM EDT
//
package com.ibm.jbatch.jsl.model.v2;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Batchlet complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Batchlet">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="properties" type="{https://jakarta.ee/xml/ns/jakartaee}Properties" minOccurs="0"/>
* </sequence>
* <attribute name="ref" use="required" type="{https://jakarta.ee/xml/ns/jakartaee}artifactRef" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Batchlet", propOrder = {
"properties"
})
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public class Batchlet extends com.ibm.jbatch.jsl.model.Batchlet {
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected JSLProperties properties;
@XmlAttribute(name = "ref", required = true)
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
protected String ref;
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public JSLProperties getProperties() {
return properties;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setProperties(com.ibm.jbatch.jsl.model.JSLProperties value) {
this.properties = (JSLProperties) value;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public String getRef() {
return ref;
}
/** {@inheritDoc} */
@Override
@Generated(value = "com.ibm.jtc.jax.tools.xjc.Driver", date = "2014-06-11T05:49:00-04:00", comments = "JAXB RI v2.2.3-11/28/2011 06:21 AM(foreman)-")
public void setRef(String value) {
this.ref = value;
}
/**
* Copyright 2013 International Business Machines Corp.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Appended by build tooling.
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder(100);
buf.append("Batchlet: ref=" + ref);
buf.append("\n");
buf.append("Properties = " + com.ibm.jbatch.jsl.model.helper.PropertiesToStringHelper.getString(properties));
return buf.toString();
}
} | epl-1.0 |
TypeFox/che | multiuser/machine-auth/che-multiuser-machine-authentication/src/main/java/org/eclipse/che/multiuser/machine/authentication/server/MachineLoginFilter.java | 3592 | /*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.machine.authentication.server;
import static com.google.common.base.Strings.nullToEmpty;
import java.io.IOException;
import java.security.Principal;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.model.user.User;
import org.eclipse.che.api.user.server.UserManager;
import org.eclipse.che.commons.auth.token.RequestTokenExtractor;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.subject.Subject;
import org.eclipse.che.commons.subject.SubjectImpl;
import org.eclipse.che.multiuser.api.permission.server.AuthorizedSubject;
import org.eclipse.che.multiuser.api.permission.server.PermissionChecker;
/** @author Max Shaposhnik (mshaposhnik@codenvy.com) */
@Singleton
public class MachineLoginFilter implements Filter {
@Inject private RequestTokenExtractor tokenExtractor;
@Inject private MachineTokenRegistry machineTokenRegistry;
@Inject private UserManager userManager;
@Inject private PermissionChecker permissionChecker;
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
if (httpRequest.getScheme().startsWith("ws")
|| !nullToEmpty(tokenExtractor.getToken(httpRequest)).startsWith("machine")) {
filterChain.doFilter(servletRequest, servletResponse);
return;
} else {
String tokenString;
User user;
try {
tokenString = tokenExtractor.getToken(httpRequest);
String userId = machineTokenRegistry.getUserId(tokenString);
user = userManager.getById(userId);
} catch (NotFoundException | ServerException e) {
throw new ServletException("Cannot find user by machine token.");
}
final Subject subject =
new AuthorizedSubject(
new SubjectImpl(user.getName(), user.getId(), tokenString, false), permissionChecker);
try {
EnvironmentContext.getCurrent().setSubject(subject);
filterChain.doFilter(addUserInRequest(httpRequest, subject), servletResponse);
} finally {
EnvironmentContext.reset();
}
}
}
private HttpServletRequest addUserInRequest(
final HttpServletRequest httpRequest, final Subject subject) {
return new HttpServletRequestWrapper(httpRequest) {
@Override
public String getRemoteUser() {
return subject.getUserName();
}
@Override
public Principal getUserPrincipal() {
return subject::getUserName;
}
};
}
@Override
public void destroy() {}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.cdi.jee_fat/test-applications/resourceWebServicesProvider.war/src/com/ibm/ws/cdi/services/impl/MyPojoUser.java | 840 | /*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.cdi.services.impl;
import javax.enterprise.context.Dependent;
/**
* This class only needs to be here to make sure this is a BDA with a BeanManager
*/
@Dependent
public class MyPojoUser {
public String getUser() {
String s = "DefaultPojoUser";
return s;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.websphere.javaee.jsf.2.2/src/javax/faces/_FactoryFinderProviderFactory.java | 12732 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package javax.faces;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.context.ExternalContext;
/**
* Provide utility methods used by FactoryFinder class to lookup for SPI interface FactoryFinderProvider.
*
* @since 2.0.5
*/
class _FactoryFinderProviderFactory
{
public static final String FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME = "org.apache.myfaces.spi" +
".FactoryFinderProviderFactory";
public static final String FACTORY_FINDER_PROVIDER_CLASS_NAME = "org.apache.myfaces.spi.FactoryFinderProvider";
public static final String INJECTION_PROVIDER_FACTORY_CLASS_NAME =
"org.apache.myfaces.spi.InjectionProviderFactory";
// INJECTION_PROVIDER_CLASS_NAME to provide use of new Injection Provider methods which take a
// a class as an input. This is required for CDI 1.2, particularly in regard to constructor injection/
public static final String INJECTION_PROVIDER_CLASS_NAME = "com.ibm.ws.jsf.spi.WASInjectionProvider";
// MANAGED_OBJECT_CLASS_NAME added for CDI 1.2 support. Because CDI now creates the class, inject needs
// to return two objects : the instance of the required class and the creational context. To do this
// an Managed object is returned from which both of the required objects can be obtained.
public static final String MANAGED_OBJECT_CLASS_NAME = "com.ibm.ws.managedobject.ManagedObject";
public static final Class<?> FACTORY_FINDER_PROVIDER_FACTORY_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD;
public static final Class<?> FACTORY_FINDER_PROVIDER_CLASS;
public static final Method FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD;
public static final Method FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD;
public static final Class<?> INJECTION_PROVIDER_FACTORY_CLASS;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD;
public static final Method INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD;
public static final Class<?> INJECTION_PROVIDER_CLASS;
public static final Method INJECTION_PROVIDER_INJECT_OBJECT_METHOD;
public static final Method INJECTION_PROVIDER_INJECT_CLASS_METHOD;
public static final Method INJECTION_PROVIDER_POST_CONSTRUCT_METHOD;
public static final Method INJECTION_PROVIDER_PRE_DESTROY_METHOD;
// New for CDI 1.2
public static final Class<?> MANAGED_OBJECT_CLASS;
public static final Method MANAGED_OBJECT_GET_OBJECT_METHOD;
public static final Method MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD;
static
{
Class factoryFinderFactoryClass = null;
Method factoryFinderproviderFactoryGetMethod = null;
Method factoryFinderproviderFactoryGetFactoryFinderMethod = null;
Class<?> factoryFinderProviderClass = null;
Method factoryFinderProviderGetFactoryMethod = null;
Method factoryFinderProviderSetFactoryMethod = null;
Method factoryFinderProviderReleaseFactoriesMethod = null;
Class injectionProviderFactoryClass = null;
Method injectionProviderFactoryGetInstanceMethod = null;
Method injectionProviderFactoryGetInjectionProviderMethod = null;
Class injectionProviderClass = null;
Method injectionProviderInjectObjectMethod = null;
Method injectionProviderInjectClassMethod = null;
Method injectionProviderPostConstructMethod = null;
Method injectionProviderPreDestroyMethod = null;
Class managedObjectClass = null;
Method managedObjectGetObjectMethod = null;
Method managedObjectGetContextDataMethod = null;
try
{
factoryFinderFactoryClass = classForName(FACTORY_FINDER_PROVIDER_FACTORY_CLASS_NAME);
if (factoryFinderFactoryClass != null)
{
factoryFinderproviderFactoryGetMethod = factoryFinderFactoryClass.getMethod
("getInstance", null);
factoryFinderproviderFactoryGetFactoryFinderMethod = factoryFinderFactoryClass
.getMethod("getFactoryFinderProvider", null);
}
factoryFinderProviderClass = classForName(FACTORY_FINDER_PROVIDER_CLASS_NAME);
if (factoryFinderProviderClass != null)
{
factoryFinderProviderGetFactoryMethod = factoryFinderProviderClass.getMethod("getFactory",
new Class[]{String.class});
factoryFinderProviderSetFactoryMethod = factoryFinderProviderClass.getMethod("setFactory",
new Class[]{String.class, String.class});
factoryFinderProviderReleaseFactoriesMethod = factoryFinderProviderClass.getMethod
("releaseFactories", null);
}
injectionProviderFactoryClass = classForName(INJECTION_PROVIDER_FACTORY_CLASS_NAME);
if (injectionProviderFactoryClass != null)
{
injectionProviderFactoryGetInstanceMethod = injectionProviderFactoryClass.
getMethod("getInjectionProviderFactory", null);
injectionProviderFactoryGetInjectionProviderMethod = injectionProviderFactoryClass.
getMethod("getInjectionProvider", ExternalContext.class);
}
injectionProviderClass = classForName(INJECTION_PROVIDER_CLASS_NAME);
if (injectionProviderClass != null)
{
injectionProviderInjectObjectMethod = injectionProviderClass.
getMethod("inject", Object.class);
injectionProviderInjectClassMethod = injectionProviderClass.
getMethod("inject", Class.class);
injectionProviderPostConstructMethod = injectionProviderClass.
getMethod("postConstruct", Object.class, Object.class);
injectionProviderPreDestroyMethod = injectionProviderClass.
getMethod("preDestroy", Object.class, Object.class);
}
// get managed object and getObject and getContextData methods for CDI 1.2 support.
// getObject() is used to the created object instance
// getContextData(Class) is used to get the creational context
managedObjectClass = classForName(MANAGED_OBJECT_CLASS_NAME);
if (managedObjectClass != null)
{
managedObjectGetObjectMethod = managedObjectClass.getMethod("getObject", null);
managedObjectGetContextDataMethod = managedObjectClass.getMethod("getContextData", Class.class);
}
}
catch (Exception e)
{
// no op
}
FACTORY_FINDER_PROVIDER_FACTORY_CLASS = factoryFinderFactoryClass;
FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD = factoryFinderproviderFactoryGetMethod;
FACTORY_FINDER_PROVIDER_FACTORY_GET_FACTORY_FINDER_METHOD = factoryFinderproviderFactoryGetFactoryFinderMethod;
FACTORY_FINDER_PROVIDER_CLASS = factoryFinderProviderClass;
FACTORY_FINDER_PROVIDER_GET_FACTORY_METHOD = factoryFinderProviderGetFactoryMethod;
FACTORY_FINDER_PROVIDER_SET_FACTORY_METHOD = factoryFinderProviderSetFactoryMethod;
FACTORY_FINDER_PROVIDER_RELEASE_FACTORIES_METHOD = factoryFinderProviderReleaseFactoriesMethod;
INJECTION_PROVIDER_FACTORY_CLASS = injectionProviderFactoryClass;
INJECTION_PROVIDER_FACTORY_GET_INSTANCE_METHOD = injectionProviderFactoryGetInstanceMethod;
INJECTION_PROVIDER_FACTORY_GET_INJECTION_PROVIDER_METHOD = injectionProviderFactoryGetInjectionProviderMethod;
INJECTION_PROVIDER_CLASS = injectionProviderClass;
INJECTION_PROVIDER_INJECT_OBJECT_METHOD = injectionProviderInjectObjectMethod;
INJECTION_PROVIDER_INJECT_CLASS_METHOD = injectionProviderInjectClassMethod;
INJECTION_PROVIDER_POST_CONSTRUCT_METHOD = injectionProviderPostConstructMethod;
INJECTION_PROVIDER_PRE_DESTROY_METHOD = injectionProviderPreDestroyMethod;
MANAGED_OBJECT_CLASS = managedObjectClass;
MANAGED_OBJECT_GET_OBJECT_METHOD = managedObjectGetObjectMethod;
MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD = managedObjectGetContextDataMethod;
}
public static Object getInstance()
{
if (FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD != null)
{
try
{
return FACTORY_FINDER_PROVIDER_GET_INSTANCE_METHOD.invoke(FACTORY_FINDER_PROVIDER_FACTORY_CLASS, null);
}
catch (Exception e)
{
//No op
Logger log = Logger.getLogger(_FactoryFinderProviderFactory.class.getName());
if (log.isLoggable(Level.WARNING))
{
log.log(Level.WARNING, "Cannot retrieve current FactoryFinder instance from " +
"FactoryFinderProviderFactory." +
" Default strategy using thread context class loader will be used.", e);
}
}
}
return null;
}
// ~ Methods Copied from _ClassUtils
// ------------------------------------------------------------------------------------
/**
* Tries a Class.loadClass with the context class loader of the current thread first and automatically falls back
* to
* the ClassUtils class loader (i.e. the loader of the myfaces.jar lib) if necessary.
*
* @param type fully qualified name of a non-primitive non-array class
* @return the corresponding Class
* @throws NullPointerException if type is null
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String type) throws ClassNotFoundException
{
if (type == null)
{
throw new NullPointerException("type");
}
try
{
// Try WebApp ClassLoader first
return Class.forName(type, false, // do not initialize for faster startup
getContextClassLoader());
}
catch (ClassNotFoundException ignore)
{
// fallback: Try ClassLoader for ClassUtils (i.e. the myfaces.jar lib)
return Class.forName(type, false, // do not initialize for faster startup
_FactoryFinderProviderFactory.class.getClassLoader());
}
}
/**
* Gets the ClassLoader associated with the current thread. Returns the class loader associated with the specified
* default object if no context loader is associated with the current thread.
*
* @return ClassLoader
*/
protected static ClassLoader getContextClassLoader()
{
if (System.getSecurityManager() != null)
{
try
{
Object cl = AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws PrivilegedActionException
{
return Thread.currentThread().getContextClassLoader();
}
});
return (ClassLoader) cl;
}
catch (PrivilegedActionException pae)
{
throw new FacesException(pae);
}
}
else
{
return Thread.currentThread().getContextClassLoader();
}
}
}
| epl-1.0 |
openhab/openhab2 | bundles/org.openhab.binding.http/src/main/java/org/openhab/binding/http/internal/config/HttpChannelConfig.java | 4709 | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.http.internal.config;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.http.internal.converter.ColorItemConverter;
import org.openhab.core.library.types.IncreaseDecreaseType;
import org.openhab.core.library.types.NextPreviousType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.OpenClosedType;
import org.openhab.core.library.types.PlayPauseType;
import org.openhab.core.library.types.RewindFastforwardType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
/**
* The {@link HttpChannelConfig} class contains fields mapping channel configuration parameters.
*
* @author Jan N. Klug - Initial contribution
*/
@NonNullByDefault
public class HttpChannelConfig {
private final Map<String, State> stringStateMap = new HashMap<>();
private final Map<Command, @Nullable String> commandStringMap = new HashMap<>();
private boolean initialized = false;
public @Nullable String stateExtension;
public @Nullable String commandExtension;
public @Nullable String stateTransformation;
public @Nullable String commandTransformation;
public HttpChannelMode mode = HttpChannelMode.READWRITE;
// switch, dimmer, color
public @Nullable String onValue;
public @Nullable String offValue;
// dimmer, color
public BigDecimal step = BigDecimal.ONE;
public @Nullable String increaseValue;
public @Nullable String decreaseValue;
// color
public ColorItemConverter.ColorMode colorMode = ColorItemConverter.ColorMode.RGB;
// contact
public @Nullable String openValue;
public @Nullable String closedValue;
// rollershutter
public @Nullable String upValue;
public @Nullable String downValue;
public @Nullable String stopValue;
public @Nullable String moveValue;
// player
public @Nullable String playValue;
public @Nullable String pauseValue;
public @Nullable String nextValue;
public @Nullable String previousValue;
public @Nullable String rewindValue;
public @Nullable String fastforwardValue;
/**
* maps a command to a user-defined string
*
* @param command the command to map
* @return a string or null if no mapping found
*/
public @Nullable String commandToFixedValue(Command command) {
if (!initialized) {
createMaps();
}
return commandStringMap.get(command);
}
/**
* maps a user-defined string to a state
*
* @param string the string to map
* @return the state or null if no mapping found
*/
public @Nullable State fixedValueToState(String string) {
if (!initialized) {
createMaps();
}
return stringStateMap.get(string);
}
private void createMaps() {
addToMaps(this.onValue, OnOffType.ON);
addToMaps(this.offValue, OnOffType.OFF);
addToMaps(this.openValue, OpenClosedType.OPEN);
addToMaps(this.closedValue, OpenClosedType.CLOSED);
addToMaps(this.upValue, UpDownType.UP);
addToMaps(this.downValue, UpDownType.DOWN);
commandStringMap.put(IncreaseDecreaseType.INCREASE, increaseValue);
commandStringMap.put(IncreaseDecreaseType.DECREASE, decreaseValue);
commandStringMap.put(StopMoveType.STOP, stopValue);
commandStringMap.put(StopMoveType.MOVE, moveValue);
commandStringMap.put(PlayPauseType.PLAY, playValue);
commandStringMap.put(PlayPauseType.PAUSE, pauseValue);
commandStringMap.put(NextPreviousType.NEXT, nextValue);
commandStringMap.put(NextPreviousType.PREVIOUS, previousValue);
commandStringMap.put(RewindFastforwardType.REWIND, rewindValue);
commandStringMap.put(RewindFastforwardType.FASTFORWARD, fastforwardValue);
initialized = true;
}
private void addToMaps(@Nullable String value, State state) {
if (value != null) {
commandStringMap.put((Command) state, value);
stringStateMap.put(value, state);
}
}
}
| epl-1.0 |
Treehopper/c0ffee_tips | eu.hohenegger.c0ffee_tips.tests/src/eu/hohenegger/c0ffee_tips/tests/AllTests.java | 791 | /*******************************************************************************
* Copyright (c) 2012 Max Hohenegger.
* All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Max Hohenegger - initial implementation
******************************************************************************/
package eu.hohenegger.c0ffee_tips.tests;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import eu.hohenegger.c0ffee_tips.TestBasic;
@RunWith(Suite.class)
@SuiteClasses({TestBasic.class})
public class AllTests {
}
| epl-1.0 |
ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/hql/ast/util/JoinProcessor.java | 9793 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.hql.ast.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Collection;
import org.hibernate.AssertionFailure;
import org.hibernate.dialect.Dialect;
import org.hibernate.impl.FilterImpl;
import org.hibernate.type.Type;
import org.hibernate.param.DynamicFilterParameterSpecification;
import org.hibernate.param.CollectionFilterKeyParameterSpecification;
import org.hibernate.engine.JoinSequence;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.LoadQueryInfluencers;
import org.hibernate.hql.antlr.SqlTokenTypes;
import org.hibernate.hql.ast.HqlSqlWalker;
import org.hibernate.hql.ast.tree.FromClause;
import org.hibernate.hql.ast.tree.FromElement;
import org.hibernate.hql.ast.tree.QueryNode;
import org.hibernate.hql.ast.tree.DotNode;
import org.hibernate.hql.ast.tree.ParameterContainer;
import org.hibernate.hql.classic.ParserHelper;
import org.hibernate.sql.JoinFragment;
import org.hibernate.util.StringHelper;
import org.hibernate.util.ArrayHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Performs the post-processing of the join information gathered during semantic analysis.
* The join generating classes are complex, this encapsulates some of the JoinSequence-related
* code.
*
* @author Joshua Davis
*/
public class JoinProcessor implements SqlTokenTypes {
private static final Logger log = LoggerFactory.getLogger( JoinProcessor.class );
private final HqlSqlWalker walker;
private final SyntheticAndFactory syntheticAndFactory;
/**
* Constructs a new JoinProcessor.
*
* @param walker The walker to which we are bound, giving us access to needed resources.
*/
public JoinProcessor(HqlSqlWalker walker) {
this.walker = walker;
this.syntheticAndFactory = new SyntheticAndFactory( walker );
}
/**
* Translates an AST join type (i.e., the token type) into a JoinFragment.XXX join type.
*
* @param astJoinType The AST join type (from HqlSqlTokenTypes or SqlTokenTypes)
* @return a JoinFragment.XXX join type.
* @see JoinFragment
* @see SqlTokenTypes
*/
public static int toHibernateJoinType(int astJoinType) {
switch ( astJoinType ) {
case LEFT_OUTER:
return JoinFragment.LEFT_OUTER_JOIN;
case INNER:
return JoinFragment.INNER_JOIN;
case RIGHT_OUTER:
return JoinFragment.RIGHT_OUTER_JOIN;
default:
throw new AssertionFailure( "undefined join type " + astJoinType );
}
}
public void processJoins(QueryNode query) {
final FromClause fromClause = query.getFromClause();
final List fromElements;
if ( DotNode.useThetaStyleImplicitJoins ) {
// for regression testing against output from the old parser...
// found it easiest to simply reorder the FromElements here into ascending order
// in terms of injecting them into the resulting sql ast in orders relative to those
// expected by the old parser; this is definitely another of those "only needed
// for regression purposes". The SyntheticAndFactory, then, simply injects them as it
// encounters them.
fromElements = new ArrayList();
ListIterator liter = fromClause.getFromElements().listIterator( fromClause.getFromElements().size() );
while ( liter.hasPrevious() ) {
fromElements.add( liter.previous() );
}
}
else {
fromElements = fromClause.getFromElements();
}
// Iterate through the alias,JoinSequence pairs and generate SQL token nodes.
Iterator iter = fromElements.iterator();
while ( iter.hasNext() ) {
final FromElement fromElement = ( FromElement ) iter.next();
JoinSequence join = fromElement.getJoinSequence();
join.setSelector(
new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) {
// The uber-rule here is that we need to include subclass joins if
// the FromElement is in any way dereferenced by a property from
// the subclass table; otherwise we end up with column references
// qualified by a non-existent table reference in the resulting SQL...
boolean containsTableAlias = fromClause.containsTableAlias( alias );
if ( fromElement.isDereferencedBySubclassProperty() ) {
// TODO : or should we return 'containsTableAlias'??
log.trace( "forcing inclusion of extra joins [alias=" + alias + ", containsTableAlias=" + containsTableAlias + "]" );
return true;
}
boolean shallowQuery = walker.isShallowQuery();
boolean includeSubclasses = fromElement.isIncludeSubclasses();
boolean subQuery = fromClause.isSubQuery();
return includeSubclasses && containsTableAlias && !subQuery && !shallowQuery;
}
}
);
addJoinNodes( query, join, fromElement );
}
}
private void addJoinNodes(QueryNode query, JoinSequence join, FromElement fromElement) {
JoinFragment joinFragment = join.toJoinFragment(
walker.getEnabledFilters(),
fromElement.useFromFragment() || fromElement.isDereferencedBySuperclassOrSubclassProperty(),
fromElement.getWithClauseFragment(),
fromElement.getWithClauseJoinAlias()
);
String frag = joinFragment.toFromFragmentString();
String whereFrag = joinFragment.toWhereFragmentString();
// If the from element represents a JOIN_FRAGMENT and it is
// a theta-style join, convert its type from JOIN_FRAGMENT
// to FROM_FRAGMENT
if ( fromElement.getType() == JOIN_FRAGMENT &&
( join.isThetaStyle() || StringHelper.isNotEmpty( whereFrag ) ) ) {
fromElement.setType( FROM_FRAGMENT );
fromElement.getJoinSequence().setUseThetaStyle( true ); // this is used during SqlGenerator processing
}
// If there is a FROM fragment and the FROM element is an explicit, then add the from part.
if ( fromElement.useFromFragment() /*&& StringHelper.isNotEmpty( frag )*/ ) {
String fromFragment = processFromFragment( frag, join ).trim();
if ( log.isDebugEnabled() ) {
log.debug( "Using FROM fragment [" + fromFragment + "]" );
}
processDynamicFilterParameters(
fromFragment,
fromElement,
walker
);
}
syntheticAndFactory.addWhereFragment(
joinFragment,
whereFrag,
query,
fromElement,
walker
);
}
private String processFromFragment(String frag, JoinSequence join) {
String fromFragment = frag.trim();
// The FROM fragment will probably begin with ', '. Remove this if it is present.
if ( fromFragment.startsWith( ", " ) ) {
fromFragment = fromFragment.substring( 2 );
}
return fromFragment;
}
public static void processDynamicFilterParameters(
final String sqlFragment,
final ParameterContainer container,
final HqlSqlWalker walker) {
if ( walker.getEnabledFilters().isEmpty()
&& ( ! hasDynamicFilterParam( sqlFragment ) )
&& ( ! ( hasCollectionFilterParam( sqlFragment ) ) ) ) {
return;
}
Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
String symbols = new StringBuffer().append( ParserHelper.HQL_SEPARATORS )
.append( dialect.openQuote() )
.append( dialect.closeQuote() )
.toString();
StringTokenizer tokens = new StringTokenizer( sqlFragment, symbols, true );
StringBuffer result = new StringBuffer();
while ( tokens.hasMoreTokens() ) {
final String token = tokens.nextToken();
if ( token.startsWith( ParserHelper.HQL_VARIABLE_PREFIX ) ) {
final String filterParameterName = token.substring( 1 );
final String[] parts = LoadQueryInfluencers.parseFilterParameterName( filterParameterName );
final FilterImpl filter = ( FilterImpl ) walker.getEnabledFilters().get( parts[0] );
final Object value = filter.getParameter( parts[1] );
final Type type = filter.getFilterDefinition().getParameterType( parts[1] );
final String typeBindFragment = StringHelper.join(
",",
ArrayHelper.fillArray( "?", type.getColumnSpan( walker.getSessionFactoryHelper().getFactory() ) )
);
final String bindFragment = ( value != null && Collection.class.isInstance( value ) )
? StringHelper.join( ",", ArrayHelper.fillArray( typeBindFragment, ( ( Collection ) value ).size() ) )
: typeBindFragment;
result.append( bindFragment );
container.addEmbeddedParameter( new DynamicFilterParameterSpecification( parts[0], parts[1], type ) );
}
else {
result.append( token );
}
}
container.setText( result.toString() );
}
private static boolean hasDynamicFilterParam(String sqlFragment) {
return sqlFragment.indexOf( ParserHelper.HQL_VARIABLE_PREFIX ) < 0;
}
private static boolean hasCollectionFilterParam(String sqlFragment) {
return sqlFragment.indexOf( "?" ) < 0;
}
}
| epl-1.0 |
sytone/openhab | bundles/binding/org.openhab.binding.tinkerforge/src/main/java/org/openhab/binding/tinkerforge/internal/model/impl/MIndustrialQuadRelayImpl.java | 28553 | /**
* Copyright (c) 2010-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.tinkerforge.internal.model.impl;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.openhab.binding.tinkerforge.internal.LoggerConstants;
import org.openhab.binding.tinkerforge.internal.TinkerforgeErrorHandler;
import org.openhab.binding.tinkerforge.internal.model.MBaseDevice;
import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelay;
import org.openhab.binding.tinkerforge.internal.model.MIndustrialQuadRelayBricklet;
import org.openhab.binding.tinkerforge.internal.model.MSubDevice;
import org.openhab.binding.tinkerforge.internal.model.MSubDeviceHolder;
import org.openhab.binding.tinkerforge.internal.model.ModelPackage;
import org.openhab.binding.tinkerforge.internal.types.OnOffValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.tinkerforge.NotConnectedException;
import com.tinkerforge.TimeoutException;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>MIndustrial Quad Relay</b></em>'.
*
* @author Theo Weiss
* @since 1.4.0
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSwitchState
* <em>Switch State</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getLogger
* <em>Logger</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getUid <em>Uid</em>}
* </li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#isPoll <em>Poll</em>}
* </li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getEnabledA
* <em>Enabled A</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getSubId
* <em>Sub Id</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getMbrick
* <em>Mbrick</em>}</li>
* <li>{@link org.openhab.binding.tinkerforge.internal.model.impl.MIndustrialQuadRelayImpl#getDeviceType
* <em>Device Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class MIndustrialQuadRelayImpl extends MinimalEObjectImpl.Container implements MIndustrialQuadRelay {
/**
* The default value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSwitchState()
* @generated
* @ordered
*/
protected static final OnOffValue SWITCH_STATE_EDEFAULT = null;
/**
* The cached value of the '{@link #getSwitchState() <em>Switch State</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSwitchState()
* @generated
* @ordered
*/
protected OnOffValue switchState = SWITCH_STATE_EDEFAULT;
/**
* The default value of the '{@link #getLogger() <em>Logger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getLogger()
* @generated
* @ordered
*/
protected static final Logger LOGGER_EDEFAULT = null;
/**
* The cached value of the '{@link #getLogger() <em>Logger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getLogger()
* @generated
* @ordered
*/
protected Logger logger = LOGGER_EDEFAULT;
/**
* The default value of the '{@link #getUid() <em>Uid</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getUid()
* @generated
* @ordered
*/
protected static final String UID_EDEFAULT = null;
/**
* The cached value of the '{@link #getUid() <em>Uid</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getUid()
* @generated
* @ordered
*/
protected String uid = UID_EDEFAULT;
/**
* The default value of the '{@link #isPoll() <em>Poll</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPoll()
* @generated
* @ordered
*/
protected static final boolean POLL_EDEFAULT = true;
/**
* The cached value of the '{@link #isPoll() <em>Poll</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #isPoll()
* @generated
* @ordered
*/
protected boolean poll = POLL_EDEFAULT;
/**
* The default value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getEnabledA()
* @generated
* @ordered
*/
protected static final AtomicBoolean ENABLED_A_EDEFAULT = null;
/**
* The cached value of the '{@link #getEnabledA() <em>Enabled A</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getEnabledA()
* @generated
* @ordered
*/
protected AtomicBoolean enabledA = ENABLED_A_EDEFAULT;
/**
* The default value of the '{@link #getSubId() <em>Sub Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSubId()
* @generated
* @ordered
*/
protected static final String SUB_ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getSubId() <em>Sub Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getSubId()
* @generated
* @ordered
*/
protected String subId = SUB_ID_EDEFAULT;
/**
* The default value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getDeviceType()
* @generated
* @ordered
*/
protected static final String DEVICE_TYPE_EDEFAULT = "quad_relay";
/**
* The cached value of the '{@link #getDeviceType() <em>Device Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @see #getDeviceType()
* @generated
* @ordered
*/
protected String deviceType = DEVICE_TYPE_EDEFAULT;
private short relayNum;
private int mask;
private static final byte DEFAULT_SELECTION_MASK = 0000000000000001;
private static final byte OFF_BYTE = 0000000000000000;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
protected MIndustrialQuadRelayImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return ModelPackage.Literals.MINDUSTRIAL_QUAD_RELAY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public OnOffValue getSwitchState() {
return switchState;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setSwitchState(OnOffValue newSwitchState) {
OnOffValue oldSwitchState = switchState;
switchState = newSwitchState;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE,
oldSwitchState, switchState));
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void turnSwitch(OnOffValue state) {
logger.debug("turnSwitchState called on: {}", MIndustrialQuadRelayBrickletImpl.class);
try {
if (state == OnOffValue.OFF) {
logger.debug("setSwitchValue off");
getMbrick().getTinkerforgeDevice().setSelectedValues(mask, OFF_BYTE);
} else if (state == OnOffValue.ON) {
logger.debug("setSwitchState on");
getMbrick().getTinkerforgeDevice().setSelectedValues(mask, mask);
} else {
logger.error("{} unkown switchstate {}", LoggerConstants.TFMODELUPDATE, state);
}
setSwitchState(state);
} catch (TimeoutException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e);
} catch (NotConnectedException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e);
}
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void fetchSwitchState() {
OnOffValue value = OnOffValue.UNDEF;
try {
int deviceValue = getMbrick().getTinkerforgeDevice().getValue();
if ((deviceValue & mask) == mask) {
value = OnOffValue.ON;
} else {
value = OnOffValue.OFF;
}
setSwitchState(value);
} catch (TimeoutException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_TIMEOUT_EXCEPTION, e);
} catch (NotConnectedException e) {
TinkerforgeErrorHandler.handleError(this, TinkerforgeErrorHandler.TF_NOT_CONNECTION_EXCEPTION, e);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Logger getLogger() {
return logger;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setLogger(Logger newLogger) {
Logger oldLogger = logger;
logger = newLogger;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER,
oldLogger, logger));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getUid() {
return uid;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setUid(String newUid) {
String oldUid = uid;
uid = newUid;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID, oldUid,
uid));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean isPoll() {
return poll;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setPoll(boolean newPoll) {
boolean oldPoll = poll;
poll = newPoll;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL, oldPoll,
poll));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public AtomicBoolean getEnabledA() {
return enabledA;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setEnabledA(AtomicBoolean newEnabledA) {
AtomicBoolean oldEnabledA = enabledA;
enabledA = newEnabledA;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A,
oldEnabledA, enabledA));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getSubId() {
return subId;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setSubId(String newSubId) {
String oldSubId = subId;
subId = newSubId;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID, oldSubId,
subId));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public MIndustrialQuadRelayBricklet getMbrick() {
if (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK) {
return null;
}
return (MIndustrialQuadRelayBricklet) eContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public NotificationChain basicSetMbrick(MIndustrialQuadRelayBricklet newMbrick, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject) newMbrick, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void setMbrick(MIndustrialQuadRelayBricklet newMbrick) {
if (newMbrick != eInternalContainer()
|| (eContainerFeatureID() != ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK && newMbrick != null)) {
if (EcoreUtil.isAncestor(this, newMbrick)) {
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
}
NotificationChain msgs = null;
if (eInternalContainer() != null) {
msgs = eBasicRemoveFromContainer(msgs);
}
if (newMbrick != null) {
msgs = ((InternalEObject) newMbrick).eInverseAdd(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES,
MSubDeviceHolder.class, msgs);
}
msgs = basicSetMbrick(newMbrick, msgs);
if (msgs != null) {
msgs.dispatch();
}
} else if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK,
newMbrick, newMbrick));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String getDeviceType() {
return deviceType;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void init() {
setEnabledA(new AtomicBoolean());
poll = true; // don't use the setter to prevent notification
logger = LoggerFactory.getLogger(MIndustrialQuadRelay.class);
relayNum = Short.parseShort(String.valueOf(subId.charAt(subId.length() - 1)));
mask = DEFAULT_SELECTION_MASK << relayNum;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void enable() {
logger.debug("enable called on MIndustrialQuadRelayImpl");
fetchSwitchState();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated NOT
*/
@Override
public void disable() {
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
if (eInternalContainer() != null) {
msgs = eBasicRemoveFromContainer(msgs);
}
return basicSetMbrick((MIndustrialQuadRelayBricklet) otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return basicSetMbrick(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return eInternalContainer().eInverseRemove(this, ModelPackage.MSUB_DEVICE_HOLDER__MSUBDEVICES,
MSubDeviceHolder.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
return getSwitchState();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return getLogger();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return getUid();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return isPoll();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return getEnabledA();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return getSubId();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return getMbrick();
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE:
return getDeviceType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
setSwitchState((OnOffValue) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
setLogger((Logger) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
setUid((String) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
setPoll((Boolean) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
setEnabledA((AtomicBoolean) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
setSubId((String) newValue);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
setMbrick((MIndustrialQuadRelayBricklet) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
setSwitchState(SWITCH_STATE_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
setLogger(LOGGER_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
setUid(UID_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
setPoll(POLL_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
setEnabledA(ENABLED_A_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
setSubId(SUB_ID_EDEFAULT);
return;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
setMbrick((MIndustrialQuadRelayBricklet) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SWITCH_STATE:
return SWITCH_STATE_EDEFAULT == null ? switchState != null : !SWITCH_STATE_EDEFAULT.equals(switchState);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return LOGGER_EDEFAULT == null ? logger != null : !LOGGER_EDEFAULT.equals(logger);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return UID_EDEFAULT == null ? uid != null : !UID_EDEFAULT.equals(uid);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return poll != POLL_EDEFAULT;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return ENABLED_A_EDEFAULT == null ? enabledA != null : !ENABLED_A_EDEFAULT.equals(enabledA);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return SUB_ID_EDEFAULT == null ? subId != null : !SUB_ID_EDEFAULT.equals(subId);
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return getMbrick() != null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__DEVICE_TYPE:
return DEVICE_TYPE_EDEFAULT == null ? deviceType != null : !DEVICE_TYPE_EDEFAULT.equals(deviceType);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (derivedFeatureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER:
return ModelPackage.MBASE_DEVICE__LOGGER;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID:
return ModelPackage.MBASE_DEVICE__UID;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL:
return ModelPackage.MBASE_DEVICE__POLL;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A:
return ModelPackage.MBASE_DEVICE__ENABLED_A;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (derivedFeatureID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID:
return ModelPackage.MSUB_DEVICE__SUB_ID;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK:
return ModelPackage.MSUB_DEVICE__MBRICK;
default:
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (baseFeatureID) {
case ModelPackage.MBASE_DEVICE__LOGGER:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__LOGGER;
case ModelPackage.MBASE_DEVICE__UID:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__UID;
case ModelPackage.MBASE_DEVICE__POLL:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__POLL;
case ModelPackage.MBASE_DEVICE__ENABLED_A:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__ENABLED_A;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (baseFeatureID) {
case ModelPackage.MSUB_DEVICE__SUB_ID:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__SUB_ID;
case ModelPackage.MSUB_DEVICE__MBRICK:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY__MBRICK;
default:
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public int eDerivedOperationID(int baseOperationID, Class<?> baseClass) {
if (baseClass == MBaseDevice.class) {
switch (baseOperationID) {
case ModelPackage.MBASE_DEVICE___INIT:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT;
case ModelPackage.MBASE_DEVICE___ENABLE:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE;
case ModelPackage.MBASE_DEVICE___DISABLE:
return ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE;
default:
return -1;
}
}
if (baseClass == MSubDevice.class) {
switch (baseOperationID) {
default:
return -1;
}
}
return super.eDerivedOperationID(baseOperationID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___INIT:
init();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___ENABLE:
enable();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___DISABLE:
disable();
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___TURN_SWITCH__ONOFFVALUE:
turnSwitch((OnOffValue) arguments.get(0));
return null;
case ModelPackage.MINDUSTRIAL_QUAD_RELAY___FETCH_SWITCH_STATE:
fetchSwitchState();
return null;
}
return super.eInvoke(operationID, arguments);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (switchState: ");
result.append(switchState);
result.append(", logger: ");
result.append(logger);
result.append(", uid: ");
result.append(uid);
result.append(", poll: ");
result.append(poll);
result.append(", enabledA: ");
result.append(enabledA);
result.append(", subId: ");
result.append(subId);
result.append(", deviceType: ");
result.append(deviceType);
result.append(')');
return result.toString();
}
} // MIndustrialQuadRelayImpl
| epl-1.0 |
ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/envers/src/main/java/org/hibernate/envers/tools/MappingTools.java | 1365 | package org.hibernate.envers.tools;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.Value;
/**
* @author Adam Warski (adam at warski dot org)
*/
public class MappingTools {
/**
* @param componentName Name of the component, that is, name of the property in the entity that references the
* component.
* @return A prefix for properties in the given component.
*/
public static String createComponentPrefix(String componentName) {
return componentName + "_";
}
/**
* @param referencePropertyName The name of the property that holds the relation to the entity.
* @return A prefix which should be used to prefix an id mapper for the related entity.
*/
public static String createToOneRelationPrefix(String referencePropertyName) {
return referencePropertyName + "_";
}
public static String getReferencedEntityName(Value value) {
if (value instanceof ToOne) {
return ((ToOne) value).getReferencedEntityName();
} else if (value instanceof OneToMany) {
return ((OneToMany) value).getReferencedEntityName();
} else if (value instanceof Collection) {
return getReferencedEntityName(((Collection) value).getElement());
}
return null;
}
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.security.oauth/src/com/ibm/ws/security/oauth20/web/OAuth20EndpointServices.java | 60040 | /*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.oauth20.web;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Principal;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import javax.security.auth.Subject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import com.ibm.ejs.ras.TraceNLS;
import com.ibm.oauth.core.api.OAuthResult;
import com.ibm.oauth.core.api.attributes.AttributeList;
import com.ibm.oauth.core.api.error.OidcServerException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20AccessDeniedException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20DuplicateParameterException;
import com.ibm.oauth.core.api.error.oauth20.OAuth20Exception;
import com.ibm.oauth.core.api.oauth20.token.OAuth20Token;
import com.ibm.oauth.core.internal.oauth20.OAuth20Constants;
import com.ibm.oauth.core.internal.oauth20.OAuth20Util;
import com.ibm.oauth.core.internal.oauth20.OAuthResultImpl;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.security.WSSecurityException;
import com.ibm.websphere.security.auth.WSSubject;
import com.ibm.ws.ffdc.FFDCFilter;
import com.ibm.ws.ffdc.annotation.FFDCIgnore;
import com.ibm.ws.security.SecurityService;
import com.ibm.ws.security.common.claims.UserClaims;
import com.ibm.ws.security.oauth20.ProvidersService;
import com.ibm.ws.security.oauth20.api.Constants;
import com.ibm.ws.security.oauth20.api.OAuth20EnhancedTokenCache;
import com.ibm.ws.security.oauth20.api.OAuth20Provider;
import com.ibm.ws.security.oauth20.error.impl.OAuth20TokenRequestExceptionHandler;
import com.ibm.ws.security.oauth20.exception.OAuth20BadParameterException;
import com.ibm.ws.security.oauth20.plugins.OAuth20TokenImpl;
import com.ibm.ws.security.oauth20.plugins.OidcBaseClient;
import com.ibm.ws.security.oauth20.util.ConfigUtils;
import com.ibm.ws.security.oauth20.util.Nonce;
import com.ibm.ws.security.oauth20.util.OAuth20ProviderUtils;
import com.ibm.ws.security.oauth20.util.OIDCConstants;
import com.ibm.ws.security.oauth20.util.OidcOAuth20Util;
import com.ibm.ws.security.oauth20.web.OAuth20Request.EndpointType;
import com.ibm.ws.webcontainer.security.CookieHelper;
import com.ibm.ws.webcontainer.security.ReferrerURLCookieHandler;
import com.ibm.ws.webcontainer.security.WebAppSecurityCollaboratorImpl;
import com.ibm.wsspi.kernel.service.utils.AtomicServiceReference;
import com.ibm.wsspi.kernel.service.utils.ConcurrentServiceReferenceMap;
import com.ibm.wsspi.security.oauth20.JwtAccessTokenMediator;
import com.ibm.wsspi.security.oauth20.TokenIntrospectProvider;
@Component(service = OAuth20EndpointServices.class, name = "com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", immediate = true, configurationPolicy = ConfigurationPolicy.IGNORE, property = "service.vendor=IBM")
public class OAuth20EndpointServices {
private static TraceComponent tc = Tr.register(OAuth20EndpointServices.class);
private static TraceComponent tc2 = Tr.register(OAuth20EndpointServices.class, // use this one when bundle is the usual bundle.
TraceConstants.TRACE_GROUP,
TraceConstants.MESSAGE_BUNDLE);
protected static final String MESSAGE_BUNDLE = "com.ibm.ws.security.oauth20.internal.resources.OAuthMessages";
protected static final String MSG_RESOURCE_BUNDLE = "com.ibm.ws.security.oauth20.resources.ProviderMsgs";
public static final String KEY_SERVICE_PID = "service.pid";
public static final String KEY_SECURITY_SERVICE = "securityService";
protected final AtomicServiceReference<SecurityService> securityServiceRef = new AtomicServiceReference<SecurityService>(KEY_SECURITY_SERVICE);
public static final String KEY_TOKEN_INTROSPECT_PROVIDER = "tokenIntrospectProvider";
private final ConcurrentServiceReferenceMap<String, TokenIntrospectProvider> tokenIntrospectProviderRef = new ConcurrentServiceReferenceMap<String, TokenIntrospectProvider>(KEY_TOKEN_INTROSPECT_PROVIDER);
public static final String KEY_JWT_MEDIATOR = "jwtAccessTokenMediator";
private final ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator> jwtAccessTokenMediatorRef = new ConcurrentServiceReferenceMap<String, JwtAccessTokenMediator>(KEY_JWT_MEDIATOR);
public static final String KEY_OAUTH_CLIENT_METATYPE_SERVICE = "oauth20ClientMetatypeService";
private static final AtomicServiceReference<OAuth20ClientMetatypeService> oauth20ClientMetatypeServiceRef = new AtomicServiceReference<OAuth20ClientMetatypeService>(KEY_OAUTH_CLIENT_METATYPE_SERVICE);
private static final String ATTR_NONCE = "consentNonce";
public static final String AUTHENTICATED = "authenticated";
protected volatile ClientAuthentication clientAuthentication = new ClientAuthentication();
protected volatile ClientAuthorization clientAuthorization = new ClientAuthorization();
protected volatile UserAuthentication userAuthentication = new UserAuthentication();
protected volatile CoverageMapEndpointServices coverageMapServices = new CoverageMapEndpointServices();
protected volatile RegistrationEndpointServices registrationEndpointServices = new RegistrationEndpointServices();
protected volatile Consent consent = new Consent();
protected volatile TokenExchange tokenExchange = new TokenExchange();
@Reference(service = SecurityService.class, name = KEY_SECURITY_SERVICE, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
protected void setSecurityService(ServiceReference<SecurityService> reference) {
securityServiceRef.setReference(reference);
}
protected void unsetSecurityService(ServiceReference<SecurityService> reference) {
securityServiceRef.unsetReference(reference);
}
@Reference(service = TokenIntrospectProvider.class, name = KEY_TOKEN_INTROSPECT_PROVIDER, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY)
protected void setTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) {
synchronized (tokenIntrospectProviderRef) {
tokenIntrospectProviderRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
protected void unsetTokenIntrospectProvider(ServiceReference<TokenIntrospectProvider> ref) {
synchronized (tokenIntrospectProviderRef) {
tokenIntrospectProviderRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
@Reference(service = JwtAccessTokenMediator.class, name = KEY_JWT_MEDIATOR, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL, policyOption = ReferencePolicyOption.GREEDY)
protected void setJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) {
synchronized (jwtAccessTokenMediatorRef) {
jwtAccessTokenMediatorRef.putReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
protected void unsetJwtAccessTokenMediator(ServiceReference<JwtAccessTokenMediator> ref) {
synchronized (jwtAccessTokenMediatorRef) {
jwtAccessTokenMediatorRef.removeReference((String) ref.getProperty(KEY_SERVICE_PID), ref);
}
}
@Reference(service = OAuth20ClientMetatypeService.class, name = KEY_OAUTH_CLIENT_METATYPE_SERVICE, policy = ReferencePolicy.DYNAMIC)
protected void setOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) {
oauth20ClientMetatypeServiceRef.setReference(ref);
}
protected void unsetOAuth20ClientMetatypeService(ServiceReference<OAuth20ClientMetatypeService> ref) {
oauth20ClientMetatypeServiceRef.unsetReference(ref);
}
@Activate
protected void activate(ComponentContext cc) {
securityServiceRef.activate(cc);
tokenIntrospectProviderRef.activate(cc);
jwtAccessTokenMediatorRef.activate(cc);
oauth20ClientMetatypeServiceRef.activate(cc);
ConfigUtils.setJwtAccessTokenMediatorService(jwtAccessTokenMediatorRef);
TokenIntrospect.setTokenIntrospect(tokenIntrospectProviderRef);
// The TraceComponent object was not initialized with the message bundle containing this message, so we cannot use
// Tr.info(tc, "OAUTH_ENDPOINT_SERVICE_ACTIVATED"). Eventually these messages will be merged into one file, making this infoMsg variable unnecessary
String infoMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_ENDPOINT_SERVICE_ACTIVATED",
null,
"CWWKS1410I: The OAuth endpoint service is activated.");
Tr.info(tc, infoMsg);
}
@Deactivate
protected void deactivate(ComponentContext cc) {
securityServiceRef.deactivate(cc);
tokenIntrospectProviderRef.deactivate(cc);
jwtAccessTokenMediatorRef.deactivate(cc);
oauth20ClientMetatypeServiceRef.deactivate(cc);
}
protected void handleOAuthRequest(HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext) throws ServletException, IOException {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Checking if OAuth20 Provider should process the request.");
Tr.debug(tc, "Inbound request " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret"));
}
OAuth20Request oauth20Request = getAuth20Request(request, response);
OAuth20Provider oauth20Provider = null;
if (oauth20Request != null) {
EndpointType endpointType = oauth20Request.getType();
oauth20Provider = getProvider(response, oauth20Request);
if (oauth20Provider != null) {
AttributeList optionalParams = new AttributeList();
if (tc.isDebugEnabled()) {
Tr.debug(tc, "OAUTH20 _SSO OP PROCESS IS STARTING.");
Tr.debug(tc, "OAUTH20 _SSO OP inbound URL " + com.ibm.ws.security.common.web.WebUtils.getRequestStringForTrace(request, "client_secret"));
}
handleEndpointRequest(request, response, servletContext, oauth20Provider, endpointType, optionalParams);
}
}
if (tc.isDebugEnabled()) {
if (oauth20Provider != null) {
Tr.debug(tc, "OAUTH20 _SSO OP PROCESS HAS ENDED.");
} else {
Tr.debug(tc, "OAUTH20 _SSO OP WILL NOT PROCESS THE REQUEST");
}
}
}
@FFDCIgnore({ OidcServerException.class })
protected void handleEndpointRequest(HttpServletRequest request,
HttpServletResponse response,
ServletContext servletContext,
OAuth20Provider oauth20Provider,
EndpointType endpointType,
AttributeList oidcOptionalParams) throws ServletException, IOException {
checkHttpsRequirement(request, response, oauth20Provider);
if (response.isCommitted()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Response has already been committed, so likely did not pass HTTPS requirement");
}
return;
}
boolean isBrowserWithBasicAuth = false;
UIAccessTokenBuilder uitb = null;
if (tc.isDebugEnabled()) {
Tr.debug(tc, "endpointType[" + endpointType + "]");
}
try {
switch (endpointType) {
case authorize:
OAuthResult result = processAuthorizationRequest(oauth20Provider, request, response, servletContext, oidcOptionalParams);
if (result != null) {
if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate
break;
} else if (result.getStatus() != OAuthResult.STATUS_OK) {
userAuthentication.renderErrorPage(oauth20Provider, request, response, result);
}
}
break;
case token:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
processTokenRequest(oauth20Provider, request, response);
}
break;
case introspect:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
introspect(oauth20Provider, request, response);
}
break;
case revoke:
if (clientAuthentication.verify(oauth20Provider, request, response, endpointType)) {
revoke(oauth20Provider, request, response);
}
break;
case coverage_map: // non-spec extension
coverageMapServices.handleEndpointRequest(oauth20Provider, request, response);
break;
case registration:
secureEndpointServices(oauth20Provider, request, response, servletContext, RegistrationEndpointServices.ROLE_REQUIRED, true);
registrationEndpointServices.handleEndpointRequest(oauth20Provider, request, response);
break;
case logout:
// no need to authenticate
logout(oauth20Provider, request, response);
break;
case app_password:
tokenExchange.processAppPassword(oauth20Provider, request, response);
break;
case app_token:
tokenExchange.processAppToken(oauth20Provider, request, response);
break;
// these next 3 are for UI pages
case clientManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, RegistrationEndpointServices.ROLE_REQUIRED)) {
break;
}
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd = servletContext.getRequestDispatcher("WEB-CONTENT/clientAdmin/index.jsp");
rd.forward(request, response);
break;
case personalTokenManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, null)) {
break;
}
checkUIConfig(oauth20Provider, request);
// put auth header and access token and feature enablement state into request attributes for ui to use
uitb = new UIAccessTokenBuilder(oauth20Provider, request);
uitb.createHeaderValuesForUI();
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd2 = servletContext.getRequestDispatcher("WEB-CONTENT/accountManager/index.jsp");
rd2.forward(request, response);
break;
case usersTokenManagement:
if (!authenticateUI(request, response, servletContext, oauth20Provider, oidcOptionalParams, OAuth20Constants.TOKEN_MANAGER_ROLE)) {
break;
}
checkUIConfig(oauth20Provider, request);
// put auth header and access token and feature enablement state into request attributes for ui to use
uitb = new UIAccessTokenBuilder(oauth20Provider, request);
uitb.createHeaderValuesForUI();
// new MockUiPage(request, response).render(); // TODO: replace with hook to real ui.
RequestDispatcher rd3 = servletContext.getRequestDispatcher("WEB-CONTENT/tokenManager/index.jsp");
rd3.forward(request, response);
break;
case clientMetatype:
serveClientMetatypeRequest(request, response);
break;
default:
break;
}
} catch (OidcServerException e) {
if (!isBrowserWithBasicAuth) {
// we don't want routine browser auth challenges producing ffdc's.
// (but if a login is invalid in that case, we will still get a CWIML4537E from base sec.)
// however for non-browsers we want ffdc's like we had before, so generate manually
if (!e.getErrorDescription().contains("CWWKS1424E")) { // no ffdc for nonexistent clients
com.ibm.ws.ffdc.FFDCFilter.processException(e,
"com.ibm.ws.security.oauth20.web.OAuth20EndpointServices", "324", this);
}
}
boolean suppressBasicAuthChallenge = isBrowserWithBasicAuth; // ui must NOT log in using basic auth, so logout function will work.
WebUtils.sendErrorJSON(response, e.getHttpStatus(), e.getErrorCode(), e.getErrorDescription(request.getLocales()), suppressBasicAuthChallenge);
}
}
// return true if clear to go, false otherwise. Log message and/or throw exception if unsuccessful
private boolean authenticateUI(HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider, AttributeList options, String requiredRole)
throws ServletException, IOException, OidcServerException {
OAuthResult result = handleUIUserAuthentication(request, response, servletContext, provider, options);
if (!isUIAuthenticationComplete(request, response, provider, result, requiredRole)) {
return false;
}
return true;
}
private boolean isUIAuthenticationComplete(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider, OAuthResult result, String requiredRole) throws OidcServerException {
if (result == null) { // sent to login page
return false;
}
if (result.getStatus() == OAuthResult.TAI_CHALLENGE) { // SPNEGO negotiate
return false;
}
if (result.getStatus() != OAuthResult.STATUS_OK) {
try {
userAuthentication.renderErrorPage(provider, request, response, result);
} catch (Exception e) {
// ffdc
}
return false;
}
if (requiredRole != null && !request.isUserInRole(requiredRole)) {
throw new OidcServerException("403", OIDCConstants.ERROR_ACCESS_DENIED, HttpServletResponse.SC_FORBIDDEN);
}
return true;
}
void serveClientMetatypeRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
OAuth20ClientMetatypeService metatypeService = oauth20ClientMetatypeServiceRef.getService();
if (metatypeService == null) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
metatypeService.sendClientMetatypeData(request, response);
}
private boolean checkUIConfig(OAuth20Provider provider, HttpServletRequest request) {
String uri = request.getRequestURI();
String id = provider.getInternalClientId();
String secret = provider.getInternalClientSecret();
OidcBaseClient client = null;
boolean result = false;
try {
client = provider.getClientProvider().get(id);
} catch (OidcServerException e) {
// ffdc
}
if (client != null) {
result = secret != null && client.isEnabled() && (client.isAppPasswordAllowed() || client.isAppTokenAllowed());
}
if (!result) {
Tr.warning(tc2, "OAUTH_UI_ENDPOINT_NOT_ENABLED", uri);
}
return result;
}
/**
* Perform logout. call base security logout to clear ltpa cookie.
* Then redirect to a configured logout page if available, else a default.
*
* This does NOT implement
* OpenID Connect Session Management 1.0 draft 28. as of Nov. 2017
* https://openid.net/specs/openid-connect-session-1_0.html#RedirectionAfterLogout
*
* Instead it is a simpler approach that just deletes the ltpa (sso) cookie
* and sends a simple error page if things go wrong.
*
* @param provider
* @param request
* @param response
*/
public void logout(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Processing logout");
}
try {
request.logout(); // ltpa cookie removed if present. No exception if not.
} catch (ServletException e) {
FFDCFilter.processException(e,
this.getClass().getName(), "logout",
new Object[] {});
new LogoutPages().sendDefaultErrorPage(request, response);
return;
}
// not part of spec: logout url defined in config, not client-specific
String logoutRedirectURL = provider.getLogoutRedirectURL();
try {
if (logoutRedirectURL != null) {
String encodedURL = URLEncodeParams(logoutRedirectURL);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "OAUTH20 _SSO OP redirecting to [" + logoutRedirectURL + "], url encoded to [" + encodedURL + "]");
}
response.sendRedirect(encodedURL);
return;
} else {
// send default logout page
new LogoutPages().sendDefaultLogoutPage(request, response);
}
} catch (IOException e) {
FFDCFilter.processException(e,
this.getClass().getName(), "logout",
new Object[] {});
new LogoutPages().sendDefaultErrorPage(request, response);
}
}
String URLEncodeParams(String UrlStr) {
String sep = "?";
String encodedURL = UrlStr;
int index = UrlStr.indexOf(sep);
// if encoded url in server.xml, don't encode it again.
boolean alreadyEncoded = UrlStr.contains("%");
if (index > -1 && !alreadyEncoded) {
index++; // don't encode ?
String prefix = UrlStr.substring(0, index);
String suffix = UrlStr.substring(index);
try {
encodedURL = prefix + java.net.URLEncoder.encode(suffix, StandardCharsets.UTF_8.toString());
// shouldn't encode = in queries, so flip those back
encodedURL = encodedURL.replace("%3D", "=");
} catch (UnsupportedEncodingException e) {
// ffdc
}
}
return encodedURL;
}
public OAuthResult processAuthorizationRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, AttributeList options)
throws ServletException, IOException, OidcServerException {
OAuthResult oauthResult = checkForError(request);
if (oauthResult != null) {
return oauthResult;
}
boolean autoAuthz = clientAuthorization.isClientAutoAuthorized(provider, request);
String reqConsentNonce = getReqConsentNonce(request);
boolean afterLogin = isAfterLogin(request); // we've been to login.jsp or it's replacement.
if (reqConsentNonce == null) { // validate request for initial authorization request only
oauthResult = clientAuthorization.validateAuthorization(provider, request, response);
if (oauthResult.getStatus() != OAuthResult.STATUS_OK) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Status is OK, returning result");
}
return oauthResult;
}
}
oauthResult = handleUserAuthentication(oauthResult, request, response, servletContext,
provider, reqConsentNonce, options, autoAuthz, afterLogin);
return oauthResult;
}
/**
* Adds the id_token_hint_status, id_token_hint_username, and id_token_hint_clientid attributes from the options list
* into attrList, if those attributes exist.
*
* @param options
* @param attrList
*/
private void setTokenHintAttributes(AttributeList options, AttributeList attrList) {
String value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_STATUS, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_USERNAME, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
value = options.getAttributeValueByName(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID);
if (value != null) {
attrList.setAttribute(OIDCConstants.OIDC_AUTHZ_PARAM_ID_TOKEN_HINT_CLIENTID, OAuth20Constants.ATTRTYPE_REQUEST, new String[] { value });
}
}
/**
* @param attrs
* @param request
* @return OAuthResultImpl if validation failed, null otherwise.
*/
private OAuthResultImpl validateIdTokenHintIfPresent(AttributeList attrs, HttpServletRequest request) {
if (attrs != null) {
Principal user = request.getUserPrincipal();
String username = null;
if (user != null) {
username = user.getName();
}
try {
userAuthentication.validateIdTokenHint(username, attrs);
} catch (OAuth20Exception oe) {
return new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, oe);
}
}
return null;
}
/**
* Creates a 401 STATUS_FAILED result due to the token limit being reached.
*
* @param attrs
* @param request
* @param clientId
* @return
*/
private OAuthResult createTokenLimitResult(AttributeList attrs, HttpServletRequest request, String clientId) {
if (attrs == null) {
attrs = new AttributeList();
String responseType = request.getParameter(OAuth20Constants.RESPONSE_TYPE);
attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { responseType });
attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { clientId });
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Attribute responseType:" + responseType + " client_id:" + clientId);
}
}
OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.token.limit.external.error");
e.setHttpStatusCode(HttpServletResponse.SC_BAD_REQUEST);
OAuthResult oauthResultWithExcep = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e);
return oauthResultWithExcep;
}
private OAuthResult handleUIUserAuthentication(HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider, AttributeList options) throws IOException, ServletException, OidcServerException {
OAuthResult oauthResult = null;
Prompt prompt = new Prompt();
if (request.getUserPrincipal() == null) {
// authenticate user if not done yet. Send to login page.
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authenticate user if not done yet");
}
oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult);
}
if (request.getUserPrincipal() == null) { // must be redirect
return oauthResult;
} else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) {
ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31
// ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig());
handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
}
if (!request.isUserInRole(AUTHENTICATED)) { // must be authorized, we'll check userInRole later.
Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return oauthResult;
}
return new OAuthResultImpl(OAuthResult.STATUS_OK, new AttributeList());
}
@FFDCIgnore({ OAuth20BadParameterException.class })
private OAuthResult handleUserAuthentication(OAuthResult oauthResult, HttpServletRequest request, HttpServletResponse response,
ServletContext servletContext, OAuth20Provider provider,
String reqConsentNonce, AttributeList options, boolean autoauthz, boolean afterLogin) throws IOException, ServletException, OidcServerException {
Prompt prompt = null;
String[] scopesAttr = null;
AttributeList attrs = null;
if (oauthResult != null) {
attrs = oauthResult.getAttributeList();
scopesAttr = attrs.getAttributeValuesByName(OAuth20Constants.SCOPE);
if (options != null) {
setTokenHintAttributes(options, attrs);
}
String[] validResources = attrs.getAttributeValuesByName(OAuth20Constants.RESOURCE);
if (validResources != null) {
options.setAttribute(OAuth20Constants.RESOURCE, OAuth20Constants.ATTRTYPE_PARAM_OAUTH, validResources);
}
}
// Per section 4.1.2.1 of the OAuth 2.0 spec (RFC6749), the state parameter must be included in any error response if it was
// originally provided in the request. Adding it to the attribute list here will ensure it is propagated to any failure response.
String[] stateParams = request.getParameterValues(OAuth20Constants.STATE);
if (stateParams != null) {
if (attrs == null) {
attrs = new AttributeList();
}
attrs.setAttribute(OAuth20Constants.STATE, OAuth20Constants.ATTRTYPE_PARAM_QUERY, stateParams);
}
boolean isOpenId = false;
if (scopesAttr != null) {
for (String scope : scopesAttr) {
if (OIDCConstants.SCOPE_OPENID.equals(scope)) {
isOpenId = true;
break;
}
}
}
if (isOpenId) {
// if id_token_hint exists and user is already logged in, compare...
OAuthResultImpl result = validateIdTokenHintIfPresent(attrs, request);
if (result != null) {
return result;
}
}
prompt = new Prompt(request);
if (request.getUserPrincipal() == null || (prompt.hasLogin() && !afterLogin)) {
// authenticate user if not done yet
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Authenticate user if not done yet");
}
oauthResult = userAuthentication.handleAuthenticationWithOAuthResult(provider, request, response, prompt, securityServiceRef, servletContext, OAuth20EndpointServices.AUTHENTICATED, oauthResult);
}
if (request.getUserPrincipal() == null) { // must be redirect
return oauthResult;
} else if (CookieHelper.getCookieValue(request.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME) != null) {
ReferrerURLCookieHandler handler = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig().createReferrerURLCookieHandler(); // GM 2017.05.31
// ReferrerURLCookieHandler handler = new ReferrerURLCookieHandler(WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig());
handler.invalidateReferrerURLCookie(request, response, ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
}
if (!request.isUserInRole(AUTHENTICATED) && !request.isUserInRole(OAuth20Constants.TOKEN_MANAGER_ROLE)) { // must be authorized
Tr.audit(tc, "security.oauth20.error.authorization", request.getUserPrincipal().getName());
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return oauthResult;
}
if (reqConsentNonce != null && !consent.isNonceValid(request, reqConsentNonce)) { // nonce must be valid if has one
consent.handleNonceError(request, response);
return oauthResult;
}
String clientId = getClientId(request);
String[] reducedScopes = null;
try {
reducedScopes = clientAuthorization.getReducedScopes(provider, request, clientId, true);
} catch (Exception e1) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught exception, so setting reduced scopes to null. Exception was: " + e1);
}
reducedScopes = null;
}
boolean preAuthzed = false;
if (reqConsentNonce == null) {
try {
preAuthzed = clientAuthorization.isPreAuthorizedScope(provider, clientId, reducedScopes);
} catch (Exception e) {
preAuthzed = false;
}
}
// Handle consent
if (!autoauthz && !preAuthzed && reqConsentNonce == null && !consent.isCachedAndValid(oauthResult, provider, request, response)) {
if (prompt.hasNone()) {
// Prompt includes "none," however authorization has not been obtained or cached; return error
oauthResult = prompt.errorConsentRequired(attrs);
} else {
// ask user for approval if not auto authorized, or not approved
Nonce nonce = consent.setNonce(request);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "_SSO OP redirecting for consent");
}
consent.renderConsentForm(request, response, provider, clientId, nonce, oauthResult.getAttributeList(), servletContext);
}
return oauthResult;
}
if (reachedTokenLimit(provider, request)) {
return createTokenLimitResult(attrs, request, clientId);
}
if (request.getAttribute(OAuth20Constants.OIDC_REQUEST_OBJECT_ATTR_NAME) != null) {
// Ensure that the reduced scopes list is not empty
oauthResult = clientAuthorization.checkForEmptyScopeSetAfterConsent(reducedScopes, oauthResult, request, provider, clientId);
if (oauthResult != null && oauthResult.getStatus() != OAuthResult.STATUS_OK) {
response.setStatus(HttpServletResponse.SC_FOUND);
return oauthResult;
}
}
// getBack the resource. better double check it
OidcBaseClient client;
try {
client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId);
OAuth20ProviderUtils.validateResource(request, options, client);
} catch (OAuth20BadParameterException e) { // some exceptions need to handled separately
WebUtils.throwOidcServerException(request, e);
} catch (OAuth20Exception e) {
WebUtils.throwOidcServerException(request, e);
}
if (options != null) {
options.setAttribute(OAuth20Constants.SCOPE, OAuth20Constants.ATTRTYPE_RESPONSE_ATTRIBUTE, reducedScopes);
}
if (provider.isTrackOAuthClients()) {
OAuthClientTracker clientTracker = new OAuthClientTracker(request, response, provider);
clientTracker.trackOAuthClient(clientId);
}
consent.handleConsent(provider, request, prompt, clientId);
getExternalClaimsFromWSSubject(request, options);
oauthResult = provider.processAuthorization(request, response, options);
return oauthResult;
}
/**
* Secure registration services with BASIC Auth and validating against the required role.
*
* @param provider
* @param request
* @param response
* @param servletContext
* @param requiredRole - user must be in this role.
* @param fallbacktoBasicAuth - if false, if there is no cookie on the request, then no basic auth challenge will be sent back to browser.
* @throws OidcServerException
*/
@FFDCIgnore({ OidcServerException.class })
private void secureEndpointServices(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext, String requiredRole, boolean fallbackToBasicAuth) throws OidcServerException {
try {
userAuthentication.handleBasicAuthenticationWithRequiredRole(provider, request, response, securityServiceRef, servletContext, requiredRole, fallbackToBasicAuth);
} catch (OidcServerException e) {
if (fallbackToBasicAuth) {
if (e.getHttpStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
response.setHeader(RegistrationEndpointServices.HDR_WWW_AUTHENTICATE, RegistrationEndpointServices.UNAUTHORIZED_HEADER_VALUE);
}
}
throw e;
}
}
@FFDCIgnore({ OAuth20BadParameterException.class })
public void processTokenRequest(OAuth20Provider provider, HttpServletRequest request, HttpServletResponse response) throws ServletException, OidcServerException {
String clientId = (String) request.getAttribute("authenticatedClient");
try {
// checking resource
OidcBaseClient client = OAuth20ProviderUtils.getOidcOAuth20Client(provider, clientId);
if (client == null || !client.isEnabled()) {
throw new OidcServerException("security.oauth20.error.invalid.client", OIDCConstants.ERROR_INVALID_CLIENT_METADATA, HttpServletResponse.SC_BAD_REQUEST);
}
OAuth20ProviderUtils.validateResource(request, null, client);
} catch (OAuth20BadParameterException e) { // some exceptions need to handled separately
WebUtils.throwOidcServerException(request, e);
} catch (OAuth20Exception e) {
WebUtils.throwOidcServerException(request, e);
}
OAuthResult result = clientAuthorization.validateAndHandle2LegsScope(provider, request, response, clientId);
if (result.getStatus() == OAuthResult.STATUS_OK) {
result = provider.processTokenRequest(clientId, request, response);
}
if (result.getStatus() != OAuthResult.STATUS_OK) {
OAuth20TokenRequestExceptionHandler handler = new OAuth20TokenRequestExceptionHandler();
handler.handleResultException(request, response, result);
}
}
/**
* Get the access token from the request's token parameter and look it up in
* the token cache.
*
* If the access token is found in the cache return status 200 and a JSON object.
*
* If the token is not found or the request had errors return status 400.
*
* @param provider
* @param request
* @param response
* @throws OidcServerException
* @throws IOException
*/
public void introspect(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) throws OidcServerException, IOException {
TokenIntrospect tokenIntrospect = new TokenIntrospect();
tokenIntrospect.introspect(provider, request, response);
}
/**
* Revoke the provided token by removing it from the cache
*
* If the access token is found in the cache remove it from the cache
* and return status 200.
*
* @param provider
* @param request
* @param response
*/
public void revoke(OAuth20Provider provider,
HttpServletRequest request,
HttpServletResponse response) {
try {
String tokenString = request.getParameter(com.ibm.ws.security.oauth20.util.UtilConstants.TOKEN);
if (tokenString == null) {
// send 400 per OAuth Token revocation spec
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_INVALID_REQUEST, null); // invalid_request
return;
}
String tokenLookupStr = tokenString;
OAuth20Token token = null;
boolean isAppPasswordOrToken = false;
if (OidcOAuth20Util.isJwtToken(tokenString)) {
tokenLookupStr = com.ibm.ws.security.oauth20.util.HashUtils.digest(tokenString);
} else if (tokenString.length() == (provider.getAccessTokenLength() + 2)) {
// app-token
String encode = provider.getAccessTokenEncoding();
if (OAuth20Constants.PLAIN_ENCODING.equals(encode)) { // must be app-password or app-token
tokenLookupStr = EndpointUtils.computeTokenHash(tokenString);
} else {
tokenLookupStr = EndpointUtils.computeTokenHash(tokenString, encode);
}
isAppPasswordOrToken = true;
}
if (isAppPasswordOrToken) {
token = provider.getTokenCache().getByHash(tokenLookupStr);
} else {
token = provider.getTokenCache().get(tokenLookupStr);
}
boolean isAppPassword = false;
if (token != null && OAuth20Constants.APP_PASSWORD.equals(token.getGrantType())) {
isAppPassword = true;
Tr.error(tc, "security.oauth20.apppwtok.revoke.disallowed", new Object[] {});
}
if (token == null) {
// send 200 per OAuth Token revocation spec
response.setStatus(HttpServletResponse.SC_OK);
if (tc.isDebugEnabled()) {
Tr.debug(tc, "token " + tokenString + " not in cache or wrong token type, return");
}
return;
}
if (tc.isDebugEnabled()) {
Tr.debug(tc, "token type: " + token.getType());
}
ClientAuthnData clientAuthData = new ClientAuthnData(request, response);
if (clientAuthData.hasAuthnData() &&
clientAuthData.getUserName().equals(token.getClientId()) == true) {
if (!isAppPassword && ((token.getType().equals(OAuth20Constants.TOKENTYPE_AUTHORIZATION_GRANT) &&
token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) ||
token.getType().equals(OAuth20Constants.TOKENTYPE_ACCESS_TOKEN))) {
// Revoke the token by removing it from the cache
if (tc.isDebugEnabled()) {
OAuth20Token theToken = provider.getTokenCache().get(tokenLookupStr);
String buf = (theToken != null) ? "is in the cache" : "is not in the cache";
Tr.debug(tc, "token " + tokenLookupStr + " " + buf + ", calling remove");
}
if (isAppPasswordOrToken) {
provider.getTokenCache().removeByHash(tokenLookupStr);
} else {
provider.getTokenCache().remove(tokenLookupStr);
}
if (token.getSubType().equals(OAuth20Constants.SUBTYPE_REFRESH_TOKEN)) {
removeAssociatedAccessTokens(request, provider, token);
}
response.setStatus(HttpServletResponse.SC_OK);
} else {
// Unsupported token type, send 400 per RFC7009 OAuth Token revocation spec
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_UNSUPPORTED_TOKEN_TYPE, null);
}
} else {
// client is not authorized. send 400 per RFC6749 5.2 OAuth Token revocation spec
String defaultMsg = "CWWKS1406E: The revoke request had an invalid client credential. The request URI was {" + request.getRequestURI() + "}.";
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_INVALID_CLIENT",
new Object[] { "revoke", request.getRequestURI() },
defaultMsg);
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST,
Constants.ERROR_CODE_INVALID_CLIENT, errorMsg);
}
} catch (OAuth20DuplicateParameterException e) {
// Duplicate parameter found in request
WebUtils.sendErrorJSON(response, HttpServletResponse.SC_BAD_REQUEST, Constants.ERROR_CODE_INVALID_REQUEST, e.getMessage());
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Internal error processing token revoke request", e);
}
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
} catch (IOException ioe) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Internal error process token introspect revoke error", ioe);
}
}
}
}
/**
* For OpenidConnect, when a refresh token is revoked, also delete all access tokens that have become associated with it.
* (Each time a refresh token is submitted for a new one, the prior access tokens become associated with the new refresh token)
* @param request
* @param provider
* @param refreshToken
* @throws Exception
*/
private void removeAssociatedAccessTokens(HttpServletRequest request, OAuth20Provider provider, OAuth20Token refreshToken) throws Exception {
String contextPath = request.getContextPath();
if (contextPath != null && !contextPath.equals("/oidc")) {
// if this is for oauth, return. Oauth's persistence code doesn't support this token association.
// and we only wanted revocation for oidc, we wanted to leave oauth alone.
if (tc.isDebugEnabled()) {
Tr.debug(tc, "not oidc, returning");
}
return;
}
if (!provider.getRevokeAccessTokensWithRefreshTokens()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "provider prop revokeAccessTokensWithRefreshTokens is false, returning");
}
return;
}
String username = refreshToken.getUsername();
String clientId = refreshToken.getClientId();
String refreshTokenId = refreshToken.getId();
OAuth20EnhancedTokenCache cache = provider.getTokenCache();
Collection<OAuth20Token> ctokens = cache.getAllUserTokens(username);
for (OAuth20Token ctoken : ctokens) {
boolean nullGuard = (cache != null && ctoken.getType() != null && clientId != null && ctoken.getClientId() != null && ctoken.getId() != null);
if (nullGuard && OAuth20Constants.TOKENTYPE_ACCESS_TOKEN.equals(ctoken.getType()) && clientId.equals(ctoken.getClientId())
&& refreshTokenId.equals(((OAuth20TokenImpl) ctoken).getRefreshTokenKey())) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "removing token: " + ctoken.getId());
}
cache.remove(ctoken.getId());
}
}
}
protected void checkHttpsRequirement(HttpServletRequest request, HttpServletResponse response, OAuth20Provider provider) throws IOException {
String url = request.getRequestURL().toString();
if (provider.isHttpsRequired()) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Checking if URL starts with https: " + url);
}
if (url != null && !url.startsWith("https")) {
Tr.error(tc, "security.oauth20.error.wrong.http.scheme", new Object[] { url });
response.sendError(HttpServletResponse.SC_NOT_FOUND,
Tr.formatMessage(tc, "security.oauth20.error.wrong.http.scheme",
new Object[] { url }));
}
}
}
/**
* Determines if this user hit the token limit for the user / client combination
*
* @param provider
* @param request
* @return
*/
protected boolean reachedTokenLimit(OAuth20Provider provider, HttpServletRequest request) {
String userName = getUserName(request);
String clientId = getClientId(request);
long limit = provider.getClientTokenCacheSize();
if (limit > 0) {
long numtokens = provider.getTokenCache().getNumTokens(userName, clientId);
if (numtokens >= limit) {
Tr.error(tc, "security.oauth20.token.limit.error", new Object[] { userName, clientId, limit });
return true;
}
}
return false;
}
private OAuth20Request getAuth20Request(HttpServletRequest request, HttpServletResponse response) throws IOException {
OAuth20Request oauth20Request = (OAuth20Request) request.getAttribute(OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME);
if (oauth20Request == null) {
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_REQUEST_ATTRIBUTE_MISSING",
new Object[] { request.getRequestURI(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME },
"CWWKS1412E: The request endpoint {0} does not have attribute {1}.");
Tr.error(tc, errorMsg);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return oauth20Request;
}
private OAuth20Provider getProvider(HttpServletResponse response, OAuth20Request oauth20Request) throws IOException {
OAuth20Provider provider = ProvidersService.getOAuth20Provider(oauth20Request.getProviderName());
if (provider == null) {
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"OAUTH_PROVIDER_OBJECT_NULL",
new Object[] { oauth20Request.getProviderName(), OAuth20Constants.OAUTH_REQUEST_OBJECT_ATTR_NAME },
"CWWKS1413E: The OAuth20Provider object is null for OAuth provider {0}.");
Tr.error(tc, errorMsg);
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
return provider;
}
private String getReqConsentNonce(HttpServletRequest request) {
return request.getParameter(ATTR_NONCE);
}
private String getUserName(HttpServletRequest request) {
return request.getUserPrincipal().getName();
}
private String getClientId(HttpServletRequest request) {
return request.getParameter(OAuth20Constants.CLIENT_ID);
}
/* returns whether login form had been presented */
protected boolean isAfterLogin(HttpServletRequest request) {
boolean output = false;
HttpSession session = request.getSession(false);
if (session != null) {
if (session.getAttribute(Constants.ATTR_AFTERLOGIN) != null) {
session.removeAttribute(Constants.ATTR_AFTERLOGIN);
output = true;
}
}
return output;
}
/**
* @return
*/
@SuppressWarnings("unchecked")
public Map<String, String[]> getExternalClaimsFromWSSubject(HttpServletRequest request, AttributeList options) {
final String methodName = "getExternalClaimsFromWSSubject";
try {
String externalClaimNames = options.getAttributeValueByName(OAuth20Constants.EXTERNAL_CLAIM_NAMES);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " externalClamiNames:" + externalClaimNames);
if (externalClaimNames != null) {
Map<String, String[]> map2 = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_MEDIATION);
if (map2 != null && map2.size() > 0) {
Set<Entry<String, String[]>> entries = map2.entrySet();
for (Entry<String, String[]> entry : entries) {
options.setAttribute(entry.getKey(), OAuth20Constants.EXTERNAL_MEDIATION, entry.getValue());
}
}
// get the external claims
Map<String, String[]> map = (Map<String, String[]>) getFromWSSubject(OAuth20Constants.EXTERNAL_CLAIMS);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " externalClaims:" + map);
if (map == null)
return null;
// filter properties by externalClaimNames
StringTokenizer strTokenizer = new StringTokenizer(externalClaimNames, ", ");
while (strTokenizer.hasMoreTokens()) {
String key = strTokenizer.nextToken();
String[] values = map.get(key);
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " key:" + key + " values:'" + OAuth20Util.arrayToSpaceString(values) + "'");
if (values != null && values.length > 0) {
options.setAttribute(OAuth20Constants.EXTERNAL_CLAIMS_PREFIX + key, OAuth20Constants.EXTERNAL_CLAIMS, values);
}
}
return map;
}
} catch (WSSecurityException e) {
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " failed. Nothing changed. WSSecurityException:" + e);
}
return null;
}
/**
* @param externalClaims
* @return
*/
private Object getFromWSSubject(String externalClaims) throws WSSecurityException {
Subject runAsSubject = WSSubject.getRunAsSubject();
Object obj = null;
try {
Set<Object> publicCreds = runAsSubject.getPublicCredentials();
if (publicCreds != null && publicCreds.size() > 0) {
Iterator<Object> publicCredIterator = publicCreds.iterator();
while (publicCredIterator.hasNext()) {
Object cred = publicCredIterator.next();
if (cred != null && cred instanceof Hashtable) {
@SuppressWarnings("rawtypes")
Hashtable userCred = (Hashtable) cred;
obj = userCred.get(externalClaims);
if (obj != null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "getFromWSSubject found:" + obj);
}
break;
}
}
}
}
} catch (Exception e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Unable to match predefined cache key." + e);
}
}
return obj;
}
/**
* Check if the request contains an "error" parameter. If one is present and equals the OAuth 2.0 error type "access_denied", a message indicating the user likely canceled the request will be
* logged and a failure result will be returned.
*
* @param request
* @return A {@code OAuthResult} object initialized with AuthResult.FAILURE and 403 status code if an "error" parameter is present and equals "access_denied." Returns null otherwise.
*/
private OAuthResult checkForError(HttpServletRequest request) {
OAuthResult result = null;
String error = request.getParameter("error");
if (error != null && error.length() > 0 && OAuth20Exception.ACCESS_DENIED.equals(error)) {
// User likely canceled the request
String errorMsg = TraceNLS.getFormattedMessage(this.getClass(),
MESSAGE_BUNDLE,
"security.oauth20.request.denied",
new Object[] {},
"CWOAU0067E: The request has been denied by the user, or another error occurred that resulted in denial of the request.");
Tr.error(tc, errorMsg);
OAuth20AccessDeniedException e = new OAuth20AccessDeniedException("security.oauth20.request.denied");
e.setHttpStatusCode(HttpServletResponse.SC_FORBIDDEN);
AttributeList attrs = new AttributeList();
String value = request.getParameter(OAuth20Constants.RESPONSE_TYPE);
if (value != null && value.length() > 0) {
attrs.setAttribute(OAuth20Constants.RESPONSE_TYPE, OAuth20Constants.RESPONSE_TYPE, new String[] { value });
}
value = getClientId(request);
if (value != null && value.length() > 0) {
attrs.setAttribute(OAuth20Constants.CLIENT_ID, OAuth20Constants.CLIENT_ID, new String[] { value });
}
result = new OAuthResultImpl(OAuthResult.STATUS_FAILED, attrs, e);
}
return result;
}
/**
* @param provider
* @param responseJSON
* @param accessToken
* @param groupsOnly
* @throws IOException
*/
protected Map<String, Object> getUserClaimsMap(UserClaims userClaims, boolean groupsOnly) throws IOException {
// keep this method for OidcEndpointServices
return TokenIntrospect.getUserClaimsMap(userClaims, groupsOnly);
}
protected UserClaims getUserClaimsObj(OAuth20Provider provider, OAuth20Token accessToken) throws IOException {
// keep this method for OidcEndpointServices
return TokenIntrospect.getUserClaimsObj(provider, accessToken);
}
}
| epl-1.0 |
sazgin/elexis-3-core | ch.elexis.core.ui/src/ch/elexis/core/ui/wizards/DBImportFirstPage.java | 4493 | /*******************************************************************************
* Copyright (c) 2005-2010, G. Weirich and Elexis
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* G. Weirich - initial implementation
* D. Lutz - adapted for importing data from other databases
*
*******************************************************************************/
package ch.elexis.core.ui.wizards;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import ch.elexis.core.ui.UiDesk;
import ch.elexis.core.ui.icons.ImageSize;
import ch.elexis.core.ui.icons.Images;
import ch.rgw.tools.JdbcLink;
import ch.rgw.tools.StringTool;
public class DBImportFirstPage extends WizardPage {
List dbTypes;
Text server, dbName;
String defaultUser, defaultPassword;
JdbcLink j = null;
static final String[] supportedDB = new String[] {
"mySQl", "PostgreSQL", "H2", "ODBC" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
};
static final int MYSQL = 0;
static final int POSTGRESQL = 1;
static final int ODBC = 3;
static final int H2 = 2;
public DBImportFirstPage(String pageName){
super(Messages.DBImportFirstPage_connection, Messages.DBImportFirstPage_typeOfDB,
Images.IMG_LOGO.getImageDescriptor(ImageSize._75x66_TitleDialogIconSize)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
setMessage(Messages.DBImportFirstPage_selectType + Messages.DBImportFirstPage_enterNameODBC); //$NON-NLS-1$
setDescription(Messages.DBImportFirstPage_theDesrciption); //$NON-NLS-1$
}
public DBImportFirstPage(String pageName, String title, ImageDescriptor titleImage){
super(pageName, title, titleImage);
// TODO Automatisch erstellter Konstruktoren-Stub
}
public void createControl(Composite parent){
DBImportWizard wiz = (DBImportWizard) getWizard();
FormToolkit tk = UiDesk.getToolkit();
Form form = tk.createForm(parent);
form.setText(Messages.DBImportFirstPage_Connection); //$NON-NLS-1$
Composite body = form.getBody();
body.setLayout(new TableWrapLayout());
tk.createLabel(body, Messages.DBImportFirstPage_EnterType); //$NON-NLS-1$
dbTypes = new List(body, SWT.BORDER);
dbTypes.setItems(supportedDB);
dbTypes.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e){
int it = dbTypes.getSelectionIndex();
switch (it) {
case MYSQL:
case POSTGRESQL:
server.setEnabled(true);
dbName.setEnabled(true);
defaultUser = ""; //$NON-NLS-1$
defaultPassword = ""; //$NON-NLS-1$
break;
case H2:
server.setEnabled(false);
dbName.setEnabled(true);
defaultUser = "sa";
defaultPassword = "";
break;
case ODBC:
server.setEnabled(false);
dbName.setEnabled(true);
defaultUser = "sa"; //$NON-NLS-1$
defaultPassword = ""; //$NON-NLS-1$
break;
default:
break;
}
DBImportSecondPage sec = (DBImportSecondPage) getNextPage();
sec.name.setText(defaultUser);
sec.pwd.setText(defaultPassword);
}
});
tk.adapt(dbTypes, true, true);
tk.createLabel(body, Messages.DBImportFirstPage_serverAddress); //$NON-NLS-1$
server = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$
TableWrapData twr = new TableWrapData(TableWrapData.FILL_GRAB);
server.setLayoutData(twr);
tk.createLabel(body, Messages.DBImportFirstPage_databaseName); //$NON-NLS-1$
dbName = tk.createText(body, "", SWT.BORDER); //$NON-NLS-1$
TableWrapData twr2 = new TableWrapData(TableWrapData.FILL_GRAB);
dbName.setLayoutData(twr2);
if (wiz.preset != null && wiz.preset.length > 1) {
int idx = StringTool.getIndex(supportedDB, wiz.preset[0]);
if (idx < dbTypes.getItemCount()) {
dbTypes.select(idx);
}
server.setText(wiz.preset[1]);
dbName.setText(wiz.preset[2]);
}
setControl(form);
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.install/src/com/ibm/ws/install/internal/MavenRepository.java | 1293 | /*******************************************************************************
* Copyright (c) 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.install.internal;
public class MavenRepository {
private String name;
private String repositoryUrl;
private String userId;
private String password;
public MavenRepository(String name, String repositoryUrl, String userId, String password) {
this.name = name;
this.repositoryUrl = repositoryUrl;
this.userId = userId;
this.password = password;
}
public String getName(){
return name;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public String getUserId() {
return userId;
}
public String getPassword() {
return password;
}
public String toString(){
return this.repositoryUrl;
}
}
| epl-1.0 |
muros-ct/kapua | service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/AbstractStorableListResult.java | 1524 | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua.service.datastore.internal.model.query;
import java.util.ArrayList;
import org.eclipse.kapua.service.datastore.model.Storable;
import org.eclipse.kapua.service.datastore.model.StorableListResult;
@SuppressWarnings("serial")
public class AbstractStorableListResult<E extends Storable> extends ArrayList<E> implements StorableListResult<E>
{
private Object nextKey;
private Integer totalCount;
public AbstractStorableListResult()
{
nextKey = null;
totalCount = null;
}
public AbstractStorableListResult(Object nextKey)
{
this.nextKey = nextKey;
this.totalCount = null;
}
public AbstractStorableListResult(Object nextKeyOffset, Integer totalCount)
{
this(nextKeyOffset);
this.totalCount = totalCount;
}
public Object getNextKey()
{
return nextKey;
}
public Integer getTotalCount()
{
return totalCount;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transaction.core_fat.startMultiEJB/fat/src/com/ibm/ws/transaction/test/FATSuite.java | 1724 | /*******************************************************************************
* Copyright (c) 2017, 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.transaction.test;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.ibm.ws.transaction.test.tests.EJBNewTxDBRoSTest;
import com.ibm.ws.transaction.test.tests.EJBNewTxDBTest;
import com.ibm.ws.transaction.test.tests.EJBNewTxRoSTest;
import com.ibm.ws.transaction.test.tests.EJBNewTxTest;
import componenttest.rules.repeater.FeatureReplacementAction;
import componenttest.rules.repeater.JakartaEE9Action;
import componenttest.rules.repeater.RepeatTests;
@RunWith(Suite.class)
@SuiteClasses({
EJBNewTxTest.class,
EJBNewTxDBTest.class,
EJBNewTxRoSTest.class,
EJBNewTxDBRoSTest.class
})
public class FATSuite {
// Using the RepeatTests @ClassRule will cause all tests to be run twice.
// First without any modifications, then again with all features upgraded to their EE8 equivalents.
@ClassRule
public static RepeatTests r = RepeatTests.withoutModification()
.andWith(FeatureReplacementAction.EE8_FEATURES())
.andWith(new JakartaEE9Action());
}
| epl-1.0 |
MikeJMajor/openhab2-addons-dlinksmarthome | bundles/org.openhab.binding.loxone/src/test/java/org/openhab/binding/loxone/internal/controls/LxControlTrackerTest.java | 1684 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.loxone.internal.controls;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.library.types.StringType;
/**
* Test class for (@link LxControlTracker}
*
* @author Pawel Pieczul - initial contribution
*
*/
public class LxControlTrackerTest extends LxControlTest {
@BeforeEach
public void setup() {
setupControl("132aa43b-01d4-56ea-ffff403fb0c34b9e", "0b734138-037d-034e-ffff403fb0c34b9e",
"0fe650c2-0004-d446-ffff504f9410790f", "Tracker Control");
}
@Test
public void testControlCreation() {
testControlCreation(LxControlTracker.class, 1, 0, 1, 1, 1);
}
@Test
public void testChannels() {
testChannel("String", null, null, null, null, null, true, null);
}
@Test
public void testLoxoneStateChanges() {
for (int i = 0; i < 20; i++) {
String s = new String();
for (int j = 0; j < i; j++) {
for (char c = 'a'; c <= 'a' + j; c++) {
s = s + c;
}
if (j != i - 1) {
s = s + '|';
}
}
changeLoxoneState("entries", s);
testChannelState(new StringType(s));
}
}
}
| epl-1.0 |
sehrgut/minecraft-smp-mocreatures | moCreatures/server/debug/sources/moCreatures/items/ItemSharkEgg.java | 1137 | package moCreatures.items;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.World;
import moCreatures.entities.EntitySharkEgg;
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
public class ItemSharkEgg extends Item
{
public ItemSharkEgg(int i)
{
super(i);
maxStackSize = 16;
}
public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer)
{
itemstack.stackSize--;
if(!world.singleplayerWorld)
{
EntitySharkEgg entitysharkegg = new EntitySharkEgg(world);
entitysharkegg.setPosition(entityplayer.posX, entityplayer.posY, entityplayer.posZ);
world.entityJoinedWorld(entitysharkegg);
entitysharkegg.motionY += world.rand.nextFloat() * 0.05F;
entitysharkegg.motionX += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F;
entitysharkegg.motionZ += (world.rand.nextFloat() - world.rand.nextFloat()) * 0.3F;
}
return itemstack;
}
}
| epl-1.0 |
jdcasey/EGit | org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java | 8708 | /*******************************************************************************
* Copyright (C) 2008, 2009 Robin Rosenberg <robin.rosenberg@dewire.com>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.internal.decorators;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;
import org.eclipse.core.resources.IResource;
import org.eclipse.egit.core.GitProvider;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.internal.CompareUtils;
import org.eclipse.egit.ui.internal.trace.GitTraceLocation;
import org.eclipse.jface.text.Document;
import org.eclipse.jgit.events.ListenerHandle;
import org.eclipse.jgit.events.RefsChangedEvent;
import org.eclipse.jgit.events.RefsChangedListener;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.osgi.util.NLS;
import org.eclipse.team.core.RepositoryProvider;
class GitDocument extends Document implements RefsChangedListener {
private final IResource resource;
private ObjectId lastCommit;
private ObjectId lastTree;
private ObjectId lastBlob;
private ListenerHandle myRefsChangedHandle;
static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>();
static GitDocument create(final IResource resource) throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) create: " + resource); //$NON-NLS-1$
GitDocument ret = null;
if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) {
ret = new GitDocument(resource);
ret.populate();
final Repository repository = ret.getRepository();
if (repository != null)
ret.myRefsChangedHandle = repository.getListenerList()
.addRefsChangedListener(ret);
}
return ret;
}
private GitDocument(IResource resource) {
this.resource = resource;
GitDocument.doc2repo.put(this, getRepository());
}
private void setResolved(final AnyObjectId commit, final AnyObjectId tree,
final AnyObjectId blob, final String value) {
lastCommit = commit != null ? commit.copy() : null;
lastTree = tree != null ? tree.copy() : null;
lastBlob = blob != null ? blob.copy() : null;
set(value);
if (blob != null)
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
else if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) unresolved " + resource); //$NON-NLS-1$
}
void populate() throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.QUICKDIFF.getLocation(), resource);
TreeWalk tw = null;
RevWalk rw = null;
try {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
if (mapping == null) {
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
final String gitPath = mapping.getRepoRelativePath(resource);
final Repository repository = mapping.getRepository();
String baseline = GitQuickDiffProvider.baseline.get(repository);
if (baseline == null)
baseline = Constants.HEAD;
ObjectId commitId = repository.resolve(baseline);
if (commitId != null) {
if (commitId.equals(lastCommit)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
} else {
String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff,
new Object[] { baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
rw = new RevWalk(repository);
RevCommit baselineCommit;
try {
baselineCommit = rw.parseCommit(commitId);
} catch (IOException err) {
String msg = NLS
.bind(UIText.GitDocument_errorLoadCommit, new Object[] {
commitId, baseline, resource, repository });
Activator.logError(msg, err);
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
RevTree treeId = baselineCommit.getTree();
if (treeId.equals(lastTree)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
tw = TreeWalk.forPath(repository, gitPath, treeId);
if (tw == null) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) resource " + resource + " not found in " + treeId + " in " + repository + ", baseline=" + baseline); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
ObjectId id = tw.getObjectId(0);
if (id.equals(ObjectId.zeroId())) {
setResolved(null, null, null, ""); //$NON-NLS-1$
String msg = NLS
.bind(UIText.GitDocument_errorLoadTree, new Object[] {
treeId.getName(), baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
if (!id.equals(lastBlob)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) compareTo: " + baseline); //$NON-NLS-1$
ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB);
byte[] bytes = loader.getBytes();
String charset;
charset = CompareUtils.getResourceEncoding(resource);
// Finally we could consider validating the content with respect
// to the content. We don't do that here.
String s = new String(bytes, charset);
setResolved(commitId, treeId, id, s);
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
}
} finally {
if (tw != null)
tw.release();
if (rw != null)
rw.release();
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.QUICKDIFF.getLocation());
}
}
void dispose() {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) dispose: " + resource); //$NON-NLS-1$
doc2repo.remove(this);
if (myRefsChangedHandle != null) {
myRefsChangedHandle.remove();
myRefsChangedHandle = null;
}
}
public void onRefsChanged(final RefsChangedEvent e) {
try {
populate();
} catch (IOException e1) {
Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1);
}
}
private Repository getRepository() {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
return (mapping != null) ? mapping.getRepository() : null;
}
/**
* A change occurred to a repository. Update any GitDocument instances
* referring to such repositories.
*
* @param repository
* Repository which changed
* @throws IOException
*/
static void refreshRelevant(final Repository repository) throws IOException {
for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) {
if (i.getValue() == repository) {
i.getKey().populate();
}
}
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/mfp/schema/JsHdrAccess.java | 1422 | /*******************************************************************************
* Copyright (c) 2017 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
// Generated from C:\SIB\Code\WASX.SIB\dd\SIB\ws\code\sib.mfp.impl\src\com\ibm\ws\sib\mfp\schema\JsHdrSchema.schema: do not edit directly
package com.ibm.ws.sib.mfp.schema;
import com.ibm.ws.sib.mfp.jmf.impl.JSchema;
public final class JsHdrAccess {
public final static JSchema schema = new JsHdrSchema();
public final static int DISCRIMINATOR = 0;
public final static int ARRIVALTIMESTAMP = 1;
public final static int SYSTEMMESSAGESOURCEUUID = 2;
public final static int SYSTEMMESSAGEVALUE = 3;
public final static int SECURITYUSERID = 4;
public final static int SECURITYSENTBYSYSTEM = 5;
public final static int MESSAGETYPE = 6;
public final static int SUBTYPE = 7;
public final static int HDR2 = 8;
public final static int API = 10;
public final static int IS_API_EMPTY = 0;
public final static int IS_API_DATA = 1;
public final static int API_DATA = 9;
}
| epl-1.0 |
alexmonthy/lttng-scope | lttng-scope/src/main/java/org/lttng/scope/lami/viewers/ILamiViewer.java | 2501 | ///*******************************************************************************
// * Copyright (c) 2015, 2016 EfficiOS Inc., Alexandre Montplaisir
// *
// * All rights reserved. This program and the accompanying materials are
// * made available under the terms of the Eclipse Public License v1.0 which
// * accompanies this distribution, and is available at
// * http://www.eclipse.org/legal/epl-v10.html
// *******************************************************************************/
//
//package org.lttng.scope.lami.ui.viewers;
//
//import org.eclipse.jface.viewers.TableViewer;
//import org.eclipse.swt.SWT;
//import org.eclipse.swt.widgets.Composite;
//import org.lttng.scope.lami.core.module.LamiChartModel;
//import org.lttng.scope.lami.ui.views.LamiReportViewTabPage;
//
///**
// * Common interface for all Lami viewers.
// *
// * @author Alexandre Montplaisir
// */
//public interface ILamiViewer {
//
// /**
// * Dispose the viewer widget.
// */
// void dispose();
//
// /**
// * Factory method to create a new Table viewer.
// *
// * @param parent
// * The parent composite
// * @param page
// * The {@link LamiReportViewTabPage} parent page
// * @return The new viewer
// */
// static ILamiViewer createLamiTable(Composite parent, LamiReportViewTabPage page) {
// TableViewer tableViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.MULTI | SWT.VIRTUAL);
// return new LamiTableViewer(tableViewer, page);
// }
//
// /**
// * Factory method to create a new chart viewer. The chart type is specified
// * by the 'chartModel' parameter.
// *
// * @param parent
// * The parent composite
// * @param page
// * The {@link LamiReportViewTabPage} parent page
// * @param chartModel
// * The information about the chart to display
// * @return The new viewer
// */
// static ILamiViewer createLamiChart(Composite parent, LamiReportViewTabPage page, LamiChartModel chartModel) {
// switch (chartModel.getChartType()) {
// case BAR_CHART:
// return new LamiBarChartViewer(parent, page, chartModel);
// case XY_SCATTER:
// return new LamiScatterViewer(parent, page, chartModel);
// case PIE_CHART:
// default:
// throw new UnsupportedOperationException("Unsupported chart type: " + chartModel.toString()); //$NON-NLS-1$
// }
// }
//}
| epl-1.0 |
stzilli/kapua | simulator-kura/src/main/java/org/eclipse/kapua/kura/simulator/app/deploy/DeploymentUninstallPackageRequest.java | 1787 | /*******************************************************************************
* Copyright (c) 2017, 2021 Red Hat Inc and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat Inc - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.kura.simulator.app.deploy;
import org.eclipse.kapua.kura.simulator.payload.Metric;
import org.eclipse.kapua.kura.simulator.payload.Optional;
public class DeploymentUninstallPackageRequest {
@Metric("dp.name")
private String name;
@Metric("dp.version")
private String version;
@Metric("job.id")
private long jobId;
@Optional
@Metric("dp.reboot")
private Boolean reboot;
@Optional
@Metric("dp.reboot.delay")
private Integer rebootDelay;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(final String version) {
this.version = version;
}
public long getJobId() {
return jobId;
}
public void setJobId(final long jobId) {
this.jobId = jobId;
}
public Boolean getReboot() {
return reboot;
}
public void setReboot(final Boolean reboot) {
this.reboot = reboot;
}
public Integer getRebootDelay() {
return rebootDelay;
}
public void setRebootDelay(final Integer rebootDelay) {
this.rebootDelay = rebootDelay;
}
}
| epl-1.0 |
eclipse/hawkbit | hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TagAssignementComboBox.java | 6274 | /**
* Copyright (c) 2020 Bosch.IO GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ui.common.tagdetails;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.ui.common.data.proxies.ProxyTag;
import org.eclipse.hawkbit.ui.common.tagdetails.TagPanelLayout.TagAssignmentListener;
import org.eclipse.hawkbit.ui.utils.UIComponentIdProvider;
import org.eclipse.hawkbit.ui.utils.UIMessageIdProvider;
import org.eclipse.hawkbit.ui.utils.VaadinMessageSource;
import com.google.common.collect.Sets;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.themes.ValoTheme;
/**
* Combobox that lists all available Tags that can be assigned to a
* {@link Target} or {@link DistributionSet}.
*/
public class TagAssignementComboBox extends HorizontalLayout {
private static final long serialVersionUID = 1L;
private final Collection<ProxyTag> allAssignableTags;
private final transient Set<TagAssignmentListener> listeners = Sets.newConcurrentHashSet();
private final ComboBox<ProxyTag> assignableTagsComboBox;
private final boolean readOnlyMode;
/**
* Constructor.
*
* @param i18n
* the i18n
* @param readOnlyMode
* if true the combobox will be disabled so no assignment can be
* done.
*/
TagAssignementComboBox(final VaadinMessageSource i18n, final boolean readOnlyMode) {
this.readOnlyMode = readOnlyMode;
setWidth("100%");
this.assignableTagsComboBox = getAssignableTagsComboBox(
i18n.getMessage(UIMessageIdProvider.TOOLTIP_SELECT_TAG));
this.allAssignableTags = new HashSet<>();
this.assignableTagsComboBox.setItems(allAssignableTags);
addComponent(assignableTagsComboBox);
}
private ComboBox<ProxyTag> getAssignableTagsComboBox(final String description) {
final ComboBox<ProxyTag> tagsComboBox = new ComboBox<>();
tagsComboBox.setId(UIComponentIdProvider.TAG_SELECTION_ID);
tagsComboBox.setDescription(description);
tagsComboBox.addStyleName(ValoTheme.COMBOBOX_TINY);
tagsComboBox.setEnabled(!readOnlyMode);
tagsComboBox.setWidth("100%");
tagsComboBox.setEmptySelectionAllowed(true);
tagsComboBox.setItemCaptionGenerator(ProxyTag::getName);
tagsComboBox.addValueChangeListener(event -> assignTag(event.getValue()));
return tagsComboBox;
}
private void assignTag(final ProxyTag tagData) {
if (tagData == null || readOnlyMode) {
return;
}
allAssignableTags.remove(tagData);
assignableTagsComboBox.clear();
assignableTagsComboBox.getDataProvider().refreshAll();
notifyListenersTagAssigned(tagData);
}
/**
* Initializes the Combobox with all assignable tags.
*
* @param assignableTags
* assignable tags
*/
void initializeAssignableTags(final List<ProxyTag> assignableTags) {
allAssignableTags.addAll(assignableTags);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Removes all Tags from Combobox.
*/
void removeAllTags() {
allAssignableTags.clear();
assignableTagsComboBox.clear();
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Adds an assignable Tag to the combobox.
*
* @param tagData
* the data of the Tag
*/
void addAssignableTag(final ProxyTag tagData) {
if (tagData == null) {
return;
}
allAssignableTags.add(tagData);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Updates an assignable Tag in the combobox.
*
* @param tagData
* the data of the Tag
*/
void updateAssignableTag(final ProxyTag tagData) {
if (tagData == null) {
return;
}
findAssignableTagById(tagData.getId()).ifPresent(tagToUpdate -> updateAssignableTag(tagToUpdate, tagData));
}
private Optional<ProxyTag> findAssignableTagById(final Long id) {
return allAssignableTags.stream().filter(tag -> tag.getId().equals(id)).findAny();
}
private void updateAssignableTag(final ProxyTag oldTag, final ProxyTag newTag) {
allAssignableTags.remove(oldTag);
allAssignableTags.add(newTag);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Removes an assignable tag from the combobox.
*
* @param tagId
* the tag Id of the Tag that should be removed.
*/
void removeAssignableTag(final Long tagId) {
findAssignableTagById(tagId).ifPresent(this::removeAssignableTag);
}
/**
* Removes an assignable tag from the combobox.
*
* @param tagData
* the {@link ProxyTag} of the Tag that should be removed.
*/
void removeAssignableTag(final ProxyTag tagData) {
allAssignableTags.remove(tagData);
assignableTagsComboBox.getDataProvider().refreshAll();
}
/**
* Registers an {@link TagAssignmentListener} on the combobox.
*
* @param listener
* the listener to register
*/
void addTagAssignmentListener(final TagAssignmentListener listener) {
listeners.add(listener);
}
/**
* Removes a {@link TagAssignmentListener} from the combobox,
*
* @param listener
* the listener that should be removed.
*/
void removeTagAssignmentListener(final TagAssignmentListener listener) {
listeners.remove(listener);
}
private void notifyListenersTagAssigned(final ProxyTag tagData) {
listeners.forEach(listener -> listener.assignTag(tagData));
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.fronius/src/main/java/org/openhab/binding/fronius/internal/api/HeadRequestArguments.java | 1893 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.fronius.internal.api;
import com.google.gson.annotations.SerializedName;
/**
* The {@link HeadRequestArguments} is responsible for storing
* the "RequestArguments" node from the {@link Head}
*
* @author Thomas Rokohl - Initial contribution
*/
public class HeadRequestArguments {
@SerializedName("DataCollection")
private String dataCollection;
@SerializedName("DeviceClass")
private String deviceClass;
@SerializedName("DeviceId")
private String deviceId;
@SerializedName("Scope")
private String scope;
public String getDataCollection() {
if (null == dataCollection) {
dataCollection = "";
}
return dataCollection;
}
public void setDataCollection(String dataCollection) {
this.dataCollection = dataCollection;
}
public String getDeviceClass() {
if (null == deviceClass) {
deviceClass = "";
}
return deviceClass;
}
public void setDeviceClass(String deviceClass) {
this.deviceClass = deviceClass;
}
public String getDeviceId() {
if (null == deviceId) {
deviceId = "";
}
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getScope() {
if (null == scope) {
scope = "";
}
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
| epl-1.0 |
openhab/openhab2 | bundles/org.openhab.binding.vigicrues/src/main/java/org/openhab/binding/vigicrues/internal/dto/vigicrues/TerEntVigiCru.java | 1863 | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.vigicrues.internal.dto.vigicrues;
import java.util.List;
import com.google.gson.annotations.SerializedName;
/**
* The {@link TerEntVigiCru} is the Java class used to map the JSON
* response to an vigicrue api endpoint request.
*
* @author Gaël L'hopital - Initial contribution
*/
public class TerEntVigiCru {
public class VicTerEntVigiCru {
@SerializedName("vic:aNMoinsUn")
public List<VicANMoinsUn> vicANMoinsUn;
/*
* Currently unused, maybe interesting in the future
*
* @SerializedName("@id")
* public String id;
*
* @SerializedName("vic:CdEntVigiCru")
* public String vicCdEntVigiCru;
*
* @SerializedName("vic:TypEntVigiCru")
* public String vicTypEntVigiCru;
*
* @SerializedName("vic:LbEntVigiCru")
* public String vicLbEntVigiCru;
*
* @SerializedName("vic:DtHrCreatEntVigiCru")
* public String vicDtHrCreatEntVigiCru;
*
* @SerializedName("vic:DtHrMajEntVigiCru")
* public String vicDtHrMajEntVigiCru;
*
* @SerializedName("vic:StEntVigiCru")
* public String vicStEntVigiCru;
* public int count_aNMoinsUn;
*
* @SerializedName("LinkInfoCru")
* public String linkInfoCru;
*/
}
@SerializedName("vic:TerEntVigiCru")
public VicTerEntVigiCru vicTerEntVigiCru;
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.oidc.server_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/OAuth/OAuthMapToUserRegistryWithRegMismatch2ServerTests.java | 4019 | /*******************************************************************************
* Copyright (c) 2016, 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.security.openidconnect.server.fat.jaxrs.config.OAuth;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import com.ibm.websphere.simplicity.log.Log;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.Constants;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestServer;
import com.ibm.ws.security.oauth_oidc.fat.commonTest.TestSettings;
import com.ibm.ws.security.openidconnect.server.fat.jaxrs.config.CommonTests.MapToUserRegistryWithRegMismatch2ServerTests;
import componenttest.custom.junit.runner.FATRunner;
import componenttest.custom.junit.runner.Mode;
import componenttest.custom.junit.runner.Mode.TestMode;
import componenttest.topology.impl.LibertyServerWrapper;
import componenttest.topology.utils.LDAPUtils;
// See test description in
// com.ibm.ws.security.openidconnect.server-1.0_fat.jaxrs.config/fat/src/com/ibm/ws/security/openidconnect/server/fat/jaxrs/config/CommonTests/MapToUserRegistryWithRegMismatch2ServerTests.java
@LibertyServerWrapper
@Mode(TestMode.FULL)
@RunWith(FATRunner.class)
public class OAuthMapToUserRegistryWithRegMismatch2ServerTests extends MapToUserRegistryWithRegMismatch2ServerTests {
private static final Class<?> thisClass = OAuthMapToUserRegistryWithRegMismatch2ServerTests.class;
@BeforeClass
public static void setupBeforeTest() throws Exception {
/*
* These tests have not been configured to run with the local LDAP server.
*/
Assume.assumeTrue(!LDAPUtils.USE_LOCAL_LDAP_SERVER);
msgUtils.printClassName(thisClass.toString());
Log.info(thisClass, "setupBeforeTest", "Prep for test");
// add any additional messages that you want the "start" to wait for
// we should wait for any providers that this test requires
List<String> extraMsgs = new ArrayList<String>();
extraMsgs.add("CWWKS1631I.*");
List<String> extraApps = new ArrayList<String>();
TestServer.addTestApp(null, extraMsgs, Constants.OP_SAMPLE_APP, Constants.OAUTH_OP);
TestServer.addTestApp(extraApps, null, Constants.OP_CLIENT_APP, Constants.OAUTH_OP);
TestServer.addTestApp(extraApps, extraMsgs, Constants.OP_TAI_APP, Constants.OAUTH_OP);
List<String> extraMsgs2 = new ArrayList<String>();
List<String> extraApps2 = new ArrayList<String>();
extraApps2.add(Constants.HELLOWORLD_SERVLET);
testSettings = new TestSettings();
testOPServer = commonSetUp(OPServerName, "server_orig_maptest_ldap.xml", Constants.OAUTH_OP, extraApps, Constants.DO_NOT_USE_DERBY, extraApps);
genericTestServer = commonSetUp(RSServerName, "server_orig_maptest_mismatchregistry.xml", Constants.GENERIC_SERVER, extraApps2, Constants.DO_NOT_USE_DERBY, extraMsgs2, null, Constants.OAUTH_OP);
targetProvider = Constants.OAUTHCONFIGSAMPLE_APP;
flowType = Constants.WEB_CLIENT_FLOW;
goodActions = Constants.BASIC_PROTECTED_RESOURCE_RS_PROTECTED_RESOURCE_ACTIONS;
// set RS protected resource to point to second server.
testSettings.setRSProtectedResource(genericTestServer.getHttpsString() + "/helloworld/rest/helloworld");
// Initial user settings for default user. Individual tests override as needed.
testSettings.setAdminUser("oidcu1");
testSettings.setAdminPswd("security");
testSettings.setGroupIds("RSGroup");
}
}
| epl-1.0 |
stzilli/kapua | service/api/src/main/java/org/eclipse/kapua/KapuaIllegalNullArgumentException.java | 1278 | /*******************************************************************************
* Copyright (c) 2016, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua;
/**
* KapuaIllegalNullArgumentException is thrown when <tt>null</tt> is passed to a method for an argument
* or as a value for field in an object where <tt>null</tt> is not allowed.<br>
* This should always be used instead of <tt>NullPointerException</tt> as the latter is too easily confused with programming bugs.
*
* @since 1.0
*
*/
public class KapuaIllegalNullArgumentException extends KapuaIllegalArgumentException {
private static final long serialVersionUID = -8762712571192128282L;
/**
* Constructor
*
* @param argumentName
*/
public KapuaIllegalNullArgumentException(String argumentName) {
super(KapuaErrorCodes.ILLEGAL_NULL_ARGUMENT, argumentName, null);
}
}
| epl-1.0 |
emmental/isetools | src/main/java/ca/nines/ise/util/LocationAnnotator.java | 5912 | /*
* Copyright (C) 2014 Michael Joyce <ubermichael@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package ca.nines.ise.util;
import java.util.ArrayDeque;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.UserDataHandler;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.LocatorImpl;
/**
* Annotates a DOM with location data during the construction process.
* <p>
* http://javacoalface.blogspot.ca/2011/04/line-and-column-numbers-in-xml-dom.html
* <p>
* @author Michael Joyce <ubermichael@gmail.com>
*/
public class LocationAnnotator extends XMLFilterImpl {
/**
* Locator returned by the construction process.
*/
private Locator locator;
/**
* The systemID of the XML.
*/
private final String source;
/**
* Stack to hold the locators which haven't been completed yet.
*/
private final ArrayDeque<Locator> locatorStack = new ArrayDeque<>();
/**
* Stack holding incomplete elements.
*/
private final ArrayDeque<Element> elementStack = new ArrayDeque<>();
/**
* A data handler to add the location data.
*/
private final UserDataHandler dataHandler = new LocationDataHandler();
/**
* Construct a location annotator for an XMLReader and Document. The systemID
* is determined automatically.
*
* @param xmlReader the reader to use the annotator
* @param dom the DOM to annotate
*/
LocationAnnotator(XMLReader xmlReader, Document dom) {
super(xmlReader);
source = "";
EventListener modListener = new EventListener() {
@Override
public void handleEvent(Event e) {
EventTarget target = e.getTarget();
elementStack.push((Element) target);
}
};
((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
}
/**
* Construct a location annotator for an XMLReader and Document. The systemID
* is NOT determined automatically.
*
* @param source the systemID of the XML
* @param xmlReader the reader to use the annotator
* @param dom the DOM to annotate
*/
LocationAnnotator(String source, XMLReader xmlReader, Document dom) {
super(xmlReader);
this.source = source;
EventListener modListener = new EventListener() {
@Override
public void handleEvent(Event e) {
EventTarget target = e.getTarget();
elementStack.push((Element) target);
}
};
((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
}
/**
* Add the locator to the document during the parse.
*
* @param locator the locator to add
*/
@Override
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator = locator;
}
/**
* Handle the start tag of an element by adding locator data.
*
* @param uri The systemID of the XML.
* @param localName the name of the tag. unused.
* @param qName the FQDN of the tag. unused.
* @param atts the attributes of the tag. unused.
* @throws SAXException
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
locatorStack.push(new LocatorImpl(locator));
}
/**
* Handle the end tag of an element by adding locator data.
*
* @param uri The systemID of the XML.
* @param localName the name of the tag. unused.
* @param qName the FQDN of the tag. unused.
* @throws SAXException
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if (locatorStack.size() > 0) {
Locator startLocator = locatorStack.pop();
LocationData location = new LocationData(
(startLocator.getSystemId() == null ? source : startLocator.getSystemId()),
startLocator.getLineNumber(),
startLocator.getColumnNumber(),
locator.getLineNumber(),
locator.getColumnNumber()
);
Element e = elementStack.pop();
e.setUserData(
LocationData.LOCATION_DATA_KEY, location,
dataHandler);
}
}
/**
* UserDataHandler to insert location data into the XML DOM.
*/
private class LocationDataHandler implements UserDataHandler {
/**
* Handle an even during a parse. An even is a start/end/empty tag or some
* data.
*
* @param operation unused.
* @param key unused
* @param data unused
* @param src the source of the data
* @param dst the destination of the data
*/
@Override
public void handle(short operation, String key, Object data, Node src, Node dst) {
if (src != null && dst != null) {
LocationData locatonData = (LocationData) src.getUserData(LocationData.LOCATION_DATA_KEY);
if (locatonData != null) {
dst.setUserData(LocationData.LOCATION_DATA_KEY, locatonData, dataHandler);
}
}
}
}
}
| gpl-2.0 |
BackupTheBerlios/arara-svn | core/trunk/src/main/java/net/indrix/arara/servlets/pagination/SoundBySpeciePaginationController.java | 1289 | package net.indrix.arara.servlets.pagination;
import java.sql.SQLException;
import java.util.List;
import net.indrix.arara.dao.DatabaseDownException;
public class SoundBySpeciePaginationController extends
SoundPaginationController {
/**
* Creates a new PaginationController object, with the given number of elements per page, and
* with the flag identification
*
* @param soundsPerPage The amount of sounds per page
* @param identification The flag for identification
*/
public SoundBySpeciePaginationController(int soundsPerPage, boolean identification) {
super(soundsPerPage, identification);
}
@Override
protected List retrieveAllData() throws DatabaseDownException, SQLException {
logger.debug("SoundBySpeciePaginationController.retrieveAllData : retrieving all sounds...");
List listOfSounds = null;
if (id != -1){
listOfSounds = model.retrieveIDsForSpecie(getId());
} else {
listOfSounds = model.retrieveIDsForSpecieName(getText());
}
logger.debug("SoundBySpeciePaginationController.retrieveAllData : " + listOfSounds.size() + " sounds retrieved...");
return listOfSounds;
}
}
| gpl-2.0 |
Disguiser-w/SE2 | ELS_SERVICE/src/main/java/dataservice/businessdataservice/BusinessDataService.java | 5469 | package dataservice.businessdataservice;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import po.BusinessPO;
import po.DistributeReceiptPO;
import po.DriverPO;
import po.EnVehicleReceiptPO;
import po.GatheringReceiptPO;
import po.OrderAcceptReceiptPO;
import po.OrganizationPO;
import po.VehiclePO;
/**
* BusinessData
*/
public interface BusinessDataService extends Remote {
// 根据营业厅ID(找到文件)和营业厅业务员ID(查找文件内容),ID为null就返回第一个
public BusinessPO getBusinessInfo(String organizationID, String ID) throws RemoteException;
// 根据营业厅ID和车辆ID查询车辆PO
public VehiclePO getVehicleInfo(String organizationID, String vehicleID) throws RemoteException;
// 营业厅每日一个,每日早上8点发货一次
public boolean addReceipt(String organizationID, OrderAcceptReceiptPO po) throws RemoteException;
// 获得某营业厅的全部车辆信息
public ArrayList<VehiclePO> getVehicleInfos(String organizationID) throws RemoteException;
// 添加装车单到今日装车单文件中
public boolean addEnVehicleReceipt(String organizationID, ArrayList<EnVehicleReceiptPO> pos) throws RemoteException;
// 增加一个车辆信息VehiclePO到VehiclePOList中
public boolean addVehicle(String organizationID, VehiclePO po) throws RemoteException;
// 删除VehiclePOList中的一个车辆信息VehiclePO
public boolean deleteVehicle(String organizationID, VehiclePO po) throws RemoteException;
// 修改VehiclePOList中的一个车辆信息VehiclePO
public boolean modifyVehicle(String organizationID, VehiclePO po) throws RemoteException;
// 返回本营业厅司机信息列表
public ArrayList<DriverPO> getDriverInfos(String organizationID) throws RemoteException;
// 增加一个GatheringReceipt到本营业厅今日的文件中,一天也就一个
public boolean addGatheringReceipt(String organizationID, GatheringReceiptPO grp) throws RemoteException;
// 获得今日本营业厅OrderAcceptReceiptPO的个数
public int getNumOfOrderAcceptReceipt(String organizationID) throws RemoteException;
// 返回规定日期的所有GatheringReceipt,time格式 2015-11-23
public ArrayList<GatheringReceiptPO> getGatheringReceipt(String time) throws RemoteException;
public ArrayList<GatheringReceiptPO> getGatheringReceiptByHallID(String organization) throws RemoteException;
public ArrayList<GatheringReceiptPO> getGatheringReceiptByBoth(String organization, String time)
throws RemoteException;
// 增加一个DistributeOrder到本营业厅今日的文件中,一天也就一个
public boolean addDistributeReceipt(String organizationID, DistributeReceiptPO po) throws RemoteException;
// 查照死机
public DriverPO getDriverInfo(String organizationID, String ID) throws RemoteException;
// 增加一个司机到本营业厅
public boolean addDriver(String organizationID, DriverPO po) throws RemoteException;
// 删除一个司机到本营业厅
public boolean deleteDriver(String organizationID, DriverPO po) throws RemoteException;
// 修改本营业厅该司机信息
public boolean modifyDriver(String organizationID, DriverPO po) throws RemoteException;
/**
* Lizi 收款单
*/
public ArrayList<GatheringReceiptPO> getSubmittedGatheringReceiptInfo() throws RemoteException;
/**
* Lizi 派件单
*/
public ArrayList<DistributeReceiptPO> getSubmittedDistributeReceiptInfo() throws RemoteException;
/**
* Lizi 装车
*/
public ArrayList<EnVehicleReceiptPO> getSubmittedEnVehicleReceiptInfo() throws RemoteException;
/**
* Lizi 到达单
*/
public ArrayList<OrderAcceptReceiptPO> getSubmittedOrderAcceptReceiptInfo() throws RemoteException;
public void saveDistributeReceiptInfo(DistributeReceiptPO po) throws RemoteException;
public void saveOrderAcceptReceiptInfo(OrderAcceptReceiptPO po) throws RemoteException;
public void saveEnVehicleReceiptInfo(EnVehicleReceiptPO po) throws RemoteException;
public void saveGatheringReceiptInfo(GatheringReceiptPO po) throws RemoteException;
//
public boolean addDriverTime(String organizationID, String driverID) throws RemoteException;
public ArrayList<OrganizationPO> getOrganizationInfos() throws RemoteException;
public int getNumOfVehicles(String organizationID) throws RemoteException;
public int getNumOfDrivers(String organizationID) throws RemoteException;
public int getNumOfEnVechileReceipt(String organizationID) throws RemoteException;
public int getNumOfOrderReceipt(String organizationID) throws RemoteException;
public int getNumOfOrderDistributeReceipt(String organizationID) throws RemoteException;
//
// /**
// * 返回待转运的订单的列表
// */
// public ArrayList<OrderPO> getTransferOrders() throws RemoteException;
//
// /**
// * 返回待派送的订单的列表
// */
// public ArrayList<VehiclePO> getFreeVehicles() throws RemoteException;
//
// /**
// * 生成装车单
// */
// public boolean addEnVehicleReceiptPO(EnVehicleReceiptPO po) throws
// RemoteException;
//
// /**
// * 获取收款汇总单
// */
// public ArrayList<GatheringReceiptPO> getGatheringReceiptPOs() throws
// RemoteException;
//
// /**
// * 增加收货单
// */
// public boolean addReceipt(OrderAcceptReceiptPO po) throws
// RemoteException;
//
// /**
// * 增加收款汇总单
// */
//
// public boolean addGatheringReceipt(GatheringReceiptPO po);
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/CFGregorianDate.java | 755 | package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CFGregorianDate {
/*
* Variables
*/
public int year;
public byte month;
public byte day;
public byte hour;
public byte minute;
public double second;
/*
* Constructors
*/
/** Default constructor */
CFGregorianDate() {}
/*
* Instance methods
*/
/**
* Boolean CFGregorianDateIsValid(CFGregorianDate gdate, CFOptionFlags unitFlags);
*/
public byte isValid(long unitFlags){
throw new RuntimeException("Stub");
}
/**
* CFAbsoluteTime CFGregorianDateGetAbsoluteTime(CFGregorianDate gdate, CFTimeZoneRef tz);
*/
public double getAbsoluteTime(NSTimeZone tz){
throw new RuntimeException("Stub");
}
}
| gpl-2.0 |
Beau-M/document-management-system | src/main/java/com/openkm/frontend/client/bean/GWTUserConfig.java | 1807 | /**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2017 Paco Avila & Josep Llort
* <p>
* No bytes were intentionally harmed during the development of this application.
* <p>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.bean;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* @author jllort
*
*/
public class GWTUserConfig implements IsSerializable {
private String user = "";
private String homePath = "";
private String homeType = "";
private String homeNode = "";
/**
* GWTUserConfig
*/
public GWTUserConfig() {
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getHomePath() {
return homePath;
}
public void setHomePath(String homePath) {
this.homePath = homePath;
}
public String getHomeType() {
return homeType;
}
public void setHomeType(String homeType) {
this.homeType = homeType;
}
public String getHomeNode() {
return homeNode;
}
public void setHomeNode(String homeNode) {
this.homeNode = homeNode;
}
}
| gpl-2.0 |
netizen539/civcraft | civcraft/src/com/avrgaming/civcraft/endgame/EndConditionScience.java | 3584 | package com.avrgaming.civcraft.endgame;
import java.util.ArrayList;
import com.avrgaming.civcraft.main.CivGlobal;
import com.avrgaming.civcraft.main.CivMessage;
import com.avrgaming.civcraft.object.Civilization;
import com.avrgaming.civcraft.object.Town;
import com.avrgaming.civcraft.sessiondb.SessionEntry;
import com.avrgaming.civcraft.structure.wonders.Wonder;
public class EndConditionScience extends EndGameCondition {
String techname;
@Override
public void onLoad() {
techname = this.getString("tech");
}
@Override
public boolean check(Civilization civ) {
if (!civ.hasTechnology(techname)) {
return false;
}
if (civ.isAdminCiv()) {
return false;
}
boolean hasGreatLibrary = false;
for (Town town : civ.getTowns()) {
if (town.getMotherCiv() != null) {
continue;
}
for (Wonder wonder :town.getWonders()) {
if (wonder.isActive()) {
if (wonder.getConfigId().equals("w_greatlibrary")) {
hasGreatLibrary = true;
break;
}
}
}
if (hasGreatLibrary) {
break;
}
}
if (!hasGreatLibrary) {
return false;
}
return true;
}
@Override
public boolean finalWinCheck(Civilization civ) {
Civilization rival = getMostAccumulatedBeakers();
if (rival != civ) {
CivMessage.global(civ.getName()+" doesn't have enough beakers for a scientific victory. The rival civilization of "+rival.getName()+" has more!");
return false;
}
return true;
}
public Civilization getMostAccumulatedBeakers() {
double most = 0;
Civilization mostCiv = null;
for (Civilization civ : CivGlobal.getCivs()) {
double beakers = getExtraBeakersInCiv(civ);
if (beakers > most) {
most = beakers;
mostCiv = civ;
}
}
return mostCiv;
}
@Override
public String getSessionKey() {
return "endgame:science";
}
@Override
protected void onWarDefeat(Civilization civ) {
/* remove any extra beakers we might have. */
CivGlobal.getSessionDB().delete_all(getBeakerSessionKey(civ));
civ.removeTech(techname);
CivMessage.sendCiv(civ, "We were defeated while trying to achieve a science victory! We've lost all of our accumulated beakers and our victory tech!");
civ.save();
this.onFailure(civ);
}
public static String getBeakerSessionKey(Civilization civ) {
return "endgame:sciencebeakers:"+civ.getId();
}
public double getExtraBeakersInCiv(Civilization civ) {
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ));
if (entries.size() == 0) {
return 0;
}
return Double.valueOf(entries.get(0).value);
}
public void addExtraBeakersToCiv(Civilization civ, double beakers) {
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ));
double current = 0;
if (entries.size() == 0) {
CivGlobal.getSessionDB().add(getBeakerSessionKey(civ), ""+beakers, civ.getId(), 0, 0);
current += beakers;
} else {
current = Double.valueOf(entries.get(0).value);
current += beakers;
CivGlobal.getSessionDB().update(entries.get(0).request_id, entries.get(0).key, ""+current);
}
//DecimalFormat df = new DecimalFormat("#.#");
//CivMessage.sendCiv(civ, "Added "+df.format(beakers)+" beakers to our scientific victory! We now have "+df.format(current)+" beakers saved up.");
}
public static Double getBeakersFor(Civilization civ) {
ArrayList<SessionEntry> entries = CivGlobal.getSessionDB().lookup(getBeakerSessionKey(civ));
if (entries.size() == 0) {
return 0.0;
} else {
return Double.valueOf(entries.get(0).value);
}
}
}
| gpl-2.0 |
pron/visage-compiler | visagejdi/src/org/visage/jdi/request/VisageStepRequest.java | 2405 | /*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package org.visage.jdi.request;
import org.visage.jdi.VisageThreadReference;
import org.visage.jdi.VisageVirtualMachine;
import org.visage.jdi.VisageWrapper;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.request.StepRequest;
/**
*
* @author sundar
*/
public class VisageStepRequest extends VisageEventRequest implements StepRequest {
public VisageStepRequest(VisageVirtualMachine visagevm, StepRequest underlying) {
super(visagevm, underlying);
}
public void addClassExclusionFilter(String arg0) {
underlying().addClassExclusionFilter(arg0);
}
public void addClassFilter(ReferenceType arg0) {
underlying().addClassFilter(VisageWrapper.unwrap(arg0));
}
public void addClassFilter(String arg0) {
underlying().addClassFilter(arg0);
}
public void addInstanceFilter(ObjectReference ref) {
underlying().addInstanceFilter(VisageWrapper.unwrap(ref));
}
public int depth() {
return underlying().depth();
}
public int size() {
return underlying().size();
}
public VisageThreadReference thread() {
return VisageWrapper.wrap(virtualMachine(), underlying().thread());
}
@Override
protected StepRequest underlying() {
return (StepRequest) super.underlying();
}
}
| gpl-2.0 |
siggouroglou/innovathens | webnew/src/main/java/gr/softaware/lib_1_3/data/convert/csv/CsvGenerator.java | 1153 | package gr.softaware.lib_1_3.data.convert.csv;
import java.util.List;
/**
*
* @author siggouroglou
* @param <T> A class that implements the CsvGenerationModel interface.
*/
final public class CsvGenerator<T extends CsvGenerationModel> {
private final List<CsvGenerationModel> modelList;
public CsvGenerator(List<T> modelList) {
this.modelList = (List<CsvGenerationModel>)modelList;
}
public StringBuilder getContent() {
return getContent("\t", "\\t");
}
public StringBuilder getContent(String separator, String separatorAsString) {
StringBuilder builder = new StringBuilder();
// First line contains the separator.
builder.append("sep=").append(separatorAsString).append("\n");
// Get the header.
if(!modelList.isEmpty()) {
builder.append(modelList.get(0).toCsvFormattedHeader(separator)).append("\n");
}
// Get the data.
modelList.stream().forEach((model) -> {
builder.append(model.toCsvFormattedRow(separator)).append("\n");
});
return builder;
}
}
| gpl-2.0 |
simontb/kitcard-reader | src/de/Ox539/kitcard/reader/ReadCardTask.java | 3022 | /*
* This file is part of KITCard Reader.
* Ⓒ 2012 Philipp Kern <phil@philkern.de>
*
* KITCard Reader is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* KITCard Reader is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KITCard Reader. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Ox539.kitcard.reader;
/**
* ReadCardTask: Read an NFC tag using the Wallet class asynchronously.
*
* This class provides the glue calling the Wallet class and passing
* the information back to the Android UI layer. Detailed error
* information is not provided yet.
*
* @author Philipp Kern <pkern@debian.org>
*/
import de.Ox539.kitcard.reader.Wallet.ReadCardResult;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.os.AsyncTask;
import android.widget.Toast;
public class ReadCardTask extends AsyncTask<Tag, Integer, Pair<ReadCardResult, Wallet>> {
private ScanActivity mActivity;
public ReadCardTask(ScanActivity activity) {
super();
this.mActivity = activity;
}
protected Pair<ReadCardResult, Wallet> doInBackground(Tag... tags) {
MifareClassic card = null;
try {
card = MifareClassic.get(tags[0]);
} catch (NullPointerException e) {
/* Error while reading card. This problem occurs on HTC devices from the ONE series with Android Lollipop (status of June 2015)
* Try to repair the tag.
*/
card = MifareClassic.get(MifareUtils.repairTag(tags[0]));
}
if(card == null)
return new Pair<ReadCardResult, Wallet>(null, null);
final Wallet wallet = new Wallet(card);
final ReadCardResult result = wallet.readCard();
return new Pair<ReadCardResult, Wallet>(result, wallet);
}
protected void onPostExecute(Pair<ReadCardResult, Wallet> data) {
ReadCardResult result = data.getValue0();
if(result == ReadCardResult.FAILURE) {
// read failed
Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_read_failed), Toast.LENGTH_LONG).show();
return;
} else if(result == ReadCardResult.OLD_STYLE_WALLET) {
// old-style wallet encountered
Toast.makeText(mActivity, mActivity.getResources().getString(R.string.kitcard_needs_reencode), Toast.LENGTH_LONG).show();
return;
}
final Wallet wallet = data.getValue1();
mActivity.updateCardNumber(wallet.getCardNumber());
mActivity.updateBalance(wallet.getCurrentBalance());
mActivity.updateLastTransaction(wallet.getLastTransactionValue());
mActivity.updateCardIssuer(wallet.getCardIssuer());
mActivity.updateCardType(wallet.getCardType());
}
}
| gpl-2.0 |
nareddyt/Bitter | app/src/main/java/gitmad/bitter/ui/CommentAdapter.java | 1425 | package gitmad.bitter.ui;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import gitmad.bitter.R;
import gitmad.bitter.model.Comment;
import gitmad.bitter.model.User;
import java.util.Map;
/**
* Created by prabh on 10/19/2015.
*/
public class CommentAdapter extends ArrayAdapter<Comment> {
private Comment[] comments;
private Map<Comment, User> commentAuthors;
public CommentAdapter(Context context, Comment[] comments, Map<Comment,
User> commentAuthors) {
super(context, 0, comments); // TODO is the zero here correct?
this.comments = comments;
this.commentAuthors = commentAuthors;
}
public View getView(int position, View convertView, ViewGroup parent) {
Comment comment = comments[position];
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout
.view_comment, parent, false);
}
TextView userText = (TextView) convertView.findViewById(R.id.user_text);
TextView commentText = (TextView) convertView.findViewById(R.id
.comment_text);
userText.setText(commentAuthors.get(comment).getName());
commentText.setText(comment.getText());
return convertView;
}
}
| gpl-2.0 |
petersalomonsen/frinika | src/com/frinika/tootX/midi/MidiHashUtil.java | 2069 | /*
* Created on 5 Sep 2007
*
* Copyright (c) 2004-2007 Paul John Leonard
*
* http://www.frinika.com
*
* This file is part of Frinika.
*
* Frinika is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* Frinika is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Frinika; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.frinika.tootX.midi;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.ShortMessage;
public class MidiHashUtil {
static public long hashValue(ShortMessage mess) {
byte data[] = mess.getMessage();
long cmd = mess.getCommand();
if (cmd == ShortMessage.PITCH_BEND) {
return ((long) data[0] << 8);
} else {
return (((long) data[0] << 8) + data[1]);
}
}
static public void hashDisp(long hash) {
long cntrl = hash & 0xFF;
long cmd = (hash >> 8) & 0xFF;
long chn = (hash >> 16) & 0xFF;
System.out.println(chn + " " + cmd + " " + cntrl);
}
static ShortMessage reconstructShortMessage(long hash, ShortMessage mess) {
if (mess == null) mess=new ShortMessage();
int status = (int) ((hash >> 8) & 0xFF);
int data1 = (int) (hash & 0xFF);
try {
mess.setMessage(status, data1, 0);
} catch (InvalidMidiDataException ex) {
Logger.getLogger(MidiHashUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return mess;
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/dbPort/Convert_PostgreSQL_Native.java | 393 | package org.compiere.dbPort;
import java.util.Collections;
import java.util.List;
/**
* Native PostgreSQL (pass-through) implementation of {@link Convert}
*
* @author tsa
*
*/
public final class Convert_PostgreSQL_Native extends Convert
{
@Override
protected final List<String> convertStatement(final String sqlStatement)
{
return Collections.singletonList(sqlStatement);
}
}
| gpl-2.0 |
psteinb/SPIM_Registration | src/main/java/mpicbg/spim/segmentation/InteractiveDoG.java | 30536 | package mpicbg.spim.segmentation;
import fiji.tool.SliceListener;
import fiji.tool.SliceObserver;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.WindowManager;
import ij.gui.OvalRoi;
import ij.gui.Overlay;
import ij.gui.Roi;
import ij.io.Opener;
import ij.plugin.PlugIn;
import ij.process.ByteProcessor;
import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Rectangle;
import java.awt.Scrollbar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import mpicbg.imglib.algorithm.gauss.GaussianConvolutionReal;
import mpicbg.imglib.algorithm.math.LocalizablePoint;
import mpicbg.imglib.algorithm.scalespace.DifferenceOfGaussianPeak;
import mpicbg.imglib.algorithm.scalespace.DifferenceOfGaussianReal1;
import mpicbg.imglib.algorithm.scalespace.SubpixelLocalization;
import mpicbg.imglib.container.array.ArrayContainerFactory;
import mpicbg.imglib.cursor.LocalizableByDimCursor;
import mpicbg.imglib.cursor.LocalizableCursor;
import mpicbg.imglib.image.Image;
import mpicbg.imglib.image.ImageFactory;
import mpicbg.imglib.image.display.imagej.ImageJFunctions;
import mpicbg.imglib.multithreading.SimpleMultiThreading;
import mpicbg.imglib.outofbounds.OutOfBoundsStrategyMirrorFactory;
import mpicbg.imglib.outofbounds.OutOfBoundsStrategyValueFactory;
import mpicbg.imglib.type.numeric.real.FloatType;
import mpicbg.imglib.util.Util;
import mpicbg.spim.io.IOFunctions;
import mpicbg.spim.registration.ViewStructure;
import mpicbg.spim.registration.detection.DetectionSegmentation;
import net.imglib2.RandomAccess;
import net.imglib2.exception.ImgLibException;
import net.imglib2.img.ImagePlusAdapter;
import net.imglib2.img.imageplus.FloatImagePlus;
import net.imglib2.view.Views;
import spim.process.fusion.FusionHelper;
/**
* An interactive tool for determining the required sigma and peak threshold
*
* @author Stephan Preibisch
*/
public class InteractiveDoG implements PlugIn
{
final int extraSize = 40;
final int scrollbarSize = 1000;
float sigma = 0.5f;
float sigma2 = 0.5f;
float threshold = 0.0001f;
// steps per octave
public static int standardSenstivity = 4;
int sensitivity = standardSenstivity;
float imageSigma = 0.5f;
float sigmaMin = 0.5f;
float sigmaMax = 10f;
int sigmaInit = 300;
float thresholdMin = 0.0001f;
float thresholdMax = 1f;
int thresholdInit = 500;
double minIntensityImage = Double.NaN;
double maxIntensityImage = Double.NaN;
SliceObserver sliceObserver;
RoiListener roiListener;
ImagePlus imp;
int channel = 0;
Rectangle rectangle;
Image<FloatType> img;
FloatImagePlus< net.imglib2.type.numeric.real.FloatType > source;
ArrayList<DifferenceOfGaussianPeak<FloatType>> peaks;
Color originalColor = new Color( 0.8f, 0.8f, 0.8f );
Color inactiveColor = new Color( 0.95f, 0.95f, 0.95f );
public Rectangle standardRectangle;
boolean isComputing = false;
boolean isStarted = false;
boolean enableSigma2 = false;
boolean sigma2IsAdjustable = true;
boolean lookForMinima = false;
boolean lookForMaxima = true;
public static enum ValueChange { SIGMA, THRESHOLD, SLICE, ROI, MINMAX, ALL }
boolean isFinished = false;
boolean wasCanceled = false;
public boolean isFinished() { return isFinished; }
public boolean wasCanceled() { return wasCanceled; }
public double getInitialSigma() { return sigma; }
public void setInitialSigma( final float value )
{
sigma = value;
sigmaInit = computeScrollbarPositionFromValue( sigma, sigmaMin, sigmaMax, scrollbarSize );
}
public double getSigma2() { return sigma2; }
public double getThreshold() { return threshold; }
public void setThreshold( final float value )
{
threshold = value;
final double log1001 = Math.log10( scrollbarSize + 1);
thresholdInit = (int)Math.round( 1001-Math.pow(10, -(((threshold - thresholdMin)/(thresholdMax-thresholdMin))*log1001) + log1001 ) );
}
public boolean getSigma2WasAdjusted() { return enableSigma2; }
public boolean getLookForMaxima() { return lookForMaxima; }
public boolean getLookForMinima() { return lookForMinima; }
public void setLookForMaxima( final boolean lookForMaxima ) { this.lookForMaxima = lookForMaxima; }
public void setLookForMinima( final boolean lookForMinima ) { this.lookForMinima = lookForMinima; }
public void setSigmaMax( final float sigmaMax ) { this.sigmaMax = sigmaMax; }
public void setSigma2isAdjustable( final boolean state ) { sigma2IsAdjustable = state; }
// for the case that it is needed again, we can save one conversion
public FloatImagePlus< net.imglib2.type.numeric.real.FloatType > getConvertedImage() { return source; }
public InteractiveDoG( final ImagePlus imp, final int channel )
{
this.imp = imp;
this.channel = channel;
}
public InteractiveDoG( final ImagePlus imp ) { this.imp = imp; }
public InteractiveDoG() {}
public void setMinIntensityImage( final double min ) { this.minIntensityImage = min; }
public void setMaxIntensityImage( final double max ) { this.maxIntensityImage = max; }
@Override
public void run( String arg )
{
if ( imp == null )
imp = WindowManager.getCurrentImage();
standardRectangle = new Rectangle( imp.getWidth()/4, imp.getHeight()/4, imp.getWidth()/2, imp.getHeight()/2 );
if ( imp.getType() == ImagePlus.COLOR_RGB || imp.getType() == ImagePlus.COLOR_256 )
{
IJ.log( "Color images are not supported, please convert to 8, 16 or 32-bit grayscale" );
return;
}
Roi roi = imp.getRoi();
if ( roi == null )
{
//IJ.log( "A rectangular ROI is required to define the area..." );
imp.setRoi( standardRectangle );
roi = imp.getRoi();
}
if ( roi.getType() != Roi.RECTANGLE )
{
IJ.log( "Only rectangular rois are supported..." );
return;
}
// copy the ImagePlus into an ArrayImage<FloatType> for faster access
source = convertToFloat( imp, channel, 0, minIntensityImage, maxIntensityImage );
// show the interactive kit
displaySliders();
// add listener to the imageplus slice slider
sliceObserver = new SliceObserver( imp, new ImagePlusListener() );
// compute first version
updatePreview( ValueChange.ALL );
isStarted = true;
// check whenever roi is modified to update accordingly
roiListener = new RoiListener();
imp.getCanvas().addMouseListener( roiListener );
}
/**
* Updates the Preview with the current parameters (sigma, threshold, roi, slicenumber)
*
* @param change - what did change
*/
protected void updatePreview( final ValueChange change )
{
// check if Roi changed
boolean roiChanged = false;
Roi roi = imp.getRoi();
if ( roi == null || roi.getType() != Roi.RECTANGLE )
{
imp.setRoi( new Rectangle( standardRectangle ) );
roi = imp.getRoi();
roiChanged = true;
}
final Rectangle rect = roi.getBounds();
if ( roiChanged || img == null || change == ValueChange.SLICE ||
rect.getMinX() != rectangle.getMinX() || rect.getMaxX() != rectangle.getMaxX() ||
rect.getMinY() != rectangle.getMinY() || rect.getMaxY() != rectangle.getMaxY() )
{
rectangle = rect;
img = extractImage( source, rectangle, extraSize );
roiChanged = true;
}
// if we got some mouse click but the ROI did not change we can return
if ( !roiChanged && change == ValueChange.ROI )
{
isComputing = false;
return;
}
// compute the Difference Of Gaussian if necessary
if ( peaks == null || roiChanged || change == ValueChange.SIGMA || change == ValueChange.SLICE || change == ValueChange.ALL )
{
//
// Compute the Sigmas for the gaussian folding
//
final float k, K_MIN1_INV;
final float[] sigma, sigmaDiff;
if ( enableSigma2 )
{
sigma = new float[ 2 ];
sigma[ 0 ] = this.sigma;
sigma[ 1 ] = this.sigma2;
k = sigma[ 1 ] / sigma[ 0 ];
K_MIN1_INV = DetectionSegmentation.computeKWeight( k );
sigmaDiff = DetectionSegmentation.computeSigmaDiff( sigma, imageSigma );
}
else
{
k = (float)DetectionSegmentation.computeK( sensitivity );
K_MIN1_INV = DetectionSegmentation.computeKWeight( k );
sigma = DetectionSegmentation.computeSigma( k, this.sigma );
sigmaDiff = DetectionSegmentation.computeSigmaDiff( sigma, imageSigma );
}
// the upper boundary
this.sigma2 = sigma[ 1 ];
final DifferenceOfGaussianReal1<FloatType> dog = new DifferenceOfGaussianReal1<FloatType>( img, new OutOfBoundsStrategyValueFactory<FloatType>(), sigmaDiff[ 0 ], sigmaDiff[ 1 ], thresholdMin/4, K_MIN1_INV );
dog.setKeepDoGImage( true );
dog.process();
final SubpixelLocalization<FloatType> subpixel = new SubpixelLocalization<FloatType>( dog.getDoGImage(), dog.getPeaks() );
subpixel.process();
peaks = dog.getPeaks();
}
// extract peaks to show
Overlay o = imp.getOverlay();
if ( o == null )
{
o = new Overlay();
imp.setOverlay( o );
}
o.clear();
for ( final DifferenceOfGaussianPeak<FloatType> peak : peaks )
{
if ( ( peak.isMax() && lookForMaxima ) || ( peak.isMin() && lookForMinima ) )
{
final float x = peak.getPosition( 0 );
final float y = peak.getPosition( 1 );
if ( Math.abs( peak.getValue().get() ) > threshold &&
x >= extraSize/2 && y >= extraSize/2 &&
x < rect.width+extraSize/2 && y < rect.height+extraSize/2 )
{
final OvalRoi or = new OvalRoi( Util.round( x - sigma ) + rect.x - extraSize/2, Util.round( y - sigma ) + rect.y - extraSize/2, Util.round( sigma+sigma2 ), Util.round( sigma+sigma2 ) );
if ( peak.isMax() )
or.setStrokeColor( Color.green );
else if ( peak.isMin() )
or.setStrokeColor( Color.red );
o.add( or );
}
}
}
imp.updateAndDraw();
isComputing = false;
}
public static float computeSigma2( final float sigma1, final int sensitivity )
{
final float k = (float)DetectionSegmentation.computeK( sensitivity );
final float[] sigma = DetectionSegmentation.computeSigma( k, sigma1 );
return sigma[ 1 ];
}
/**
* Extract the current 2d region of interest from the souce image
*
* @param source - the source image, a {@link Image} which is a copy of the {@link ImagePlus}
* @param rectangle - the area of interest
* @param extraSize - the extra size around so that detections at the border of the roi are not messed up
* @return
*/
protected Image<FloatType> extractImage( final FloatImagePlus< net.imglib2.type.numeric.real.FloatType > source, final Rectangle rectangle, final int extraSize )
{
final Image<FloatType> img = new ImageFactory<FloatType>( new FloatType(), new ArrayContainerFactory() ).createImage( new int[]{ rectangle.width+extraSize, rectangle.height+extraSize } );
final int offsetX = rectangle.x - extraSize/2;
final int offsetY = rectangle.y - extraSize/2;
final int[] location = new int[ source.numDimensions() ];
if ( location.length > 2 )
location[ 2 ] = (imp.getCurrentSlice()-1)/imp.getNChannels();
final LocalizableCursor<FloatType> cursor = img.createLocalizableCursor();
final RandomAccess<net.imglib2.type.numeric.real.FloatType> positionable;
if ( offsetX >= 0 && offsetY >= 0 &&
offsetX + img.getDimension( 0 ) < source.dimension( 0 ) &&
offsetY + img.getDimension( 1 ) < source.dimension( 1 ) )
{
// it is completely inside so we need no outofbounds for copying
positionable = source.randomAccess();
}
else
{
positionable = Views.extendMirrorSingle( source ).randomAccess();
}
while ( cursor.hasNext() )
{
cursor.fwd();
cursor.getPosition( location );
location[ 0 ] += offsetX;
location[ 1 ] += offsetY;
positionable.setPosition( location );
cursor.getType().set( positionable.get().get() );
}
return img;
}
/**
* Normalize and make a copy of the {@link ImagePlus} into an {@link Image}>FloatType< for faster access when copying the slices
*
* @param imp - the {@link ImagePlus} input image
* @return - the normalized copy [0...1]
*/
public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > convertToFloat( final ImagePlus imp, int channel, int timepoint )
{
return convertToFloat( imp, channel, timepoint, Double.NaN, Double.NaN );
}
public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > convertToFloat( final ImagePlus imp, int channel, int timepoint, final double min, final double max )
{
// stupid 1-offset of imagej
channel++;
timepoint++;
final int h = imp.getHeight();
final int w = imp.getWidth();
final ArrayList< float[] > img = new ArrayList< float[] >();
if ( imp.getProcessor() instanceof FloatProcessor )
{
for ( int z = 0; z < imp.getNSlices(); ++z )
img.add( ( (float[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels() ).clone() );
}
else if ( imp.getProcessor() instanceof ByteProcessor )
{
for ( int z = 0; z < imp.getNSlices(); ++z )
{
final byte[] pixels = (byte[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels();
final float[] pixelsF = new float[ pixels.length ];
for ( int i = 0; i < pixels.length; ++i )
pixelsF[ i ] = pixels[ i ] & 0xff;
img.add( pixelsF );
}
}
else if ( imp.getProcessor() instanceof ShortProcessor )
{
for ( int z = 0; z < imp.getNSlices(); ++z )
{
final short[] pixels = (short[])imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) ).getPixels();
final float[] pixelsF = new float[ pixels.length ];
for ( int i = 0; i < pixels.length; ++i )
pixelsF[ i ] = pixels[ i ] & 0xffff;
img.add( pixelsF );
}
}
else // some color stuff or so
{
for ( int z = 0; z < imp.getNSlices(); ++z )
{
final ImageProcessor ip = imp.getStack().getProcessor( imp.getStackIndex( channel, z + 1, timepoint ) );
final float[] pixelsF = new float[ w * h ];
int i = 0;
for ( int y = 0; y < h; ++y )
for ( int x = 0; x < w; ++x )
pixelsF[ i++ ] = ip.getPixelValue( x, y );
img.add( pixelsF );
}
}
final FloatImagePlus< net.imglib2.type.numeric.real.FloatType > i = createImgLib2( img, w, h );
if ( Double.isNaN( min ) || Double.isNaN( max ) || Double.isInfinite( min ) || Double.isInfinite( max ) || min == max )
FusionHelper.normalizeImage( i );
else
FusionHelper.normalizeImage( i, (float)min, (float)max );
return i;
}
public static FloatImagePlus< net.imglib2.type.numeric.real.FloatType > createImgLib2( final List< float[] > img, final int w, final int h )
{
final ImagePlus imp;
if ( img.size() > 1 )
{
final ImageStack stack = new ImageStack( w, h );
for ( int z = 0; z < img.size(); ++z )
stack.addSlice( new FloatProcessor( w, h, img.get( z ) ) );
imp = new ImagePlus( "ImgLib2 FloatImagePlus (3d)", stack );
}
else
{
imp = new ImagePlus( "ImgLib2 FloatImagePlus (2d)", new FloatProcessor( w, h, img.get( 0 ) ) );
}
return ImagePlusAdapter.wrapFloat( imp );
}
/**
* Instantiates the panel for adjusting the paramters
*/
protected void displaySliders()
{
final Frame frame = new Frame("Adjust Difference-of-Gaussian Values");
frame.setSize( 400, 330 );
/* Instantiation */
final GridBagLayout layout = new GridBagLayout();
final GridBagConstraints c = new GridBagConstraints();
final Scrollbar sigma1 = new Scrollbar ( Scrollbar.HORIZONTAL, sigmaInit, 10, 0, 10 + scrollbarSize );
this.sigma = computeValueFromScrollbarPosition( sigmaInit, sigmaMin, sigmaMax, scrollbarSize);
final Scrollbar threshold = new Scrollbar ( Scrollbar.HORIZONTAL, thresholdInit, 10, 0, 10 + scrollbarSize );
final float log1001 = (float)Math.log10( scrollbarSize + 1);
this.threshold = thresholdMin + ( (log1001 - (float)Math.log10(1001-thresholdInit))/log1001 ) * (thresholdMax-thresholdMin);
this.sigma2 = computeSigma2( this.sigma, this.sensitivity );
final int sigma2init = computeScrollbarPositionFromValue( this.sigma2, sigmaMin, sigmaMax, scrollbarSize );
final Scrollbar sigma2 = new Scrollbar ( Scrollbar.HORIZONTAL, sigma2init, 10, 0, 10 + scrollbarSize );
final Label sigmaText1 = new Label( "Sigma 1 = " + this.sigma, Label.CENTER );
final Label sigmaText2 = new Label( "Sigma 2 = " + this.sigma2, Label.CENTER );
final Label thresholdText = new Label( "Threshold = " + this.threshold, Label.CENTER );
final Button apply = new Button( "Apply to Stack (will take some time)" );
final Button button = new Button( "Done" );
final Button cancel = new Button( "Cancel" );
final Checkbox sigma2Enable = new Checkbox( "Enable Manual Adjustment of Sigma 2 ", enableSigma2 );
final Checkbox min = new Checkbox( "Look for Minima (red)", lookForMinima );
final Checkbox max = new Checkbox( "Look for Maxima (green)", lookForMaxima );
/* Location */
frame.setLayout( layout );
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
frame.add ( sigma1, c );
++c.gridy;
frame.add( sigmaText1, c );
++c.gridy;
frame.add ( sigma2, c );
++c.gridy;
frame.add( sigmaText2, c );
++c.gridy;
c.insets = new Insets(0,65,0,65);
frame.add( sigma2Enable, c );
++c.gridy;
c.insets = new Insets(10,0,0,0);
frame.add ( threshold, c );
c.insets = new Insets(0,0,0,0);
++c.gridy;
frame.add( thresholdText, c );
++c.gridy;
c.insets = new Insets(0,130,0,75);
frame.add( min, c );
++c.gridy;
c.insets = new Insets(0,125,0,75);
frame.add( max, c );
++c.gridy;
c.insets = new Insets(0,75,0,75);
frame.add( apply, c );
++c.gridy;
c.insets = new Insets(10,150,0,150);
frame.add( button, c );
++c.gridy;
c.insets = new Insets(10,150,0,150);
frame.add( cancel, c );
/* Configuration */
sigma1.addAdjustmentListener( new SigmaListener( sigmaText1, sigmaMin, sigmaMax, scrollbarSize, sigma1, sigma2, sigmaText2 ) );
sigma2.addAdjustmentListener( new Sigma2Listener( sigmaMin, sigmaMax, scrollbarSize, sigma2, sigmaText2 ) );
threshold.addAdjustmentListener( new ThresholdListener( thresholdText, thresholdMin, thresholdMax ) );
button.addActionListener( new FinishedButtonListener( frame, false ) );
cancel.addActionListener( new FinishedButtonListener( frame, true ) );
apply.addActionListener( new ApplyButtonListener() );
min.addItemListener( new MinListener() );
max.addItemListener( new MaxListener() );
sigma2Enable.addItemListener( new EnableListener( sigma2, sigmaText2 ) );
if ( !sigma2IsAdjustable )
sigma2Enable.setEnabled( false );
frame.addWindowListener( new FrameListener( frame ) );
frame.setVisible( true );
originalColor = sigma2.getBackground();
sigma2.setBackground( inactiveColor );
sigmaText1.setFont( sigmaText1.getFont().deriveFont( Font.BOLD ) );
thresholdText.setFont( thresholdText.getFont().deriveFont( Font.BOLD ) );
}
protected class EnableListener implements ItemListener
{
final Scrollbar sigma2;
final Label sigmaText2;
public EnableListener( final Scrollbar sigma2, final Label sigmaText2 )
{
this.sigmaText2 = sigmaText2;
this.sigma2 = sigma2;
}
@Override
public void itemStateChanged( final ItemEvent arg0 )
{
if ( arg0.getStateChange() == ItemEvent.DESELECTED )
{
sigmaText2.setFont( sigmaText2.getFont().deriveFont( Font.PLAIN ) );
sigma2.setBackground( inactiveColor );
enableSigma2 = false;
}
else if ( arg0.getStateChange() == ItemEvent.SELECTED )
{
sigmaText2.setFont( sigmaText2.getFont().deriveFont( Font.BOLD ) );
sigma2.setBackground( originalColor );
enableSigma2 = true;
}
}
}
protected class MinListener implements ItemListener
{
@Override
public void itemStateChanged( final ItemEvent arg0 )
{
boolean oldState = lookForMinima;
if ( arg0.getStateChange() == ItemEvent.DESELECTED )
lookForMinima = false;
else if ( arg0.getStateChange() == ItemEvent.SELECTED )
lookForMinima = true;
if ( lookForMinima != oldState )
{
while ( isComputing )
SimpleMultiThreading.threadWait( 10 );
updatePreview( ValueChange.MINMAX );
}
}
}
protected class MaxListener implements ItemListener
{
@Override
public void itemStateChanged( final ItemEvent arg0 )
{
boolean oldState = lookForMaxima;
if ( arg0.getStateChange() == ItemEvent.DESELECTED )
lookForMaxima = false;
else if ( arg0.getStateChange() == ItemEvent.SELECTED )
lookForMaxima = true;
if ( lookForMaxima != oldState )
{
while ( isComputing )
SimpleMultiThreading.threadWait( 10 );
updatePreview( ValueChange.MINMAX );
}
}
}
/**
* Tests whether the ROI was changed and will recompute the preview
*
* @author Stephan Preibisch
*/
protected class RoiListener implements MouseListener
{
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased( final MouseEvent e )
{
// here the ROI might have been modified, let's test for that
final Roi roi = imp.getRoi();
if ( roi == null || roi.getType() != Roi.RECTANGLE )
return;
while ( isComputing )
SimpleMultiThreading.threadWait( 10 );
updatePreview( ValueChange.ROI );
}
}
protected class ApplyButtonListener implements ActionListener
{
@Override
public void actionPerformed( final ActionEvent arg0 )
{
ImagePlus imp;
try
{
imp = source.getImagePlus();
}
catch (ImgLibException e)
{
imp = null;
e.printStackTrace();
}
// convert ImgLib2 image to ImgLib1 image via the imageplus
final Image< FloatType > source = ImageJFunctions.wrapFloat( imp );
IOFunctions.println( "Computing DoG ... " );
// test the parameters on the complete stack
final ArrayList<DifferenceOfGaussianPeak<FloatType>> peaks =
DetectionSegmentation.extractBeadsLaPlaceImgLib(
source,
new OutOfBoundsStrategyMirrorFactory<FloatType>(),
imageSigma,
sigma,
sigma2,
threshold,
threshold/4,
lookForMaxima,
lookForMinima,
ViewStructure.DEBUG_MAIN );
IOFunctions.println( "Drawing DoG result ... " );
// display as extra image
Image<FloatType> detections = source.createNewImage();
final LocalizableByDimCursor<FloatType> c = detections.createLocalizableByDimCursor();
for ( final DifferenceOfGaussianPeak<FloatType> peak : peaks )
{
final LocalizablePoint p = new LocalizablePoint( new float[]{ peak.getSubPixelPosition( 0 ), peak.getSubPixelPosition( 1 ), peak.getSubPixelPosition( 2 ) } );
c.setPosition( p );
c.getType().set( 1 );
}
IOFunctions.println( "Convolving DoG result ... " );
final GaussianConvolutionReal<FloatType> gauss = new GaussianConvolutionReal<FloatType>( detections, new OutOfBoundsStrategyValueFactory<FloatType>(), 2 );
gauss.process();
detections = gauss.getResult();
IOFunctions.println( "Showing DoG result ... " );
ImageJFunctions.show( detections );
}
}
protected class FinishedButtonListener implements ActionListener
{
final Frame parent;
final boolean cancel;
public FinishedButtonListener( Frame parent, final boolean cancel )
{
this.parent = parent;
this.cancel = cancel;
}
@Override
public void actionPerformed( final ActionEvent arg0 )
{
wasCanceled = cancel;
close( parent, sliceObserver, imp, roiListener );
}
}
protected class FrameListener extends WindowAdapter
{
final Frame parent;
public FrameListener( Frame parent )
{
super();
this.parent = parent;
}
@Override
public void windowClosing (WindowEvent e)
{
close( parent, sliceObserver, imp, roiListener );
}
}
protected final void close( final Frame parent, final SliceObserver sliceObserver, final ImagePlus imp, final RoiListener roiListener )
{
if ( parent != null )
parent.dispose();
if ( sliceObserver != null )
sliceObserver.unregister();
if ( imp != null )
{
if ( roiListener != null )
imp.getCanvas().removeMouseListener( roiListener );
imp.getOverlay().clear();
imp.updateAndDraw();
}
isFinished = true;
}
protected class Sigma2Listener implements AdjustmentListener
{
final float min, max;
final int scrollbarSize;
final Scrollbar sigmaScrollbar2;
final Label sigma2Label;
public Sigma2Listener( final float min, final float max, final int scrollbarSize, final Scrollbar sigmaScrollbar2, final Label sigma2Label )
{
this.min = min;
this.max = max;
this.scrollbarSize = scrollbarSize;
this.sigmaScrollbar2 = sigmaScrollbar2;
this.sigma2Label = sigma2Label;
}
@Override
public void adjustmentValueChanged( final AdjustmentEvent event )
{
if ( enableSigma2 )
{
sigma2 = computeValueFromScrollbarPosition( event.getValue(), min, max, scrollbarSize );
if ( sigma2 < sigma )
{
sigma2 = sigma + 0.001f;
sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) );
}
sigma2Label.setText( "Sigma 2 = " + sigma2 );
if ( !event.getValueIsAdjusting() )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.SIGMA );
}
}
else
{
// if no manual adjustment simply reset it
sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) );
}
}
}
protected class SigmaListener implements AdjustmentListener
{
final Label label;
final float min, max;
final int scrollbarSize;
final Scrollbar sigmaScrollbar1;
final Scrollbar sigmaScrollbar2;
final Label sigmaText2;
public SigmaListener( final Label label, final float min, final float max, final int scrollbarSize, final Scrollbar sigmaScrollbar1, final Scrollbar sigmaScrollbar2, final Label sigmaText2 )
{
this.label = label;
this.min = min;
this.max = max;
this.scrollbarSize = scrollbarSize;
this.sigmaScrollbar1 = sigmaScrollbar1;
this.sigmaScrollbar2 = sigmaScrollbar2;
this.sigmaText2 = sigmaText2;
}
@Override
public void adjustmentValueChanged( final AdjustmentEvent event )
{
sigma = computeValueFromScrollbarPosition( event.getValue(), min, max, scrollbarSize );
if ( !enableSigma2 )
{
sigma2 = computeSigma2( sigma, sensitivity );
sigmaText2.setText( "Sigma 2 = " + sigma2 );
sigmaScrollbar2.setValue( computeScrollbarPositionFromValue( sigma2, min, max, scrollbarSize ) );
}
else if ( sigma > sigma2 )
{
sigma = sigma2 - 0.001f;
sigmaScrollbar1.setValue( computeScrollbarPositionFromValue( sigma, min, max, scrollbarSize ) );
}
label.setText( "Sigma 1 = " + sigma );
if ( !event.getValueIsAdjusting() )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.SIGMA );
}
}
}
protected static float computeValueFromScrollbarPosition( final int scrollbarPosition, final float min, final float max, final int scrollbarSize )
{
return min + (scrollbarPosition/(float)scrollbarSize) * (max-min);
}
protected static int computeScrollbarPositionFromValue( final float sigma, final float min, final float max, final int scrollbarSize )
{
return Util.round( ((sigma - min)/(max-min)) * scrollbarSize );
}
protected class ThresholdListener implements AdjustmentListener
{
final Label label;
final float min, max;
final float log1001 = (float)Math.log10(1001);
public ThresholdListener( final Label label, final float min, final float max )
{
this.label = label;
this.min = min;
this.max = max;
}
@Override
public void adjustmentValueChanged( final AdjustmentEvent event )
{
threshold = min + ( (log1001 - (float)Math.log10(1001-event.getValue()))/log1001 ) * (max-min);
label.setText( "Threshold = " + threshold );
if ( !isComputing )
{
updatePreview( ValueChange.THRESHOLD );
}
else if ( !event.getValueIsAdjusting() )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.THRESHOLD );
}
}
}
protected class ImagePlusListener implements SliceListener
{
@Override
public void sliceChanged(ImagePlus arg0)
{
if ( isStarted )
{
while ( isComputing )
{
SimpleMultiThreading.threadWait( 10 );
}
updatePreview( ValueChange.SLICE );
}
}
}
public static void main( String[] args )
{
new ImageJ();
ImagePlus imp = new Opener().openImage( "/home/preibisch/Documents/Microscopy/SPIM/Harvard/f11e6/exp3/img_Ch0_Angle0.tif.zip" );
//ImagePlus imp = new Opener().openImage( "D:/Documents and Settings/Stephan/My Documents/Downloads/1-315--0.08-isotropic-subvolume/1-315--0.08-isotropic-subvolume.tif" );
imp.show();
imp.setSlice( 27 );
imp.setRoi( imp.getWidth()/4, imp.getHeight()/4, imp.getWidth()/2, imp.getHeight()/2 );
new InteractiveDoG().run( null );
}
}
| gpl-2.0 |
lostdj/Jaklin-OpenJDK-JAXP | test/javax/xml/jaxp/functional/test/auctionportal/AuctionController.java | 14668 | /*
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package test.auctionportal;
import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_LANGUAGE;
import static com.sun.org.apache.xerces.internal.jaxp.JAXPConstants.JAXP_SCHEMA_SOURCE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Paths;
import java.util.GregorianCalendar;
import static javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import jaxp.library.JAXPFileReadOnlyBaseTest;
import static jaxp.library.JAXPTestUtilities.bomStream;
import org.testng.annotations.Test;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import static test.auctionportal.HiBidConstants.PORTAL_ACCOUNT_NS;
import static test.auctionportal.HiBidConstants.XML_DIR;
/**
* This is the user controller class for the Auction portal HiBid.com.
*/
public class AuctionController extends JAXPFileReadOnlyBaseTest {
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4890927
* DOMConfiguration.setParameter("well-formed",true) throws an exception.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCreateNewItem2Sell() throws Exception {
String xmlFile = XML_DIR + "novelsInvalid.xml";
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(xmlFile);
document.getDomConfig().setParameter("well-formed", true);
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
MyDOMOutput domOutput = new MyDOMOutput();
domOutput.setByteStream(System.out);
LSSerializer writer = impl.createLSSerializer();
writer.write(document, domOutput);
}
/**
* Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
* test throws DOM Level 1 node error.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCreateNewItem2SellRetry() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
DOMConfiguration domConfig = document.getDomConfig();
MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
domConfig.setParameter("error-handler", errHandler);
DOMImplementationLS impl =
(DOMImplementationLS) DOMImplementationRegistry.newInstance()
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
MyDOMOutput domoutput = new MyDOMOutput();
domoutput.setByteStream(System.out);
writer.write(document, domoutput);
document.normalizeDocument();
writer.write(document, domoutput);
assertFalse(errHandler.isError());
}
/**
* Check if setting the attribute to be of type ID works. This will affect
* the Attr.isID method according to the spec.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCreateID() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
Element account = (Element)document
.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
account.setIdAttributeNS(PORTAL_ACCOUNT_NS, "accountID", true);
Attr aID = account.getAttributeNodeNS(PORTAL_ACCOUNT_NS, "accountID");
assertTrue(aID.isId());
}
/**
* Check the user data on the node.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testCheckingUserData() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(xmlFile);
Element account = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Account").item(0);
assertEquals(account.getNodeName(), "acc:Account");
Element firstName = (Element) document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "FirstName").item(0);
assertEquals(firstName.getNodeName(), "FirstName");
Document doc1 = docBuilder.newDocument();
Element someName = doc1.createElement("newelem");
someName.setUserData("mykey", "dd",
(operation, key, data, src, dst) -> {
System.err.println("In UserDataHandler" + key);
System.out.println("In UserDataHandler");
});
Element impAccount = (Element)document.importNode(someName, true);
assertEquals(impAccount.getNodeName(), "newelem");
document.normalizeDocument();
String data = (someName.getUserData("mykey")).toString();
assertEquals(data, "dd");
}
/**
* Check the UTF-16 XMLEncoding xml file.
*
* @throws Exception If any errors occur.
* @see <a href="content/movies.xml">movies.xml</a>
*/
@Test(groups = {"readLocalFiles"})
public void testCheckingEncoding() throws Exception {
// Note since movies.xml is UTF-16 encoding. We're not using stanard XML
// file suffix.
String xmlFile = XML_DIR + "movies.xml.data";
try (InputStream source = bomStream("UTF-16", xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(source);
assertEquals(document.getXmlEncoding(), "UTF-16");
assertEquals(document.getXmlStandalone(), true);
}
}
/**
* Check validation API features. A schema which is including in Bug 4909119
* used to be testing for the functionalities.
*
* @throws Exception If any errors occur.
* @see <a href="content/userDetails.xsd">userDetails.xsd</a>
*/
@Test(groups = {"readLocalFiles"})
public void testGetOwnerInfo() throws Exception {
String schemaFile = XML_DIR + "userDetails.xsd";
String xmlFile = XML_DIR + "userDetails.xml";
try(FileInputStream fis = new FileInputStream(xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile());
Validator validator = schema.newValidator();
MyErrorHandler eh = new MyErrorHandler();
validator.setErrorHandler(eh);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(eh);
Document document = docBuilder.parse(fis);
DOMResult dResult = new DOMResult();
DOMSource domSource = new DOMSource(document);
validator.validate(domSource, dResult);
assertFalse(eh.isAnyError());
}
}
/**
* Check grammar caching with imported schemas.
*
* @throws Exception If any errors occur.
* @see <a href="content/coins.xsd">coins.xsd</a>
* @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
*/
@Test(groups = {"readLocalFiles"})
public void testGetOwnerItemList() throws Exception {
String xsdFile = XML_DIR + "coins.xsd";
String xmlFile = XML_DIR + "coins.xml";
try(FileInputStream fis = new FileInputStream(xmlFile)) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
dbf.setValidating(false);
SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new File(((xsdFile))));
MyErrorHandler eh = new MyErrorHandler();
Validator validator = schema.newValidator();
validator.setErrorHandler(eh);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(fis);
validator.validate(new DOMSource(document), new DOMResult());
assertFalse(eh.isAnyError());
}
}
/**
* Check for the same imported schemas but will use SAXParserFactory and try
* parsing using the SAXParser. SCHEMA_SOURCE attribute is using for this
* test.
*
* @throws Exception If any errors occur.
* @see <a href="content/coins.xsd">coins.xsd</a>
* @see <a href="content/coinsImportMe.xsd">coinsImportMe.xsd</a>
*/
@Test(groups = {"readLocalFiles"})
public void testGetOwnerItemList1() throws Exception {
String xsdFile = XML_DIR + "coins.xsd";
String xmlFile = XML_DIR + "coins.xml";
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
sp.setProperty(JAXP_SCHEMA_SOURCE, xsdFile);
MyErrorHandler eh = new MyErrorHandler();
sp.parse(new File(xmlFile), eh);
assertFalse(eh.isAnyError());
}
/**
* Check usage of javax.xml.datatype.Duration class.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testGetItemDuration() throws Exception {
String xmlFile = XML_DIR + "itemsDuration.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document document = dbf.newDocumentBuilder().parse(xmlFile);
Element durationElement = (Element) document.getElementsByTagName("sellDuration").item(0);
NodeList childList = durationElement.getChildNodes();
for (int i = 0; i < childList.getLength(); i++) {
System.out.println("child " + i + childList.item(i));
}
Duration duration = DatatypeFactory.newInstance().newDuration("P365D");
Duration sellDuration = DatatypeFactory.newInstance().newDuration(childList.item(0).getNodeValue());
assertFalse(sellDuration.isShorterThan(duration));
assertFalse(sellDuration.isLongerThan(duration));
assertEquals(sellDuration.getField(DatatypeConstants.DAYS), BigInteger.valueOf(365));
assertEquals(sellDuration.normalizeWith(new GregorianCalendar(1999, 2, 22)), duration);
Duration myDuration = sellDuration.add(duration);
assertEquals(myDuration.normalizeWith(new GregorianCalendar(2003, 2, 22)),
DatatypeFactory.newInstance().newDuration("P730D"));
}
/**
* Check usage of TypeInfo interface introduced in DOM L3.
*
* @throws Exception If any errors occur.
*/
@Test(groups = {"readLocalFiles"})
public void testGetTypeInfo() throws Exception {
String xmlFile = XML_DIR + "accountInfo.xml";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
docBuilder.setErrorHandler(new MyErrorHandler());
Document document = docBuilder.parse(xmlFile);
Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
TypeInfo typeInfo = userId.getSchemaTypeInfo();
assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));
Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
TypeInfo roletypeInfo = role.getSchemaTypeInfo();
assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}
}
| gpl-2.0 |
sfe1012/Robot | java/com/mobilerobots/Aria/ArUrg.java | 3101 | /*
Adept MobileRobots Robotics Interface for Applications (ARIA)
Copyright (C) 2004-2005 ActivMedia Robotics LLC
Copyright (C) 2006-2010 MobileRobots Inc.
Copyright (C) 2011-2014 Adept Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.40
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.mobilerobots.Aria;
public class ArUrg extends ArLaser {
/* (begin code from javabody_derived typemap) */
private long swigCPtr;
/* for internal use by swig only */
public ArUrg(long cPtr, boolean cMemoryOwn) {
super(AriaJavaJNI.SWIGArUrgUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/* for internal use by swig only */
public static long getCPtr(ArUrg obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
/* (end code from javabody_derived typemap) */
protected void finalize() {
delete();
}
public synchronized void delete() {
if (swigCPtr != 0) {
if (swigCMemOwn) {
swigCMemOwn = false;
AriaJavaJNI.delete_ArUrg(swigCPtr);
}
swigCPtr = 0;
}
super.delete();
}
public ArUrg(int laserNumber, String name) {
this(AriaJavaJNI.new_ArUrg__SWIG_0(laserNumber, name), true);
}
public ArUrg(int laserNumber) {
this(AriaJavaJNI.new_ArUrg__SWIG_1(laserNumber), true);
}
public boolean blockingConnect() {
return AriaJavaJNI.ArUrg_blockingConnect(swigCPtr, this);
}
public boolean asyncConnect() {
return AriaJavaJNI.ArUrg_asyncConnect(swigCPtr, this);
}
public boolean disconnect() {
return AriaJavaJNI.ArUrg_disconnect(swigCPtr, this);
}
public boolean isConnected() {
return AriaJavaJNI.ArUrg_isConnected(swigCPtr, this);
}
public boolean isTryingToConnect() {
return AriaJavaJNI.ArUrg_isTryingToConnect(swigCPtr, this);
}
public void log() {
AriaJavaJNI.ArUrg_log(swigCPtr, this);
}
}
| gpl-2.0 |
imunro/bioformats | components/formats-bsd/src/loci/formats/codec/LosslessJPEGCodec.java | 12867 | /*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2016 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package loci.formats.codec;
import java.io.IOException;
import java.util.Vector;
import loci.common.ByteArrayHandle;
import loci.common.DataTools;
import loci.common.RandomAccessInputStream;
import loci.formats.FormatException;
import loci.formats.UnsupportedCompressionException;
/**
* Decompresses lossless JPEG images.
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class LosslessJPEGCodec extends BaseCodec {
// -- Constants --
// Start of Frame markers - non-differential, Huffman coding
private static final int SOF0 = 0xffc0; // baseline DCT
private static final int SOF1 = 0xffc1; // extended sequential DCT
private static final int SOF2 = 0xffc2; // progressive DCT
private static final int SOF3 = 0xffc3; // lossless (sequential)
// Start of Frame markers - differential, Huffman coding
private static final int SOF5 = 0xffc5; // differential sequential DCT
private static final int SOF6 = 0xffc6; // differential progressive DCT
private static final int SOF7 = 0xffc7; // differential lossless (sequential)
// Start of Frame markers - non-differential, arithmetic coding
private static final int JPG = 0xffc8; // reserved for JPEG extensions
private static final int SOF9 = 0xffc9; // extended sequential DCT
private static final int SOF10 = 0xffca; // progressive DCT
private static final int SOF11 = 0xffcb; // lossless (sequential)
// Start of Frame markers - differential, arithmetic coding
private static final int SOF13 = 0xffcd; // differential sequential DCT
private static final int SOF14 = 0xffce; // differential progressive DCT
private static final int SOF15 = 0xffcf; // differential lossless (sequential)
private static final int DHT = 0xffc4; // define Huffman table(s)
private static final int DAC = 0xffcc; // define arithmetic coding conditions
// Restart interval termination
private static final int RST_0 = 0xffd0;
private static final int RST_1 = 0xffd1;
private static final int RST_2 = 0xffd2;
private static final int RST_3 = 0xffd3;
private static final int RST_4 = 0xffd4;
private static final int RST_5 = 0xffd5;
private static final int RST_6 = 0xffd6;
private static final int RST_7 = 0xffd7;
private static final int SOI = 0xffd8; // start of image
private static final int EOI = 0xffd9; // end of image
private static final int SOS = 0xffda; // start of scan
private static final int DQT = 0xffdb; // define quantization table(s)
private static final int DNL = 0xffdc; // define number of lines
private static final int DRI = 0xffdd; // define restart interval
private static final int DHP = 0xffde; // define hierarchical progression
private static final int EXP = 0xffdf; // expand reference components
private static final int COM = 0xfffe; // comment
// -- Codec API methods --
/* @see Codec#compress(byte[], CodecOptions) */
@Override
public byte[] compress(byte[] data, CodecOptions options)
throws FormatException
{
throw new UnsupportedCompressionException(
"Lossless JPEG compression not supported");
}
/**
* The CodecOptions parameter should have the following fields set:
* {@link CodecOptions#interleaved interleaved}
* {@link CodecOptions#littleEndian littleEndian}
*
* @see Codec#decompress(RandomAccessInputStream, CodecOptions)
*/
@Override
public byte[] decompress(RandomAccessInputStream in, CodecOptions options)
throws FormatException, IOException
{
if (in == null)
throw new IllegalArgumentException("No data to decompress.");
if (options == null) options = CodecOptions.getDefaultOptions();
byte[] buf = new byte[0];
int width = 0, height = 0;
int bitsPerSample = 0, nComponents = 0, bytesPerSample = 0;
int[] horizontalSampling = null, verticalSampling = null;
int[] quantizationTable = null;
short[][] huffmanTables = null;
int startPredictor = 0, endPredictor = 0;
int pointTransform = 0;
int[] dcTable = null, acTable = null;
while (in.getFilePointer() < in.length() - 1) {
int code = in.readShort() & 0xffff;
int length = in.readShort() & 0xffff;
long fp = in.getFilePointer();
if (length > 0xff00) {
length = 0;
in.seek(fp - 2);
}
else if (code == SOS) {
nComponents = in.read();
dcTable = new int[nComponents];
acTable = new int[nComponents];
for (int i=0; i<nComponents; i++) {
int componentSelector = in.read();
int tableSelector = in.read();
dcTable[i] = (tableSelector & 0xf0) >> 4;
acTable[i] = tableSelector & 0xf;
}
startPredictor = in.read();
endPredictor = in.read();
pointTransform = in.read() & 0xf;
// read image data
byte[] toDecode = new byte[(int) (in.length() - in.getFilePointer())];
in.read(toDecode);
// scrub out byte stuffing
ByteVector b = new ByteVector();
for (int i=0; i<toDecode.length; i++) {
byte val = toDecode[i];
if (val == (byte) 0xff) {
if (toDecode[i + 1] == 0)
b.add(val);
i++;
} else {
b.add(val);
}
}
toDecode = b.toByteArray();
RandomAccessInputStream bb = new RandomAccessInputStream(
new ByteArrayHandle(toDecode));
HuffmanCodec huffman = new HuffmanCodec();
HuffmanCodecOptions huffmanOptions = new HuffmanCodecOptions();
huffmanOptions.bitsPerSample = bitsPerSample;
huffmanOptions.maxBytes = buf.length / nComponents;
int nextSample = 0;
while (nextSample < buf.length / nComponents) {
for (int i=0; i<nComponents; i++) {
huffmanOptions.table = huffmanTables[dcTable[i]];
int v = 0;
if (huffmanTables != null) {
v = huffman.getSample(bb, huffmanOptions);
if (nextSample == 0) {
v += (int) Math.pow(2, bitsPerSample - 1);
}
}
else {
throw new UnsupportedCompressionException(
"Arithmetic coding not supported");
}
// apply predictor to the sample
int predictor = startPredictor;
if (nextSample < width * bytesPerSample) predictor = 1;
else if ((nextSample % (width * bytesPerSample)) == 0) {
predictor = 2;
}
int componentOffset = i * (buf.length / nComponents);
int indexA = nextSample - bytesPerSample + componentOffset;
int indexB = nextSample - width * bytesPerSample + componentOffset;
int indexC = nextSample - (width + 1) * bytesPerSample +
componentOffset;
int sampleA = indexA < 0 ? 0 :
DataTools.bytesToInt(buf, indexA, bytesPerSample, false);
int sampleB = indexB < 0 ? 0 :
DataTools.bytesToInt(buf, indexB, bytesPerSample, false);
int sampleC = indexC < 0 ? 0 :
DataTools.bytesToInt(buf, indexC, bytesPerSample, false);
if (nextSample > 0) {
int pred = 0;
switch (predictor) {
case 1:
pred = sampleA;
break;
case 2:
pred = sampleB;
break;
case 3:
pred = sampleC;
break;
case 4:
pred = sampleA + sampleB + sampleC;
break;
case 5:
pred = sampleA + ((sampleB - sampleC) / 2);
break;
case 6:
pred = sampleB + ((sampleA - sampleC) / 2);
break;
case 7:
pred = (sampleA + sampleB) / 2;
break;
}
v += pred;
}
int offset = componentOffset + nextSample;
DataTools.unpackBytes(v, buf, offset, bytesPerSample, false);
}
nextSample += bytesPerSample;
}
bb.close();
}
else {
length -= 2; // stored length includes length param
if (length == 0) continue;
if (code == EOI) { }
else if (code == SOF3) {
// lossless w/Huffman coding
bitsPerSample = in.read();
height = in.readShort();
width = in.readShort();
nComponents = in.read();
horizontalSampling = new int[nComponents];
verticalSampling = new int[nComponents];
quantizationTable = new int[nComponents];
for (int i=0; i<nComponents; i++) {
in.skipBytes(1);
int s = in.read();
horizontalSampling[i] = (s & 0xf0) >> 4;
verticalSampling[i] = s & 0x0f;
quantizationTable[i] = in.read();
}
bytesPerSample = bitsPerSample / 8;
if ((bitsPerSample % 8) != 0) bytesPerSample++;
buf = new byte[width * height * nComponents * bytesPerSample];
}
else if (code == SOF11) {
throw new UnsupportedCompressionException(
"Arithmetic coding is not yet supported");
}
else if (code == DHT) {
if (huffmanTables == null) {
huffmanTables = new short[4][];
}
int bytesRead = 0;
while (bytesRead < length) {
int s = in.read();
byte tableClass = (byte) ((s & 0xf0) >> 4);
byte destination = (byte) (s & 0xf);
int[] nCodes = new int[16];
Vector table = new Vector();
for (int i=0; i<nCodes.length; i++) {
nCodes[i] = in.read();
table.add(new Short((short) nCodes[i]));
}
for (int i=0; i<nCodes.length; i++) {
for (int j=0; j<nCodes[i]; j++) {
table.add(new Short((short) (in.read() & 0xff)));
}
}
huffmanTables[destination] = new short[table.size()];
for (int i=0; i<huffmanTables[destination].length; i++) {
huffmanTables[destination][i] = ((Short) table.get(i)).shortValue();
}
bytesRead += table.size() + 1;
}
}
in.seek(fp + length);
}
}
if (options.interleaved && nComponents > 1) {
// data is stored in planar (RRR...GGG...BBB...) order
byte[] newBuf = new byte[buf.length];
for (int i=0; i<buf.length; i+=nComponents*bytesPerSample) {
for (int c=0; c<nComponents; c++) {
int src = c * (buf.length / nComponents) + (i / nComponents);
int dst = i + c * bytesPerSample;
System.arraycopy(buf, src, newBuf, dst, bytesPerSample);
}
}
buf = newBuf;
}
if (options.littleEndian && bytesPerSample > 1) {
// data is stored in big endian order
// reverse the bytes in each sample
byte[] newBuf = new byte[buf.length];
for (int i=0; i<buf.length; i+=bytesPerSample) {
for (int q=0; q<bytesPerSample; q++) {
newBuf[i + bytesPerSample - q - 1] = buf[i + q];
}
}
buf = newBuf;
}
return buf;
}
}
| gpl-2.0 |
JetBrains/jdk8u_jdk | test/sun/java2d/marlin/ScaleClipTest.java | 8526 | /*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Scaled Line Clipping rendering test
*/
public class ScaleClipTest {
static final boolean SAVE_IMAGE = false;
static final int SIZE = 50;
enum SCALE_MODE {
ORTHO,
NON_ORTHO,
COMPLEX
};
public static void main(String[] args) {
// First display which renderer is tested:
// JDK9 only:
System.setProperty("sun.java2d.renderer.verbose", "true");
System.out.println("Testing renderer: ");
// Other JDK:
String renderer = "undefined";
try {
renderer = sun.java2d.pipe.RenderingEngine.getInstance().getClass().getName();
System.out.println(renderer);
} catch (Throwable th) {
// may fail with JDK9 jigsaw (jake)
if (false) {
System.err.println("Unable to get RenderingEngine.getInstance()");
th.printStackTrace();
}
}
System.out.println("ScaleClipTest: size = " + SIZE);
final BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
boolean fail = false;
// testNegativeScale:
for (SCALE_MODE mode : SCALE_MODE.values()) {
try {
testNegativeScale(image, mode);
} catch (IllegalStateException ise) {
System.err.println("testNegativeScale[" + mode + "] failed:");
ise.printStackTrace();
fail = true;
}
}
// testMarginScale:
for (SCALE_MODE mode : SCALE_MODE.values()) {
try {
testMarginScale(image, mode);
} catch (IllegalStateException ise) {
System.err.println("testMarginScale[" + mode + "] failed:");
ise.printStackTrace();
fail = true;
}
}
// Fail at the end:
if (fail) {
throw new RuntimeException("ScaleClipTest has failures.");
}
}
private static void testNegativeScale(final BufferedImage image, final SCALE_MODE mode) {
final Graphics2D g2d = (Graphics2D) image.getGraphics();
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, SIZE, SIZE);
g2d.setColor(Color.BLACK);
// Bug in TransformingPathConsumer2D.adjustClipScale()
// non ortho scale only
final double scale = -1.0;
final AffineTransform at;
switch (mode) {
default:
case ORTHO:
at = AffineTransform.getScaleInstance(scale, scale);
break;
case NON_ORTHO:
at = AffineTransform.getScaleInstance(scale, scale + 1e-5);
break;
case COMPLEX:
at = AffineTransform.getScaleInstance(scale, scale);
at.concatenate(AffineTransform.getShearInstance(1e-4, 1e-4));
break;
}
g2d.setTransform(at);
// Set cap/join to reduce clip margin:
g2d.setStroke(new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
final Path2D p = new Path2D.Double();
p.moveTo(scale * 10, scale * 10);
p.lineTo(scale * (SIZE - 10), scale * (SIZE - 10));
g2d.draw(p);
if (SAVE_IMAGE) {
try {
final File file = new File("ScaleClipTest-testNegativeScale-" + mode + ".png");
System.out.println("Writing file: " + file.getAbsolutePath());
ImageIO.write(image, "PNG", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// Check image:
// 25, 25 = black
checkPixel(image.getData(), 25, 25, Color.BLACK.getRGB());
} finally {
g2d.dispose();
}
}
private static void testMarginScale(final BufferedImage image, final SCALE_MODE mode) {
final Graphics2D g2d = (Graphics2D) image.getGraphics();
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, SIZE, SIZE);
g2d.setColor(Color.BLACK);
// Bug in Stroker.init()
// ortho scale only: scale used twice !
final double scale = 1e-2;
final AffineTransform at;
switch (mode) {
default:
case ORTHO:
at = AffineTransform.getScaleInstance(scale, scale);
break;
case NON_ORTHO:
at = AffineTransform.getScaleInstance(scale, scale + 1e-5);
break;
case COMPLEX:
at = AffineTransform.getScaleInstance(scale, scale);
at.concatenate(AffineTransform.getShearInstance(1e-4, 1e-4));
break;
}
g2d.setTransform(at);
final double invScale = 1.0 / scale;
// Set cap/join to reduce clip margin:
final float w = (float) (3.0 * invScale);
g2d.setStroke(new BasicStroke(w, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
final Path2D p = new Path2D.Double();
p.moveTo(invScale * -0.5, invScale * 10);
p.lineTo(invScale * -0.5, invScale * (SIZE - 10));
g2d.draw(p);
if (SAVE_IMAGE) {
try {
final File file = new File("ScaleClipTest-testMarginScale-" + mode + ".png");
System.out.println("Writing file: " + file.getAbsolutePath());
ImageIO.write(image, "PNG", file);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
// Check image:
// 0, 25 = black
checkPixel(image.getData(), 0, 25, Color.BLACK.getRGB());
} finally {
g2d.dispose();
}
}
private static void checkPixel(final Raster raster,
final int x, final int y,
final int expected) {
final int[] rgb = (int[]) raster.getDataElements(x, y, null);
if (rgb[0] != expected) {
throw new IllegalStateException("bad pixel at (" + x + ", " + y
+ ") = " + rgb[0] + " expected: " + expected);
}
}
}
| gpl-2.0 |
phcp/AmadeusLMS | src/br/ufpe/cin/amadeus/amadeus_mobile/util/Conversor.java | 24368 | /**
Copyright 2008, 2009 UFPE - Universidade Federal de Pernambuco
Este arquivo é parte do programa Amadeus Sistema de Gestão de Aprendizagem, ou simplesmente Amadeus LMS
O Amadeus LMS é um software livre; você pode redistribui-lo e/ou modifica-lo dentro dos termos da Licença Pública Geral GNU como
publicada pela Fundação do Software Livre (FSF); na versão 2 da Licença.
Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU para maiores detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título "LICENCA.txt", junto com este programa, se não, escreva para a Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
**/
package br.ufpe.cin.amadeus.amadeus_mobile.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject;
import br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll;
public class Conversor {
/**
* Method that converts AMADeUs Course object into Mobile Course object
* @param curso - AMADeUs Course to be converted
* @return - Converted Mobile Course object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile converterCurso(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course curso){
br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile();
retorno.setId(curso.getId());
retorno.setName(curso.getName());
retorno.setContent(curso.getContent());
retorno.setObjectives(curso.getObjectives());
retorno.setModules(converterModulos(curso.getModules()));
retorno.setKeywords(converterKeywords(curso.getKeywords()));
ArrayList<String> nomes = new ArrayList<String>();
nomes.add(curso.getProfessor().getName());
retorno.setTeachers(nomes);
retorno.setCount(0);
retorno.setMaxAmountStudents(curso.getMaxAmountStudents());
retorno.setFinalCourseDate(curso.getFinalCourseDate());
retorno.setInitialCourseDate(curso.getInitialCourseDate());
return retorno;
}
/**
* Method that converts a AMADeUs Course object list into Mobile Course object list
* @param cursos - AMADeUs Course object list to be converted
* @return - Converted Mobile Course object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> converterCursos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course> cursos){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.CourseMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Course c : cursos){
retorno.add(Conversor.converterCurso(c));
}
return retorno;
}
/**
* Method that converts AMADeUs Module object into Mobile Module object
* @param modulo - AMADeUs Module object to be converted
* @return - Converted Mobile Module object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile converterModulo(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module modulo){
br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile mod = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile(modulo.getId(), modulo.getName());
List<HomeworkMobile> listHomeworks = new ArrayList<HomeworkMobile>();
for (Poll poll : modulo.getPolls()) {
listHomeworks.add( Conversor.converterPollToHomework(poll) );
}
for (Forum forum : modulo.getForums()) {
listHomeworks.add( Conversor.converterForumToHomework(forum) );
}
for(Game game : modulo.getGames()){
listHomeworks.add( Conversor.converterGameToHomework(game) );
}
for(LearningObject learning : modulo.getLearningObjects()){
listHomeworks.add( Conversor.converterLearningObjectToHomework(learning) );
}
mod.setHomeworks(listHomeworks);
mod.setMaterials(converterMaterials(modulo.getMaterials()));
return mod;
}
/**
* Mothod that converts a AMADeUs Module object list into Mobile Module object list
* @param modulos - AMADeUs Module object list to be converted
* @return - Converted Mobile Module object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> converterModulos(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module> modulos){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ModuleMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Module m : modulos){
retorno.add(Conversor.converterModulo(m));
}
return retorno;
}
/**
* Method that converts AMADeUs Homework object into Mobile Homework object
* @param home - AMADeUs Homework object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework home){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(home.getId());
retorno.setName(home.getName());
retorno.setDescription(home.getDescription());
retorno.setInitDate(home.getInitDate());
retorno.setDeadline(home.getDeadline());
retorno.setAlowPostponing(home.getAllowPostponing());
retorno.setInfoExtra("");
retorno.setTypeActivity(HomeworkMobile.HOMEWORK);
return retorno;
}
/**
* Method that converts AMADeUs Game object into Mobile Homework object
* @param game - AMADeUs Game object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterGameToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Game game){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(game.getId());
retorno.setName(game.getName());
retorno.setDescription(game.getDescription());
retorno.setInfoExtra(game.getUrl());
retorno.setTypeActivity(HomeworkMobile.GAME);
return retorno;
}
/**
* Method that converts AMADeUs Forum object into Mobile Homework object
* @param forum - AMADeUs Forum object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterForumToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Forum forum){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(forum.getId());
retorno.setName(forum.getName());
retorno.setDescription(forum.getDescription());
retorno.setInitDate(forum.getCreationDate());
retorno.setInfoExtra("");
retorno.setTypeActivity(HomeworkMobile.FORUM);
return retorno;
}
/**
* Method that converts AMADeUs Poll object into Mobile Homework object
* @param poll - AMADeUs Poll object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterPollToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll poll){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(poll.getId());
retorno.setName(poll.getName());
retorno.setDescription(poll.getQuestion());
retorno.setInitDate(poll.getCreationDate());
retorno.setDeadline(poll.getFinishDate());
retorno.setInfoExtra("");
retorno.setTypeActivity(HomeworkMobile.POLL);
return retorno;
}
/**
* Method that converts AMADeUs Multimedia object into Mobile Homework object
* @param media - AMADeUs Multimedia object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterMultimediaToHomework(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Multimedia media){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(media.getId());
retorno.setName(media.getName());
retorno.setDescription(media.getDescription());
retorno.setInfoExtra(media.getUrl());
retorno.setTypeActivity(HomeworkMobile.MULTIMEDIA);
return retorno;
}
/**
* Method that converts AMADeUs Video object into Mobile Homework object
* @param video - AMADeUs Video object to be converted
* @return - Converted Mobile Homework object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterVideoToHomework(br.ufpe.cin.amadeus.amadeus_sdmm.dao.Video video){
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(video.getId());
retorno.setName(video.getName());
retorno.setDescription(video.getDescription());
retorno.setInitDate(video.getDateinsertion());
retorno.setInfoExtra(video.getTags());
retorno.setTypeActivity(HomeworkMobile.VIDEO);
return retorno;
}
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile converterLearningObjectToHomework(
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning) {
br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile();
retorno.setId(learning.getId());
retorno.setName(learning.getName());
retorno.setUrl(learning.getUrl());
retorno.setDescription(learning.getDescription());
retorno.setDeadline(learning.getCreationDate());
retorno.setTypeActivity(HomeworkMobile.LEARNING_OBJECT);
return retorno;
}
/**
* Method that converts AMADeUs Homework object list into Mobile Homework object list
* @param homes - AMADeUs Homework object list to be converted
* @return - Converted Mobile Homework object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> converterHomeworks(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework> homes){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.HomeworkMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Homework h : homes){
retorno.add(Conversor.converterHomework(h));
}
return retorno;
}
/**
* Method that converts AMADeUs Material object into Mobile Material object
* @param mat - AMADeUs Material object to be converted
* @return - Mobile Material object converted
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile converterMaterial(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat){
br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile();
retorno.setId(mat.getId());
retorno.setName(mat.getArchiveName());
retorno.setAuthor(converterPerson(mat.getAuthor()));
retorno.setPostDate(mat.getCreationDate());
return retorno;
}
/**
* Method that converts AMADeUs Mobile Material object list into Mobile Material object list
* @param mats - AMADeUs Material object list
* @return - Mobile Material object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> converterMaterials(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material> mats){
ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.MaterialMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Material mat : mats){
retorno.add(Conversor.converterMaterial(mat));
}
return retorno;
}
/**
* Method that converts AMADeUs Keyword object into Mobile Keyword object
* @param key - AMADeUs Keyword object to be converted
* @return - Converted Keywork object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile converterKeyword(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword key){
br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile();
retorno.setId(key.getId());
retorno.setName(key.getName());
retorno.setPopularity(key.getPopularity());
return retorno;
}
/**
* Method that converts AMADeUs Keyword object list into a Mobile Keyword HashSet object
* @param keys - AMADeUs Keyword object list to be converted
* @return - Mobile Keywork HashSet object list
*/
public static HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> converterKeywords(Set<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword> keys){
HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile> retorno = new HashSet<br.ufpe.cin.amadeus.amadeus_mobile.basics.KeywordMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Keyword k : keys){
retorno.add(Conversor.converterKeyword(k));
}
return retorno;
}
/**
* Method that converts AMADeUs Choice object into Mobile Choice object
* @param ch - AMADeUs Choice object to be converted
* @return - Converted Mobile Choice object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile converterChoice(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice ch){
br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile();
retorno.setId(ch.getId());
retorno.setAlternative(ch.getAlternative());
retorno.setVotes(ch.getVotes());
retorno.setPercentage(ch.getPercentage());
return retorno;
}
/**
* Method that converts AMADeUs Choice object list into Mobile Choice object list
* @param chs - AMADeUs Choice object list to be converted
* @return - Converted Mobile Choice object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> converterChoices(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> chs){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice c : chs){
retorno.add(Conversor.converterChoice(c));
}
return retorno;
}
/**
* Method that converts AMADeUs Poll object into Mobile Poll Object
* @param p - AMADeUs Poll object to be converted
* @return - Converted Mobile Poll object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile converterPool(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p){
br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile();
retorno.setId(p.getId());
retorno.setName(p.getName());
retorno.setQuestion(p.getQuestion());
retorno.setInitDate(p.getCreationDate());
retorno.setFinishDate(p.getFinishDate());
retorno.setAnswered(false);
retorno.setChoices(converterChoices(p.getChoices()));
retorno.setAnsewered(converterAnswers(p.getAnswers()));
return retorno;
}
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile converterLearningObject (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.LearningObject learning){
br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.LearningObjectMobile();
retorno.setId(learning.getId());
retorno.setName(learning.getName());
retorno.setDescription(learning.getDescription());
retorno.setDatePublication(learning.getCreationDate());
retorno.setUrl(learning.getUrl());
return retorno;
}
/**
* Method that converts AMADeUs Poll object list into Mobile Poll object list
* @param pls - AMADeUs Poll object list
* @return - Converted Mobile object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> converterPools(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll> pls){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll p : pls){
retorno.add(Conversor.converterPool(p));
}
return retorno;
}
/**
* Method that converts AMADeUs Answer object into Mobile Answer object
* @param ans - AMADeUs Answer object to be converted
* @return - Converted Mobile Answer object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile converterAnswer(br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer ans){
br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile retorno = new br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile();
retorno.setId(ans.getId());
retorno.setAnswerDate(ans.getAnswerDate());
retorno.setPerson(converterPerson(ans.getPerson()));
return retorno;
}
/**
* Method that converts AMADeUs Answer object list into Mobile Answer object list
* @param anss - AMADeUs Answer object list
* @return - Converted Mobile object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> converterAnswers(List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> anss){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer an : anss){
retorno.add(Conversor.converterAnswer(an));
}
return retorno;
}
/**
* Method that converts AMADeUs Person object into Mobile Person object
* @param p - AMADeUs Person object to be converted
* @return - Converted Mobile Person object
*/
public static br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile converterPerson(br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p){
return new br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile(p.getId(), p.getAccessInfo().getLogin(), p.getPhoneNumber());
}
/**
* Method that converts AMADeUs Person object list into Mobile Person object list
* @param persons - AMADeUs Person object list to be converted
* @return - Converted Mobile Person object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> converterPersons(List<br.ufpe.cin.amadeus.amadeus_web.domain.register.Person> persons){
List<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile>();
for (br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p : persons){
retorno.add(Conversor.converterPerson(p));
}
return retorno;
}
/**
* Method that converts Mobile Poll object into AMADeUs Poll Object
* @param p - Mobile Poll object to be converted
* @return - Converted AMADeUs Poll object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll converterPool(br.ufpe.cin.amadeus.amadeus_mobile.basics.PollMobile p){
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Poll();
retorno.setId(p.getId());
retorno.setName(p.getName());
retorno.setQuestion(p.getQuestion());
retorno.setCreationDate(p.getInitDate());
retorno.setFinishDate(p.getFinishDate());
retorno.setChoices(converterChoices2(p.getChoices()));
retorno.setAnswers(converterAnswers2(p.getAnsewered()));
return retorno;
}
/**
* Method that converts Mobile Choice object into AMADeUs Choice object
* @param ch - Mobile Choice object to be converted
* @return - Converted AMADeUs Choice object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice converterChoice(br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile ch){
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice();
retorno.setId(ch.getId());
retorno.setAlternative(ch.getAlternative());
retorno.setVotes(ch.getVotes());
retorno.setPercentage(ch.getPercentage());
return retorno;
}
/**
* Method that converts Mobile Choiceobject list into AMADeUs Choice object list
* @param chs - Mobile Choice object list to be converted
* @return - Converted AMADeUs Choice object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> converterChoices2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile> chs){
List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Choice>();
for (br.ufpe.cin.amadeus.amadeus_mobile.basics.ChoiceMobile c : chs){
retorno.add(Conversor.converterChoice(c));
}
return retorno;
}
/**
* Method that converts Mobile Answer object into AMADeUs Answer object
* @param ans - Mobile Answer object to be converted
* @return - Converted AMADeUs Answer object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer converterAnswer(br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile ans){
br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer retorno = new br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer();
retorno.setId(ans.getId());
retorno.setAnswerDate(ans.getAnswerDate());
retorno.setPerson(converterPerson(ans.getPerson()));
return retorno;
}
/**
* Method that converts Mobile Answer object list into AMADeUs Answer object list
* @param anss - Mobile Answer object list
* @return - Converted AMADeUs Answer object list
*/
public static List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> converterAnswers2(List<br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile> anss){
List<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer> retorno = new ArrayList<br.ufpe.cin.amadeus.amadeus_web.domain.content_management.Answer>();
for (br.ufpe.cin.amadeus.amadeus_mobile.basics.AnswerMobile an : anss){
retorno.add(Conversor.converterAnswer(an));
}
return retorno;
}
/**
* Method that converts Mobile Person object into AMADeUs Person object
* @param p - Mobile Person object to be converted
* @return - Converted AMADeUs Person object
*/
public static br.ufpe.cin.amadeus.amadeus_web.domain.register.Person converterPerson(br.ufpe.cin.amadeus.amadeus_mobile.basics.PersonMobile p){
br.ufpe.cin.amadeus.amadeus_web.domain.register.Person p1 = new br.ufpe.cin.amadeus.amadeus_web.domain.register.Person();
p1.setId(p.getId());
p1.setName(p.getName());
p1.setPhoneNumber(p.getPhoneNumber());
return p1;
}
} | gpl-2.0 |
jzalden/SER316-Karlsruhe | src/net/sf/memoranda/ui/htmleditor/ImageDialog.java | 13558 | package net.sf.memoranda.ui.htmleditor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import net.sf.memoranda.ui.htmleditor.util.Local;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: </p>
* @author unascribed
* @version 1.0
*/
public class ImageDialog extends JDialog implements WindowListener {
/**
*
*/
private static final long serialVersionUID = 5326851249529076804L;
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel header = new JLabel();
JPanel areaPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc;
JLabel jLabel1 = new JLabel();
public JTextField fileField = new JTextField();
JButton browseB = new JButton();
JLabel jLabel2 = new JLabel();
public JTextField altField = new JTextField();
JLabel jLabel3 = new JLabel();
public JTextField widthField = new JTextField();
JLabel jLabel4 = new JLabel();
public JTextField heightField = new JTextField();
JLabel jLabel5 = new JLabel();
public JTextField hspaceField = new JTextField();
JLabel jLabel6 = new JLabel();
public JTextField vspaceField = new JTextField();
JLabel jLabel7 = new JLabel();
public JTextField borderField = new JTextField();
JLabel jLabel8 = new JLabel();
String[] aligns = {"left", "right", "top", "middle", "bottom", "absmiddle",
"texttop", "baseline"};
// Note: align values are not localized because they are HTML keywords
public JComboBox<String> alignCB = new JComboBox<String>(aligns);
JLabel jLabel9 = new JLabel();
public JTextField urlField = new JTextField();
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
JButton okB = new JButton();
JButton cancelB = new JButton();
public boolean CANCELLED = false;
public ImageDialog(Frame frame) {
super(frame, Local.getString("Image"), true);
try {
jbInit();
pack();
}
catch (Exception ex) {
ex.printStackTrace();
}
super.addWindowListener(this);
}
public ImageDialog() {
this(null);
}
void jbInit() throws Exception {
this.setResizable(false);
// three Panels, so used BorderLayout for this dialog.
headerPanel.setBorder(new EmptyBorder(new Insets(0, 5, 0, 5)));
headerPanel.setBackground(Color.WHITE);
header.setFont(new java.awt.Font("Dialog", 0, 20));
header.setForeground(new Color(0, 0, 124));
header.setText(Local.getString("Image"));
header.setIcon(new ImageIcon(
net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource(
"resources/icons/imgbig.png")));
headerPanel.add(header);
this.getContentPane().add(headerPanel, BorderLayout.NORTH);
areaPanel.setBorder(new EtchedBorder(Color.white, new Color(142, 142,
142)));
jLabel1.setText(Local.getString("Image file"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(10, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel1, gbc);
fileField.setMinimumSize(new Dimension(200, 25));
fileField.setPreferredSize(new Dimension(285, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.insets = new Insets(10, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
areaPanel.add(fileField, gbc);
browseB.setMinimumSize(new Dimension(25, 25));
browseB.setPreferredSize(new Dimension(25, 25));
browseB.setIcon(new ImageIcon(
net.sf.memoranda.ui.htmleditor.ImageDialog.class.getResource(
"resources/icons/fileopen16.png")));
browseB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
browseB_actionPerformed(e);
}
});
gbc = new GridBagConstraints();
gbc.gridx = 6;
gbc.gridy = 0;
gbc.insets = new Insets(10, 5, 5, 10);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(browseB, gbc);
jLabel2.setText(Local.getString("ALT text"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel2, gbc);
altField.setPreferredSize(new Dimension(315, 25));
altField.setMinimumSize(new Dimension(200, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 6;
gbc.insets = new Insets(5, 5, 5, 10);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
areaPanel.add(altField, gbc);
jLabel3.setText(Local.getString("Width"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel3, gbc);
widthField.setPreferredSize(new Dimension(30, 25));
widthField.setMinimumSize(new Dimension(30, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(widthField, gbc);
jLabel4.setText(Local.getString("Height"));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 2;
gbc.insets = new Insets(5, 50, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel4, gbc);
heightField.setMinimumSize(new Dimension(30, 25));
heightField.setPreferredSize(new Dimension(30, 25));
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(heightField, gbc);
jLabel5.setText(Local.getString("H. space"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel5, gbc);
hspaceField.setMinimumSize(new Dimension(30, 25));
hspaceField.setPreferredSize(new Dimension(30, 25));
hspaceField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(hspaceField, gbc);
jLabel6.setText(Local.getString("V. space"));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 3;
gbc.insets = new Insets(5, 50, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel6, gbc);
vspaceField.setMinimumSize(new Dimension(30, 25));
vspaceField.setPreferredSize(new Dimension(30, 25));
vspaceField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 3;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(vspaceField, gbc);
jLabel7.setText(Local.getString("Border"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 4;
gbc.insets = new Insets(5, 10, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel7, gbc);
borderField.setMinimumSize(new Dimension(30, 25));
borderField.setPreferredSize(new Dimension(30, 25));
borderField.setText("0");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 4;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(borderField, gbc);
jLabel8.setText(Local.getString("Align"));
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 4;
gbc.insets = new Insets(5, 50, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel8, gbc);
alignCB.setBackground(new Color(230, 230, 230));
alignCB.setFont(new java.awt.Font("Dialog", 1, 10));
alignCB.setPreferredSize(new Dimension(100, 25));
alignCB.setSelectedIndex(0);
gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(alignCB, gbc);
jLabel9.setText(Local.getString("Hyperlink"));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 5;
gbc.insets = new Insets(5, 10, 10, 5);
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(jLabel9, gbc);
urlField.setPreferredSize(new Dimension(315, 25));
urlField.setMinimumSize(new Dimension(200, 25));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 5;
gbc.gridwidth = 6;
gbc.insets = new Insets(5, 5, 10, 10);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.WEST;
areaPanel.add(urlField, gbc);
this.getContentPane().add(areaPanel, BorderLayout.CENTER);
okB.setMaximumSize(new Dimension(100, 26));
okB.setMinimumSize(new Dimension(100, 26));
okB.setPreferredSize(new Dimension(100, 26));
okB.setText(Local.getString("Ok"));
okB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
okB_actionPerformed(e);
}
});
this.getRootPane().setDefaultButton(okB);
cancelB.setMaximumSize(new Dimension(100, 26));
cancelB.setMinimumSize(new Dimension(100, 26));
cancelB.setPreferredSize(new Dimension(100, 26));
cancelB.setText(Local.getString("Cancel"));
cancelB.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelB_actionPerformed(e);
}
});
buttonsPanel.add(okB, null);
buttonsPanel.add(cancelB, null);
this.getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
}
void okB_actionPerformed(ActionEvent e) {
this.dispose();
}
void cancelB_actionPerformed(ActionEvent e) {
CANCELLED = true;
this.dispose();
}
private ImageIcon getPreviewIcon(java.io.File file) {
ImageIcon tmpIcon = new ImageIcon(file.getPath());
ImageIcon thmb = null;
if (tmpIcon.getIconHeight() > 48) {
thmb = new ImageIcon(tmpIcon.getImage()
.getScaledInstance( -1, 48, Image.SCALE_DEFAULT));
}
else {
thmb = tmpIcon;
}
if (thmb.getIconWidth() > 350) {
return new ImageIcon(thmb.getImage()
.getScaledInstance(350, -1, Image.SCALE_DEFAULT));
}
else {
return thmb;
}
}
public void updatePreview() {
try {
if (!(new java.net.URL(fileField.getText()).getPath()).equals(""))
header.setIcon(getPreviewIcon(new java.io.File(
new java.net.URL(fileField.getText()).getPath())));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
CANCELLED = true;
this.dispose();
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
void browseB_actionPerformed(ActionEvent e) {
// Fix until Sun's JVM supports more locales...
UIManager.put("FileChooser.lookInLabelText", Local
.getString("Look in:"));
UIManager.put("FileChooser.upFolderToolTipText", Local.getString(
"Up One Level"));
UIManager.put("FileChooser.newFolderToolTipText", Local.getString(
"Create New Folder"));
UIManager.put("FileChooser.listViewButtonToolTipText", Local
.getString("List"));
UIManager.put("FileChooser.detailsViewButtonToolTipText", Local
.getString("Details"));
UIManager.put("FileChooser.fileNameLabelText", Local.getString(
"File Name:"));
UIManager.put("FileChooser.filesOfTypeLabelText", Local.getString(
"Files of Type:"));
UIManager.put("FileChooser.openButtonText", Local.getString("Open"));
UIManager.put("FileChooser.openButtonToolTipText", Local.getString(
"Open selected file"));
UIManager
.put("FileChooser.cancelButtonText", Local.getString("Cancel"));
UIManager.put("FileChooser.cancelButtonToolTipText", Local.getString(
"Cancel"));
JFileChooser chooser = new JFileChooser();
chooser.setFileHidingEnabled(false);
chooser.setDialogTitle(Local.getString("Choose an image file"));
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.addChoosableFileFilter(
new net.sf.memoranda.ui.htmleditor.filechooser.ImageFilter());
chooser.setAccessory(
new net.sf.memoranda.ui.htmleditor.filechooser.ImagePreview(
chooser));
chooser.setPreferredSize(new Dimension(550, 375));
java.io.File lastSel = (java.io.File) Context.get(
"LAST_SELECTED_IMG_FILE");
if (lastSel != null)
chooser.setCurrentDirectory(lastSel);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
try {
fileField.setText(chooser.getSelectedFile().toURI().toURL().toString());
header.setIcon(getPreviewIcon(chooser.getSelectedFile()));
Context
.put("LAST_SELECTED_IMG_FILE", chooser
.getSelectedFile());
}
catch (Exception ex) {
fileField.setText(chooser.getSelectedFile().getPath());
}
try {
ImageIcon img = new ImageIcon(chooser.getSelectedFile()
.getPath());
widthField.setText(new Integer(img.getIconWidth()).toString());
heightField
.setText(new Integer(img.getIconHeight()).toString());
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
} | gpl-2.0 |
acsid/stendhal | tests/games/stendhal/server/actions/chat/AwayActionTest.java | 2201 | /***************************************************************************
* (C) Copyright 2003-2015 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.actions.chat;
import static org.junit.Assert.assertEquals;
import games.stendhal.server.entity.player.Player;
import marauroa.common.game.RPAction;
import org.junit.Test;
import utilities.PlayerTestHelper;
public class AwayActionTest {
/**
* Tests for playerIsNull.
*/
@Test(expected = NullPointerException.class)
public void testPlayerIsNull() {
final RPAction action = new RPAction();
action.put("type", "away");
final AwayAction aa = new AwayAction();
aa.onAction(null, action);
}
/**
* Tests for onAction.
*/
@Test
public void testOnAction() {
final Player bob = PlayerTestHelper.createPlayer("bob");
final RPAction action = new RPAction();
action.put("type", "away");
final AwayAction aa = new AwayAction();
aa.onAction(bob, action);
assertEquals(null, bob.getAwayMessage());
action.put("message", "bla");
aa.onAction(bob, action);
assertEquals("\"bla\"", bob.getAwayMessage());
}
/**
* Tests for onInvalidAction.
*/
@Test
public void testOnInvalidAction() {
final Player bob = PlayerTestHelper.createPlayer("bob");
bob.clearEvents();
final RPAction action = new RPAction();
action.put("type", "bla");
action.put("message", "bla");
final AwayAction aa = new AwayAction();
aa.onAction(bob, action);
assertEquals(null, bob.getAwayMessage());
}
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/pack200/src/main/java/org/apache/harmony/unpack200/bytecode/forms/IMethodRefForm.java | 2333 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.unpack200.bytecode.forms;
import org.apache.harmony.unpack200.SegmentConstantPool;
import org.apache.harmony.unpack200.bytecode.ByteCode;
import org.apache.harmony.unpack200.bytecode.CPInterfaceMethodRef;
import org.apache.harmony.unpack200.bytecode.OperandManager;
/**
* This class implements the byte code form for those bytecodes which have
* IMethod references (and only IMethod references).
*/
public class IMethodRefForm extends ReferenceForm {
public IMethodRefForm(int opcode, String name, int[] rewrite) {
super(opcode, name, rewrite);
}
protected int getOffset(OperandManager operandManager) {
return operandManager.nextIMethodRef();
}
protected int getPoolID() {
return SegmentConstantPool.CP_IMETHOD;
}
/*
* (non-Javadoc)
*
* @see org.apache.harmony.unpack200.bytecode.forms.ByteCodeForm#setByteCodeOperands(org.apache.harmony.unpack200.bytecode.ByteCode,
* org.apache.harmony.unpack200.bytecode.OperandTable,
* org.apache.harmony.unpack200.Segment)
*/
public void setByteCodeOperands(ByteCode byteCode,
OperandManager operandManager, int codeLength) {
super.setByteCodeOperands(byteCode, operandManager, codeLength);
final int count = ((CPInterfaceMethodRef) byteCode
.getNestedClassFileEntries()[0]).invokeInterfaceCount();
byteCode.getRewrite()[3] = count;
}
}
| gpl-2.0 |
Fakkar/TeligramFars | TMessagesProj/src/main/java/com/teligramfars/ui/SettingsActivity.java | 80162 | /*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.pouyadr.ui;
import android.animation.ObjectAnimator;
import android.animation.StateListAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Outline;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.InputType;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Base64;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.pouyadr.PhoneFormat.PhoneFormat;
import org.pouyadr.Pouya.Helper.GhostPorotocol;
import org.pouyadr.Pouya.Helper.ThemeChanger;
import org.pouyadr.Pouya.Setting.Setting;
import org.pouyadr.finalsoft.FontActivity;
import org.pouyadr.finalsoft.Fonts;
import org.pouyadr.messenger.AndroidUtilities;
import org.pouyadr.messenger.AnimationCompat.AnimatorListenerAdapterProxy;
import org.pouyadr.messenger.AnimationCompat.AnimatorSetProxy;
import org.pouyadr.messenger.AnimationCompat.ObjectAnimatorProxy;
import org.pouyadr.messenger.AnimationCompat.ViewProxy;
import org.pouyadr.messenger.ApplicationLoader;
import org.pouyadr.messenger.BuildVars;
import org.pouyadr.messenger.FileLoader;
import org.pouyadr.messenger.FileLog;
import org.pouyadr.messenger.LocaleController;
import org.pouyadr.messenger.MediaController;
import org.pouyadr.messenger.MessageObject;
import org.pouyadr.messenger.MessagesController;
import org.pouyadr.messenger.MessagesStorage;
import org.pouyadr.messenger.NotificationCenter;
import org.pouyadr.messenger.R;
import org.pouyadr.messenger.UserConfig;
import org.pouyadr.messenger.UserObject;
import org.pouyadr.messenger.browser.Browser;
import org.pouyadr.tgnet.ConnectionsManager;
import org.pouyadr.tgnet.RequestDelegate;
import org.pouyadr.tgnet.SerializedData;
import org.pouyadr.tgnet.TLObject;
import org.pouyadr.tgnet.TLRPC;
import org.pouyadr.ui.ActionBar.ActionBar;
import org.pouyadr.ui.ActionBar.ActionBarMenu;
import org.pouyadr.ui.ActionBar.ActionBarMenuItem;
import org.pouyadr.ui.ActionBar.BaseFragment;
import org.pouyadr.ui.ActionBar.BottomSheet;
import org.pouyadr.ui.ActionBar.Theme;
import org.pouyadr.ui.Adapters.BaseFragmentAdapter;
import org.pouyadr.ui.Cells.CheckBoxCell;
import org.pouyadr.ui.Cells.EmptyCell;
import org.pouyadr.ui.Cells.HeaderCell;
import org.pouyadr.ui.Cells.ShadowSectionCell;
import org.pouyadr.ui.Cells.TextCheckCell;
import org.pouyadr.ui.Cells.TextDetailSettingsCell;
import org.pouyadr.ui.Cells.TextInfoCell;
import org.pouyadr.ui.Cells.TextSettingsCell;
import org.pouyadr.ui.Components.AvatarDrawable;
import org.pouyadr.ui.Components.AvatarUpdater;
import org.pouyadr.ui.Components.BackupImageView;
import org.pouyadr.ui.Components.LayoutHelper;
import org.pouyadr.ui.Components.NumberPicker;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider {
private ListView listView;
private ListAdapter listAdapter;
private BackupImageView avatarImage;
private TextView nameTextView;
private TextView onlineTextView;
private ImageView writeButton;
private AnimatorSetProxy writeButtonAnimation;
private AvatarUpdater avatarUpdater = new AvatarUpdater();
private View extraHeightView;
private View shadowView;
private int extraHeight;
private int overscrollRow;
private int emptyRow;
private int numberSectionRow;
private int newgeramsectionrow;
private int newgeramsectionrow2;
private int ghostactivate;
private int showdateshamsi;
private int sendtyping;
private int showtimeago;
private int numberRow;
private int usernameRow;
private int settingsSectionRow;
private int settingsSectionRow2;
private int enableAnimationsRow;
private int notificationRow;
private int backgroundRow;
private int languageRow;
private int privacyRow;
private int mediaDownloadSection;
private int mediaDownloadSection2;
private int mobileDownloadRow;
private int wifiDownloadRow;
private int roamingDownloadRow;
private int saveToGalleryRow;
private int messagesSectionRow;
private int messagesSectionRow2;
private int customTabsRow;
private int directShareRow;
private int textSizeRow;
private int fontType;
private int stickersRow;
private int cacheRow;
private int raiseToSpeakRow;
private int sendByEnterRow;
private int supportSectionRow;
private int supportSectionRow2;
private int askQuestionRow;
private int telegramFaqRow;
private int privacyPolicyRow;
private int sendLogsRow;
private int clearLogsRow;
private int switchBackendButtonRow;
private int versionRow;
private int contactsSectionRow;
private int contactsReimportRow;
private int contactsSortRow;
private int autoplayGifsRow;
private int rowCount;
private final static int edit_name = 1;
private final static int logout = 2;
private int answeringmachinerow2;
private int answeringmachinerow;
private int tabletforceoverride;
private int anweringmachinactive;
private int answermachinetext;
private static class LinkMovementMethodMy extends LinkMovementMethod {
@Override
public boolean onTouchEvent(@NonNull TextView widget, @NonNull Spannable buffer, @NonNull MotionEvent event) {
try {
return super.onTouchEvent(widget, buffer, event);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return false;
}
}
@Override
public boolean onFragmentCreate() {
super.onFragmentCreate();
avatarUpdater.parentFragment = this;
avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() {
@Override
public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) {
TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();
req.caption = "";
req.crop = new TLRPC.TL_inputPhotoCropAuto();
req.file = file;
req.geo_point = new TLRPC.TL_inputGeoPointEmpty();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
if (user == null) {
return;
}
MessagesController.getInstance().putUser(user, false);
} else {
UserConfig.setCurrentUser(user);
}
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
user.photo = new TLRPC.TL_userProfilePhoto();
user.photo.photo_id = photo.photo.id;
if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
if (bigSize != null) {
user.photo.photo_big = bigSize.location;
} else if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
MessagesStorage.getInstance().clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
UserConfig.saveConfig(true);
}
});
}
}
});
}
};
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
rowCount = 0;
overscrollRow = rowCount++;
emptyRow = rowCount++;
numberSectionRow = rowCount++;
numberRow = rowCount++;
usernameRow = rowCount++;
newgeramsectionrow = rowCount++;
newgeramsectionrow2 = rowCount++;
ghostactivate = rowCount++;
sendtyping = rowCount++;
showtimeago = rowCount++;
showdateshamsi = rowCount++;
tabletforceoverride = rowCount++;
answeringmachinerow = rowCount++;
answeringmachinerow2 = rowCount++;
anweringmachinactive = rowCount++;
answermachinetext = rowCount++;
settingsSectionRow = rowCount++;
settingsSectionRow2 = rowCount++;
notificationRow = rowCount++;
privacyRow = rowCount++;
backgroundRow = rowCount++;
languageRow = rowCount++;
enableAnimationsRow = rowCount++;
mediaDownloadSection = rowCount++;
mediaDownloadSection2 = rowCount++;
mobileDownloadRow = rowCount++;
wifiDownloadRow = rowCount++;
roamingDownloadRow = rowCount++;
if (Build.VERSION.SDK_INT >= 11) {
autoplayGifsRow = rowCount++;
}
saveToGalleryRow = rowCount++;
messagesSectionRow = rowCount++;
messagesSectionRow2 = rowCount++;
customTabsRow = rowCount++;
if (Build.VERSION.SDK_INT >= 23) {
directShareRow = rowCount++;
}
textSizeRow = rowCount++;
fontType = rowCount++;
stickersRow = rowCount++;
cacheRow = rowCount++;
raiseToSpeakRow = rowCount++;
sendByEnterRow = rowCount++;
supportSectionRow = rowCount++;
supportSectionRow2 = rowCount++;
askQuestionRow = rowCount++;
telegramFaqRow = rowCount++;
privacyPolicyRow = rowCount++;
if (BuildVars.DEBUG_VERSION) {
sendLogsRow = rowCount++;
clearLogsRow = rowCount++;
switchBackendButtonRow = rowCount++;
}
versionRow = rowCount++;
//contactsSectionRow = rowCount++;
//contactsReimportRow = rowCount++;
//contactsSortRow = rowCount++;
MessagesController.getInstance().loadFullUser(UserConfig.getCurrentUser(), classGuid, true);
return true;
}
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
if (avatarImage != null) {
avatarImage.setImageDrawable(null);
}
MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId());
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
avatarUpdater.clear();
}
@Override
public View createView(final Context context) {
actionBar.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor());
actionBar.setItemsBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor());
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAddToContainer(false);
extraHeight = 88;
if (AndroidUtilities.isTablet()) {
actionBar.setOccupyStatusBar(false);
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
@Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == edit_name) {
presentFragment(new ChangeNameActivity());
} else if (id == logout) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().performLogout(true);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
}
});
ActionBarMenu menu = actionBar.createMenu();
ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0);
item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0);
listAdapter = new ListAdapter(context);
fragmentView = new FrameLayout(context) {
@Override
protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
if (child == listView) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (parentLayout != null) {
int actionBarHeight = 0;
int childCount = getChildCount();
for (int a = 0; a < childCount; a++) {
View view = getChildAt(a);
if (view == child) {
continue;
}
if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
if (((ActionBar) view).getCastShadows()) {
actionBarHeight = view.getMeasuredHeight();
}
break;
}
}
parentLayout.drawHeaderShadow(canvas, actionBarHeight);
}
return result;
} else {
return super.drawChild(canvas, child, drawingTime);
}
}
};
FrameLayout frameLayout = (FrameLayout) fragmentView;
listView = new ListView(context);
listView.setDivider(null);
listView.setDividerHeight(0);
listView.setVerticalScrollBarEnabled(false);
AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5));
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == textSizeRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize));
final NumberPicker numberPicker = new NumberPicker(getParentActivity());
numberPicker.setMinValue(12);
numberPicker.setMaxValue(30);
numberPicker.setValue(MessagesController.getInstance().fontSize);
builder.setView(numberPicker);
builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("fons_size", numberPicker.getValue());
MessagesController.getInstance().fontSize = numberPicker.getValue();
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
showDialog(builder.create());
} else if (i == fontType) {
// Toast.makeText(context, "ssssssssssss", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, FontActivity.class);
context.startActivity(intent);
} else if (i == enableAnimationsRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("view_animations", !animations);
editor.commit();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!animations);
}
} else if (i == notificationRow) {
presentFragment(new NotificationsSettingsActivity());
} else if (i == answermachinetext) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext));
final EditText input = new EditText(context);
input.setText(Setting.getAnsweringmachineText());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Setting.setAnsweringmachineText(input.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (i == backgroundRow) {
presentFragment(new WallpapersActivity());
} else if (i == askQuestionRow) {
if (getParentActivity() == null) {
return;
}
final TextView message = new TextView(getParentActivity());
message.setText(Html.fromHtml(LocaleController.getString("AskAQuestionInfo", R.string.AskAQuestionInfo)));
message.setTextSize(18);
message.setLinkTextColor(Theme.MSG_LINK_TEXT_COLOR);
// message.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont()));
message.setPadding(AndroidUtilities.dp(8), AndroidUtilities.dp(5), AndroidUtilities.dp(8), AndroidUtilities.dp(6));
message.setMovementMethod(new LinkMovementMethodMy());
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setView(message);
builder.setPositiveButton(LocaleController.getString("AskButton", R.string.AskButton), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
performAskAQuestion();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (i == sendLogsRow) {
sendLogs();
} else if (i == clearLogsRow) {
FileLog.cleanupLogs();
} else if (i == sendByEnterRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean send = preferences.getBoolean("send_by_enter", false);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("send_by_enter", !send);
editor.commit();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == ghostactivate) {
boolean send = Setting.getGhostMode();
GhostPorotocol.toggleGhostPortocol();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == sendtyping) {
boolean send = Setting.getSendTyping();
Setting.setSendTyping(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == anweringmachinactive) {
boolean send = Setting.getAnsweringMachine();
Setting.setAnsweringMachine(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == showtimeago) {
boolean send = Setting.getShowTimeAgo();
Setting.setShowTimeAgo(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == showdateshamsi) {
boolean send = Setting.getDatePersian();
Setting.setDatePersian(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == tabletforceoverride) {
boolean send = Setting.getTabletMode();
Setting.setTabletMode(!send);
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!send);
}
} else if (i == raiseToSpeakRow) {
MediaController.getInstance().toogleRaiseToSpeak();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canRaiseToSpeak());
}
} else if (i == autoplayGifsRow) {
MediaController.getInstance().toggleAutoplayGifs();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canAutoplayGifs());
}
} else if (i == saveToGalleryRow) {
MediaController.getInstance().toggleSaveToGallery();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canSaveToGallery());
}
} else if (i == customTabsRow) {
MediaController.getInstance().toggleCustomTabs();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canCustomTabs());
}
} else if (i == directShareRow) {
MediaController.getInstance().toggleDirectShare();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(MediaController.getInstance().canDirectShare());
}
} else if (i == privacyRow) {
presentFragment(new PrivacySettingsActivity());
} else if (i == languageRow) {
presentFragment(new LanguageSelectActivity());
} else if (i == switchBackendButtonRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ConnectionsManager.getInstance().switchBackend();
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (i == telegramFaqRow) {
Browser.openUrl(getParentActivity(), LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
} else if (i == privacyPolicyRow) {
Browser.openUrl(getParentActivity(), LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl));
} else if (i == contactsReimportRow) {
//not implemented
} else if (i == contactsSortRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy));
builder.setItems(new CharSequence[]{
LocaleController.getString("Default", R.string.Default),
LocaleController.getString("SortFirstName", R.string.SortFirstName),
LocaleController.getString("SortLastName", R.string.SortLastName)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("sortContactsBy", which);
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
} else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow) {
if (getParentActivity() == null) {
return;
}
final boolean maskValues[] = new boolean[6];
BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
int mask = 0;
if (i == mobileDownloadRow) {
mask = MediaController.getInstance().mobileDataDownloadMask;
} else if (i == wifiDownloadRow) {
mask = MediaController.getInstance().wifiDownloadMask;
} else if (i == roamingDownloadRow) {
mask = MediaController.getInstance().roamingDownloadMask;
}
builder.setApplyTopPadding(false);
builder.setApplyBottomPadding(false);
LinearLayout linearLayout = new LinearLayout(getParentActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
for (int a = 0; a < 6; a++) {
String name = null;
if (a == 0) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0;
name = LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
} else if (a == 1) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0;
name = LocaleController.getString("AttachAudio", R.string.AttachAudio);
} else if (a == 2) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0;
name = LocaleController.getString("AttachVideo", R.string.AttachVideo);
} else if (a == 3) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0;
name = LocaleController.getString("AttachDocument", R.string.AttachDocument);
} else if (a == 4) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0;
name = LocaleController.getString("AttachMusic", R.string.AttachMusic);
} else if (a == 5) {
if (Build.VERSION.SDK_INT >= 11) {
maskValues[a] = (mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0;
name = LocaleController.getString("AttachGif", R.string.AttachGif);
} else {
continue;
}
}
CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
checkBoxCell.setTag(a);
checkBoxCell.setBackgroundResource(R.drawable.list_selector);
linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
checkBoxCell.setText(name, "", maskValues[a], true);
checkBoxCell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBoxCell cell = (CheckBoxCell) v;
int num = (Integer) cell.getTag();
maskValues[num] = !maskValues[num];
cell.setChecked(maskValues[num], true);
}
});
}
BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
cell.setBackgroundResource(R.drawable.list_selector);
cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0);
cell.setTextColor(Theme.AUTODOWNLOAD_SHEET_SAVE_TEXT_COLOR);
cell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (visibleDialog != null) {
visibleDialog.dismiss();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
int newMask = 0;
for (int a = 0; a < 6; a++) {
if (maskValues[a]) {
if (a == 0) {
newMask |= MediaController.AUTODOWNLOAD_MASK_PHOTO;
} else if (a == 1) {
newMask |= MediaController.AUTODOWNLOAD_MASK_AUDIO;
} else if (a == 2) {
newMask |= MediaController.AUTODOWNLOAD_MASK_VIDEO;
} else if (a == 3) {
newMask |= MediaController.AUTODOWNLOAD_MASK_DOCUMENT;
} else if (a == 4) {
newMask |= MediaController.AUTODOWNLOAD_MASK_MUSIC;
} else if (a == 5) {
newMask |= MediaController.AUTODOWNLOAD_MASK_GIF;
}
}
}
SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
if (i == mobileDownloadRow) {
editor.putInt("mobileDataDownloadMask", newMask);
MediaController.getInstance().mobileDataDownloadMask = newMask;
} else if (i == wifiDownloadRow) {
editor.putInt("wifiDownloadMask", newMask);
MediaController.getInstance().wifiDownloadMask = newMask;
} else if (i == roamingDownloadRow) {
editor.putInt("roamingDownloadMask", newMask);
MediaController.getInstance().roamingDownloadMask = newMask;
}
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
builder.setCustomView(linearLayout);
showDialog(builder.create());
} else if (i == usernameRow) {
presentFragment(new ChangeUsernameActivity());
} else if (i == numberRow) {
presentFragment(new ChangePhoneHelpActivity());
} else if (i == stickersRow) {
presentFragment(new StickersActivity());
} else if (i == cacheRow) {
presentFragment(new CacheControlActivity());
}
}
});
frameLayout.addView(actionBar);
extraHeightView = new View(context);
ViewProxy.setPivotY(extraHeightView, 0);
extraHeightView.setBackgroundColor(ThemeChanger.getcurrent().getActionbarcolor());
frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88));
shadowView = new View(context);
shadowView.setBackgroundResource(R.drawable.header_shadow);
frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));
avatarImage = new BackupImageView(context);
avatarImage.setRoundRadius(AndroidUtilities.dp(21));
ViewProxy.setPivotX(avatarImage, 0);
ViewProxy.setPivotY(avatarImage, 0);
frameLayout.addView(avatarImage, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0));
avatarImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) {
PhotoViewer.getInstance().setParentActivity(getParentActivity());
PhotoViewer.getInstance().openPhoto(user.photo.photo_big, SettingsActivity.this);
}
}
});
nameTextView = new TextView(context);
nameTextView.setTextColor(0xffffffff);
nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
nameTextView.setLines(1);
nameTextView.setMaxLines(1);
nameTextView.setSingleLine(true);
nameTextView.setEllipsize(TextUtils.TruncateAt.END);
nameTextView.setGravity(Gravity.LEFT);
nameTextView.setTypeface(AndroidUtilities.getTypeface(org.pouyadr.finalsoft.Fonts.CurrentFont()));
ViewProxy.setPivotX(nameTextView, 0);
ViewProxy.setPivotY(nameTextView, 0);
frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0));
onlineTextView = new TextView(context);
onlineTextView.setTextColor(AvatarDrawable.getProfileTextColorForId(5));
onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
onlineTextView.setLines(1);
onlineTextView.setMaxLines(1);
onlineTextView.setSingleLine(true);
onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
onlineTextView.setGravity(Gravity.LEFT);
frameLayout.addView(onlineTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, 48, 0));
writeButton = new ImageView(context);
writeButton.setBackgroundResource(R.drawable.floating_user_states);
writeButton.setImageResource(R.drawable.floating_camera);
writeButton.setScaleType(ImageView.ScaleType.CENTER);
if (Build.VERSION.SDK_INT >= 21) {
StateListAnimator animator = new StateListAnimator();
animator.addState(new int[]{android.R.attr.state_pressed}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
animator.addState(new int[]{}, ObjectAnimator.ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
writeButton.setStateListAnimator(animator);
writeButton.setOutlineProvider(new ViewOutlineProvider() {
@SuppressLint("NewApi")
@Override
public void getOutline(View view, Outline outline) {
outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
}
});
}
frameLayout.addView(writeButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0));
writeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
CharSequence[] items;
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
}
if (user == null) {
return;
}
boolean fullMenu = false;
if (user.photo != null && user.photo.photo_big != null && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty)) {
items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley), LocaleController.getString("DeletePhoto", R.string.DeletePhoto)};
fullMenu = true;
} else {
items = new CharSequence[]{LocaleController.getString("FromCamera", R.string.FromCamera), LocaleController.getString("FromGalley", R.string.FromGalley)};
}
final boolean full = fullMenu;
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
avatarUpdater.openCamera();
} else if (i == 1) {
avatarUpdater.openGallery();
} else if (i == 2) {
MessagesController.getInstance().deleteUserPhoto(null);
}
}
});
showDialog(builder.create());
}
});
needLayout();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (totalItemCount == 0) {
return;
}
int height = 0;
View child = view.getChildAt(0);
if (child != null) {
if (firstVisibleItem == 0) {
height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0);
}
if (extraHeight != height) {
extraHeight = height;
needLayout();
}
}
}
});
return fragmentView;
}
@Override
protected void onDialogDismiss(Dialog dialog) {
MediaController.getInstance().checkAutodownloadSettings();
}
@Override
public void updatePhotoAtIndex(int index) {
}
@Override
public PhotoViewer.PlaceProviderObject getPlaceForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
if (fileLocation == null) {
return null;
}
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user != null && user.photo != null && user.photo.photo_big != null) {
TLRPC.FileLocation photoBig = user.photo.photo_big;
if (photoBig.local_id == fileLocation.local_id && photoBig.volume_id == fileLocation.volume_id && photoBig.dc_id == fileLocation.dc_id) {
int coords[] = new int[2];
avatarImage.getLocationInWindow(coords);
PhotoViewer.PlaceProviderObject object = new PhotoViewer.PlaceProviderObject();
object.viewX = coords[0];
object.viewY = coords[1] - AndroidUtilities.statusBarHeight;
object.parentView = avatarImage;
object.imageReceiver = avatarImage.getImageReceiver();
object.user_id = UserConfig.getClientUserId();
object.thumb = object.imageReceiver.getBitmap();
object.size = -1;
object.radius = avatarImage.getImageReceiver().getRoundRadius();
object.scale = ViewProxy.getScaleX(avatarImage);
return object;
}
}
return null;
}
@Override
public Bitmap getThumbForPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
return null;
}
@Override
public void willSwitchFromPhoto(MessageObject messageObject, TLRPC.FileLocation fileLocation, int index) {
}
@Override
public void willHidePhotoViewer() {
avatarImage.getImageReceiver().setVisible(true, true);
}
@Override
public boolean isPhotoChecked(int index) {
return false;
}
@Override
public void setPhotoChecked(int index) {
}
@Override
public boolean cancelButtonPressed() {
return true;
}
@Override
public void sendButtonPressed(int index) {
}
@Override
public int getSelectedCount() {
return 0;
}
public void performAskAQuestion() {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int uid = preferences.getInt("support_id", 0);
TLRPC.User supportUser = null;
if (uid != 0) {
supportUser = MessagesController.getInstance().getUser(uid);
if (supportUser == null) {
String userString = preferences.getString("support_user", null);
if (userString != null) {
try {
byte[] datacentersBytes = Base64.decode(userString, Base64.DEFAULT);
if (datacentersBytes != null) {
SerializedData data = new SerializedData(datacentersBytes);
supportUser = TLRPC.User.TLdeserialize(data, data.readInt32(false), false);
if (supportUser != null && supportUser.id == 333000) {
supportUser = null;
}
data.cleanup();
}
} catch (Exception e) {
FileLog.e("tmessages", e);
supportUser = null;
}
}
}
}
if (supportUser == null) {
final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
TLRPC.TL_help_getSupport req = new TLRPC.TL_help_getSupport();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
@Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
final TLRPC.TL_help_support res = (TLRPC.TL_help_support) response;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("support_id", res.user.id);
SerializedData data = new SerializedData();
res.user.serializeToStream(data);
editor.putString("support_user", Base64.encodeToString(data.toByteArray(), Base64.DEFAULT));
editor.commit();
data.cleanup();
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(res.user);
MessagesStorage.getInstance().putUsersAndChats(users, null, true, true);
MessagesController.getInstance().putUser(res.user, false);
Bundle args = new Bundle();
args.putInt("user_id", res.user.id);
presentFragment(new ChatActivity(args));
}
});
} else {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
}
});
} else {
MessagesController.getInstance().putUser(supportUser, true);
Bundle args = new Bundle();
args.putInt("user_id", supportUser.id);
presentFragment(new ChatActivity(args));
}
}
@Override
public void onActivityResultFragment(int requestCode, int resultCode, Intent data) {
avatarUpdater.onActivityResult(requestCode, resultCode, data);
}
@Override
public void saveSelfArgs(Bundle args) {
if (avatarUpdater != null && avatarUpdater.currentPicturePath != null) {
args.putString("path", avatarUpdater.currentPicturePath);
}
}
@Override
public void restoreSelfArgs(Bundle args) {
if (avatarUpdater != null) {
avatarUpdater.currentPicturePath = args.getString("path");
}
}
@Override
public void didReceivedNotification(int id, Object... args) {
if (id == NotificationCenter.updateInterfaces) {
int mask = (Integer) args[0];
if ((mask & MessagesController.UPDATE_MASK_AVATAR) != 0 || (mask & MessagesController.UPDATE_MASK_NAME) != 0) {
updateUserData();
}
}
}
@Override
public void onResume() {
super.onResume();
if (listAdapter != null) {
listAdapter.notifyDataSetChanged();
}
updateUserData();
fixLayout();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
fixLayout();
}
private void needLayout() {
FrameLayout.LayoutParams layoutParams;
int newTop = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight();
if (listView != null) {
layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
if (layoutParams.topMargin != newTop) {
layoutParams.topMargin = newTop;
listView.setLayoutParams(layoutParams);
ViewProxy.setTranslationY(extraHeightView, newTop);
}
}
if (avatarImage != null) {
float diff = extraHeight / (float) AndroidUtilities.dp(88);
ViewProxy.setScaleY(extraHeightView, diff);
ViewProxy.setTranslationY(shadowView, newTop + extraHeight);
if (Build.VERSION.SDK_INT < 11) {
layoutParams = (FrameLayout.LayoutParams) writeButton.getLayoutParams();
layoutParams.topMargin = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f);
writeButton.setLayoutParams(layoutParams);
} else {
ViewProxy.setTranslationY(writeButton, (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() + extraHeight - AndroidUtilities.dp(29.5f));
}
final boolean setVisible = diff > 0.2f;
boolean currentVisible = writeButton.getTag() == null;
if (setVisible != currentVisible) {
if (setVisible) {
writeButton.setTag(null);
writeButton.setVisibility(View.VISIBLE);
} else {
writeButton.setTag(0);
}
if (writeButtonAnimation != null) {
AnimatorSetProxy old = writeButtonAnimation;
writeButtonAnimation = null;
old.cancel();
}
writeButtonAnimation = new AnimatorSetProxy();
if (setVisible) {
writeButtonAnimation.setInterpolator(new DecelerateInterpolator());
writeButtonAnimation.playTogether(
ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 1.0f),
ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 1.0f),
ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 1.0f)
);
} else {
writeButtonAnimation.setInterpolator(new AccelerateInterpolator());
writeButtonAnimation.playTogether(
ObjectAnimatorProxy.ofFloat(writeButton, "scaleX", 0.2f),
ObjectAnimatorProxy.ofFloat(writeButton, "scaleY", 0.2f),
ObjectAnimatorProxy.ofFloat(writeButton, "alpha", 0.0f)
);
}
writeButtonAnimation.setDuration(150);
writeButtonAnimation.addListener(new AnimatorListenerAdapterProxy() {
@Override
public void onAnimationEnd(Object animation) {
if (writeButtonAnimation != null && writeButtonAnimation.equals(animation)) {
writeButton.clearAnimation();
writeButton.setVisibility(setVisible ? View.VISIBLE : View.GONE);
writeButtonAnimation = null;
}
}
});
writeButtonAnimation.start();
}
ViewProxy.setScaleX(avatarImage, (42 + 18 * diff) / 42.0f);
ViewProxy.setScaleY(avatarImage, (42 + 18 * diff) / 42.0f);
float avatarY = (actionBar.getOccupyStatusBar() ? AndroidUtilities.statusBarHeight : 0) + ActionBar.getCurrentActionBarHeight() / 2.0f * (1.0f + diff) - 21 * AndroidUtilities.density + 27 * AndroidUtilities.density * diff;
ViewProxy.setTranslationX(avatarImage, -AndroidUtilities.dp(47) * diff);
ViewProxy.setTranslationY(avatarImage, (float) Math.ceil(avatarY));
ViewProxy.setTranslationX(nameTextView, -21 * AndroidUtilities.density * diff);
ViewProxy.setTranslationY(nameTextView, (float) Math.floor(avatarY) - (float) Math.ceil(AndroidUtilities.density) + (float) Math.floor(7 * AndroidUtilities.density * diff));
ViewProxy.setTranslationX(onlineTextView, -21 * AndroidUtilities.density * diff);
ViewProxy.setTranslationY(onlineTextView, (float) Math.floor(avatarY) + AndroidUtilities.dp(22) + (float) Math.floor(11 * AndroidUtilities.density) * diff);
ViewProxy.setScaleX(nameTextView, 1.0f + 0.12f * diff);
ViewProxy.setScaleY(nameTextView, 1.0f + 0.12f * diff);
}
}
private void fixLayout() {
if (fragmentView == null) {
return;
}
fragmentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (fragmentView != null) {
needLayout();
fragmentView.getViewTreeObserver().removeOnPreDrawListener(this);
}
return true;
}
});
}
private void updateUserData() {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
TLRPC.FileLocation photo = null;
TLRPC.FileLocation photoBig = null;
if (user.photo != null) {
photo = user.photo.photo_small;
photoBig = user.photo.photo_big;
}
AvatarDrawable avatarDrawable = new AvatarDrawable(user, true);
avatarDrawable.setColor(Theme.ACTION_BAR_MAIN_AVATAR_COLOR);
if (avatarImage != null) {
avatarImage.setImage(photo, "50_50", avatarDrawable);
avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false);
nameTextView.setText(UserObject.getUserName(user));
onlineTextView.setText(LocaleController.getString("Online", R.string.Online));
avatarImage.getImageReceiver().setVisible(!PhotoViewer.getInstance().isShowingImage(photoBig), false);
}
}
private void sendLogs() {
try {
ArrayList<Uri> uris = new ArrayList<>();
File sdCard = ApplicationLoader.applicationContext.getExternalFilesDir(null);
File dir = new File(sdCard.getAbsolutePath() + "/logs");
File[] files = dir.listFiles();
for (File file : files) {
uris.add(Uri.fromFile(file));
}
if (uris.isEmpty()) {
return;
}
Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{BuildVars.SEND_LOGS_EMAIL});
i.putExtra(Intent.EXTRA_SUBJECT, "last logs");
i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
getParentActivity().startActivityForResult(Intent.createChooser(i, "Select email application."), 500);
} catch (Exception e) {
e.printStackTrace();
}
}
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;
public ListAdapter(Context context) {
mContext = context;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int i) {
return i == textSizeRow || i == fontType || i == tabletforceoverride || i == anweringmachinactive || i == answermachinetext || i == sendtyping || i == showdateshamsi || i == showtimeago || i == ghostactivate || i == enableAnimationsRow || i == notificationRow || i == backgroundRow || i == numberRow ||
i == askQuestionRow || i == sendLogsRow || i == sendByEnterRow || i == autoplayGifsRow || i == privacyRow || i == wifiDownloadRow ||
i == mobileDownloadRow || i == clearLogsRow || i == roamingDownloadRow || i == languageRow || i == usernameRow ||
i == switchBackendButtonRow || i == telegramFaqRow || i == contactsSortRow || i == contactsReimportRow || i == saveToGalleryRow ||
i == stickersRow || i == cacheRow || i == raiseToSpeakRow || i == privacyPolicyRow || i == customTabsRow || i == directShareRow;
}
@Override
public int getCount() {
return rowCount;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
int type = getItemViewType(i);
if (type == 0) {
if (view == null) {
view = new EmptyCell(mContext);
}
if (i == overscrollRow) {
((EmptyCell) view).setHeight(AndroidUtilities.dp(88));
} else {
((EmptyCell) view).setHeight(AndroidUtilities.dp(16));
}
} else if (type == 1) {
if (view == null) {
view = new ShadowSectionCell(mContext);
}
} else if (type == 2) {
if (view == null) {
view = new TextSettingsCell(mContext);
}
TextSettingsCell textCell = (TextSettingsCell) view;
if (i == textSizeRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int size = preferences.getInt("fons_size", AndroidUtilities.isTablet() ? 18 : 16);
textCell.setTextAndValue(LocaleController.getString("TextSize", R.string.TextSize), String.format("%d", size), true);
} else if (i == fontType) {
textCell.setTextAndValue( "نوع خط نوشتاری", Fonts.CurrentFont().replace("fonts/","").replace(".ttf",""), true);
} else if (i == languageRow) {
textCell.setTextAndValue(LocaleController.getString("Language", R.string.Language), LocaleController.getCurrentLanguageName(), true);
} else if (i == contactsSortRow) {
String value;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
int sort = preferences.getInt("sortContactsBy", 0);
if (sort == 0) {
value = LocaleController.getString("Default", R.string.Default);
} else if (sort == 1) {
value = LocaleController.getString("FirstName", R.string.SortFirstName);
} else {
value = LocaleController.getString("LastName", R.string.SortLastName);
}
textCell.setTextAndValue(LocaleController.getString("SortBy", R.string.SortBy), value, true);
} else if (i == notificationRow) {
textCell.setText(LocaleController.getString("NotificationsAndSounds", R.string.NotificationsAndSounds), true);
} else if (i == backgroundRow) {
textCell.setText(LocaleController.getString("ChatBackground", R.string.ChatBackground), true);
} else if (i == answermachinetext) {
textCell.setTextAndValue(LocaleController.getString("Answeringmachinetext", R.string.Answeringmachinetext), Setting.getAnsweringmachineText(), true);
} else if (i == sendLogsRow) {
textCell.setText("Send Logs", true);
} else if (i == clearLogsRow) {
textCell.setText("Clear Logs", true);
} else if (i == askQuestionRow) {
textCell.setText(LocaleController.getString("AskAQuestion", R.string.AskAQuestion), true);
} else if (i == privacyRow) {
textCell.setText(LocaleController.getString("PrivacySettings", R.string.PrivacySettings), true);
} else if (i == switchBackendButtonRow) {
textCell.setText("Switch Backend", true);
} else if (i == telegramFaqRow) {
textCell.setText(LocaleController.getString("TelegramFAQ", R.string.TelegramFaq), true);
} else if (i == contactsReimportRow) {
textCell.setText(LocaleController.getString("ImportContacts", R.string.ImportContacts), true);
} else if (i == stickersRow) {
textCell.setText(LocaleController.getString("Stickers", R.string.Stickers), true);
} else if (i == cacheRow) {
textCell.setText(LocaleController.getString("CacheSettings", R.string.CacheSettings), true);
} else if (i == privacyPolicyRow) {
textCell.setText(LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy), true);
}
} else if (type == 3) {
if (view == null) {
view = new TextCheckCell(mContext);
}
TextCheckCell textCell = (TextCheckCell) view;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (i == enableAnimationsRow) {
textCell.setTextAndCheck(LocaleController.getString("EnableAnimations", R.string.EnableAnimations), preferences.getBoolean("view_animations", true), false);
} else if (i == sendByEnterRow) {
textCell.setTextAndCheck(LocaleController.getString("SendByEnter", R.string.SendByEnter), preferences.getBoolean("send_by_enter", false), false);
} else if (i == ghostactivate) {
textCell.setTextAndValueAndCheck(LocaleController.getString("GhostMode", R.string.GhostMode), LocaleController.getString("GhostModeInfo", R.string.GhostModeInfo), Setting.getGhostMode(), true, true);
} else if (i == sendtyping) {
textCell.setTextAndValueAndCheck(LocaleController.getString("HideTypingState", R.string.HideTypingState), LocaleController.getString("HideTypingStateinfo", R.string.HideTypingStateinfo), Setting.getSendTyping(), true, true);
} else if (i == anweringmachinactive) {
textCell.setTextAndValueAndCheck(LocaleController.getString("Answeringmachineenable", R.string.Answeringmachineenable), LocaleController.getString("Answeringmachineenableinfo", R.string.Answeringmachineenableinfo), Setting.getAnsweringMachine(), true, true);
} else if (i == showtimeago) {
textCell.setTextAndValueAndCheck(LocaleController.getString("showtimeago", R.string.showtimeago), LocaleController.getString("showtimeagoinfo", R.string.showtimeagoinfo), Setting.getShowTimeAgo(), true, true);
} else if (i == showdateshamsi) {
textCell.setTextAndValueAndCheck(LocaleController.getString("showshamsidate", R.string.Showshamsidate), LocaleController.getString("showshamsidateinfo", R.string.showshamsidateinfo), Setting.getDatePersian(), true, true);
} else if (i == tabletforceoverride) {
textCell.setTextAndValueAndCheck(LocaleController.getString("TabletMode", R.string.TabletMode), LocaleController.getString("tabletmodeinfo", R.string.tabletmodeinfo), Setting.getTabletMode(), true, true);
} else if (i == saveToGalleryRow) {
textCell.setTextAndCheck(LocaleController.getString("SaveToGallerySettings", R.string.SaveToGallerySettings), MediaController.getInstance().canSaveToGallery(), false);
} else if (i == autoplayGifsRow) {
textCell.setTextAndCheck(LocaleController.getString("AutoplayGifs", R.string.AutoplayGifs), MediaController.getInstance().canAutoplayGifs(), true);
} else if (i == raiseToSpeakRow) {
textCell.setTextAndCheck(LocaleController.getString("RaiseToSpeak", R.string.RaiseToSpeak), MediaController.getInstance().canRaiseToSpeak(), true);
} else if (i == customTabsRow) {
textCell.setTextAndValueAndCheck(LocaleController.getString("ChromeCustomTabs", R.string.ChromeCustomTabs), LocaleController.getString("ChromeCustomTabsInfo", R.string.ChromeCustomTabsInfo), MediaController.getInstance().canCustomTabs(), false, true);
} else if (i == directShareRow) {
textCell.setTextAndValueAndCheck(LocaleController.getString("DirectShare", R.string.DirectShare), LocaleController.getString("DirectShareInfo", R.string.DirectShareInfo), MediaController.getInstance().canDirectShare(), false, true);
}
} else if (type == 4) {
if (view == null) {
view = new HeaderCell(mContext);
}
if (i == answeringmachinerow2) {
((HeaderCell) view).setText(LocaleController.getString("AnsweringMachin", R.string.answeringmachine));
} else if (i == settingsSectionRow2) {
((HeaderCell) view).setText(LocaleController.getString("SETTINGS", R.string.SETTINGS));
} else if (i == supportSectionRow2) {
((HeaderCell) view).setText(LocaleController.getString("Support", R.string.Support));
} else if (i == messagesSectionRow2) {
((HeaderCell) view).setText(LocaleController.getString("MessagesSettings", R.string.MessagesSettings));
} else if (i == mediaDownloadSection2) {
((HeaderCell) view).setText(LocaleController.getString("AutomaticMediaDownload", R.string.AutomaticMediaDownload));
} else if (i == numberSectionRow) {
((HeaderCell) view).setText(LocaleController.getString("Info", R.string.Info));
} else if (i == newgeramsectionrow2) {
((HeaderCell) view).setText(LocaleController.getString("NewGramSettings", R.string.newgeramsettings));
}
} else if (type == 5) {
if (view == null) {
view = new TextInfoCell(mContext);
try {
PackageInfo pInfo = ApplicationLoader.applicationContext.getPackageManager().getPackageInfo(ApplicationLoader.applicationContext.getPackageName(), 0);
int code = pInfo.versionCode / 10;
String abi = "";
switch (pInfo.versionCode % 10) {
case 0:
abi = "arm";
break;
case 1:
abi = "arm-v7a";
break;
case 2:
abi = "x86";
break;
case 3:
abi = "universal";
break;
}
((TextInfoCell) view).setText(String.format(Locale.US, "AriaGram for Android v%s (%d) %s", pInfo.versionName, code, abi));
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
} else if (type == 6) {
if (view == null) {
view = new TextDetailSettingsCell(mContext);
}
TextDetailSettingsCell textCell = (TextDetailSettingsCell) view;
if (i == mobileDownloadRow || i == wifiDownloadRow || i == roamingDownloadRow) {
int mask;
String value;
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (i == mobileDownloadRow) {
value = LocaleController.getString("WhenUsingMobileData", R.string.WhenUsingMobileData);
mask = MediaController.getInstance().mobileDataDownloadMask;
} else if (i == wifiDownloadRow) {
value = LocaleController.getString("WhenConnectedOnWiFi", R.string.WhenConnectedOnWiFi);
mask = MediaController.getInstance().wifiDownloadMask;
} else {
value = LocaleController.getString("WhenRoaming", R.string.WhenRoaming);
mask = MediaController.getInstance().roamingDownloadMask;
}
String text = "";
if ((mask & MediaController.AUTODOWNLOAD_MASK_PHOTO) != 0) {
text += LocaleController.getString("AttachPhoto", R.string.AttachPhoto);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_AUDIO) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachAudio", R.string.AttachAudio);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_VIDEO) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachVideo", R.string.AttachVideo);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_DOCUMENT) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachDocument", R.string.AttachDocument);
}
if ((mask & MediaController.AUTODOWNLOAD_MASK_MUSIC) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachMusic", R.string.AttachMusic);
}
if (Build.VERSION.SDK_INT >= 11) {
if ((mask & MediaController.AUTODOWNLOAD_MASK_GIF) != 0) {
if (text.length() != 0) {
text += ", ";
}
text += LocaleController.getString("AttachGif", R.string.AttachGif);
}
}
if (text.length() == 0) {
text = LocaleController.getString("NoMediaAutoDownload", R.string.NoMediaAutoDownload);
}
textCell.setTextAndValue(value, text, true);
} else if (i == numberRow) {
TLRPC.User user = UserConfig.getCurrentUser();
String value;
if (user != null && user.phone != null && user.phone.length() != 0) {
value = PhoneFormat.getInstance().format("+" + user.phone);
} else {
value = LocaleController.getString("NumberUnknown", R.string.NumberUnknown);
}
textCell.setTextAndValue(value, LocaleController.getString("Phone", R.string.Phone), true);
} else if (i == usernameRow) {
TLRPC.User user = UserConfig.getCurrentUser();
String value;
if (user != null && user.username != null && user.username.length() != 0) {
value = "@" + user.username;
} else {
value = LocaleController.getString("UsernameEmpty", R.string.UsernameEmpty);
}
// Log.i("username",""+ user.username);
textCell.setTextAndValue(value, LocaleController.getString("Username", R.string.Username), false);
}
}
return view;
}
@Override
public int getItemViewType(int i) {
if (i == emptyRow || i == overscrollRow) {
return 0;
}
if (i == answeringmachinerow || i == settingsSectionRow || i == newgeramsectionrow || i == supportSectionRow || i == messagesSectionRow || i == mediaDownloadSection || i == contactsSectionRow) {
return 1;
} else if (i == enableAnimationsRow || i == tabletforceoverride || i == showdateshamsi || i == showtimeago || i == anweringmachinactive || i == sendtyping || i == ghostactivate || i == sendByEnterRow || i == saveToGalleryRow || i == autoplayGifsRow || i == raiseToSpeakRow || i == customTabsRow || i == directShareRow) {
return 3;
} else if (i == notificationRow || i == answermachinetext || i == backgroundRow || i == askQuestionRow || i == sendLogsRow || i == privacyRow || i == clearLogsRow || i == switchBackendButtonRow || i == telegramFaqRow || i == contactsReimportRow || i == textSizeRow || i == fontType || i == languageRow || i == contactsSortRow || i == stickersRow || i == cacheRow || i == privacyPolicyRow) {
return 2;
} else if (i == versionRow) {
return 5;
} else if (i == wifiDownloadRow || i == mobileDownloadRow || i == roamingDownloadRow || i == numberRow || i == usernameRow) {
return 6;
} else if (i == settingsSectionRow2 || i == answeringmachinerow2 || i == newgeramsectionrow2 || i == messagesSectionRow2 || i == supportSectionRow2 || i == numberSectionRow || i == mediaDownloadSection2) {
return 4;
} else {
return 2;
}
}
@Override
public int getViewTypeCount() {
return 7;
}
@Override
public boolean isEmpty() {
return false;
}
}
}
| gpl-2.0 |
ntj/ComplexRapidMiner | src/com/rapidminer/operator/similarity/SimilarityExampleSet.java | 5564 | /*
* RapidMiner
*
* Copyright (C) 2001-2008 by Rapid-I and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapid-i.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.similarity;
import java.util.Iterator;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.SimpleAttributes;
import com.rapidminer.example.set.AbstractExampleReader;
import com.rapidminer.example.set.AbstractExampleSet;
import com.rapidminer.example.set.MappedExampleSet;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.DoubleArrayDataRow;
import com.rapidminer.example.table.ExampleTable;
import com.rapidminer.example.table.NominalMapping;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.math.similarity.DistanceMeasure;
/**
* This similarity based example set is used for the operator
* {@link ExampleSet2SimilarityExampleSet}.
*
* @author Ingo Mierswa
* @version $Id: SimilarityExampleSet.java,v 1.1 2008/09/08 18:53:49 ingomierswa Exp $
*/
public class SimilarityExampleSet extends AbstractExampleSet {
private static final long serialVersionUID = 4757975818441794105L;
private static class IndexExampleReader extends AbstractExampleReader {
private int index = 0;
private ExampleSet exampleSet;
public IndexExampleReader(ExampleSet exampleSet) {
this.exampleSet = exampleSet;
}
public boolean hasNext() {
return index < exampleSet.size() - 1;
}
public Example next() {
Example example = exampleSet.getExample(index);
index++;
return example;
}
}
private ExampleSet parent;
private Attribute parentIdAttribute;
private Attributes attributes;
private DistanceMeasure measure;
public SimilarityExampleSet(ExampleSet parent, DistanceMeasure measure) {
this.parent = parent;
this.parentIdAttribute = parent.getAttributes().getId();
this.attributes = new SimpleAttributes();
Attribute firstIdAttribute = null;
Attribute secondIdAttribute = null;
if (parentIdAttribute.isNominal()) {
firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NOMINAL);
secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NOMINAL);
} else {
firstIdAttribute = AttributeFactory.createAttribute("FIRST_ID", Ontology.NUMERICAL);
secondIdAttribute = AttributeFactory.createAttribute("SECOND_ID", Ontology.NUMERICAL);
}
this.attributes.addRegular(firstIdAttribute);
this.attributes.addRegular(secondIdAttribute);
firstIdAttribute.setTableIndex(0);
secondIdAttribute.setTableIndex(1);
// copying mapping of original id attribute
if (parentIdAttribute.isNominal()) {
NominalMapping mapping = parentIdAttribute.getMapping();
firstIdAttribute.setMapping(mapping);
secondIdAttribute.setMapping(mapping);
}
String name = "SIMILARITY";
if (measure.isDistance()) {
name = "DISTANCE";
}
Attribute similarityAttribute = AttributeFactory.createAttribute(name, Ontology.REAL);
this.attributes.addRegular(similarityAttribute);
similarityAttribute.setTableIndex(2);
this.measure = measure;
}
public boolean equals(Object o) {
if (!super.equals(o))
return false;
if (!(o instanceof MappedExampleSet))
return false;
SimilarityExampleSet other = (SimilarityExampleSet)o;
if (!this.measure.getClass().equals(other.measure.getClass()))
return false;
return true;
}
public int hashCode() {
return super.hashCode() ^ this.measure.getClass().hashCode();
}
public Attributes getAttributes() {
return this.attributes;
}
public Example getExample(int index) {
int firstIndex = index / this.parent.size();
int secondIndex = index % this.parent.size();
Example firstExample = this.parent.getExample(firstIndex);
Example secondExample = this.parent.getExample(secondIndex);
double[] data = new double[3];
data[0] = firstExample.getValue(parentIdAttribute);
data[1] = secondExample.getValue(parentIdAttribute);
if (measure.isDistance())
data[2] = measure.calculateDistance(firstExample, secondExample);
else
data[2] = measure.calculateSimilarity(firstExample, secondExample);
return new Example(new DoubleArrayDataRow(data), this);
}
public Iterator<Example> iterator() {
return new IndexExampleReader(this);
}
public ExampleTable getExampleTable() {
return null;//this.parent.getExampleTable();
}
public int size() {
return this.parent.size() * this.parent.size();
}
}
| gpl-2.0 |
droberg/yamsLog | client-backend/src/NewDebugger.java | 8996 | /**
* yamsLog is a program for real time multi sensor logging and
* supervision
* Copyright (C) 2014
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import Database.Messages.ProjectMetaData;
import Database.Sensors.Sensor;
import Errors.BackendError;
import FrontendConnection.Backend;
import FrontendConnection.Listeners.ProjectCreationStatusListener;
import protobuf.Protocol;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created with IntelliJ IDEA.
* User: Aitesh
* Date: 2014-04-10
* Time: 09:34
* To change this template use File | Settings | File Templates.
*/
public class NewDebugger implements ProjectCreationStatusListener {
private boolean projectListChanged;
public NewDebugger(){
try{
Backend.createInstance(null); //args[0],Integer.parseInt(args[1]),
Backend.getInstance().addProjectCreationStatusListener(this);
Backend.getInstance().connectToServer("130.236.63.46",2001);
} catch (BackendError b){
b.printStackTrace();
}
projectListChanged = false;
}
private synchronized boolean readWriteBoolean(Boolean b){
if(b!=null) projectListChanged=b;
return projectListChanged;
}
public void runPlayback() {
try{
Thread.sleep(1000); //Backend.getInstance().sendSettingsRequestMessageALlSensors(0);
readWriteBoolean(false);
Random r = new Random();
String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"};
String project = "projectName" +r.nextInt()%10000;
String playbackProject = "realCollection";
Thread.sleep(1000);
System.out.println("Setting active project to : " + playbackProject);
Backend.getInstance().setActiveProject(playbackProject);
ProjectMetaData d = new ProjectMetaData();
d.setTest_leader("ffu");
d.setDate(1l);
List<String> s = new ArrayList<String>();
s.add("memer1");
d.setMember_names(s);
d.setTags(s);
d.setDescription("desc");
List l = d.getMember_names();
l.add(r.nextInt()+". name");
d.setMember_names(l);
Backend.getInstance().sendProjectMetaData(d);
System.out.println("starting data collection");
Thread.sleep(100);
String experimentName = "smallrun";
//Backend.getInstance().setActiveProject(playbackProject);
// projektnamn:
Thread.sleep(3000);
// Backend.getInstance().getSensorConfigurationForPlayback().getSensorId();
List<Protocol.SensorConfiguration> playbackConfig;
playbackConfig = Backend.getInstance().getSensorConfigurationForPlayback();
List<Integer> listOfIds = new ArrayList<Integer>();
/* for (Protocol.SensorConfiguration aPlaybackConfig : playbackConfig) {
listOfIds.add(aPlaybackConfig.getSensorId());
}*/
System.out.println("LIST OF IDS SENT TO SERVER-------------------------------------------");
System.out.println(listOfIds);
System.out.println("LIST OF IDS END -----------------------------------------------------");
System.out.println("LIST OF IDS CURRENTLY IN DATABASE -----------------------------------");
System.out.println(Backend.getInstance().getSensors());
System.out.println("LIST IN DATABASE END ------------------------------------------------");
Backend.getInstance().sendExperimentPlaybackRequest(experimentName, listOfIds);
//Thread.sleep(3000);
//Backend.getInstance().stopConnection();
} catch (BackendError b){
b.printStackTrace();
} catch (InterruptedException ignore){
}
}
public void run(){
try{
Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0);
readWriteBoolean(false);
Random r = new Random();
String[] strings = new String[]{"Name","Code","File","Today","Monday","Tuesday","Wednesday","Thursday","Friday","Gotta","Get","Out","It","S","Friday"};
String project = "projectName" +r.nextInt()%10000;
String playbackProject = "realCollection";
for(int i = 0; i < 1000; i++){
// project+=strings[r.nextInt(strings.length)];
}
//System.out.println(project);
//if(r.nextInt()>0) return;
Thread.sleep(1000); Backend.getInstance().createNewProjectRequest(project);//"projectName"+ System.currentTimeMillis());
if(!readWriteBoolean(null)){
System.out.println("Waiting on projectListAgain");
while (!readWriteBoolean(null));
System.out.println("finished waiting");
}
// = Backend.getInstance().getProjectFilesFromServer().get());
System.out.println("Setting active project to : " + project);
Backend.getInstance().setActiveProject(project);
ProjectMetaData d = new ProjectMetaData();
//d.setEmail("NotMyEmail@gmail.com");
d.setTest_leader("ffu");
d.setDate(1l);
List<String> s = new ArrayList<String>();
s.add("memer1");
d.setMember_names(s);
d.setTags(s);
d.setDescription("desc");
List l = d.getMember_names();
l.add(r.nextInt() + ". name");
d.setMember_names(l);
Backend.getInstance().sendProjectMetaData(d);
/* while(!readWriteBoolean(null) && readWriteBoolean(null)){
Backend.getInstance().sendProjectMetaData(d);
List<String> f =d.getTags();
f.add(String.valueOf(System.currentTimeMillis()));
d.setTags(f);
} **/
System.out.println("starting data collection");
Thread.sleep(100);
String experimentName = "experimentNam5"+System.currentTimeMillis();
//String experimentName = "smallrun";
// projektnamn:
Backend.getInstance().startDataCollection(experimentName);
Thread.sleep(3000);
Backend.getInstance().stopDataCollection(); Thread.sleep(1);
} catch (BackendError b){
b.printStackTrace();
} catch (InterruptedException ignore){
}
System.out.println("Exiting");
}
public void runTest(){
// try{
// Thread.sleep(1000); Backend.getInstance().sendSettingsRequestMessageALlSensors(0);
// Thread.sleep(1000); Backend.getInstance().createNewProjectRequest("projectName"+ System.currentTimeMillis());
//
// //Backend.getInstance().startDataCollection("test1234");
//
// //Thread.sleep(5000); Backend.getInstance().stopDataCollection();
// Backend localInstance = Backend.getInstance();
//
// Sensor sensor = localInstance.getSensors().get(0);
// for(int i = 0; i<sensor.getAttributeList(0).size();i++){
// System.out.print(String.format("%f", sensor.getAttributeList(0).get(i).floatValue()).replace(',', '.') + ",");
//
// System.out.print(sensor.getId() + ",");
// for (int j = 1; j < sensor.getAttributesName().length;j++){
//
// System.out.print(sensor.getAttributeList(j).get(i).floatValue() + " ,");
// }
// System.out.println();
// }
//
// } catch (BackendError b){
// b.printStackTrace();
// } catch (InterruptedException ignore){}
}
@Override
public void projectCreationStatusChanged(Protocol.CreateNewProjectResponseMsg.ResponseType responseType) {
readWriteBoolean(true);
}
}
| gpl-2.0 |
blazegraph/database | bigdata-gas/src/test/java/com/bigdata/rdf/graph/analytics/TestCC.java | 7408 | /**
Copyright (C) SYSTAP, LLC 2006-2012. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.bigdata.rdf.graph.analytics;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.openrdf.model.Value;
import org.openrdf.sail.SailConnection;
import com.bigdata.rdf.graph.IGASContext;
import com.bigdata.rdf.graph.IGASEngine;
import com.bigdata.rdf.graph.IGASState;
import com.bigdata.rdf.graph.IGASStats;
import com.bigdata.rdf.graph.IGraphAccessor;
import com.bigdata.rdf.graph.analytics.CC.VS;
import com.bigdata.rdf.graph.impl.sail.AbstractSailGraphTestCase;
/**
* Test class for Breadth First Search (BFS) traversal.
*
* @see BFS
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
*/
public class TestCC extends AbstractSailGraphTestCase {
public TestCC() {
}
public TestCC(String name) {
super(name);
}
public void testCC() throws Exception {
/*
* Load two graphs. These graphs are not connected with one another (no
* shared vertices). This means that each graph will be its own
* connected component (all vertices in each source graph are
* connected within that source graph).
*/
final SmallGraphProblem p1 = setupSmallGraphProblem();
final SSSPGraphProblem p2 = setupSSSPGraphProblem();
final IGASEngine gasEngine = getGraphFixture()
.newGASEngine(1/* nthreads */);
try {
final SailConnection cxn = getGraphFixture().getSail()
.getConnection();
try {
final IGraphAccessor graphAccessor = getGraphFixture()
.newGraphAccessor(cxn);
final CC gasProgram = new CC();
final IGASContext<CC.VS, CC.ES, Value> gasContext = gasEngine
.newGASContext(graphAccessor, gasProgram);
final IGASState<CC.VS, CC.ES, Value> gasState = gasContext
.getGASState();
// Converge.
final IGASStats stats = gasContext.call();
if(log.isInfoEnabled())
log.info(stats);
/*
* Check the #of connected components that are self-reported and
* the #of vertices in each connected component. This helps to
* detect vertices that should have been visited but were not
* due to the initial frontier. E.g., "DC" will not be reported
* as a connected component of size (1) unless it gets into the
* initial frontier (it has no edges, only an attribute).
*/
final Map<Value, AtomicInteger> labels = gasProgram
.getConnectedComponents(gasState);
// the size of the connected component for this vertex.
{
final VS valueState = gasState.getState(p1.getFoafPerson());
final Value label = valueState != null?valueState.getLabel():null;
assertEquals(4, labels.get(label).get());
}
// the size of the connected component for this vertex.
{
final VS valueState = gasState.getState(p2.get_v1());
final Value label = valueState != null?valueState.getLabel():null;
final AtomicInteger ai = labels.get(label);
final int count = ai!=null?ai.get():-1;
assertEquals(5, count);
}
if (false) {
/*
* The size of the connected component for this vertex.
*
* Note: The vertex sampling code ignores self-loops and
* ignores vertices that do not have ANY edges. Thus "DC" is
* not put into the frontier and is not visited.
*/
final Value label = gasState.getState(p1.getDC())
.getLabel();
assertNotNull(label);
/*
* If DC was not put into the initial frontier, then it will
* be missing here.
*/
assertNotNull(labels.get(label));
assertEquals(1, labels.get(label).get());
}
// the #of connected components.
assertEquals(2, labels.size());
/*
* Most vertices in problem1 have the same label (the exception
* is DC, which is it its own connected component).
*/
Value label1 = null;
for (Value v : p1.getVertices()) {
final CC.VS vs = gasState.getState(v);
if (log.isInfoEnabled())
log.info("v=" + v + ", label=" + vs.getLabel());
if(v.equals(p1.getDC())) {
/*
* This vertex is in its own connected component and is
* therefore labeled by itself.
*/
assertEquals("vertex=" + v, v, vs.getLabel());
continue;
}
if (label1 == null) {
label1 = vs.getLabel();
assertNotNull(label1);
}
assertEquals("vertex=" + v, label1, vs.getLabel());
}
// All vertices in problem2 have the same label.
Value label2 = null;
for (Value v : p2.getVertices()) {
final CC.VS vs = gasState.getState(v);
if (log.isInfoEnabled())
log.info("v=" + v + ", label=" + vs.getLabel());
if (label2 == null) {
label2 = vs.getLabel();
assertNotNull(label2);
}
assertEquals("vertex=" + v, label2, vs.getLabel());
}
// The labels for the two connected components are distinct.
assertNotSame(label1, label2);
} finally {
try {
cxn.rollback();
} finally {
cxn.close();
}
}
} finally {
gasEngine.shutdownNow();
}
}
}
| gpl-2.0 |
bercik/BIO | impl/bioc/src/pl/rcebula/code_generation/final_steps/AddInformationsAboutModules.java | 1977 | /*
* Copyright (C) 2016 robert
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.rcebula.code_generation.final_steps;
import java.util.ArrayList;
import java.util.List;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IField;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.IntermediateCode;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.Line;
import pl.rcebula.code_generation.intermediate.intermediate_code_structure.StringField;
/**
*
* @author robert
*/
public class AddInformationsAboutModules
{
private final IntermediateCode ic;
private final List<String> modulesName;
public AddInformationsAboutModules(IntermediateCode ic, List<String> modulesName)
{
this.ic = ic;
this.modulesName = modulesName;
analyse();
}
private void analyse()
{
// tworzymy pola
List<IField> fields = new ArrayList<>();
for (String m : modulesName)
{
IField f = new StringField(m);
fields.add(f);
}
// wstawiamy pustą linię na początek
ic.insertLine(Line.generateEmptyStringLine(), 0);
// tworzymy linię i wstawiamy na początek
Line line = new Line(fields);
ic.insertLine(line, 0);
}
}
| gpl-2.0 |
oliversride/Wordryo | src/main/java/com/oliversride/wordryo/XWActivity.java | 5258 | /* -*- compile-command: "cd ../../../../../; ant debug install"; -*- */
/*
* Copyright 2010 by Eric House (xwords@eehouse.org). All rights
* reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.oliversride.wordryo;
import junit.framework.Assert;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
public class XWActivity extends Activity
implements DlgDelegate.DlgClickNotify, MultiService.MultiEventListener {
private final static String TAG = "XWActivity";
private DlgDelegate m_delegate;
@Override
protected void onCreate( Bundle savedInstanceState )
{
DbgUtils.logf( "%s.onCreate(this=%H)", getClass().getName(), this );
super.onCreate( savedInstanceState );
m_delegate = new DlgDelegate( this, this, savedInstanceState );
}
@Override
protected void onStart()
{
DbgUtils.logf( "%s.onStart(this=%H)", getClass().getName(), this );
super.onStart();
}
@Override
protected void onResume()
{
DbgUtils.logf( "%s.onResume(this=%H)", getClass().getName(), this );
BTService.setListener( this );
SMSService.setListener( this );
super.onResume();
}
@Override
protected void onPause()
{
DbgUtils.logf( "%s.onPause(this=%H)", getClass().getName(), this );
BTService.setListener( null );
SMSService.setListener( null );
super.onPause();
}
@Override
protected void onStop()
{
DbgUtils.logf( "%s.onStop(this=%H)", getClass().getName(), this );
super.onStop();
}
@Override
protected void onDestroy()
{
DbgUtils.logf( "%s.onDestroy(this=%H); isFinishing=%b",
getClass().getName(), this, isFinishing() );
super.onDestroy();
}
@Override
protected void onSaveInstanceState( Bundle outState )
{
super.onSaveInstanceState( outState );
m_delegate.onSaveInstanceState( outState );
}
@Override
protected Dialog onCreateDialog( int id )
{
Dialog dialog = super.onCreateDialog( id );
if ( null == dialog ) {
DbgUtils.logf( "%s.onCreateDialog() called", getClass().getName() );
dialog = m_delegate.onCreateDialog( id );
}
return dialog;
}
// these are duplicated in XWListActivity -- sometimes multiple
// inheritance would be nice to have...
protected void showAboutDialog()
{
m_delegate.showAboutDialog();
}
protected void showNotAgainDlgThen( int msgID, int prefsKey,
int action )
{
m_delegate.showNotAgainDlgThen( msgID, prefsKey, action );
}
protected void showNotAgainDlgThen( int msgID, int prefsKey )
{
m_delegate.showNotAgainDlgThen( msgID, prefsKey );
}
protected void showOKOnlyDialog( int msgID )
{
m_delegate.showOKOnlyDialog( msgID );
}
protected void showOKOnlyDialog( String msg )
{
m_delegate.showOKOnlyDialog( msg );
}
protected void showDictGoneFinish()
{
m_delegate.showDictGoneFinish();
}
protected void showConfirmThen( int msgID, int action )
{
m_delegate.showConfirmThen( getString(msgID), action );
}
protected void showConfirmThen( String msg, int action )
{
m_delegate.showConfirmThen( msg, action );
}
protected void showConfirmThen( int msg, int posButton, int action )
{
m_delegate.showConfirmThen( getString(msg), posButton, action );
}
public void showEmailOrSMSThen( int action )
{
m_delegate.showEmailOrSMSThen( action );
}
protected void doSyncMenuitem()
{
m_delegate.doSyncMenuitem();
}
protected void launchLookup( String[] words, int lang )
{
m_delegate.launchLookup( words, lang, false );
}
protected void startProgress( int id )
{
m_delegate.startProgress( id );
}
protected void stopProgress()
{
m_delegate.stopProgress();
}
protected boolean post( Runnable runnable )
{
return m_delegate.post( runnable );
}
// DlgDelegate.DlgClickNotify interface
public void dlgButtonClicked( int id, int which )
{
Assert.fail();
}
// BTService.MultiEventListener interface
public void eventOccurred( MultiService.MultiEvent event,
final Object ... args )
{
m_delegate.eventOccurred( event, args );
}
}
| gpl-2.0 |
sparcules/Spark_Pixels | AndroidApp/SparkPixels/src/kc/spark/pixels/android/ui/assets/Typefaces.java | 1212 | package kc.spark.pixels.android.ui.assets;
import static org.solemnsilence.util.Py.map;
import java.util.Map;
import android.content.Context;
import android.graphics.Typeface;
public class Typefaces {
// NOTE: this is tightly coupled to the filenames in assets/fonts
public static enum Style {
BOLD("Arial.ttf"),
BOLD_ITALIC("Arial.ttf"),
BOOK("Arial.ttf"),
BOOK_ITALIC("Arial.ttf"),
LIGHT("Arial.ttf"),
LIGHT_ITALIC("Arial.ttf"),
MEDIUM("Arial.ttf"),
MEDIUM_ITALIC("Arial.ttf");
// BOLD("gotham_bold.otf"),
// BOLD_ITALIC("gotham_bold_ita.otf"),
// BOOK("gotham_book.otf"),
// BOOK_ITALIC("gotham_book_ita.otf"),
// LIGHT("gotham_light.otf"),
// LIGHT_ITALIC("gotham_light_ita.otf"),
// MEDIUM("gotham_medium.otf"),
// MEDIUM_ITALIC("gotham_medium_ita.otf");
public final String fileName;
private Style(String name) {
fileName = name;
}
}
private static final Map<Style, Typeface> typefaces = map();
public static Typeface getTypeface(Context ctx, Style style) {
Typeface face = typefaces.get(style);
if (face == null) {
face = Typeface.createFromAsset(ctx.getAssets(), "fonts/" + style.fileName);
typefaces.put(style, face);
}
return face;
}
}
| gpl-2.0 |
openjdk/jdk8u | jdk/test/sun/net/www/ParseUtil_4922813.java | 5843 | /*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4922813
@summary Check the new impl of encodePath will not cause regression
@key randomness
*/
import java.util.BitSet;
import java.io.File;
import java.util.Random;
import sun.net.www.ParseUtil;
public class ParseUtil_4922813 {
public static void main(String[] argv) throws Exception {
int num = 400;
while (num-- >= 0) {
String source = getTestSource();
String ec = sun.net.www.ParseUtil.encodePath(source);
String v117 = ParseUtil_V117.encodePath(source);
if (!ec.equals(v117)) {
throw new RuntimeException("Test Failed for : \n"
+ " source =<"
+ getUnicodeString(source)
+ ">");
}
}
}
static int maxCharCount = 200;
static int maxCodePoint = 0x10ffff;
static Random random;
static String getTestSource() {
if (random == null) {
long seed = System.currentTimeMillis();
random = new Random(seed);
}
String source = "";
int i = 0;
int count = random.nextInt(maxCharCount) + 1;
while (i < count) {
int codepoint = random.nextInt(127);
source = source + String.valueOf((char)codepoint);
codepoint = random.nextInt(0x7ff);
source = source + String.valueOf((char)codepoint);
codepoint = random.nextInt(maxCodePoint);
source = source + new String(Character.toChars(codepoint));
i += 3;
}
return source;
}
static String getUnicodeString(String s){
String unicodeString = "";
for(int j=0; j< s.length(); j++){
unicodeString += "0x"+ Integer.toString(s.charAt(j), 16);
}
return unicodeString;
}
}
class ParseUtil_V117 {
static BitSet encodedInPath;
static {
encodedInPath = new BitSet(256);
// Set the bits corresponding to characters that are encoded in the
// path component of a URI.
// These characters are reserved in the path segment as described in
// RFC2396 section 3.3.
encodedInPath.set('=');
encodedInPath.set(';');
encodedInPath.set('?');
encodedInPath.set('/');
// These characters are defined as excluded in RFC2396 section 2.4.3
// and must be escaped if they occur in the data part of a URI.
encodedInPath.set('#');
encodedInPath.set(' ');
encodedInPath.set('<');
encodedInPath.set('>');
encodedInPath.set('%');
encodedInPath.set('"');
encodedInPath.set('{');
encodedInPath.set('}');
encodedInPath.set('|');
encodedInPath.set('\\');
encodedInPath.set('^');
encodedInPath.set('[');
encodedInPath.set(']');
encodedInPath.set('`');
// US ASCII control characters 00-1F and 7F.
for (int i=0; i<32; i++)
encodedInPath.set(i);
encodedInPath.set(127);
}
/**
* Constructs an encoded version of the specified path string suitable
* for use in the construction of a URL.
*
* A path separator is replaced by a forward slash. The string is UTF8
* encoded. The % escape sequence is used for characters that are above
* 0x7F or those defined in RFC2396 as reserved or excluded in the path
* component of a URL.
*/
public static String encodePath(String path) {
StringBuffer sb = new StringBuffer();
int n = path.length();
for (int i=0; i<n; i++) {
char c = path.charAt(i);
if (c == File.separatorChar)
sb.append('/');
else {
if (c <= 0x007F) {
if (encodedInPath.get(c))
escape(sb, c);
else
sb.append(c);
} else if (c > 0x07FF) {
escape(sb, (char)(0xE0 | ((c >> 12) & 0x0F)));
escape(sb, (char)(0x80 | ((c >> 6) & 0x3F)));
escape(sb, (char)(0x80 | ((c >> 0) & 0x3F)));
} else {
escape(sb, (char)(0xC0 | ((c >> 6) & 0x1F)));
escape(sb, (char)(0x80 | ((c >> 0) & 0x3F)));
}
}
}
return sb.toString();
}
/**
* Appends the URL escape sequence for the specified char to the
* specified StringBuffer.
*/
private static void escape(StringBuffer s, char c) {
s.append('%');
s.append(Character.forDigit((c >> 4) & 0xF, 16));
s.append(Character.forDigit(c & 0xF, 16));
}
}
| gpl-2.0 |
riadd/jMemorize | src/jmemorize/core/test/LessonProviderTest.java | 4360 | /*
* jMemorize - Learning made easy (and fun) - A Leitner flashcards tool
* Copyright(C) 2004-2006 Riad Djemili
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package jmemorize.core.test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import jmemorize.core.Card;
import jmemorize.core.Lesson;
import jmemorize.core.LessonObserver;
import jmemorize.core.LessonProvider;
import jmemorize.core.Main;
import junit.framework.TestCase;
public class LessonProviderTest extends TestCase implements LessonObserver
{
private LessonProvider m_lessonProvider;
private StringBuffer m_log;
protected void setUp() throws Exception
{
m_lessonProvider = new Main();
m_lessonProvider.addLessonObserver(this);
m_log = new StringBuffer();
}
public void testLessonNewEvent()
{
m_lessonProvider.createNewLesson();
assertEquals("loaded ", m_log.toString());
}
public void testLessonLoadedEvent() throws IOException
{
m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml"));
assertEquals("loaded ", m_log.toString());
}
public void testLessonLoadedCardsAlwaysHaveExpiration() throws IOException
{
m_lessonProvider.loadLesson(new File("test/fixtures/no_expiration.jml"));
Lesson lesson = m_lessonProvider.getLesson();
List<Card> cards = lesson.getRootCategory().getCards();
for (Card card : cards)
{
if (card.getLevel() > 0)
assertNotNull(card.getDateExpired());
else
assertNull(card.getDateExpired());
}
}
public void testLessonLoadedClosedNewEvents() throws IOException
{
m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml"));
m_lessonProvider.createNewLesson();
assertEquals("loaded closed loaded ", m_log.toString());
// TODO also check lesson param
}
public void testLessonLoadedClosedLoadEvents() throws IOException
{
m_lessonProvider.loadLesson(new File("test/fixtures/simple_de.jml"));
m_lessonProvider.loadLesson(new File("test/fixtures/test.jml"));
assertEquals("loaded closed loaded ", m_log.toString());
// TODO also check lesson param
}
public void testLessonSavedEvent() throws Exception
{
m_lessonProvider.loadLesson(
new File("test/fixtures/simple_de.jml"));
Lesson lesson = m_lessonProvider.getLesson();
m_lessonProvider.saveLesson(lesson, new File("./test.jml"));
assertEquals("loaded saved ", m_log.toString());
}
public void testLessonModifiedEvent() throws Exception
{
m_lessonProvider.loadLesson(
new File("test/fixtures/simple_de.jml"));
Lesson lesson = m_lessonProvider.getLesson();
lesson.getRootCategory().addCard(new Card("front", "flip"));
assertEquals("loaded modified ", m_log.toString());
}
/* (non-Javadoc)
* @see jmemorize.core.LessonObserver
*/
public void lessonLoaded(Lesson lesson)
{
m_log.append("loaded ");
}
/* (non-Javadoc)
* @see jmemorize.core.LessonObserver
*/
public void lessonModified(Lesson lesson)
{
m_log.append("modified ");
}
/* (non-Javadoc)
* @see jmemorize.core.LessonObserver
*/
public void lessonSaved(Lesson lesson)
{
m_log.append("saved ");
}
/* (non-Javadoc)
* @see jmemorize.core.LessonObserver
*/
public void lessonClosed(Lesson lesson)
{
m_log.append("closed ");
}
}
| gpl-2.0 |
intelie/esper | esper/src/test/java/com/espertech/esper/multithread/TestMTStmtTwoPatternsStartStop.java | 3675 | /*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.multithread;
import junit.framework.TestCase;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.Configuration;
import com.espertech.esper.support.bean.SupportTradeEvent;
import com.espertech.esper.multithread.TwoPatternRunnable;
/**
* Test for multithread-safety for case of 2 patterns:
* 1. Thread 1 starts pattern "every event1=SupportEvent(userID in ('100','101'), amount>=1000)"
* 2. Thread 1 repeats sending 100 events and tests 5% received
* 3. Main thread starts pattern:
* ( every event1=SupportEvent(userID in ('100','101')) ->
(SupportEvent(userID in ('100','101'), direction = event1.direction ) ->
SupportEvent(userID in ('100','101'), direction = event1.direction )
) where timer:within(8 hours)
and not eventNC=SupportEvent(userID in ('100','101'), direction!= event1.direction )
) -> eventFinal=SupportEvent(userID in ('100','101'), direction != event1.direction ) where timer:within(1 hour)
* 4. Main thread waits for 2 seconds and stops all threads
*/
public class TestMTStmtTwoPatternsStartStop extends TestCase
{
private EPServiceProvider engine;
public void setUp()
{
Configuration config = new Configuration();
config.addEventType("SupportEvent", SupportTradeEvent.class);
engine = EPServiceProviderManager.getDefaultProvider(config);
engine.initialize();
}
public void tearDown()
{
engine.initialize();
}
public void test2Patterns() throws Exception
{
String statementTwo = "( every event1=SupportEvent(userId in ('100','101')) ->\n" +
" (SupportEvent(userId in ('100','101'), direction = event1.direction ) ->\n" +
" SupportEvent(userId in ('100','101'), direction = event1.direction )\n" +
" ) where timer:within(8 hours)\n" +
" and not eventNC=SupportEvent(userId in ('100','101'), direction!= event1.direction )\n" +
" ) -> eventFinal=SupportEvent(userId in ('100','101'), direction != event1.direction ) where timer:within(1 hour)";
TwoPatternRunnable runnable = new TwoPatternRunnable(engine);
Thread t = new Thread(runnable);
t.start();
Thread.sleep(200);
// Create a second pattern, wait 200 msec, destroy second pattern in a loop
for (int i = 0; i < 10; i++)
{
EPStatement statement = engine.getEPAdministrator().createPattern(statementTwo);
Thread.sleep(200);
statement.destroy();
}
runnable.setShutdown(true);
Thread.sleep(1000);
assertFalse(t.isAlive());
}
}
| gpl-2.0 |
wb-goup/webbuilder | wb-core/src/main/java/org/webbuilder/web/service/script/DynamicScriptExecutor.java | 1079 | package org.webbuilder.web.service.script;
import org.springframework.stereotype.Service;
import org.webbuilder.utils.script.engine.DynamicScriptEngine;
import org.webbuilder.utils.script.engine.DynamicScriptEngineFactory;
import org.webbuilder.utils.script.engine.ExecuteResult;
import org.webbuilder.web.po.script.DynamicScript;
import javax.annotation.Resource;
import java.util.Map;
/**
* Created by 浩 on 2015-10-29 0029.
*/
@Service
public class DynamicScriptExecutor {
@Resource
private DynamicScriptService dynamicScriptService;
public ExecuteResult exec(String id, Map<String, Object> param) throws Exception {
DynamicScript data = dynamicScriptService.selectByPk(id);
if (data == null) {
ExecuteResult result = new ExecuteResult();
result.setResult(String.format("script %s not found!", id));
result.setSuccess(false);
return result;
}
DynamicScriptEngine engine = DynamicScriptEngineFactory.getEngine(data.getType());
return engine.execute(id, param);
}
}
| gpl-2.0 |
ridoo/timeseries-api | io/src/test/java/org/n52/io/measurement/img/ChartRendererTest.java | 5333 | /*
* Copyright (C) 2013-2016 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
package org.n52.io.measurement.img;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.junit.Before;
import org.junit.Test;
import org.n52.io.IoStyleContext;
import org.n52.io.MimeType;
import org.n52.io.request.RequestSimpleParameterSet;
import org.n52.io.response.dataset.DataCollection;
import org.n52.io.response.dataset.measurement.MeasurementData;
public class ChartRendererTest {
private static final String VALID_ISO8601_RELATIVE_START = "PT6H/2013-08-13TZ";
private static final String VALID_ISO8601_ABSOLUTE_START = "2013-07-13TZ/2013-08-13TZ";
private static final String VALID_ISO8601_DAYLIGHT_SAVING_SWITCH = "2013-10-28T02:00:00+02:00/2013-10-28T02:00:00+01:00";
private MyChartRenderer chartRenderer;
@Before
public void
setUp() {
this.chartRenderer = new MyChartRenderer(IoStyleContext.createEmpty());
}
@Test
public void
shouldParseBeginFromIso8601PeriodWithRelativeStart() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_RELATIVE_START);
assertThat(start, is(DateTime.parse("2013-08-13TZ").minusHours(6).toDate()));
}
@Test
public void
shouldParseBeginFromIso8601PeriodWithAbsoluteStart() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_ABSOLUTE_START);
assertThat(start, is(DateTime.parse("2013-08-13TZ").minusMonths(1).toDate()));
}
@Test
public void
shouldParseBeginAndEndFromIso8601PeriodContainingDaylightSavingTimezoneSwith() {
Date start = chartRenderer.getStartTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
Date end = chartRenderer.getEndTime(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
assertThat(start, is(DateTime.parse("2013-10-28T00:00:00Z").toDate()));
assertThat(end, is(DateTime.parse("2013-10-28T01:00:00Z").toDate()));
}
@Test
public void
shouldHaveCETTimezoneIncludedInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_DAYLIGHT_SAVING_SWITCH);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
assertThat(label, is("Time (+01:00)"));
}
@Test
public void
shouldHandleEmptyTimespanWhenIncludingTimezoneInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(null);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
//assertThat(label, is("Time (+01:00)"));
}
@Test
public void
shouldHaveUTCTimezoneIncludedInDomainAxisLabel() {
IoStyleContext context = IoStyleContext.createEmpty();
context.getChartStyleDefinitions().setTimespan(VALID_ISO8601_ABSOLUTE_START);
this.chartRenderer = new MyChartRenderer(context);
String label = chartRenderer.getXYPlot().getDomainAxis().getLabel();
ISODateTimeFormat.dateTimeParser().withOffsetParsed().parseDateTime(VALID_ISO8601_ABSOLUTE_START.split("/")[1]);
assertThat(label, is("Time (UTC)"));
}
static class MyChartRenderer extends ChartIoHandler {
public MyChartRenderer(IoStyleContext context) {
super(new RequestSimpleParameterSet(), null, context);
}
public MyChartRenderer() {
super(new RequestSimpleParameterSet(), null, null);
}
@Override
public void setMimeType(MimeType mimetype) {
throw new UnsupportedOperationException();
}
@Override
public void writeDataToChart(DataCollection<MeasurementData> data) {
throw new UnsupportedOperationException();
}
}
}
| gpl-2.0 |
samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/bind/v2/util/CollisionCheckStack.java | 5703 | /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.bind.v2.util;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
/**
* {@link Stack}-like data structure that allows the following efficient operations:
*
* <ol>
* <li>Push/pop operation.
* <li>Duplicate check. When an object that's already in the stack is pushed,
* this class will tell you so.
* </ol>
*
* <p>
* Object equality is their identity equality.
*
* <p>
* This class implements {@link List} for accessing items in the stack,
* but {@link List} methods that alter the stack is not supported.
*
* @author Kohsuke Kawaguchi
*/
public final class CollisionCheckStack<E> extends AbstractList<E> {
private Object[] data;
private int[] next;
private int size = 0;
/**
* True if the check shall be done by using the object identity.
* False if the check shall be done with the equals method.
*/
private boolean useIdentity = true;
// for our purpose, there isn't much point in resizing this as we don't expect
// the stack to grow that much.
private final int[] initialHash;
public CollisionCheckStack() {
initialHash = new int[17];
data = new Object[16];
next = new int[16];
}
/**
* Set to false to use {@link Object#equals(Object)} to detect cycles.
* This method can be only used when the stack is empty.
*/
public void setUseIdentity(boolean useIdentity) {
this.useIdentity = useIdentity;
}
public boolean getUseIdentity() {
return useIdentity;
}
/**
* Pushes a new object to the stack.
*
* @return
* true if this object has already been pushed
*/
public boolean push(E o) {
if(data.length==size)
expandCapacity();
data[size] = o;
int hash = hash(o);
boolean r = findDuplicate(o, hash);
next[size] = initialHash[hash];
initialHash[hash] = size+1;
size++;
return r;
}
/**
* Pushes a new object to the stack without making it participate
* with the collision check.
*/
public void pushNocheck(E o) {
if(data.length==size)
expandCapacity();
data[size] = o;
next[size] = -1;
size++;
}
@Override
public E get(int index) {
return (E)data[index];
}
@Override
public int size() {
return size;
}
private int hash(Object o) {
return ((useIdentity?System.identityHashCode(o):o.hashCode())&0x7FFFFFFF) % initialHash.length;
}
/**
* Pops an object from the stack
*/
public E pop() {
size--;
Object o = data[size];
data[size] = null; // keeping references too long == memory leak
int n = next[size];
if(n<0) {
// pushed by nocheck. no need to update hash
} else {
int hash = hash(o);
assert initialHash[hash]==size+1;
initialHash[hash] = n;
}
return (E)o;
}
/**
* Returns the top of the stack.
*/
public E peek() {
return (E)data[size-1];
}
private boolean findDuplicate(E o, int hash) {
int p = initialHash[hash];
while(p!=0) {
p--;
Object existing = data[p];
if (useIdentity) {
if(existing==o) return true;
} else {
if (o.equals(existing)) return true;
}
p = next[p];
}
return false;
}
private void expandCapacity() {
int oldSize = data.length;
int newSize = oldSize * 2;
Object[] d = new Object[newSize];
int[] n = new int[newSize];
System.arraycopy(data,0,d,0,oldSize);
System.arraycopy(next,0,n,0,oldSize);
data = d;
next = n;
}
/**
* Clears all the contents in the stack.
*/
public void reset() {
if(size>0) {
size = 0;
Arrays.fill(initialHash,0);
}
}
/**
* String that represents the cycle.
*/
public String getCycleString() {
StringBuilder sb = new StringBuilder();
int i=size()-1;
E obj = get(i);
sb.append(obj);
Object x;
do {
sb.append(" -> ");
x = get(--i);
sb.append(x);
} while(obj!=x);
return sb.toString();
}
}
| gpl-2.0 |
ximenesuk/bioformats | components/loci-legacy/src/loci/common/IniWriter.java | 3258 | /*
* #%L
* OME SCIFIO package for reading and converting scientific file formats.
* %%
* Copyright (C) 2005 - 2012 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of any organization.
* #L%
*/
package loci.common;
import java.io.IOException;
/**
* A legacy delegator class for ome.scifio.common.IniWriter.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/common/src/loci/common/IniWriter.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/common/src/loci/common/IniWriter.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Melissa Linkert melissa at glencoesoftware.com
*/
public class IniWriter {
// -- Fields --
private ome.scifio.common.IniWriter writer;
// -- Constructor --
public IniWriter() {
writer = new ome.scifio.common.IniWriter();
}
// -- IniWriter API methods --
/**
* Saves the given IniList to the given file.
* If the given file already exists, then the IniList will be appended.
*/
public void saveINI(IniList ini, String path) throws IOException {
writer.saveINI(ini.list, path);
}
/** Saves the given IniList to the given file. */
public void saveINI(IniList ini, String path, boolean append)
throws IOException
{
writer.saveINI(ini.list, path, append);
}
// -- Object delegators --
@Override
public boolean equals(Object obj) {
return writer.equals(obj);
}
@Override
public int hashCode() {
return writer.hashCode();
}
@Override
public String toString() {
return writer.toString();
}
}
| gpl-2.0 |
ric2b/POO | java/src/dataset/UndefinedSampleLengthException.java | 135 | package dataset;
public class UndefinedSampleLengthException extends Exception {
private static final long serialVersionUID = 1L;
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/awt/src/main/java/common/org/apache/harmony/awt/text/TextFactory.java | 3164 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Evgeniya G. Maenkova
*/
package org.apache.harmony.awt.text;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.swing.text.Element;
import javax.swing.text.View;
public abstract class TextFactory {
private static final String FACTORY_IMPL_CLS_NAME =
"javax.swing.text.TextFactoryImpl"; //$NON-NLS-1$
private static final TextFactory viewFactory = createTextFactory();
public static TextFactory getTextFactory() {
return viewFactory;
}
private static TextFactory createTextFactory() {
PrivilegedAction<TextFactory> createAction = new PrivilegedAction<TextFactory>() {
public TextFactory run() {
try {
Class<?> factoryImplClass = Class
.forName(FACTORY_IMPL_CLS_NAME);
Constructor<?> defConstr =
factoryImplClass.getDeclaredConstructor(new Class[0]);
defConstr.setAccessible(true);
return (TextFactory)defConstr.newInstance(new Object[0]);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
};
return AccessController.doPrivileged(createAction);
}
public abstract RootViewContext createRootView(final Element element);
public abstract View createPlainView(final Element e);
public abstract View createWrappedPlainView(final Element e);
public abstract View createFieldView(final Element e);
public abstract View createPasswordView(Element e);
public abstract TextCaret createCaret();
}
| gpl-2.0 |
unofficial-opensource-apple/gcc_40 | libjava/gnu/xml/transform/OtherwiseNode.java | 3110 | /* OtherwiseNode.java --
Copyright (C) 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.xml.transform;
import javax.xml.namespace.QName;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Node;
/**
* A template node representing an XSL <code>otherwise</code> instruction.
*
* @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
*/
final class OtherwiseNode
extends TemplateNode
{
OtherwiseNode(TemplateNode children, TemplateNode next)
{
super(children, next);
}
TemplateNode clone(Stylesheet stylesheet)
{
return new OtherwiseNode((children == null) ? null :
children.clone(stylesheet),
(next == null) ? null :
next.clone(stylesheet));
}
void doApply(Stylesheet stylesheet, QName mode,
Node context, int pos, int len,
Node parent, Node nextSibling)
throws TransformerException
{
if (children != null)
{
children.apply(stylesheet, mode,
context, pos, len,
parent, nextSibling);
}
if (next != null)
{
next.apply(stylesheet, mode,
context, pos, len,
parent, nextSibling);
}
}
public String toString()
{
StringBuffer buf = new StringBuffer(getClass().getName());
buf.append('[');
buf.append(']');
return buf.toString();
}
}
| gpl-2.0 |
hbbpb/stanford-corenlp-gv | src/edu/stanford/nlp/parser/lexparser/FactoredParser.java | 23782 | // StanfordLexicalizedParser -- a probabilistic lexicalized NL CFG parser
// Copyright (c) 2002, 2003, 2004, 2005 The Board of Trustees of
// The Leland Stanford Junior University. All Rights Reserved.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// For more information, bug reports, fixes, contact:
// Christopher Manning
// Dept of Computer Science, Gates 1A
// Stanford CA 94305-9010
// USA
// parser-support@lists.stanford.edu
// http://nlp.stanford.edu/downloads/lex-parser.shtml
package edu.stanford.nlp.parser.lexparser;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import edu.stanford.nlp.io.NumberRangeFileFilter;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.parser.metrics.AbstractEval;
import edu.stanford.nlp.parser.metrics.UnlabeledAttachmentEval;
import edu.stanford.nlp.parser.metrics.Evalb;
import edu.stanford.nlp.parser.metrics.TaggingEval;
import edu.stanford.nlp.trees.LeftHeadFinder;
import edu.stanford.nlp.trees.MemoryTreebank;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeLengthComparator;
import edu.stanford.nlp.trees.TreeTransformer;
import edu.stanford.nlp.trees.Treebank;
import edu.stanford.nlp.trees.TreebankLanguagePack;
import java.util.function.Function;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.HashIndex;
import edu.stanford.nlp.util.Index;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.Timing;
import edu.stanford.nlp.util.StringUtils;
/**
* @author Dan Klein (original version)
* @author Christopher Manning (better features, ParserParams, serialization)
* @author Roger Levy (internationalization)
* @author Teg Grenager (grammar compaction, etc., tokenization, etc.)
* @author Galen Andrew (lattice parsing)
* @author Philip Resnik and Dan Zeman (n good parses)
*/
public class FactoredParser {
/* some documentation for Roger's convenience
* {pcfg,dep,combo}{PE,DE,TE} are precision/dep/tagging evals for the models
* parser is the PCFG parser
* dparser is the dependency parser
* bparser is the combining parser
* during testing:
* tree is the test tree (gold tree)
* binaryTree is the gold tree binarized
* tree2b is the best PCFG paser, binarized
* tree2 is the best PCFG parse (debinarized)
* tree3 is the dependency parse, binarized
* tree3db is the dependency parser, debinarized
* tree4 is the best combo parse, binarized and then debinarized
* tree4b is the best combo parse, binarized
*/
public static void main(String[] args) {
Options op = new Options(new EnglishTreebankParserParams());
// op.tlpParams may be changed to something else later, so don't use it till
// after options are parsed.
System.out.println(StringUtils.toInvocationString("FactoredParser", args));
String path = "/u/nlp/stuff/corpora/Treebank3/parsed/mrg/wsj";
int trainLow = 200, trainHigh = 2199, testLow = 2200, testHigh = 2219;
String serializeFile = null;
int i = 0;
while (i < args.length && args[i].startsWith("-")) {
if (args[i].equalsIgnoreCase("-path") && (i + 1 < args.length)) {
path = args[i + 1];
i += 2;
} else if (args[i].equalsIgnoreCase("-train") && (i + 2 < args.length)) {
trainLow = Integer.parseInt(args[i + 1]);
trainHigh = Integer.parseInt(args[i + 2]);
i += 3;
} else if (args[i].equalsIgnoreCase("-test") && (i + 2 < args.length)) {
testLow = Integer.parseInt(args[i + 1]);
testHigh = Integer.parseInt(args[i + 2]);
i += 3;
} else if (args[i].equalsIgnoreCase("-serialize") && (i + 1 < args.length)) {
serializeFile = args[i + 1];
i += 2;
} else if (args[i].equalsIgnoreCase("-tLPP") && (i + 1 < args.length)) {
try {
op.tlpParams = (TreebankLangParserParams) Class.forName(args[i + 1]).newInstance();
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + args[i + 1]);
throw new RuntimeException(e);
} catch (InstantiationException e) {
System.err.println("Couldn't instantiate: " + args[i + 1] + ": " + e.toString());
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
System.err.println("illegal access" + e);
throw new RuntimeException(e);
}
i += 2;
} else if (args[i].equals("-encoding")) {
// sets encoding for TreebankLangParserParams
op.tlpParams.setInputEncoding(args[i + 1]);
op.tlpParams.setOutputEncoding(args[i + 1]);
i += 2;
} else {
i = op.setOptionOrWarn(args, i);
}
}
// System.out.println(tlpParams.getClass());
TreebankLanguagePack tlp = op.tlpParams.treebankLanguagePack();
op.trainOptions.sisterSplitters = Generics.newHashSet(Arrays.asList(op.tlpParams.sisterSplitters()));
// BinarizerFactory.TreeAnnotator.setTreebankLang(tlpParams);
PrintWriter pw = op.tlpParams.pw();
op.testOptions.display();
op.trainOptions.display();
op.display();
op.tlpParams.display();
// setup tree transforms
Treebank trainTreebank = op.tlpParams.memoryTreebank();
MemoryTreebank testTreebank = op.tlpParams.testMemoryTreebank();
// Treebank blippTreebank = ((EnglishTreebankParserParams) tlpParams).diskTreebank();
// String blippPath = "/afs/ir.stanford.edu/data/linguistic-data/BLLIP-WSJ/";
// blippTreebank.loadPath(blippPath, "", true);
Timing.startTime();
System.err.print("Reading trees...");
testTreebank.loadPath(path, new NumberRangeFileFilter(testLow, testHigh, true));
if (op.testOptions.increasingLength) {
Collections.sort(testTreebank, new TreeLengthComparator());
}
trainTreebank.loadPath(path, new NumberRangeFileFilter(trainLow, trainHigh, true));
Timing.tick("done.");
System.err.print("Binarizing trees...");
TreeAnnotatorAndBinarizer binarizer;
if (!op.trainOptions.leftToRight) {
binarizer = new TreeAnnotatorAndBinarizer(op.tlpParams, op.forceCNF, !op.trainOptions.outsideFactor(), true, op);
} else {
binarizer = new TreeAnnotatorAndBinarizer(op.tlpParams.headFinder(), new LeftHeadFinder(), op.tlpParams, op.forceCNF, !op.trainOptions.outsideFactor(), true, op);
}
CollinsPuncTransformer collinsPuncTransformer = null;
if (op.trainOptions.collinsPunc) {
collinsPuncTransformer = new CollinsPuncTransformer(tlp);
}
TreeTransformer debinarizer = new Debinarizer(op.forceCNF);
List<Tree> binaryTrainTrees = new ArrayList<>();
if (op.trainOptions.selectiveSplit) {
op.trainOptions.splitters = ParentAnnotationStats.getSplitCategories(trainTreebank, op.trainOptions.tagSelectiveSplit, 0, op.trainOptions.selectiveSplitCutOff, op.trainOptions.tagSelectiveSplitCutOff, op.tlpParams.treebankLanguagePack());
if (op.trainOptions.deleteSplitters != null) {
List<String> deleted = new ArrayList<>();
for (String del : op.trainOptions.deleteSplitters) {
String baseDel = tlp.basicCategory(del);
boolean checkBasic = del.equals(baseDel);
for (Iterator<String> it = op.trainOptions.splitters.iterator(); it.hasNext(); ) {
String elem = it.next();
String baseElem = tlp.basicCategory(elem);
boolean delStr = checkBasic && baseElem.equals(baseDel) ||
elem.equals(del);
if (delStr) {
it.remove();
deleted.add(elem);
}
}
}
System.err.println("Removed from vertical splitters: " + deleted);
}
}
if (op.trainOptions.selectivePostSplit) {
TreeTransformer myTransformer = new TreeAnnotator(op.tlpParams.headFinder(), op.tlpParams, op);
Treebank annotatedTB = trainTreebank.transform(myTransformer);
op.trainOptions.postSplitters = ParentAnnotationStats.getSplitCategories(annotatedTB, true, 0, op.trainOptions.selectivePostSplitCutOff, op.trainOptions.tagSelectivePostSplitCutOff, op.tlpParams.treebankLanguagePack());
}
if (op.trainOptions.hSelSplit) {
binarizer.setDoSelectiveSplit(false);
for (Tree tree : trainTreebank) {
if (op.trainOptions.collinsPunc) {
tree = collinsPuncTransformer.transformTree(tree);
}
//tree.pennPrint(tlpParams.pw());
tree = binarizer.transformTree(tree);
//binaryTrainTrees.add(tree);
}
binarizer.setDoSelectiveSplit(true);
}
for (Tree tree : trainTreebank) {
if (op.trainOptions.collinsPunc) {
tree = collinsPuncTransformer.transformTree(tree);
}
tree = binarizer.transformTree(tree);
binaryTrainTrees.add(tree);
}
if (op.testOptions.verbose) {
binarizer.dumpStats();
}
List<Tree> binaryTestTrees = new ArrayList<>();
for (Tree tree : testTreebank) {
if (op.trainOptions.collinsPunc) {
tree = collinsPuncTransformer.transformTree(tree);
}
tree = binarizer.transformTree(tree);
binaryTestTrees.add(tree);
}
Timing.tick("done."); // binarization
BinaryGrammar bg = null;
UnaryGrammar ug = null;
DependencyGrammar dg = null;
// DependencyGrammar dgBLIPP = null;
Lexicon lex = null;
Index<String> stateIndex = new HashIndex<>();
// extract grammars
Extractor<Pair<UnaryGrammar,BinaryGrammar>> bgExtractor = new BinaryGrammarExtractor(op, stateIndex);
//Extractor bgExtractor = new SmoothedBinaryGrammarExtractor();//new BinaryGrammarExtractor();
// Extractor lexExtractor = new LexiconExtractor();
//Extractor dgExtractor = new DependencyMemGrammarExtractor();
if (op.doPCFG) {
System.err.print("Extracting PCFG...");
Pair<UnaryGrammar, BinaryGrammar> bgug = null;
if (op.trainOptions.cheatPCFG) {
List<Tree> allTrees = new ArrayList<>(binaryTrainTrees);
allTrees.addAll(binaryTestTrees);
bgug = bgExtractor.extract(allTrees);
} else {
bgug = bgExtractor.extract(binaryTrainTrees);
}
bg = bgug.second;
bg.splitRules();
ug = bgug.first;
ug.purgeRules();
Timing.tick("done.");
}
System.err.print("Extracting Lexicon...");
Index<String> wordIndex = new HashIndex<>();
Index<String> tagIndex = new HashIndex<>();
lex = op.tlpParams.lex(op, wordIndex, tagIndex);
lex.initializeTraining(binaryTrainTrees.size());
lex.train(binaryTrainTrees);
lex.finishTraining();
Timing.tick("done.");
if (op.doDep) {
System.err.print("Extracting Dependencies...");
binaryTrainTrees.clear();
Extractor<DependencyGrammar> dgExtractor = new MLEDependencyGrammarExtractor(op, wordIndex, tagIndex);
// dgBLIPP = (DependencyGrammar) dgExtractor.extract(new ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new TransformTreeDependency(tlpParams,true));
// DependencyGrammar dg1 = dgExtractor.extract(trainTreebank.iterator(), new TransformTreeDependency(op.tlpParams, true));
//dgBLIPP=(DependencyGrammar)dgExtractor.extract(blippTreebank.iterator(),new TransformTreeDependency(tlpParams));
//dg = (DependencyGrammar) dgExtractor.extract(new ConcatenationIterator(trainTreebank.iterator(),blippTreebank.iterator()),new TransformTreeDependency(tlpParams));
// dg=new DependencyGrammarCombination(dg1,dgBLIPP,2);
dg = dgExtractor.extract(binaryTrainTrees); //uses information whether the words are known or not, discards unknown words
Timing.tick("done.");
//System.out.print("Extracting Unknown Word Model...");
//UnknownWordModel uwm = (UnknownWordModel)uwmExtractor.extract(binaryTrainTrees);
//Timing.tick("done.");
System.out.print("Tuning Dependency Model...");
dg.tune(binaryTestTrees);
//System.out.println("TUNE DEPS: "+tuneDeps);
Timing.tick("done.");
}
BinaryGrammar boundBG = bg;
UnaryGrammar boundUG = ug;
GrammarProjection gp = new NullGrammarProjection(bg, ug);
// serialization
if (serializeFile != null) {
System.err.print("Serializing parser...");
LexicalizedParser parser = new LexicalizedParser(lex, bg, ug, dg, stateIndex, wordIndex, tagIndex, op);
parser.saveParserToSerialized(serializeFile);
Timing.tick("done.");
}
// test: pcfg-parse and output
ExhaustivePCFGParser parser = null;
if (op.doPCFG) {
parser = new ExhaustivePCFGParser(boundBG, boundUG, lex, op, stateIndex, wordIndex, tagIndex);
}
ExhaustiveDependencyParser dparser = ((op.doDep && ! op.testOptions.useFastFactored) ? new ExhaustiveDependencyParser(dg, lex, op, wordIndex, tagIndex) : null);
Scorer scorer = (op.doPCFG ? new TwinScorer(new ProjectionScorer(parser, gp, op), dparser) : null);
//Scorer scorer = parser;
BiLexPCFGParser bparser = null;
if (op.doPCFG && op.doDep) {
bparser = (op.testOptions.useN5) ? new BiLexPCFGParser.N5BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp, stateIndex, wordIndex, tagIndex) : new BiLexPCFGParser(scorer, parser, dparser, bg, ug, dg, lex, op, gp, stateIndex, wordIndex, tagIndex);
}
Evalb pcfgPE = new Evalb("pcfg PE", true);
Evalb comboPE = new Evalb("combo PE", true);
AbstractEval pcfgCB = new Evalb.CBEval("pcfg CB", true);
AbstractEval pcfgTE = new TaggingEval("pcfg TE");
AbstractEval comboTE = new TaggingEval("combo TE");
AbstractEval pcfgTEnoPunct = new TaggingEval("pcfg nopunct TE");
AbstractEval comboTEnoPunct = new TaggingEval("combo nopunct TE");
AbstractEval depTE = new TaggingEval("depnd TE");
AbstractEval depDE = new UnlabeledAttachmentEval("depnd DE", true, null, tlp.punctuationWordRejectFilter());
AbstractEval comboDE = new UnlabeledAttachmentEval("combo DE", true, null, tlp.punctuationWordRejectFilter());
if (op.testOptions.evalb) {
EvalbFormatWriter.initEVALBfiles(op.tlpParams);
}
// int[] countByLength = new int[op.testOptions.maxLength+1];
// Use a reflection ruse, so one can run this without needing the
// tagger. Using a function rather than a MaxentTagger means we
// can distribute a version of the parser that doesn't include the
// entire tagger.
Function<List<? extends HasWord>,ArrayList<TaggedWord>> tagger = null;
if (op.testOptions.preTag) {
try {
Class[] argsClass = { String.class };
Object[] arguments = new Object[]{op.testOptions.taggerSerializedFile};
tagger = (Function<List<? extends HasWord>,ArrayList<TaggedWord>>) Class.forName("edu.stanford.nlp.tagger.maxent.MaxentTagger").getConstructor(argsClass).newInstance(arguments);
} catch (Exception e) {
System.err.println(e);
System.err.println("Warning: No pretagging of sentences will be done.");
}
}
for (int tNum = 0, ttSize = testTreebank.size(); tNum < ttSize; tNum++) {
Tree tree = testTreebank.get(tNum);
int testTreeLen = tree.yield().size();
if (testTreeLen > op.testOptions.maxLength) {
continue;
}
Tree binaryTree = binaryTestTrees.get(tNum);
// countByLength[testTreeLen]++;
System.out.println("-------------------------------------");
System.out.println("Number: " + (tNum + 1));
System.out.println("Length: " + testTreeLen);
//tree.pennPrint(pw);
// System.out.println("XXXX The binary tree is");
// binaryTree.pennPrint(pw);
//System.out.println("Here are the tags in the lexicon:");
//System.out.println(lex.showTags());
//System.out.println("Here's the tagnumberer:");
//System.out.println(Numberer.getGlobalNumberer("tags").toString());
long timeMil1 = System.currentTimeMillis();
Timing.tick("Starting parse.");
if (op.doPCFG) {
//System.err.println(op.testOptions.forceTags);
if (op.testOptions.forceTags) {
if (tagger != null) {
//System.out.println("Using a tagger to set tags");
//System.out.println("Tagged sentence as: " + tagger.processSentence(cutLast(wordify(binaryTree.yield()))).toString(false));
parser.parse(addLast(tagger.apply(cutLast(wordify(binaryTree.yield())))));
} else {
//System.out.println("Forcing tags to match input.");
parser.parse(cleanTags(binaryTree.taggedYield(), tlp));
}
} else {
// System.out.println("XXXX Parsing " + binaryTree.yield());
parser.parse(binaryTree.yieldHasWord());
}
//Timing.tick("Done with pcfg phase.");
}
if (op.doDep) {
dparser.parse(binaryTree.yieldHasWord());
//Timing.tick("Done with dependency phase.");
}
boolean bothPassed = false;
if (op.doPCFG && op.doDep) {
bothPassed = bparser.parse(binaryTree.yieldHasWord());
//Timing.tick("Done with combination phase.");
}
long timeMil2 = System.currentTimeMillis();
long elapsed = timeMil2 - timeMil1;
System.err.println("Time: " + ((int) (elapsed / 100)) / 10.00 + " sec.");
//System.out.println("PCFG Best Parse:");
Tree tree2b = null;
Tree tree2 = null;
//System.out.println("Got full best parse...");
if (op.doPCFG) {
tree2b = parser.getBestParse();
tree2 = debinarizer.transformTree(tree2b);
}
//System.out.println("Debinarized parse...");
//tree2.pennPrint();
//System.out.println("DepG Best Parse:");
Tree tree3 = null;
Tree tree3db = null;
if (op.doDep) {
tree3 = dparser.getBestParse();
// was: but wrong Tree tree3db = debinarizer.transformTree(tree2);
tree3db = debinarizer.transformTree(tree3);
tree3.pennPrint(pw);
}
//tree.pennPrint();
//((Tree)binaryTrainTrees.get(tNum)).pennPrint();
//System.out.println("Combo Best Parse:");
Tree tree4 = null;
if (op.doPCFG && op.doDep) {
try {
tree4 = bparser.getBestParse();
if (tree4 == null) {
tree4 = tree2b;
}
} catch (NullPointerException e) {
System.err.println("Blocked, using PCFG parse!");
tree4 = tree2b;
}
}
if (op.doPCFG && !bothPassed) {
tree4 = tree2b;
}
//tree4.pennPrint();
if (op.doDep) {
depDE.evaluate(tree3, binaryTree, pw);
depTE.evaluate(tree3db, tree, pw);
}
TreeTransformer tc = op.tlpParams.collinizer();
TreeTransformer tcEvalb = op.tlpParams.collinizerEvalb();
if (op.doPCFG) {
// System.out.println("XXXX Best PCFG was: ");
// tree2.pennPrint();
// System.out.println("XXXX Transformed best PCFG is: ");
// tc.transformTree(tree2).pennPrint();
//System.out.println("True Best Parse:");
//tree.pennPrint();
//tc.transformTree(tree).pennPrint();
pcfgPE.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw);
pcfgCB.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw);
Tree tree4b = null;
if (op.doDep) {
comboDE.evaluate((bothPassed ? tree4 : tree3), binaryTree, pw);
tree4b = tree4;
tree4 = debinarizer.transformTree(tree4);
if (op.nodePrune) {
NodePruner np = new NodePruner(parser, debinarizer);
tree4 = np.prune(tree4);
}
//tree4.pennPrint();
comboPE.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw);
}
//pcfgTE.evaluate(tree2, tree);
pcfgTE.evaluate(tcEvalb.transformTree(tree2), tcEvalb.transformTree(tree), pw);
pcfgTEnoPunct.evaluate(tc.transformTree(tree2), tc.transformTree(tree), pw);
if (op.doDep) {
comboTE.evaluate(tcEvalb.transformTree(tree4), tcEvalb.transformTree(tree), pw);
comboTEnoPunct.evaluate(tc.transformTree(tree4), tc.transformTree(tree), pw);
}
System.out.println("PCFG only: " + parser.scoreBinarizedTree(tree2b, 0));
//tc.transformTree(tree2).pennPrint();
tree2.pennPrint(pw);
if (op.doDep) {
System.out.println("Combo: " + parser.scoreBinarizedTree(tree4b, 0));
// tc.transformTree(tree4).pennPrint(pw);
tree4.pennPrint(pw);
}
System.out.println("Correct:" + parser.scoreBinarizedTree(binaryTree, 0));
/*
if (parser.scoreBinarizedTree(tree2b,true) < parser.scoreBinarizedTree(binaryTree,true)) {
System.out.println("SCORE INVERSION");
parser.validateBinarizedTree(binaryTree,0);
}
*/
tree.pennPrint(pw);
} // end if doPCFG
if (op.testOptions.evalb) {
if (op.doPCFG && op.doDep) {
EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree4));
} else if (op.doPCFG) {
EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree2));
} else if (op.doDep) {
EvalbFormatWriter.writeEVALBline(tcEvalb.transformTree(tree), tcEvalb.transformTree(tree3db));
}
}
} // end for each tree in test treebank
if (op.testOptions.evalb) {
EvalbFormatWriter.closeEVALBfiles();
}
// op.testOptions.display();
if (op.doPCFG) {
pcfgPE.display(false, pw);
System.out.println("Grammar size: " + stateIndex.size());
pcfgCB.display(false, pw);
if (op.doDep) {
comboPE.display(false, pw);
}
pcfgTE.display(false, pw);
pcfgTEnoPunct.display(false, pw);
if (op.doDep) {
comboTE.display(false, pw);
comboTEnoPunct.display(false, pw);
}
}
if (op.doDep) {
depTE.display(false, pw);
depDE.display(false, pw);
}
if (op.doPCFG && op.doDep) {
comboDE.display(false, pw);
}
// pcfgPE.printGoodBad();
}
private static List<TaggedWord> cleanTags(List<TaggedWord> twList, TreebankLanguagePack tlp) {
int sz = twList.size();
List<TaggedWord> l = new ArrayList<>(sz);
for (TaggedWord tw : twList) {
TaggedWord tw2 = new TaggedWord(tw.word(), tlp.basicCategory(tw.tag()));
l.add(tw2);
}
return l;
}
private static ArrayList<Word> wordify(List wList) {
ArrayList<Word> s = new ArrayList<>();
for (Object obj : wList) {
s.add(new Word(obj.toString()));
}
return s;
}
private static ArrayList<Word> cutLast(ArrayList<Word> s) {
return new ArrayList<>(s.subList(0, s.size() - 1));
}
private static ArrayList<Word> addLast(ArrayList<? extends Word> s) {
ArrayList<Word> s2 = new ArrayList<>(s);
//s2.add(new StringLabel(Lexicon.BOUNDARY));
s2.add(new Word(Lexicon.BOUNDARY));
return s2;
}
/**
* Not an instantiable class
*/
private FactoredParser() {
}
}
| gpl-2.0 |
vaginessa/Lanmitm | src/com/oinux/lanmitm/service/BaseService.java | 1380 | package com.oinux.lanmitm.service;
import com.oinux.lanmitm.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class BaseService extends Service {
public static final int HTTP_SERVER_NOTICE = 1;
public static final int HIJACK_NOTICE = 2;
public static final int SNIFFER_NOTICE = 3;
public static final int INJECT_NOTICE = 4;
public static final int ARPSPOOF_NOTICE = 0;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressWarnings("deprecation")
protected void notice(String tickerText, int id, Class<?> cls) {
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launch_notice,
getString(R.string.app_name), System.currentTimeMillis());
n.flags = Notification.FLAG_NO_CLEAR;
Intent intent = new Intent(this, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this,
R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
n.setLatestEventInfo(this, this.getString(R.string.app_name),
tickerText, contentIntent);
nm.notify(id, n);
}
}
| gpl-2.0 |
adamdoupe/enemy-of-the-state | jcc/java/org/apache/jcc/PythonVM.java | 1466 | /* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.apache.jcc;
public class PythonVM {
static protected PythonVM vm;
static {
System.loadLibrary("jcc");
}
static public PythonVM start(String programName, String[] args)
{
if (vm == null)
{
vm = new PythonVM();
vm.init(programName, args);
}
return vm;
}
static public PythonVM start(String programName)
{
return start(programName, null);
}
static public PythonVM get()
{
return vm;
}
protected PythonVM()
{
}
protected native void init(String programName, String[] args);
public native Object instantiate(String moduleName, String className)
throws PythonException;
}
| gpl-2.0 |
SpoonLabs/astor | examples/math_63/src/test/java/org/apache/commons/math/analysis/interpolation/LinearInterpolatorTest.java | 6231 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math.analysis.interpolation;
import org.apache.commons.math.MathException;
import org.apache.commons.math.exception.NonMonotonousSequenceException;
import org.apache.commons.math.exception.DimensionMismatchException;
import org.apache.commons.math.exception.NumberIsTooSmallException;
import org.apache.commons.math.TestUtils;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.polynomials.PolynomialFunction;
import org.apache.commons.math.analysis.polynomials.PolynomialSplineFunction;
import org.junit.Assert;
import org.junit.Test;
/**
* Test the LinearInterpolator.
*/
public class LinearInterpolatorTest {
/** error tolerance for spline interpolator value at knot points */
protected double knotTolerance = 1E-12;
/** error tolerance for interpolating polynomial coefficients */
protected double coefficientTolerance = 1E-6;
/** error tolerance for interpolated values */
protected double interpolationTolerance = 1E-12;
@Test
public void testInterpolateLinearDegenerateTwoSegment()
throws Exception {
double x[] = { 0.0, 0.5, 1.0 };
double y[] = { 0.0, 0.5, 1.0 };
UnivariateRealInterpolator i = new LinearInterpolator();
UnivariateRealFunction f = i.interpolate(x, y);
verifyInterpolation(f, x, y);
// Verify coefficients using analytical values
PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials();
double target[] = {y[0], 1d};
TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[1], 1d};
TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance);
// Check interpolation
Assert.assertEquals(0.0,f.value(0.0), interpolationTolerance);
Assert.assertEquals(0.4,f.value(0.4), interpolationTolerance);
Assert.assertEquals(1.0,f.value(1.0), interpolationTolerance);
}
@Test
public void testInterpolateLinearDegenerateThreeSegment()
throws Exception {
double x[] = { 0.0, 0.5, 1.0, 1.5 };
double y[] = { 0.0, 0.5, 1.0, 1.5 };
UnivariateRealInterpolator i = new LinearInterpolator();
UnivariateRealFunction f = i.interpolate(x, y);
verifyInterpolation(f, x, y);
// Verify coefficients using analytical values
PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials();
double target[] = {y[0], 1d};
TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[1], 1d};
TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[2], 1d};
TestUtils.assertEquals(polynomials[2].getCoefficients(), target, coefficientTolerance);
// Check interpolation
Assert.assertEquals(0,f.value(0), interpolationTolerance);
Assert.assertEquals(1.4,f.value(1.4), interpolationTolerance);
Assert.assertEquals(1.5,f.value(1.5), interpolationTolerance);
}
@Test
public void testInterpolateLinear() throws Exception {
double x[] = { 0.0, 0.5, 1.0 };
double y[] = { 0.0, 0.5, 0.0 };
UnivariateRealInterpolator i = new LinearInterpolator();
UnivariateRealFunction f = i.interpolate(x, y);
verifyInterpolation(f, x, y);
// Verify coefficients using analytical values
PolynomialFunction polynomials[] = ((PolynomialSplineFunction) f).getPolynomials();
double target[] = {y[0], 1d};
TestUtils.assertEquals(polynomials[0].getCoefficients(), target, coefficientTolerance);
target = new double[]{y[1], -1d};
TestUtils.assertEquals(polynomials[1].getCoefficients(), target, coefficientTolerance);
}
@Test
public void testIllegalArguments() throws MathException {
// Data set arrays of different size.
UnivariateRealInterpolator i = new LinearInterpolator();
try {
double xval[] = { 0.0, 1.0 };
double yval[] = { 0.0, 1.0, 2.0 };
i.interpolate(xval, yval);
Assert.fail("Failed to detect data set array with different sizes.");
} catch (DimensionMismatchException iae) {
// Expected.
}
// X values not sorted.
try {
double xval[] = { 0.0, 1.0, 0.5 };
double yval[] = { 0.0, 1.0, 2.0 };
i.interpolate(xval, yval);
Assert.fail("Failed to detect unsorted arguments.");
} catch (NonMonotonousSequenceException iae) {
// Expected.
}
// Not enough data to interpolate.
try {
double xval[] = { 0.0 };
double yval[] = { 0.0 };
i.interpolate(xval, yval);
Assert.fail("Failed to detect unsorted arguments.");
} catch (NumberIsTooSmallException iae) {
// Expected.
}
}
/**
* verifies that f(x[i]) = y[i] for i = 0..n-1 where n is common length.
*/
protected void verifyInterpolation(UnivariateRealFunction f, double x[], double y[])
throws Exception{
for (int i = 0; i < x.length; i++) {
Assert.assertEquals(f.value(x[i]), y[i], knotTolerance);
}
}
}
| gpl-2.0 |
ataranlen/civcraft | civcraft/src/com/avrgaming/civcraft/structure/MobGrinder.java | 2644 | package com.avrgaming.civcraft.structure;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;
import org.bukkit.Location;
import com.avrgaming.civcraft.config.CivSettings;
import com.avrgaming.civcraft.exception.CivException;
import com.avrgaming.civcraft.exception.InvalidConfiguration;
import com.avrgaming.civcraft.object.Buff;
import com.avrgaming.civcraft.object.Town;
public class MobGrinder extends Structure {
private static final double T1_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t1_chance"); //1%
private static final double T2_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t2_chance"); //2%
private static final double T3_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t3_chance"); //1%
private static final double T4_CHANCE = CivSettings.getDoubleStructure("mobGrinder.t4_chance"); //0.25%
private static final double PACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.pack_chance"); //0.10%
private static final double BIGPACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.bigpack_chance");
private static final double HUGEPACK_CHANCE = CivSettings.getDoubleStructure("mobGrinder.hugepack_chance");
public int skippedCounter = 0;
public ReentrantLock lock = new ReentrantLock();
public enum Crystal {
T1,
T2,
T3,
T4,
PACK,
BIGPACK,
HUGEPACK
}
protected MobGrinder(Location center, String id, Town town) throws CivException {
super(center, id, town);
}
public MobGrinder(ResultSet rs) throws SQLException, CivException {
super(rs);
}
@Override
public String getDynmapDescription() {
return null;
}
@Override
public String getMarkerIconName() {
return "minecart";
}
public double getMineralChance(Crystal crystal) {
double chance = 0;
switch (crystal) {
case T1:
chance = T1_CHANCE;
break;
case T2:
chance = T2_CHANCE;
break;
case T3:
chance = T3_CHANCE;
break;
case T4:
chance = T4_CHANCE;
break;
case PACK:
chance = PACK_CHANCE;
break;
case BIGPACK:
chance = BIGPACK_CHANCE;
break;
case HUGEPACK:
chance = HUGEPACK_CHANCE;
}
double increase = chance*this.getTown().getBuffManager().getEffectiveDouble(Buff.EXTRACTION);
chance += increase;
try {
if (this.getTown().getGovernment().id.equals("gov_tribalism")) {
chance *= CivSettings.getDouble(CivSettings.structureConfig, "mobGrinder.tribalism_rate");
} else {
chance *= CivSettings.getDouble(CivSettings.structureConfig, "mobGrinder.penalty_rate");
}
} catch (InvalidConfiguration e) {
e.printStackTrace();
}
return chance;
}
}
| gpl-2.0 |
knabar/openmicroscopy | components/server/test/ome/server/itests/hibernate/ExtendedMetadataTest.java | 8808 | /*
* $Id$
*
* Copyright 2006 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.server.itests.hibernate;
import java.util.Arrays;
import java.util.Set;
import ome.model.IAnnotated;
import ome.model.ILink;
import ome.model.IObject;
import ome.model.annotations.Annotation;
import ome.model.annotations.BasicAnnotation;
import ome.model.annotations.LongAnnotation;
import ome.model.containers.Dataset;
import ome.model.containers.DatasetImageLink;
import ome.model.containers.Project;
import ome.model.containers.ProjectDatasetLink;
import ome.model.core.Image;
import ome.model.core.Pixels;
import ome.model.display.RenderingDef;
import ome.model.meta.Experimenter;
import ome.server.itests.AbstractManagedContextTest;
import ome.testing.ObjectFactory;
import ome.tools.hibernate.ExtendedMetadata;
import org.hibernate.SessionFactory;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ExtendedMetadataTest extends AbstractManagedContextTest {
ExtendedMetadata.Impl metadata;
@BeforeClass
public void init() throws Exception {
setUp();
metadata = new ExtendedMetadata.Impl();
metadata.setSessionFactory((SessionFactory)applicationContext.getBean("sessionFactory"));
tearDown();
}
@Test
public void testAnnotatedAreFound() throws Exception {
Set<Class<IAnnotated>> anns = metadata.getAnnotatableTypes();
assertTrue(anns.contains(Image.class));
assertTrue(anns.contains(Project.class));
// And several others
}
@Test
public void testAnnotationsAreFound() throws Exception {
Set<Class<Annotation>> anns = metadata.getAnnotationTypes();
assertTrue(anns.toString(), anns.contains(Annotation.class));
assertTrue(anns.toString(), anns.contains(BasicAnnotation.class));
assertTrue(anns.toString(), anns.contains(LongAnnotation.class));
// And several others
}
/**
* Where a superclass has a relationship to a class (Annotation to some link type),
* it is also necessary to be able to find the same relationship from a subclass
* (e.g. FileAnnotation).
*/
@Test
public void testLinkFromSubclassToSuperClassRel() {
assertNotNull(
metadata.getRelationship("ImageAnnotationLink", "FileAnnotation"));
}
/**
* For simplicity, the relationship map currently holds only the short
* class names. Here we are adding a test which checks for the full ones
* under "broken" to remember to re-evaluate.
*/
@Test(groups = {"broken","fixme"})
public void testAnnotatedAreFoundByFQN() throws Exception {
Set<Class<IAnnotated>> anns = metadata.getAnnotatableTypes();
assertTrue(anns.contains(Image.class));
assertTrue(anns.contains(Project.class));
// And several others
}
// ~ Locking
// =========================================================================
@Test
public void testProjectLocksDataset() throws Exception {
Project p = new Project();
Dataset d = new Dataset();
p.linkDataset(d);
ILink l = (ILink) p.collectDatasetLinks(null).iterator().next();
assertDoesntContain(metadata.getLockCandidates(p), d);
assertContains(metadata.getLockCandidates(l), d);
}
@Test
// Because Pixels does not have a reference to RenderingDef
public void testRenderingDefLocksPixels() throws Exception {
Pixels p = ObjectFactory.createPixelGraph(null);
RenderingDef r = ObjectFactory.createRenderingDef();
r.setPixels(p);
assertContains(metadata.getLockCandidates(r), p);
}
@Test(groups = "ticket:357")
// quirky because of defaultTag
// see https://trac.openmicroscopy.org/ome/ticket/357
public void testPixelsLocksImage() throws Exception {
Pixels p = ObjectFactory.createPixelGraph(null);
Image i = new Image();
i.setName("locking");
i.addPixels(p);
assertContains(metadata.getLockCandidates(p), i);
}
@Test
// omit locks for system types (TODO they shouldn't have permissions anyway)
public void testExperimenterDoesntGetLocked() throws Exception {
Experimenter e = new Experimenter();
Project p = new Project();
p.getDetails().setOwner(e);
assertDoesntContain(metadata.getLockCandidates(p), e);
}
@Test
public void testNoNulls() throws Exception {
Project p = new Project();
ProjectDatasetLink pdl = new ProjectDatasetLink();
pdl.link(p, null);
assertDoesntContain(metadata.getLockCandidates(pdl), null);
}
// ~ Unlocking
// =========================================================================
@Test
public void testProjectCanBeUnlockedFromDataset() throws Exception {
assertContains(metadata.getLockChecks(Project.class),
ProjectDatasetLink.class.getName(), "parent");
}
@Test
// Because Pixels does not have a reference to RenderingDef
public void testPixelsCanBeUnlockedFromRenderingDef() throws Exception {
assertContains(metadata.getLockChecks(Pixels.class), RenderingDef.class
.getName(), "pixels");
}
@Test(groups = "ticket:357")
// quirky because of defaultTag
// see https://trac.openmicroscopy.org/ome/ticket/357
public void testImageCanBeUnlockedFromPixels() throws Exception {
assertContains(metadata.getLockChecks(Image.class), Pixels.class
.getName(), "image");
}
// ~ Updating
// =========================================================================
@Test(groups = { "ticket:346", "broken" })
public void testCreateEventImmutable() throws Exception {
assertContains(metadata.getImmutableFields(Image.class),
"details.creationEvent");
}
// ~ Counting
// =========================================================================
@Test(groups = { "ticket:657" })
public void testCountQueriesAreCorrect() throws Exception {
assertEquals(metadata.getCountQuery(DatasetImageLink.CHILD), metadata
.getCountQuery(DatasetImageLink.CHILD),
"select target.child.id, count(target) "
+ "from ome.model.containers.DatasetImageLink target "
+ "group by target.child.id");
assertEquals(metadata.getCountQuery(Pixels.IMAGE), metadata
.getCountQuery(Pixels.IMAGE),
"select target.image.id, count(target) "
+ "from ome.model.core.Pixels target "
+ "group by target.image.id");
}
@Test(groups = { "ticket:657" })
public void testTargetTypes() throws Exception {
assertEquals(metadata.getTargetType(Pixels.IMAGE), Image.class);
assertEquals(metadata.getTargetType(DatasetImageLink.CHILD),
Image.class);
}
// ~ Relationships
// =========================================================================
@Test(groups = "ticket:2665")
public void testRelationships() {
String rel;
rel = metadata.getRelationship(Pixels.class.getSimpleName(), Image.class.getSimpleName());
assertEquals("image", rel);
rel = metadata.getRelationship(Image.class.getSimpleName(), Pixels.class.getSimpleName());
assertEquals("pixels", rel);
}
// ~ Helpers
// =========================================================================
private void assertContains(Object[] array, Object i) {
if (!contained(array, i)) {
fail(i + " not contained in " + Arrays.toString(array));
}
}
private void assertDoesntContain(IObject[] array, IObject i) {
if (contained(array, i)) {
fail(i + " contained in " + Arrays.toString(array));
}
}
private void assertContains(String[][] array, String t1, String t2) {
boolean contained = false;
for (int i = 0; i < array.length; i++) {
String[] test = array[i];
if (test[0].equals(t1) && test[1].equals(t2)) {
contained |= true;
}
}
assertTrue(contained);
}
private boolean contained(Object[] array, Object i) {
boolean contained = false;
for (Object object : array) {
if (i == null) {
if (object == null) {
contained = true;
}
} else {
if (i.equals(object)) {
contained = true;
}
}
}
return contained;
}
}
| gpl-2.0 |
jchalco/Ate | sistema/sistema-ejb/src/java/bc/ReporteFumigacionFacade.java | 663 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package bc;
import be.ReporteFumigacion;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* @author argos
*/
@Stateless
public class ReporteFumigacionFacade extends AbstractFacade<ReporteFumigacion> implements ReporteFumigacionFacadeLocal {
@PersistenceContext(unitName = "sistema-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
public ReporteFumigacionFacade() {
super(ReporteFumigacion.class);
}
}
| gpl-2.0 |
SpoonLabs/astor | examples/math_5/src/main/java/org/apache/commons/math3/stat/clustering/EuclideanDoublePoint.java | 3065 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.stat.clustering;
import java.io.Serializable;
import java.util.Collection;
import java.util.Arrays;
import org.apache.commons.math3.util.MathArrays;
/**
* A simple implementation of {@link Clusterable} for points with double coordinates.
* @version $Id$
* @since 3.1
*/
public class EuclideanDoublePoint implements Clusterable<EuclideanDoublePoint>, Serializable {
/** Serializable version identifier. */
private static final long serialVersionUID = 8026472786091227632L;
/** Point coordinates. */
private final double[] point;
/**
* Build an instance wrapping an integer array.
* <p>
* The wrapped array is referenced, it is <em>not</em> copied.
*
* @param point the n-dimensional point in integer space
*/
public EuclideanDoublePoint(final double[] point) {
this.point = point;
}
/** {@inheritDoc} */
public EuclideanDoublePoint centroidOf(final Collection<EuclideanDoublePoint> points) {
final double[] centroid = new double[getPoint().length];
for (final EuclideanDoublePoint p : points) {
for (int i = 0; i < centroid.length; i++) {
centroid[i] += p.getPoint()[i];
}
}
for (int i = 0; i < centroid.length; i++) {
centroid[i] /= points.size();
}
return new EuclideanDoublePoint(centroid);
}
/** {@inheritDoc} */
public double distanceFrom(final EuclideanDoublePoint p) {
return MathArrays.distance(point, p.getPoint());
}
/** {@inheritDoc} */
@Override
public boolean equals(final Object other) {
if (!(other instanceof EuclideanDoublePoint)) {
return false;
}
return Arrays.equals(point, ((EuclideanDoublePoint) other).point);
}
/**
* Get the n-dimensional point in integer space.
*
* @return a reference (not a copy!) to the wrapped array
*/
public double[] getPoint() {
return point;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Arrays.hashCode(point);
}
/** {@inheritDoc} */
@Override
public String toString() {
return Arrays.toString(point);
}
}
| gpl-2.0 |
netroby/hotspot9 | test/compiler/codecache/jmx/BeanTypeTest.java | 1948 | /*
* Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import com.oracle.java.testlibrary.Asserts;
import java.lang.management.MemoryType;
import sun.hotspot.code.BlobType;
/**
* @test BeanTypeTest
* @library /testlibrary /../../test/lib
* @modules java.management
* @build BeanTypeTest
* @run main ClassFileInstaller sun.hotspot.WhiteBox
* sun.hotspot.WhiteBox$WhiteBoxPermission
* @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
* -XX:+WhiteBoxAPI -XX:+SegmentedCodeCache BeanTypeTest
* @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions
* -XX:+WhiteBoxAPI -XX:-SegmentedCodeCache BeanTypeTest
* @summary verify types of code cache memory pool bean
*/
public class BeanTypeTest {
public static void main(String args[]) {
for (BlobType bt : BlobType.getAvailable()) {
Asserts.assertEQ(MemoryType.NON_HEAP, bt.getMemoryPool().getType());
}
}
}
| gpl-2.0 |
deathspeeder/class-guard | spring-framework-3.2.x/spring-context/src/main/java/org/springframework/cache/interceptor/CacheInterceptor.java | 2142 | /*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cache.interceptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* AOP Alliance MethodInterceptor for declarative cache
* management using the common Spring caching infrastructure
* ({@link org.springframework.cache.Cache}).
*
* <p>Derives from the {@link CacheAspectSupport} class which
* contains the integration with Spring's underlying caching API.
* CacheInterceptor simply calls the relevant superclass methods
* in the correct order.
*
* <p>CacheInterceptors are thread-safe.
*
* @author Costin Leau
* @author Juergen Hoeller
* @since 3.1
*/
@SuppressWarnings("serial")
public class CacheInterceptor extends CacheAspectSupport implements MethodInterceptor, Serializable {
private static class ThrowableWrapper extends RuntimeException {
private final Throwable original;
ThrowableWrapper(Throwable original) {
this.original = original;
}
}
public Object invoke(final MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
Invoker aopAllianceInvoker = new Invoker() {
public Object invoke() {
try {
return invocation.proceed();
} catch (Throwable ex) {
throw new ThrowableWrapper(ex);
}
}
};
try {
return execute(aopAllianceInvoker, invocation.getThis(), method, invocation.getArguments());
} catch (ThrowableWrapper th) {
throw th.original;
}
}
}
| gpl-2.0 |
tharindum/opennms_dashboard | opennms-services/src/main/java/org/opennms/protocols/jmx/connectors/ConnectionWrapper.java | 1879 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2006-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.protocols.jmx.connectors;
import javax.management.MBeanServerConnection;
/*
* This interface defines the ability to handle a live connection and the ability to
* close it.
*
* @author <A HREF="mailto:mike@opennms.org">Mike Jamison </A>
* @author <A HREF="http://www.opennms.org/">OpenNMS </A>
*/
/**
* <p>ConnectionWrapper interface.</p>
*
* @author ranger
* @version $Id: $
*/
public interface ConnectionWrapper {
/**
* <p>getMBeanServer</p>
*
* @return a {@link javax.management.MBeanServerConnection} object.
*/
public MBeanServerConnection getMBeanServer();
/**
* <p>close</p>
*/
public void close();
}
| gpl-2.0 |
marylinh/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest01168.java | 4339 | /**
* OWASP Benchmark Project v1.2beta
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The OWASP Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The OWASP Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest01168")
public class BenchmarkTest01168 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String param = "";
boolean flag = true;
java.util.Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements() && flag) {
String name = (String) names.nextElement();
java.util.Enumeration<String> values = request.getHeaders(name);
if (values != null) {
while (values.hasMoreElements() && flag) {
String value = (String) values.nextElement();
if (value.equals("vector")) {
param = name;
flag = false;
}
}
}
}
String bar = new Test().doSomething(param);
try {
java.util.Random numGen = java.security.SecureRandom.getInstance("SHA1PRNG");
double rand = getNextNumber(numGen);
String rememberMeKey = Double.toString(rand).substring(2); // Trim off the 0. at the front.
String user = "SafeDonatella";
String fullClassName = this.getClass().getName();
String testCaseNumber = fullClassName.substring(fullClassName.lastIndexOf('.')+1+"BenchmarkTest".length());
user+= testCaseNumber;
String cookieName = "rememberMe" + testCaseNumber;
boolean foundUser = false;
javax.servlet.http.Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && ++i < cookies.length && !foundUser;) {
javax.servlet.http.Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
if (cookie.getValue().equals(request.getSession().getAttribute(cookieName))) {
foundUser = true;
}
}
}
if (foundUser) {
response.getWriter().println("Welcome back: " + user + "<br/>");
} else {
javax.servlet.http.Cookie rememberMe = new javax.servlet.http.Cookie(cookieName, rememberMeKey);
rememberMe.setSecure(true);
request.getSession().setAttribute(cookieName, rememberMeKey);
response.addCookie(rememberMe);
response.getWriter().println(user + " has been remembered with cookie: " + rememberMe.getName()
+ " whose value is: " + rememberMe.getValue() + "<br/>");
}
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing SecureRandom.nextDouble() - TestCase");
throw new ServletException(e);
}
response.getWriter().println("Weak Randomness Test java.security.SecureRandom.nextDouble() executed");
}
double getNextNumber(java.util.Random generator) {
return generator.nextDouble();
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar;
// Simple if statement that assigns constant to bar on true condition
int num = 86;
if ( (7*42) - num > 200 )
bar = "This_should_always_happen";
else bar = param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
smalyshev/blazegraph | bigdata/src/test/com/bigdata/relation/accesspath/TestUnsynchronizedUnboundedChunkBuffer.java | 4863 | /*
Copyright (C) SYSTAP, LLC 2006-2015. All rights reserved.
Contact:
SYSTAP, LLC
2501 Calvert ST NW #106
Washington, DC 20008
licenses@systap.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Apr 18, 2009
*/
package com.bigdata.relation.accesspath;
import junit.framework.TestCase2;
import com.bigdata.striterator.IChunkedIterator;
/**
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
public class TestUnsynchronizedUnboundedChunkBuffer extends TestCase2 {
/**
*
*/
public TestUnsynchronizedUnboundedChunkBuffer() {
}
/**
* @param arg0
*/
public TestUnsynchronizedUnboundedChunkBuffer(String arg0) {
super(arg0);
}
/**
* Test empty iterator.
*/
public void test_emptyIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
// the iterator is initially empty.
assertFalse(buffer.iterator().hasNext());
}
/**
* Verify that elements are flushed when an iterator is requested so
* that they will be visited by the iterator.
*/
public void test_bufferFlushedByIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
assertSameIterator(new String[] { "a" }, buffer.iterator());
}
/**
* Verify that the iterator has snapshot semantics.
*/
public void test_snapshotIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.add("b");
buffer.add("c");
// visit once.
assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator());
// will visit again.
assertSameIterator(new String[] { "a", "b", "c" }, buffer.iterator());
}
/**
* Verify iterator visits chunks as placed onto the queue.
*/
public void test_chunkedIterator() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.flush();
buffer.add("b");
buffer.add("c");
// visit once.
assertSameChunkedIterator(new String[][] { new String[] { "a" },
new String[] { "b", "c" } }, buffer.iterator());
}
/**
* Test class of chunks created by the iterator (the array class should be
* taken from the first visited chunk's class).
*/
// @SuppressWarnings("unchecked")
public void test_chunkClass() {
final UnsynchronizedUnboundedChunkBuffer<String> buffer = new UnsynchronizedUnboundedChunkBuffer<String>(
3/* chunkCapacity */, String.class);
buffer.add("a");
buffer.flush();
buffer.add("b");
buffer.add("c");
// visit once.
assertSameChunkedIterator(new String[][] { new String[] { "a" },
new String[] { "b", "c" } }, buffer.iterator());
}
/**
* Verify that the iterator visits the expected chunks in the expected
* order.
*
* @param <E>
* @param chunks
* @param itr
*/
protected <E> void assertSameChunkedIterator(final E[][] chunks,
final IChunkedIterator<E> itr) {
for(E[] chunk : chunks) {
assertTrue(itr.hasNext());
final E[] actual = itr.nextChunk();
assertSameArray(chunk, actual);
}
assertFalse(itr.hasNext());
}
}
| gpl-2.0 |
ayuzhanin/cornell-spf-scala | src/main/java/edu/cornell/cs/nlp/spf/parser/ccg/rules/coordination/C2Rule.java | 3328 | /*******************************************************************************
* Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved.
* <p>
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or any later version.
* <p>
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
* <p>
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*******************************************************************************/
package edu.cornell.cs.nlp.spf.parser.ccg.rules.coordination;
import edu.cornell.cs.nlp.spf.ccg.categories.Category;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.ComplexSyntax;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Slash;
import edu.cornell.cs.nlp.spf.ccg.categories.syntax.Syntax;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.IBinaryParseRule;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.ParseRuleResult;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.SentenceSpan;
import edu.cornell.cs.nlp.spf.parser.ccg.rules.RuleName.Direction;
class C2Rule<MR> implements IBinaryParseRule<MR> {
private static final RuleName RULE_NAME = RuleName
.create("c2",
Direction.FORWARD);
private static final long serialVersionUID = 1876084168220307197L;
private final ICoordinationServices<MR> services;
public C2Rule(ICoordinationServices<MR> services) {
this.services = services;
}
@Override
public ParseRuleResult<MR> apply(Category<MR> left, Category<MR> right,
SentenceSpan span) {
if (left.getSyntax().equals(Syntax.C)
&& SyntaxCoordinationServices.isCoordinationOfType(
right.getSyntax(), null)) {
final MR semantics = services.expandCoordination(right
.getSemantics());
if (semantics != null) {
return new ParseRuleResult<MR>(RULE_NAME,
Category.create(
new ComplexSyntax(right.getSyntax(),
SyntaxCoordinationServices
.getCoordinationType(right
.getSyntax()),
Slash.BACKWARD), semantics));
}
}
return null;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
@SuppressWarnings("rawtypes")
final C2Rule other = (C2Rule) obj;
if (services == null) {
if (other.services != null) {
return false;
}
} else if (!services.equals(other.services)) {
return false;
}
return true;
}
@Override
public RuleName getName() {
return RULE_NAME;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ (RULE_NAME == null ? 0 : RULE_NAME.hashCode());
result = prime * result + (services == null ? 0 : services.hashCode());
return result;
}
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/sql/src/main/java/java/sql/SQLTransactionRollbackException.java | 5553 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package java.sql;
public class SQLTransactionRollbackException extends SQLTransientException {
private static final long serialVersionUID = 5246680841170837229L;
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to null, the SQLState string is set to null and the Error Code is set
* to 0.
*/
public SQLTransactionRollbackException() {
super();
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to null and
* the Error Code is set to 0.
*
* @param reason
* the string to use as the Reason string
*/
public SQLTransactionRollbackException(String reason) {
super(reason, null, 0);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the Error Code is set to 0.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
*/
public SQLTransactionRollbackException(String reason, String sqlState) {
super(reason, sqlState, 0);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the Error Code is set to the given error code value.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param vendorCode
* the integer value for the error code
*/
public SQLTransactionRollbackException(String reason, String sqlState,
int vendorCode) {
super(reason, sqlState, vendorCode);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the null if cause == null or cause.toString() if cause!=null,and
* the cause Throwable object is set to the given cause Throwable object.
*
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(Throwable cause) {
super(cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given and the cause Throwable object is set to the given cause
* Throwable object.
*
* @param reason
* the string to use as the Reason string
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, Throwable cause) {
super(reason, cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string and the cause Throwable object is set to the given cause
* Throwable object.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, String sqlState,
Throwable cause) {
super(reason, sqlState, cause);
}
/**
* Creates an SQLTransactionRollbackException object. The Reason string is
* set to the given reason string, the SQLState string is set to the given
* SQLState string , the Error Code is set to the given error code value,
* and the cause Throwable object is set to the given cause Throwable
* object.
*
* @param reason
* the string to use as the Reason string
* @param sqlState
* the string to use as the SQLState string
* @param vendorCode
* the integer value for the error code
* @param cause
* the Throwable object for the underlying reason this
* SQLException
*/
public SQLTransactionRollbackException(String reason, String sqlState,
int vendorCode, Throwable cause) {
super(reason, sqlState, vendorCode, cause);
}
} | gpl-2.0 |
dwango/quercus | src/main/java/com/caucho/quercus/expr/ClassVirtualFieldExpr.java | 4206 | /*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.quercus.expr;
import java.io.IOException;
import java.util.ArrayList;
import com.caucho.quercus.Location;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.MethodIntern;
import com.caucho.quercus.env.NullValue;
import com.caucho.quercus.env.StringValue;
import com.caucho.quercus.env.QuercusClass;
import com.caucho.quercus.env.Value;
import com.caucho.quercus.env.Var;
import com.caucho.quercus.parser.QuercusParser;
import com.caucho.util.L10N;
/**
* Represents a PHP static field reference.
*/
public class ClassVirtualFieldExpr extends AbstractVarExpr {
private static final L10N L = new L10N(ClassVirtualFieldExpr.class);
protected final StringValue _varName;
public ClassVirtualFieldExpr(String varName)
{
_varName = MethodIntern.intern(varName);
}
//
// function call creation
//
/**
* Creates a function call expression
*/
@Override
public Expr createCall(QuercusParser parser,
Location location,
ArrayList<Expr> args)
throws IOException
{
ExprFactory factory = parser.getExprFactory();
Expr var = parser.createVar(_varName.toString());
return factory.createClassVirtualMethodCall(location, var, args);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value eval(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL;
}
return qClass.getStaticFieldValue(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Var evalVar(Env env)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.getStaticFieldVar(env, _varName);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
@Override
public Value evalAssignRef(Env env, Value value)
{
Value qThis = env.getThis();
QuercusClass qClass = qThis != null ? qThis.getQuercusClass() : null;
if (qClass == null) {
env.error(L.l("No calling class found for '{0}'", this));
return NullValue.NULL.toVar();
}
return qClass.setStaticFieldRef(env, _varName, value);
}
/**
* Evaluates the expression.
*
* @param env the calling environment.
*
* @return the expression value.
*/
public void evalUnset(Env env)
{
env.error(getLocation(),
L.l("{0}::${1}: Cannot unset static variables.",
env.getCallingClass().getName(), _varName));
}
public String toString()
{
return "static::$" + _varName;
}
}
| gpl-2.0 |
martincz/AmazeFileManager | src/main/java/com/amaze/filemanager/filesystem/Operations.java | 24347 | package com.amaze.filemanager.filesystem;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.provider.DocumentFile;
import com.amaze.filemanager.exceptions.RootNotPermittedException;
import com.amaze.filemanager.utils.DataUtils;
import com.amaze.filemanager.utils.cloud.CloudUtil;
import com.amaze.filemanager.utils.Logger;
import com.amaze.filemanager.utils.MainActivityHelper;
import com.amaze.filemanager.utils.OTGUtil;
import com.amaze.filemanager.utils.OpenMode;
import com.amaze.filemanager.utils.RootUtils;
import com.cloudrail.si.interfaces.CloudStorage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
/**
* Created by arpitkh996 on 13-01-2016, modified by Emmanuel Messulam<emmanuelbendavid@gmail.com>
*/
public class Operations {
// reserved characters by OS, shall not be allowed in file names
private static final String FOREWARD_SLASH = "/";
private static final String BACKWARD_SLASH = "\\";
private static final String COLON = ":";
private static final String ASTERISK = "*";
private static final String QUESTION_MARK = "?";
private static final String QUOTE = "\"";
private static final String GREATER_THAN = ">";
private static final String LESS_THAN = "<";
private static final String FAT = "FAT";
private DataUtils dataUtils = DataUtils.getInstance();
public interface ErrorCallBack {
/**
* Callback fired when file being created in process already exists
*
* @param file
*/
void exists(HFile file);
/**
* Callback fired when creating new file/directory and required storage access framework permission
* to access SD Card is not available
*
* @param file
*/
void launchSAF(HFile file);
/**
* Callback fired when renaming file and required storage access framework permission to access
* SD Card is not available
*
* @param file
* @param file1
*/
void launchSAF(HFile file, HFile file1);
/**
* Callback fired when we're done processing the operation
*
* @param hFile
* @param b defines whether operation was successful
*/
void done(HFile hFile, boolean b);
/**
* Callback fired when an invalid file name is found.
*
* @param file
*/
void invalidName(HFile file);
}
public static void mkdir(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// checking whether filename is valid or a recursive call possible
if (MainActivityHelper.isNewDirectoryRecursive(file) ||
!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).mkdirs();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isOtgFile()) {
// first check whether new directory already exists
DocumentFile directoryToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (directoryToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createDirectory(file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.createFolder(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.createFolder(CloudUtil.stripPath(OpenMode.BOX, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.createFolder(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.createFolder(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()));
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
FileUtil.mkdir(file.getFile(), context);
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkDir(file.getParent(context), file.getName(context));
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void mkfile(@NonNull final HFile file, final Context context, final boolean rootMode,
@NonNull final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether filename is valid or not
if (!Operations.isFileNameValid(file.getName(context))) {
errorCallBack.invalidName(file);
return null;
}
if (file.exists()) {
errorCallBack.exists(file);
return null;
}
if (file.isSmb()) {
try {
file.getSmbFile(2000).createNewFile();
} catch (SmbException e) {
Logger.log(e, file.getPath(), context);
errorCallBack.done(file, false);
return null;
}
errorCallBack.done(file, file.exists());
return null;
} else if (file.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageDropbox.upload(CloudUtil.stripPath(OpenMode.DROPBOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageBox.upload(CloudUtil.stripPath(OpenMode.BOX, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageOneDrive.upload(CloudUtil.stripPath(OpenMode.ONEDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
byte[] tempBytes = new byte[0];
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tempBytes);
cloudStorageGdrive.upload(CloudUtil.stripPath(OpenMode.GDRIVE, file.getPath()),
byteArrayInputStream, 0l, true);
errorCallBack.done(file, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(file, false);
}
} else if (file.isOtgFile()) {
// first check whether new file already exists
DocumentFile fileToCreate = OTGUtil.getDocumentFile(file.getPath(), context, false);
if (fileToCreate != null) errorCallBack.exists(file);
DocumentFile parentDirectory = OTGUtil.getDocumentFile(file.getParent(), context, false);
if (parentDirectory.isDirectory()) {
parentDirectory.createFile(file.getName(context).substring(file.getName().lastIndexOf(".")),
file.getName(context));
errorCallBack.done(file, true);
} else errorCallBack.done(file, false);
return null;
} else {
if (file.isLocal() || file.isRoot()) {
int mode = checkFolder(new File(file.getParent()), context);
if (mode == 2) {
errorCallBack.launchSAF(file);
return null;
}
if (mode == 1 || mode == 0)
try {
FileUtil.mkfile(file.getFile(), context);
} catch (IOException e) {
}
if (!file.exists() && rootMode) {
file.setMode(OpenMode.ROOT);
if (file.exists()) errorCallBack.exists(file);
try {
RootUtils.mkFile(file.getPath());
} catch (RootNotPermittedException e) {
Logger.log(e, file.getPath(), context);
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
return null;
}
errorCallBack.done(file, file.exists());
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public static void rename(final HFile oldFile, final HFile newFile, final boolean rootMode,
final Context context, final ErrorCallBack errorCallBack) {
new AsyncTask<Void, Void, Void>() {
private DataUtils dataUtils = DataUtils.getInstance();
@Override
protected Void doInBackground(Void... params) {
// check whether file names for new file are valid or recursion occurs
if (MainActivityHelper.isNewDirectoryRecursive(newFile) ||
!Operations.isFileNameValid(newFile.getName(context))) {
errorCallBack.invalidName(newFile);
return null;
}
if (newFile.exists()) {
errorCallBack.exists(newFile);
return null;
}
if (oldFile.isSmb()) {
try {
SmbFile smbFile = new SmbFile(oldFile.getPath());
SmbFile smbFile1 = new SmbFile(newFile.getPath());
if (smbFile1.exists()) {
errorCallBack.exists(newFile);
return null;
}
smbFile.renameTo(smbFile1);
if (!smbFile.exists() && smbFile1.exists())
errorCallBack.done(newFile, true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (SmbException e) {
e.printStackTrace();
}
return null;
} else if (oldFile.isDropBoxFile()) {
CloudStorage cloudStorageDropbox = dataUtils.getAccount(OpenMode.DROPBOX);
try {
cloudStorageDropbox.move(CloudUtil.stripPath(OpenMode.DROPBOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.DROPBOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isBoxFile()) {
CloudStorage cloudStorageBox = dataUtils.getAccount(OpenMode.BOX);
try {
cloudStorageBox.move(CloudUtil.stripPath(OpenMode.BOX, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.BOX, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOneDriveFile()) {
CloudStorage cloudStorageOneDrive = dataUtils.getAccount(OpenMode.ONEDRIVE);
try {
cloudStorageOneDrive.move(CloudUtil.stripPath(OpenMode.ONEDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.ONEDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isGoogleDriveFile()) {
CloudStorage cloudStorageGdrive = dataUtils.getAccount(OpenMode.GDRIVE);
try {
cloudStorageGdrive.move(CloudUtil.stripPath(OpenMode.GDRIVE, oldFile.getPath()),
CloudUtil.stripPath(OpenMode.GDRIVE, newFile.getPath()));
errorCallBack.done(newFile, true);
} catch (Exception e) {
e.printStackTrace();
errorCallBack.done(newFile, false);
}
} else if (oldFile.isOtgFile()) {
DocumentFile oldDocumentFile = OTGUtil.getDocumentFile(oldFile.getPath(), context, false);
DocumentFile newDocumentFile = OTGUtil.getDocumentFile(newFile.getPath(), context, false);
if (newDocumentFile != null) {
errorCallBack.exists(newFile);
return null;
}
errorCallBack.done(newFile, oldDocumentFile.renameTo(newFile.getName(context)));
return null;
} else {
File file = new File(oldFile.getPath());
File file1 = new File(newFile.getPath());
switch (oldFile.getMode()) {
case FILE:
int mode = checkFolder(file.getParentFile(), context);
if (mode == 2) {
errorCallBack.launchSAF(oldFile, newFile);
} else if (mode == 1 || mode == 0) {
try {
FileUtil.renameFolder(file, file1, context);
} catch (RootNotPermittedException e) {
e.printStackTrace();
}
boolean a = !file.exists() && file1.exists();
if (!a && rootMode) {
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
oldFile.setMode(OpenMode.ROOT);
newFile.setMode(OpenMode.ROOT);
a = !file.exists() && file1.exists();
}
errorCallBack.done(newFile, a);
return null;
}
break;
case ROOT:
try {
RootUtils.rename(file.getPath(), file1.getPath());
} catch (Exception e) {
Logger.log(e, oldFile.getPath() + "\n" + newFile.getPath(), context);
}
newFile.setMode(OpenMode.ROOT);
errorCallBack.done(newFile, true);
break;
}
}
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private static int checkFolder(final File folder, Context context) {
boolean lol = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;
if (lol) {
boolean ext = FileUtil.isOnExtSdCard(folder, context);
if (ext) {
if (!folder.exists() || !folder.isDirectory()) {
return 0;
}
// On Android 5, trigger storage access framework.
if (!FileUtil.isWritableNormalOrSaf(folder, context)) {
return 2;
}
return 1;
}
} else if (Build.VERSION.SDK_INT == 19) {
// Assume that Kitkat workaround works
if (FileUtil.isOnExtSdCard(folder, context)) return 1;
}
// file not on external sd card
if (FileUtil.isWritable(new File(folder, "DummyFile"))) {
return 1;
} else {
return 0;
}
}
/**
* Well, we wouldn't want to copy when the target is inside the source
* otherwise it'll end into a loop
*
* @param sourceFile
* @param targetFile
* @return true when copy loop is possible
*/
public static boolean isCopyLoopPossible(BaseFile sourceFile, HFile targetFile) {
return targetFile.getPath().contains(sourceFile.getPath());
}
/**
* Validates file name
* special reserved characters shall not be allowed in the file names on FAT filesystems
*
* @param fileName the filename, not the full path!
* @return boolean if the file name is valid or invalid
*/
public static boolean isFileNameValid(String fileName) {
//String fileName = builder.substring(builder.lastIndexOf("/")+1, builder.length());
// TODO: check file name validation only for FAT filesystems
return !(fileName.contains(ASTERISK) || fileName.contains(BACKWARD_SLASH) ||
fileName.contains(COLON) || fileName.contains(FOREWARD_SLASH) ||
fileName.contains(GREATER_THAN) || fileName.contains(LESS_THAN) ||
fileName.contains(QUESTION_MARK) || fileName.contains(QUOTE));
}
private static boolean isFileSystemFAT(String mountPoint) {
String[] args = new String[]{"/bin/bash", "-c", "df -DO_NOT_REPLACE | awk '{print $1,$2,$NF}' | grep \"^"
+ mountPoint + "\""};
try {
Process proc = new ProcessBuilder(args).start();
OutputStream outputStream = proc.getOutputStream();
String buffer = null;
outputStream.write(buffer.getBytes());
return buffer != null && buffer.contains(FAT);
} catch (IOException e) {
e.printStackTrace();
// process interrupted, returning true, as a word of cation
return true;
}
}
}
| gpl-3.0 |
jtux270/translate | ovirt/backend/manager/modules/bll/src/test/java/org/ovirt/engine/core/bll/scheduling/commands/ClusterPolicyCRUDCommandTest.java | 2187 | package org.ovirt.engine.core.bll.scheduling.commands;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.scheduling.ClusterPolicy;
import org.ovirt.engine.core.common.scheduling.parameters.ClusterPolicyCRUDParameters;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.utils.MockConfigRule;
public class ClusterPolicyCRUDCommandTest {
@Rule
public MockConfigRule mockConfigRule =
new MockConfigRule((MockConfigRule.mockConfig(ConfigValues.EnableVdsLoadBalancing, false)),
(MockConfigRule.mockConfig(ConfigValues.EnableVdsHaReservation, false)));
@Test
public void testCheckAddEditValidations() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertTrue(command.checkAddEditValidations());
}
@Test
public void testCheckAddEditValidationsFailOnParameters() {
Guid clusterPolicyId = new Guid("e754440b-76a6-4099-8235-4565ab4b5521");
ClusterPolicy clusterPolicy = new ClusterPolicy();
clusterPolicy.setId(clusterPolicyId);
HashMap<String, String> parameterMap = new HashMap<String, String>();
parameterMap.put("fail?", "sure, fail!");
clusterPolicy.setParameterMap(parameterMap);
ClusterPolicyCRUDCommand command =
new ClusterPolicyCRUDCommand(new ClusterPolicyCRUDParameters(clusterPolicyId,
clusterPolicy)) {
@Override
protected void executeCommand() {
}
};
Assert.assertFalse(command.checkAddEditValidations());
}
}
| gpl-3.0 |
xuxueli/xxl-job | xxl-job-admin/src/main/java/com/xxl/job/admin/core/route/strategy/ExecutorRouteLFU.java | 3053 | package com.xxl.job.admin.core.route.strategy;
import com.xxl.job.admin.core.route.ExecutorRouter;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* 单个JOB对应的每个执行器,使用频率最低的优先被选举
* a(*)、LFU(Least Frequently Used):最不经常使用,频率/次数
* b、LRU(Least Recently Used):最近最久未使用,时间
*
* Created by xuxueli on 17/3/10.
*/
public class ExecutorRouteLFU extends ExecutorRouter {
private static ConcurrentMap<Integer, HashMap<String, Integer>> jobLfuMap = new ConcurrentHashMap<Integer, HashMap<String, Integer>>();
private static long CACHE_VALID_TIME = 0;
public String route(int jobId, List<String> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000*60*60*24;
}
// lfu item init
HashMap<String, Integer> lfuItemMap = jobLfuMap.get(jobId); // Key排序可以用TreeMap+构造入参Compare;Value排序暂时只能通过ArrayList;
if (lfuItemMap == null) {
lfuItemMap = new HashMap<String, Integer>();
jobLfuMap.putIfAbsent(jobId, lfuItemMap); // 避免重复覆盖
}
// put new
for (String address: addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) >1000000 ) {
lfuItemMap.put(address, new Random().nextInt(addressList.size())); // 初始化时主动Random一次,缓解首次压力
}
}
// remove old
List<String> delKeys = new ArrayList<>();
for (String existKey: lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (String delKey: delKeys) {
lfuItemMap.remove(delKey);
}
}
// load least userd count address
List<Map.Entry<String, Integer>> lfuItemList = new ArrayList<Map.Entry<String, Integer>>(lfuItemMap.entrySet());
Collections.sort(lfuItemList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map.Entry<String, Integer> addressItem = lfuItemList.get(0);
String minAddress = addressItem.getKey();
addressItem.setValue(addressItem.getValue() + 1);
return addressItem.getKey();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = route(triggerParam.getJobId(), addressList);
return new ReturnT<String>(address);
}
}
| gpl-3.0 |
CHeuberger/TFC2 | src/Common/com/bioxx/tfc2/gui/GuiInventoryTFC.java | 7667 | package com.bioxx.tfc2.gui;
import java.awt.Rectangle;
import java.util.Collection;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainerCreative;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.client.renderer.InventoryEffectRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Slot;
import net.minecraft.stats.AchievementList;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import com.bioxx.tfc2.Core;
import com.bioxx.tfc2.Reference;
import com.bioxx.tfc2.core.PlayerInventory;
public class GuiInventoryTFC extends InventoryEffectRenderer
{
private float xSizeLow;
private float ySizeLow;
private boolean hasEffect;
protected static final ResourceLocation UPPER_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inventory.png");
protected static final ResourceLocation UPPER_TEXTURE_2X2 = new ResourceLocation(Reference.ModID+":textures/gui/gui_inventory2x2.png");
protected static final ResourceLocation EFFECTS_TEXTURE = new ResourceLocation(Reference.ModID+":textures/gui/inv_effects.png");
protected EntityPlayer player;
protected Slot activeSlot;
public GuiInventoryTFC(EntityPlayer player)
{
super(player.inventoryContainer);
this.allowUserInput = true;
player.addStat(AchievementList.OPEN_INVENTORY, 1);
xSize = 176;
ySize = 102 + PlayerInventory.invYSize;
this.player = player;
}
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
if(player.getEntityData().hasKey("craftingTable"))
Core.bindTexture(UPPER_TEXTURE);
else
Core.bindTexture(UPPER_TEXTURE_2X2);
int k = this.guiLeft;
int l = this.guiTop;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, 102);
//Draw the player avatar
GuiInventory.drawEntityOnScreen(k + 51, l + 75, 30, k + 51 - this.xSizeLow, l + 75 - 50 - this.ySizeLow, this.mc.player);
PlayerInventory.drawInventory(this, width, height, ySize - PlayerInventory.invYSize);
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
}
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2)
{
//this.fontRenderer.drawString(I18n.format("container.crafting", new Object[0]), 86, 7, 4210752);
}
@Override
/**
* Called from the main game loop to update the screen.
*/
public void updateScreen()
{
if (this.mc.playerController.isInCreativeMode())
this.mc.displayGuiScreen(new GuiContainerCreative(player));
}
@Override
public void initGui()
{
super.buttonList.clear();
if (this.mc.playerController.isInCreativeMode())
{
this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.player));
}
else
super.initGui();
if (!this.mc.player.getActivePotionEffects().isEmpty())
{
//this.guiLeft = 160 + (this.width - this.xSize - 200) / 2;
this.guiLeft = (this.width - this.xSize) / 2;
this.hasEffect = true;
}
buttonList.clear();
buttonList.add(new GuiInventoryButton(0, new Rectangle(guiLeft+176, guiTop + 3, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Inventory"), new Rectangle(1,223,32,32)));
buttonList.add(new GuiInventoryButton(1, new Rectangle(guiLeft+176, guiTop + 22, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Skills"), new Rectangle(100,223,32,32)));
buttonList.add(new GuiInventoryButton(2, new Rectangle(guiLeft+176, guiTop + 41, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Calendar.Calendar"), new Rectangle(34,223,32,32)));
buttonList.add(new GuiInventoryButton(3, new Rectangle(guiLeft+176, guiTop + 60, 25, 20),
new Rectangle(0, 103, 25, 20), Core.translate("gui.Inventory.Health"), new Rectangle(67,223,32,32)));
}
@Override
protected void actionPerformed(GuiButton guibutton)
{
//Removed during port
if (guibutton.id == 1)
Minecraft.getMinecraft().displayGuiScreen(new GuiSkills(player));
/*else if (guibutton.id == 2)
Minecraft.getMinecraft().displayGuiScreen(new GuiCalendar(player));*/
else if (guibutton.id == 3)
Minecraft.getMinecraft().displayGuiScreen(new GuiHealth(player));
}
@Override
public void drawScreen(int par1, int par2, float par3)
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
super.drawScreen(par1, par2, par3);
this.xSizeLow = par1;
this.ySizeLow = par2;
if(hasEffect)
displayDebuffEffects();
//removed during port
/*for (int j1 = 0; j1 < this.inventorySlots.inventorySlots.size(); ++j1)
{
Slot slot = (Slot)this.inventorySlots.inventorySlots.get(j1);
if (this.isMouseOverSlot(slot, par1, par2) && slot.func_111238_b())
this.activeSlot = slot;
}*/
}
protected boolean isMouseOverSlot(Slot par1Slot, int par2, int par3)
{
return this.isPointInRegion(par1Slot.xPos, par1Slot.yPos, 16, 16, par2, par3);
}
/**
* Displays debuff/potion effects that are currently being applied to the player
*/
private void displayDebuffEffects()
{
int var1 = this.guiLeft - 124;
int var2 = this.guiTop;
Collection var4 = this.mc.player.getActivePotionEffects();
//Remvoed during port
/*if (!var4.isEmpty())
{
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glDisable(GL11.GL_LIGHTING);
int var6 = 33;
if (var4.size() > 5)
var6 = 132 / (var4.size() - 1);
for (Iterator var7 = this.mc.player.getActivePotionEffects().iterator(); var7.hasNext(); var2 += var6)
{
PotionEffect var8 = (PotionEffect)var7.next();
Potion var9 = Potion.potionTypes[var8.getPotionID()] instanceof TFCPotion ?
((TFCPotion) Potion.potionTypes[var8.getPotionID()]) :
Potion.potionTypes[var8.getPotionID()];
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
TFC_Core.bindTexture(EFFECTS_TEXTURE);
this.drawTexturedModalRect(var1, var2, 0, 166, 140, 32);
if (var9.hasStatusIcon())
{
int var10 = var9.getStatusIconIndex();
this.drawTexturedModalRect(var1 + 6, var2 + 7, 0 + var10 % 8 * 18, 198 + var10 / 8 * 18, 18, 18);
}
String var12 = Core.translate(var9.getName());
if (var8.getAmplifier() == 1)
var12 = var12 + " II";
else if (var8.getAmplifier() == 2)
var12 = var12 + " III";
else if (var8.getAmplifier() == 3)
var12 = var12 + " IV";
this.fontRenderer.drawStringWithShadow(var12, var1 + 10 + 18, var2 + 6, 16777215);
String var11 = Potion.getDurationString(var8);
this.fontRenderer.drawStringWithShadow(var11, var1 + 10 + 18, var2 + 6 + 10, 8355711);
}
}*/
}
private long spamTimer;
@Override
protected boolean checkHotbarKeys(int keycode)
{
/*if(this.activeSlot != null && this.activeSlot.slotNumber == 0 && this.activeSlot.getHasStack() &&
this.activeSlot.getStack().getItem() instanceof IFood)
return false;*/
return super.checkHotbarKeys(keycode);
}
private int getEmptyCraftSlot()
{
if(this.inventorySlots.getSlot(4).getStack() == null)
return 4;
if(this.inventorySlots.getSlot(1).getStack() == null)
return 1;
if(this.inventorySlots.getSlot(2).getStack() == null)
return 2;
if(this.inventorySlots.getSlot(3).getStack() == null)
return 3;
if(player.getEntityData().hasKey("craftingTable"))
{
if(this.inventorySlots.getSlot(45).getStack() == null)
return 45;
if(this.inventorySlots.getSlot(46).getStack() == null)
return 46;
if(this.inventorySlots.getSlot(47).getStack() == null)
return 47;
if(this.inventorySlots.getSlot(48).getStack() == null)
return 48;
if(this.inventorySlots.getSlot(49).getStack() == null)
return 49;
}
return -1;
}
}
| gpl-3.0 |
RBerliner/freeboard-server | src/main/java/org/alternativevision/gpx/GPXParser.java | 30515 | /*
* GPXParser.java
*
* Copyright (c) 2012, AlternativeVision. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package org.alternativevision.gpx;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.alternativevision.gpx.beans.GPX;
import org.alternativevision.gpx.beans.Route;
import org.alternativevision.gpx.beans.Track;
import org.alternativevision.gpx.beans.Waypoint;
import org.alternativevision.gpx.extensions.IExtensionParser;
import org.alternativevision.gpx.types.FixType;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* <p>This class defines methods for parsing and writing gpx files.</p>
* <br>
* Usage for parsing a gpx file into a {@link GPX} object:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileInputStream in = new FileInputStream("inFile.gpx");<br>
* GPX gpx = p.parseGPX(in);<br>
* </code>
* <br>
* Usage for writing a {@link GPX} object to a file:<br>
* <code>
* GPXParser p = new GPXParser();<br>
* FileOutputStream out = new FileOutputStream("outFile.gpx");<br>
* p.writeGPX(gpx, out);<br>
* out.close();<br>
* </code>
*/
public class GPXParser {
private ArrayList<IExtensionParser> extensionParsers = new ArrayList<IExtensionParser>();
private Logger logger = Logger.getLogger(this.getClass().getName());
private DocumentBuilderFactory docFactory= DocumentBuilderFactory.newInstance();
private TransformerFactory tFactory = TransformerFactory.newInstance();
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss");
private SimpleDateFormat sdfZ = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'Z'");
/**
* Adds a new extension parser to be used when parsing a gpx steam
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void addExtensionParser(IExtensionParser parser) {
extensionParsers.add(parser);
}
/**
* Removes an extension parser previously added
*
* @param parser an instance of a {@link IExtensionParser} implementation
*/
public void removeExtensionParser(IExtensionParser parser) {
extensionParsers.remove(parser);
}
public GPX parseGPX(File gpxFile) throws IOException, ParserConfigurationException, SAXException, IOException {
InputStream in = FileUtils.openInputStream(gpxFile);
GPX gpx = parseGPX(in);
in.close();
return gpx;
}
/**
* Parses a stream containing GPX data
*
* @param in the input stream
* @return {@link GPX} object containing parsed data, or null if no gpx data was found in the seream
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public GPX parseGPX(InputStream in) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.parse(in);
Node firstChild = doc.getFirstChild();
if( firstChild != null && GPXConstants.GPX_NODE.equals(firstChild.getNodeName())) {
GPX gpx = new GPX();
NamedNodeMap attrs = firstChild.getAttributes();
for(int idx = 0; idx < attrs.getLength(); idx++) {
Node attr = attrs.item(idx);
if(GPXConstants.VERSION_ATTR.equals(attr.getNodeName())) {
gpx.setVersion(attr.getNodeValue());
} else if(GPXConstants.CREATOR_ATTR.equals(attr.getNodeName())) {
gpx.setCreator(attr.getNodeValue());
}
}
NodeList nodes = firstChild.getChildNodes();
if(logger.isDebugEnabled())logger.debug("Found " +nodes.getLength()+ " child nodes. Start parsing ...");
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.WPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found waypoint node. Start parsing...");
Waypoint w = parseWaypoint(currentNode);
if(w!= null) {
logger.info("Add waypoint to gpx data. [waypointName="+ w.getName() + "]");
gpx.addWaypoint(w);
}
} else if(GPXConstants.TRK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found track node. Start parsing...");
Track trk = parseTrack(currentNode);
if(trk!= null) {
logger.info("Add track to gpx data. [trackName="+ trk.getName() + "]");
gpx.addTrack(trk);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found extensions node. Start parsing...");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseGPXExtension(currentNode);
gpx.addExtensionData(parser.getId(), data);
}
} else if(GPXConstants.RTE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("Found route node. Start parsing...");
Route rte = parseRoute(currentNode);
if(rte!= null) {
logger.info("Add route to gpx data. [routeName="+ rte.getName() + "]");
gpx.addRoute(rte);
}
}
}
//TODO: parse route node
return gpx;
} else {
logger.error("FATAL!! - Root node is not gpx.");
}
return null;
}
/**
* Parses a wpt node into a Waypoint object
*
* @param node
* @return Waypoint object with info from the received node
*/
private Waypoint parseWaypoint(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Waypoint w = new Waypoint();
NamedNodeMap attrs = node.getAttributes();
//check for lat attribute
Node latNode = attrs.getNamedItem(GPXConstants.LAT_ATTR);
if(latNode != null) {
Double latVal = null;
try {
latVal = Double.parseDouble(latNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lat value in waypoint data: " + latNode.getNodeValue());
}
w.setLatitude(latVal);
} else {
logger.warn("no lat value in waypoint data.");
}
//check for lon attribute
Node lonNode = attrs.getNamedItem(GPXConstants.LON_ATTR);
if(lonNode != null) {
Double lonVal = null;
try {
lonVal = Double.parseDouble(lonNode.getNodeValue());
} catch(NumberFormatException ex) {
logger.error("bad lon value in waypoint data: " + lonNode.getNodeValue());
}
w.setLongitude(lonVal);
} else {
logger.warn("no lon value in waypoint data.");
}
NodeList childNodes = node.getChildNodes();
if(childNodes != null) {
for(int idx = 0; idx < childNodes.getLength(); idx++) {
Node currentNode = childNodes.item(idx);
if(GPXConstants.ELE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ele node in waypoint data");
w.setElevation(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.TIME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found time node in waypoint data");
w.setTime(getNodeValueAsDate(currentNode));
} else if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found name node in waypoint data");
w.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found cmt node in waypoint data");
w.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found desc node in waypoint data");
w.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found src node in waypoint data");
w.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.MAGVAR_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found magvar node in waypoint data");
w.setMagneticDeclination(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.GEOIDHEIGHT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found geoidheight node in waypoint data");
w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found link node in waypoint data");
//TODO: parse link
//w.setGeoidHeight(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.SYM_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sym node in waypoint data");
w.setSym(getNodeValueAsString(currentNode));
} else if(GPXConstants.FIX_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found fix node in waypoint data");
w.setFix(getNodeValueAsFixType(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found type node in waypoint data");
w.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.SAT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found sat node in waypoint data");
w.setSat(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.HDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found hdop node in waypoint data");
w.setHdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.VDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found vdop node in waypoint data");
w.setVdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.PDOP_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found pdop node in waypoint data");
w.setPdop(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.AGEOFGPSDATA_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found ageofgpsdata node in waypoint data");
w.setAgeOfGPSData(getNodeValueAsDouble(currentNode));
} else if(GPXConstants.DGPSID_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found dgpsid node in waypoint data");
w.setDgpsid(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("found extensions node in waypoint data");
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
w.addExtensionData(parser.getId(), data);
}
}
}
} else {
if(logger.isDebugEnabled())logger.debug("no child nodes found in waypoint");
}
return w;
}
private Track parseTrack(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Track trk = new Track();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
trk.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
trk.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
trk.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
trk.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//trk.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
trk.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
trk.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.TRKSEG_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node trkseg found");
trk.setTrackPoints(parseTrackSeg(currentNode));
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseTrackExtension(currentNode);
trk.addExtensionData(parser.getId(), data);
}
}
}
}
}
return trk;
}
private Route parseRoute(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
Route rte = new Route();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.NAME_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
rte.setName(getNodeValueAsString(currentNode));
} else if(GPXConstants.CMT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node cmt found");
rte.setComment(getNodeValueAsString(currentNode));
} else if(GPXConstants.DESC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node desc found");
rte.setDescription(getNodeValueAsString(currentNode));
} else if(GPXConstants.SRC_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node src found");
rte.setSrc(getNodeValueAsString(currentNode));
} else if(GPXConstants.LINK_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node link found");
//TODO: parse link
//rte.setLink(getNodeValueAsLink(currentNode));
} else if(GPXConstants.NUMBER_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node number found");
rte.setNumber(getNodeValueAsInteger(currentNode));
} else if(GPXConstants.TYPE_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node type found");
rte.setType(getNodeValueAsString(currentNode));
} else if(GPXConstants.RTEPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node rtept found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
rte.addRoutePoint(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseRouteExtension(currentNode);
rte.addExtensionData(parser.getId(), data);
}
}
}
}
}
return rte;
}
private ArrayList<Waypoint> parseTrackSeg(Node node) {
if(node == null) {
logger.error("null node received");
return null;
}
ArrayList<Waypoint> trkpts = new ArrayList<Waypoint>();
NodeList nodes = node.getChildNodes();
if(nodes != null) {
for(int idx = 0; idx < nodes.getLength(); idx++) {
Node currentNode = nodes.item(idx);
if(GPXConstants.TRKPT_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node name found");
Waypoint wp = parseWaypoint(currentNode);
if(wp!=null) {
trkpts.add(wp);
}
} else if(GPXConstants.EXTENSIONS_NODE.equals(currentNode.getNodeName())) {
if(logger.isDebugEnabled())logger.debug("node extensions found");
/*
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
IExtensionParser parser = it.next();
Object data = parser.parseWaypointExtension(currentNode);
//.addExtensionData(parser.getId(), data);
}
*/
}
}
}
return trkpts;
}
private Double getNodeValueAsDouble(Node node) {
Double val = null;
try {
val = Double.parseDouble(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Double value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
private Date getNodeValueAsDate(Node node) {
//2012-02-25T09:28:45Z
Date val = null;
try {
val = sdf.parse(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Date value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private String getNodeValueAsString(Node node) {
String val = null;
try {
val = node.getFirstChild().getNodeValue();
} catch (Exception ex) {
logger.error("error getting String value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private FixType getNodeValueAsFixType(Node node) {
FixType val = null;
try {
val = FixType.returnType(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error getting FixType value form node. val=" + node.getNodeName(), ex);
}
return val;
}
private Integer getNodeValueAsInteger(Node node) {
Integer val = null;
try {
val = Integer.parseInt(node.getFirstChild().getNodeValue());
} catch (Exception ex) {
logger.error("error parsing Integer value form node. val=" + node.getNodeValue(), ex);
}
return val;
}
public void writeGPX(GPX gpx, File gpxFile) throws IOException, ParserConfigurationException, TransformerException {
OutputStream out = FileUtils.openOutputStream(gpxFile);
writeGPX(gpx,out);
out.flush();
out.close();
}
public void writeGPX(GPX gpx, OutputStream out) throws ParserConfigurationException, TransformerException {
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document doc = builder.newDocument();
Node gpxNode = doc.createElement(GPXConstants.GPX_NODE);
addBasicGPXInfoToNode(gpx, gpxNode, doc);
if(gpx.getWaypoints() != null) {
Iterator<Waypoint> itW = gpx.getWaypoints().iterator();
while(itW.hasNext()) {
addWaypointToGPXNode(itW.next(), gpxNode, doc);
}
Iterator<Track> itT = gpx.getTracks().iterator();
while(itT.hasNext()) {
addTrackToGPXNode(itT.next(), gpxNode, doc);
}
Iterator<Route> itR = gpx.getRoutes().iterator();
while(itR.hasNext()) {
addRouteToGPXNode(itR.next(), gpxNode, doc);
}
}
doc.appendChild(gpxNode);
// Use a Transformer for output
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(out);
transformer.transform(source, result);
}
private void addWaypointToGPXNode(Waypoint wpt, Node gpxNode, Document doc) {
addGenericWaypointToGPXNode(GPXConstants.WPT_NODE, wpt, gpxNode, doc);
}
private void addGenericWaypointToGPXNode(String tagName,Waypoint wpt, Node gpxNode, Document doc) {
Node wptNode = doc.createElement(tagName);
NamedNodeMap attrs = wptNode.getAttributes();
if(wpt.getLatitude() != null) {
Node latNode = doc.createAttribute(GPXConstants.LAT_ATTR);
latNode.setNodeValue(wpt.getLatitude().toString());
attrs.setNamedItem(latNode);
}
if(wpt.getLongitude() != null) {
Node longNode = doc.createAttribute(GPXConstants.LON_ATTR);
longNode.setNodeValue(wpt.getLongitude().toString());
attrs.setNamedItem(longNode);
}
if(wpt.getElevation() != null) {
Node node = doc.createElement(GPXConstants.ELE_NODE);
node.appendChild(doc.createTextNode(wpt.getElevation().toString()));
wptNode.appendChild(node);
}
if(wpt.getTime() != null) {
Node node = doc.createElement(GPXConstants.TIME_NODE);
node.appendChild(doc.createTextNode(sdfZ.format(wpt.getTime())));
wptNode.appendChild(node);
}
if(wpt.getMagneticDeclination() != null) {
Node node = doc.createElement(GPXConstants.MAGVAR_NODE);
node.appendChild(doc.createTextNode(wpt.getMagneticDeclination().toString()));
wptNode.appendChild(node);
}
if(wpt.getGeoidHeight() != null) {
Node node = doc.createElement(GPXConstants.GEOIDHEIGHT_NODE);
node.appendChild(doc.createTextNode(wpt.getGeoidHeight().toString()));
wptNode.appendChild(node);
}
if(wpt.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(wpt.getName()));
wptNode.appendChild(node);
}
if(wpt.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(wpt.getComment()));
wptNode.appendChild(node);
}
if(wpt.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(wpt.getDescription()));
wptNode.appendChild(node);
}
if(wpt.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(wpt.getSrc()));
wptNode.appendChild(node);
}
//TODO: write link node
if(wpt.getSym() != null) {
Node node = doc.createElement(GPXConstants.SYM_NODE);
node.appendChild(doc.createTextNode(wpt.getSym()));
wptNode.appendChild(node);
}
if(wpt.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(wpt.getType()));
wptNode.appendChild(node);
}
if(wpt.getFix() != null) {
Node node = doc.createElement(GPXConstants.FIX_NODE);
node.appendChild(doc.createTextNode(wpt.getFix().toString()));
wptNode.appendChild(node);
}
if(wpt.getSat() != null) {
Node node = doc.createElement(GPXConstants.SAT_NODE);
node.appendChild(doc.createTextNode(wpt.getSat().toString()));
wptNode.appendChild(node);
}
if(wpt.getHdop() != null) {
Node node = doc.createElement(GPXConstants.HDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getHdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getVdop() != null) {
Node node = doc.createElement(GPXConstants.VDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getVdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getPdop() != null) {
Node node = doc.createElement(GPXConstants.PDOP_NODE);
node.appendChild(doc.createTextNode(wpt.getPdop().toString()));
wptNode.appendChild(node);
}
if(wpt.getAgeOfGPSData() != null) {
Node node = doc.createElement(GPXConstants.AGEOFGPSDATA_NODE);
node.appendChild(doc.createTextNode(wpt.getAgeOfGPSData().toString()));
wptNode.appendChild(node);
}
if(wpt.getDgpsid() != null) {
Node node = doc.createElement(GPXConstants.DGPSID_NODE);
node.appendChild(doc.createTextNode(wpt.getDgpsid().toString()));
wptNode.appendChild(node);
}
if(wpt.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeWaypointExtensionData(node, wpt, doc);
}
wptNode.appendChild(node);
}
gpxNode.appendChild(wptNode);
}
private void addTrackToGPXNode(Track trk, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(trk.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(trk.getName()));
trkNode.appendChild(node);
}
if(trk.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(trk.getComment()));
trkNode.appendChild(node);
}
if(trk.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(trk.getDescription()));
trkNode.appendChild(node);
}
if(trk.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(trk.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(trk.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(trk.getNumber().toString()));
trkNode.appendChild(node);
}
if(trk.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(trk.getType()));
trkNode.appendChild(node);
}
if(trk.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeTrackExtensionData(node, trk, doc);
}
trkNode.appendChild(node);
}
if(trk.getTrackPoints() != null) {
Node trksegNode = doc.createElement(GPXConstants.TRKSEG_NODE);
Iterator<Waypoint> it = trk.getTrackPoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.TRKPT_NODE, it.next(), trksegNode, doc);
}
trkNode.appendChild(trksegNode);
}
gpxNode.appendChild(trkNode);
}
private void addRouteToGPXNode(Route rte, Node gpxNode, Document doc) {
Node trkNode = doc.createElement(GPXConstants.TRK_NODE);
if(rte.getName() != null) {
Node node = doc.createElement(GPXConstants.NAME_NODE);
node.appendChild(doc.createTextNode(rte.getName()));
trkNode.appendChild(node);
}
if(rte.getComment() != null) {
Node node = doc.createElement(GPXConstants.CMT_NODE);
node.appendChild(doc.createTextNode(rte.getComment()));
trkNode.appendChild(node);
}
if(rte.getDescription() != null) {
Node node = doc.createElement(GPXConstants.DESC_NODE);
node.appendChild(doc.createTextNode(rte.getDescription()));
trkNode.appendChild(node);
}
if(rte.getSrc() != null) {
Node node = doc.createElement(GPXConstants.SRC_NODE);
node.appendChild(doc.createTextNode(rte.getSrc()));
trkNode.appendChild(node);
}
//TODO: write link
if(rte.getNumber() != null) {
Node node = doc.createElement(GPXConstants.NUMBER_NODE);
node.appendChild(doc.createTextNode(rte.getNumber().toString()));
trkNode.appendChild(node);
}
if(rte.getType() != null) {
Node node = doc.createElement(GPXConstants.TYPE_NODE);
node.appendChild(doc.createTextNode(rte.getType()));
trkNode.appendChild(node);
}
if(rte.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeRouteExtensionData(node, rte, doc);
}
trkNode.appendChild(node);
}
if(rte.getRoutePoints() != null) {
Iterator<Waypoint> it = rte.getRoutePoints().iterator();
while(it.hasNext()) {
addGenericWaypointToGPXNode(GPXConstants.RTEPT_NODE, it.next(), trkNode, doc);
}
}
gpxNode.appendChild(trkNode);
}
private void addBasicGPXInfoToNode(GPX gpx, Node gpxNode, Document doc) {
NamedNodeMap attrs = gpxNode.getAttributes();
if(gpx.getVersion() != null) {
Node verNode = doc.createAttribute(GPXConstants.VERSION_ATTR);
verNode.setNodeValue(gpx.getVersion());
attrs.setNamedItem(verNode);
}
if(gpx.getCreator() != null) {
Node creatorNode = doc.createAttribute(GPXConstants.CREATOR_ATTR);
creatorNode.setNodeValue(gpx.getCreator());
attrs.setNamedItem(creatorNode);
}
if(gpx.getExtensionsParsed() > 0) {
Node node = doc.createElement(GPXConstants.EXTENSIONS_NODE);
Iterator<IExtensionParser> it = extensionParsers.iterator();
while(it.hasNext()) {
it.next().writeGPXExtensionData(node, gpx, doc);
}
gpxNode.appendChild(node);
}
}
} | gpl-3.0 |
vincenzomazzeo/kodi-video-organizer | src/main/java/it/ninjatech/kvo/async/job/CacheRemoteImageAsyncJob.java | 1058 | package it.ninjatech.kvo.async.job;
import it.ninjatech.kvo.model.ImageProvider;
import it.ninjatech.kvo.util.Logger;
import java.awt.Dimension;
import java.awt.Image;
import java.util.EnumSet;
public class CacheRemoteImageAsyncJob extends AbstractImageLoaderAsyncJob {
private static final long serialVersionUID = -8459315395025635686L;
private final String path;
private final String type;
private final Dimension size;
private Image image;
public CacheRemoteImageAsyncJob(String id, ImageProvider provider, String path, Dimension size, String type) {
super(id, EnumSet.of(LoadType.Cache, LoadType.Remote), provider);
this.path = path;
this.size = size;
this.type = type;
}
@Override
protected void execute() {
try {
Logger.log("-> executing cache-remote image %s\n", this.id);
this.image = getImage(null, null, this.id, this.path, this.size, this.type);
}
catch (Exception e) {
this.exception = e;
}
}
public Image getImage() {
return this.image;
}
}
| gpl-3.0 |