repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
mandeepdhami/controller | opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java | 3280 | package org.opendaylight.controller.sal.connect.netconf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.google.common.collect.Iterables;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
import org.opendaylight.controller.netconf.api.NetconfMessage;
import org.opendaylight.controller.netconf.notifications.NetconfNotification;
import org.opendaylight.controller.netconf.util.xml.XmlUtil;
import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
import org.w3c.dom.Document;
/**
* @author Lukas Sedlak <lsedlak@cisco.com>
*/
public class NetconfToNotificationTest {
NetconfMessageTransformer messageTransformer;
NetconfMessage userNotification;
@SuppressWarnings("deprecation")
@Before
public void setup() throws Exception {
final SchemaContext schemaContext = getNotificationSchemaContext(getClass());
messageTransformer = new NetconfMessageTransformer(schemaContext, true);
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
InputStream notifyPayloadStream = getClass().getResourceAsStream("/notification-payload.xml");
assertNotNull(notifyPayloadStream);
final Document doc = XmlUtil.readXmlToDocument(notifyPayloadStream);
assertNotNull(doc);
userNotification = new NetconfMessage(doc);
}
static SchemaContext getNotificationSchemaContext(Class<?> loadClass) {
final List<InputStream> modelsToParse = Collections.singletonList(loadClass.getResourceAsStream("/schemas/user-notification.yang"));
final YangContextParser parser = new YangParserImpl();
final Set<Module> modules = parser.parseYangModelsFromStreams(modelsToParse);
assertTrue(!modules.isEmpty());
final SchemaContext schemaContext = parser.resolveSchemaContext(modules);
assertNotNull(schemaContext);
return schemaContext;
}
@Test
public void test() throws Exception {
final DOMNotification domNotification = messageTransformer.toNotification(userNotification);
final ContainerNode root = domNotification.getBody();
assertNotNull(root);
assertEquals(6, Iterables.size(root.getValue()));
assertEquals("user-visited-page", root.getNodeType().getLocalName());
assertEquals(new SimpleDateFormat(NetconfNotification.RFC3339_DATE_FORMAT_BLUEPRINT).parse("2007-07-08T00:01:00Z"),
((DOMEvent) domNotification).getEventTime());
}
}
| epl-1.0 |
zsmartsystems/com.zsmartsystems.zigbee | com.zsmartsystems.zigbee.dongle.xbee.autocode/src/main/java/com/zsmartsystems/zigbee/dongle/xbee/autocode/xml/ParameterGroup.java | 623 | /**
* Copyright (c) 2016-2022 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 com.zsmartsystems.zigbee.dongle.xbee.autocode.xml;
import java.util.List;
/**
*
* @author Chris Jackson
*
*/
public class ParameterGroup {
public Boolean multiple;
public List<Parameter> parameters;
public String name;
public Boolean required;
public Boolean complete;
}
| epl-1.0 |
stefanreichert/wickedshell | net.sf.wickedshell/src/net/sf/wickedshell/facade/descriptor/command/CmdCommandProvider.java | 1161 | /*
* CmdCommandProvider.java
*
* Copyright 2005-2007 Stefan Reichert.
* All Rights Reserved.
*
* This software is the proprietary information of Stefan Reichert.
* Use is subject to license terms.
*
*/
package net.sf.wickedshell.facade.descriptor.command;
import java.io.File;
import net.sf.wickedshell.facade.descriptor.IShellDescriptor;
/**
* @author Stefan Reichert
*/
public class CmdCommandProvider implements ICommandProvider {
/**
* @see net.sf.wickedshell.facade.descriptor.command.ICommandProvider#getChangeDirectoryCommand(net.sf.wickedshell.facade.descriptor.IShellDescriptor,
* java.io.File)
*/
public String getChangeDirectoryCommand(IShellDescriptor shellDescriptor,
File targetDirectory) {
String absolutePathString = targetDirectory.getAbsolutePath();
StringBuffer commandBuffer = new StringBuffer();
// Change to the correct directory
commandBuffer.append(absolutePathString.substring(0, 2));
commandBuffer.append(" ");
commandBuffer.append(shellDescriptor.getCommandDelimiter());
commandBuffer.append(" cd ");
commandBuffer.append(absolutePathString);
return commandBuffer.toString();
}
}
| epl-1.0 |
Nasdanika/amur-lang | org.nasdanika.amur.lang.causality/src/org/nasdanika/amur/lang/causality/render/js/FromSynchronousRenderer.java | 1206 | package org.nasdanika.amur.lang.causality.render.js;
import org.nasdanika.amur.lang.causality.*;
public class FromSynchronousRenderer {
protected static String nl;
public static synchronized FromSynchronousRenderer create(String lineSeparator)
{
nl = lineSeparator;
FromSynchronousRenderer result = new FromSynchronousRenderer();
nl = null;
return result;
}
public final String NL = nl == null ? (System.getProperties().getProperty("line.separator")) : nl;
protected final String TEXT_1 = "\t" + NL + "\t";
protected final String TEXT_2 = ";";
protected final String TEXT_3 = NL + "\t$promiseProvider.when($out).then(";
protected final String TEXT_4 = ").then(function($newOut) { $out = $newOut }).done();";
public String render(org.nasdanika.amur.lang.causality.Mode mode, String template)
{
final StringBuffer stringBuffer = new StringBuffer();
if (Mode.SYNCHRONOUS.equals(mode)) {
stringBuffer.append(TEXT_1);
stringBuffer.append( template );
stringBuffer.append(TEXT_2);
} else {
stringBuffer.append(TEXT_3);
stringBuffer.append( template );
stringBuffer.append(TEXT_4);
}
return stringBuffer.toString();
}
} | epl-1.0 |
forge/javaee-descriptors | api/src/main/java/org/jboss/shrinkwrap/descriptor/api/orm10/DiscriminatorType.java | 767 | package org.jboss.shrinkwrap.descriptor.api.orm10;
/**
* This class implements the <code> discriminator-type </code> xsd type
* @author <a href="mailto:ralf.battenfeld@bluewin.ch">Ralf Battenfeld</a>
* @author <a href="mailto:alr@jboss.org">Andrew Lee Rubinger</a>
*/
public enum DiscriminatorType
{
_STRING("STRING"),
_CHAR("CHAR"),
_INTEGER("INTEGER");
private String value;
DiscriminatorType (String value) { this.value = value; }
public String toString() {return value;}
public static DiscriminatorType getFromStringValue(String value)
{
for(DiscriminatorType type: DiscriminatorType.values())
{
if(value != null && type.toString().equals(value))
{ return type;}
}
return null;
}
}
| epl-1.0 |
kamilfb/msg-spy | msg-spy-daemon/src/main/java/pl/baczkowicz/msgspy/daemon/generated/configuration/RemoteControl.java | 5131 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// 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: 2016.05.09 at 09:24:37 AM BST
//
package pl.baczkowicz.msgspy.daemon.generated.configuration;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
/**
* <p>Java class for RemoteControl complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RemoteControl">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="HttpListener" type="{http://baczkowicz.pl/msg-spy/daemon/configuration}HttpListener" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RemoteControl", propOrder = {
"httpListener"
})
public class RemoteControl
implements Equals, HashCode, ToString
{
@XmlElement(name = "HttpListener")
protected HttpListener httpListener;
/**
* Gets the value of the httpListener property.
*
* @return
* possible object is
* {@link HttpListener }
*
*/
public HttpListener getHttpListener() {
return httpListener;
}
/**
* Sets the value of the httpListener property.
*
* @param value
* allowed object is
* {@link HttpListener }
*
*/
public void setHttpListener(HttpListener value) {
this.httpListener = value;
}
public String toString() {
final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
final StringBuilder buffer = new StringBuilder();
append(null, buffer, strategy);
return buffer.toString();
}
public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
strategy.appendStart(locator, this, buffer);
appendFields(locator, buffer, strategy);
strategy.appendEnd(locator, this, buffer);
return buffer;
}
public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
{
HttpListener theHttpListener;
theHttpListener = this.getHttpListener();
strategy.appendField(locator, this, "httpListener", buffer, theHttpListener);
}
return buffer;
}
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
if (!(object instanceof RemoteControl)) {
return false;
}
if (this == object) {
return true;
}
final RemoteControl that = ((RemoteControl) object);
{
HttpListener lhsHttpListener;
lhsHttpListener = this.getHttpListener();
HttpListener rhsHttpListener;
rhsHttpListener = that.getHttpListener();
if (!strategy.equals(LocatorUtils.property(thisLocator, "httpListener", lhsHttpListener), LocatorUtils.property(thatLocator, "httpListener", rhsHttpListener), lhsHttpListener, rhsHttpListener)) {
return false;
}
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
int currentHashCode = 1;
{
HttpListener theHttpListener;
theHttpListener = this.getHttpListener();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "httpListener", theHttpListener), currentHashCode, theHttpListener);
}
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
}
| epl-1.0 |
iotk/iochibity-java | jni-c/src/main/java/org/iochibity/CoServiceProvider.java | 8165 | package org.iochibity;
import java.util.List;
import java.util.LinkedList;
/**
* brief desc of this file
*
* It wraps the OCDoResource parameters, plus ...
*/
/* notes
this class encapsulates both the CoSP (i.e. client request) and the SP (i.e. server response).
for example, the networking properties are one thing on the way
out, but could be sth else in the response. e.g. the response to a
multicast will be a unicast.
legacy stuff: OCClientResponse contains redundant networking info,
in that OCDevAddr contains the same info as connType
(OCConnectivityType). The source is commented: connType is for
backward compatibility.
but note that OCDevAddr is misnamed; it contains not just address info, but also info about networking params, which is not really address info.
*/
public abstract class CoServiceProvider
implements ICoServiceProvider
{
// ctor, initializes TLS vars
native private void ctorCoSP();
public CoServiceProvider() {
ctorCoSP();
}
// a CoSP object may be associated with multiple transactions, so
// keeping a handle member will not work...
// private long _handle; // OCDoHandle from OCDoResource
// THe heart of the matter: (co-)actions and (co-)reactions.
@Override
abstract public void coReact(); // must be implemented by user; called by stack
// the remaining methods implement (natively) the ICoServiceProvider interface
native public void coExhibit(); // called by user
native public int method();
native public CoServiceProvider method(int method);
// descriptor, for matching against SPs (and setting OCDoResource params)
native public String uriPath();
native public CoServiceProvider uriPath(String uriPath);
// // FIXME: do we needd types, interfaces, and props in a CoSP?
// // private List<String> _types = new LinkedList<String>();
// // public List<String> getTypes() { return _types; }
// native public List<String> types();
// native public CoServiceProvider addType(String theTypes); // { return _types.add(theTypes); }
// // private List<String> _interfaces = new LinkedList<String>();
// native public List<String> getInterfaces(); // { return _interfaces; }
// native public CoServiceProvider addInterface(String iface); // { return _interfaces.add(iface); }
// private PropertyMap _properties;
// public PropertyMap getProperties() { return _properties; }
// public Object putProperty(String key, Object val) { return _properties.put(key, val); }
// end descriptor
//////////////// NETWORKING params ////////////////
// Raw
native public int networkAdapter(); // OCTransportAdapter
native public int networkFlags(); // OCTransportFlags bitmap "flags"
// networkFlags, broken out
native public boolean transportIsSecure(); // flags & 0x0008
native public CoServiceProvider transportIsSecure(boolean torf);
// Transport Protocol flags: mutually exclusive, setting one resets all the others.
// (comments: xx_ is for CT_ or OC_)
native public boolean transportIsUDP(); // xx_ADAPTER_IP (misnamed)
native public CoServiceProvider transportIsUDP(boolean torf);
native public boolean transportIsTCP(); // xx_ADAPTER_TCP
native public CoServiceProvider transportIsTCP(boolean torf);
native public boolean transportIsGATT(); // xx_ADAPTER_GATT_BTLE
native public CoServiceProvider transportIsGATT(boolean torf);
native public boolean transportIsRFCOMM(); // xx_ADAPTER_RFCOMM_BTEDR
native public CoServiceProvider transportIsRFCOMM(boolean torf);
native public boolean transportIsNFC(); // xx_ADAPTER_NFC
native public CoServiceProvider transportIsNFC(boolean torf);
// IP flags: only needed to select version of IP protocol
native public boolean networkIsIP(); // == transportIsUDP
native public ICoServiceProvider networkIsIP(boolean torf);
native public boolean networkIsIPv4(); // xx_IP_USE_V4 (flags & 0x0010)
native public CoServiceProvider networkIsIPv4(boolean torf);
native public boolean networkIsIPv6(); // xx_IP_USE_V6 (flags & 0x0010)
native public CoServiceProvider networkIsIPv6(boolean torf);
// IPv6 only:
native public boolean scopeIsInterface(); // flags & 0x000F
native public CoServiceProvider scopeIsInterface(boolean torf); // flags & 0x000F
native public boolean scopeIsLink(); // flags & 0x000F
native public CoServiceProvider scopeIsLink(boolean torf); // flags & 0x000F
native public boolean scopeIsRealm(); // flags & 0x000F
native public CoServiceProvider scopeIsRealm(boolean torf); // flags & 0x000F
native public boolean scopeIsAdmin();
native public CoServiceProvider scopeIsAdmin(boolean torf);
native public boolean scopeIsSite();
native public CoServiceProvider scopeIsSite(boolean torf);
native public boolean scopeIsOrg();
native public CoServiceProvider scopeIsOrg(boolean torf);
native public boolean scopeIsGlobal();
native public CoServiceProvider scopeIsGlobal(boolean torf);
// Routing
native public boolean routingIsMulticast();
native public CoServiceProvider routingIsMulticast(boolean torf);
// Addressing
native public int port(); // uint16_t
native public String ipAddress(); // char addr[MAX_ADDR_STR_SIZE];
native public int qualityOfService();
native public CoServiceProvider qualityOfService(int qos);
////////////////////////////////////////////////////////////////
// OCClientResponse data:
// these data describe the corresponding SP:
// FIXME: resolve clash between CoSP's descr of SP (which are
// match patterns) and the SP description received in the
// response. The former is not really a description, or rather it
// is an open description; the latter is a closed description.
// for example, the CoSP might have type="foo.bar", and the
// response might include that plus several other types. We do
// not want to confuse the two "descriptions".
// one possible solution: leave the open ("query") description
// (associated with the CoSP) at the top, and keep the closed
// descriptions (associated with the SP) with the
// ObservationRecords. This will work for some payloads, which
// contains uri, types[], and interfaces[] (e.g. OCRepPayload,
// OCResourcePayload, etc.) but not others
// (e.g. OCSecurityPayload). Note that OCResource also contains
// uri, types, and interfaces.
native public DeviceAddress coAddress();
native public int getCoResult();
native public byte[] getCoSecurityId();
// for observables, https://tools.ietf.org/html/rfc7641
native public int getNotificationSerial();
////////////////////////////////////////////////////////////////
// OCPayload wrapper
// NB: ObservationRecords must be read-only!
// native List<ObservationRecord> observations();
// private ObservationRecord _observationRecord;
// public ObservationRecord getObservationRecord() { return _observationRecord; }
// public void setObservationRecord(ObservationRecord o) { _observationRecord = o; }
// // OCResource.rsrcChildResourcesHead (for collections)
private List<IServiceProvider> _children;
public List<IServiceProvider> getChildren() { return _children; }
// // SPs only?
// private List<ActionSet> _actionSet;
// public List<ActionSet> getActionSet() { return _actionSet; }
// for discovery and presence requests:
native public void deactivate();
}
| epl-1.0 |
sleshchenko/che | core/che-core-api-core/src/main/java/org/eclipse/che/api/core/websocket/impl/WebSocketSessionRegistry.java | 2305 | /*
* Copyright (c) 2012-2018 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.api.core.websocket.impl;
import static java.util.stream.Collectors.toSet;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Singleton;
import javax.websocket.Session;
import org.slf4j.Logger;
/**
* Binds WEB SOCKET session to a specific endpoint form which it was opened.
*
* @author Dmitry Kuleshov
*/
@Singleton
public class WebSocketSessionRegistry {
private static final Logger LOG = getLogger(WebSocketSessionRegistry.class);
private final Map<String, Session> sessionsMap = new ConcurrentHashMap<>();
public void add(String endpointId, Session session) {
LOG.debug("Registering session with endpoint {}", session.getId(), endpointId);
sessionsMap.put(endpointId, session);
}
public Optional<Session> remove(String endpointId) {
LOG.debug("Cancelling registration for session with endpoint {}", endpointId);
return Optional.ofNullable(sessionsMap.remove(endpointId));
}
public Optional<Session> remove(Session session) {
return get(session).flatMap(id -> Optional.ofNullable(sessionsMap.remove(id)));
}
public Optional<Session> get(String endpointId) {
return Optional.ofNullable(sessionsMap.get(endpointId));
}
public Set<Session> getByPartialMatch(String partialEndpointId) {
return sessionsMap
.entrySet()
.stream()
.filter(it -> it.getKey().contains(partialEndpointId))
.map(Map.Entry::getValue)
.collect(toSet());
}
public Optional<String> get(Session session) {
return sessionsMap
.entrySet()
.stream()
.filter(entry -> entry.getValue().equals(session))
.map(Map.Entry::getKey)
.findAny();
}
public Set<Session> getSessions() {
return new HashSet<>(sessionsMap.values());
}
}
| epl-1.0 |
smadelenat/CapellaModeAutomata | Semantic/Scenario/org.gemoc.scenario.xdsml/src-gen/org/gemoc/scenario/xdsml/functionscenario/adapters/functionscenariomt/fa/AbstractFunctionalStructureAdapter.java | 31904 | package org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.fa;
import fr.inria.diverse.melange.adapters.EObjectAdapter;
import java.util.Collection;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory;
import org.polarsys.capella.core.data.fa.AbstractFunctionalStructure;
@SuppressWarnings("all")
public class AbstractFunctionalStructureAdapter extends EObjectAdapter<AbstractFunctionalStructure> implements org.gemoc.scenario.xdsml.functionscenariomt.fa.AbstractFunctionalStructure {
private FunctionScenarioMTAdaptersFactory adaptersFactory;
public AbstractFunctionalStructureAdapter() {
super(org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory.getInstance());
adaptersFactory = org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory.getInstance();
}
@Override
public String getId() {
return adaptee.getId();
}
@Override
public void setId(final String o) {
adaptee.setId(o);
}
@Override
public String getSid() {
return adaptee.getSid();
}
@Override
public void setSid(final String o) {
adaptee.setSid(o);
}
@Override
public String getName() {
return adaptee.getName();
}
@Override
public void setName(final String o) {
adaptee.setName(o);
}
@Override
public boolean isVisibleInDoc() {
return adaptee.isVisibleInDoc();
}
@Override
public void setVisibleInDoc(final boolean o) {
adaptee.setVisibleInDoc(o);
}
@Override
public boolean isVisibleInLM() {
return adaptee.isVisibleInLM();
}
@Override
public void setVisibleInLM(final boolean o) {
adaptee.setVisibleInLM(o);
}
@Override
public String getSummary() {
return adaptee.getSummary();
}
@Override
public void setSummary(final String o) {
adaptee.setSummary(o);
}
@Override
public String getDescription() {
return adaptee.getDescription();
}
@Override
public void setDescription(final String o) {
adaptee.setDescription(o);
}
@Override
public String getReview() {
return adaptee.getReview();
}
@Override
public void setReview(final String o) {
adaptee.setReview(o);
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.emde.ElementExtension> */Object ownedExtensions_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.emde.ElementExtension> */Object getOwnedExtensions() {
if (ownedExtensions_ == null)
ownedExtensions_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedExtensions(), adaptersFactory, eResource);
return ownedExtensions_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object constraints_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object getConstraints() {
if (constraints_ == null)
constraints_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getConstraints(), adaptersFactory, eResource);
return constraints_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object ownedConstraints_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object getOwnedConstraints() {
if (ownedConstraints_ == null)
ownedConstraints_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedConstraints(), adaptersFactory, eResource);
return ownedConstraints_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object incomingTraces_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object getIncomingTraces() {
if (incomingTraces_ == null)
incomingTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getIncomingTraces(), adaptersFactory, eResource);
return incomingTraces_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object outgoingTraces_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object getOutgoingTraces() {
if (outgoingTraces_ == null)
outgoingTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOutgoingTraces(), adaptersFactory, eResource);
return outgoingTraces_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object ownedPropertyValues_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object getOwnedPropertyValues() {
if (ownedPropertyValues_ == null)
ownedPropertyValues_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValues(), adaptersFactory, eResource);
return ownedPropertyValues_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyType> */Object ownedEnumerationPropertyTypes_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyType> */Object getOwnedEnumerationPropertyTypes() {
if (ownedEnumerationPropertyTypes_ == null)
ownedEnumerationPropertyTypes_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedEnumerationPropertyTypes(), adaptersFactory, eResource);
return ownedEnumerationPropertyTypes_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object appliedPropertyValues_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object getAppliedPropertyValues() {
if (appliedPropertyValues_ == null)
appliedPropertyValues_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedPropertyValues(), adaptersFactory, eResource);
return appliedPropertyValues_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object ownedPropertyValueGroups_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object getOwnedPropertyValueGroups() {
if (ownedPropertyValueGroups_ == null)
ownedPropertyValueGroups_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValueGroups(), adaptersFactory, eResource);
return ownedPropertyValueGroups_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object appliedPropertyValueGroups_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object getAppliedPropertyValueGroups() {
if (appliedPropertyValueGroups_ == null)
appliedPropertyValueGroups_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedPropertyValueGroups(), adaptersFactory, eResource);
return appliedPropertyValueGroups_;
}
@Override
public org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral getStatus() {
return () adaptersFactory.createAdapter(adaptee.getStatus(), eResource);
}
@Override
public void setStatus(final org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral o) {
if (o != null)
adaptee.setStatus(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.capellacore.EnumerationPropertyLiteralAdapter) o).getAdaptee());
else adaptee.setStatus(null);
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral> */Object features_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral> */Object getFeatures() {
if (features_ == null)
features_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getFeatures(), adaptersFactory, eResource);
return features_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.Requirement> */Object appliedRequirements_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.Requirement> */Object getAppliedRequirements() {
if (appliedRequirements_ == null)
appliedRequirements_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedRequirements(), adaptersFactory, eResource);
return appliedRequirements_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Trace> */Object ownedTraces_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.Trace> */Object getOwnedTraces() {
if (ownedTraces_ == null)
ownedTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedTraces(), adaptersFactory, eResource);
return ownedTraces_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.GenericTrace> */Object containedGenericTraces_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.GenericTrace> */Object getContainedGenericTraces() {
if (containedGenericTraces_ == null)
containedGenericTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedGenericTraces(), adaptersFactory, eResource);
return containedGenericTraces_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.RequirementsTrace> */Object containedRequirementsTraces_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.RequirementsTrace> */Object getContainedRequirementsTraces() {
if (containedRequirementsTraces_ == null)
containedRequirementsTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getContainedRequirementsTraces(), adaptersFactory, eResource);
return containedRequirementsTraces_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.NamingRule> */Object namingRules_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.NamingRule> */Object getNamingRules() {
if (namingRules_ == null)
namingRules_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getNamingRules(), adaptersFactory, eResource);
return namingRules_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValuePkg> */Object ownedPropertyValuePkgs_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValuePkg> */Object getOwnedPropertyValuePkgs() {
if (ownedPropertyValuePkgs_ == null)
ownedPropertyValuePkgs_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValuePkgs(), adaptersFactory, eResource);
return ownedPropertyValuePkgs_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchange> */Object ownedComponentExchanges_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchange> */Object getOwnedComponentExchanges() {
if (ownedComponentExchanges_ == null)
ownedComponentExchanges_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedComponentExchanges(), adaptersFactory, eResource);
return ownedComponentExchanges_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchangeCategory> */Object ownedComponentExchangeCategories_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchangeCategory> */Object getOwnedComponentExchangeCategories() {
if (ownedComponentExchangeCategories_ == null)
ownedComponentExchangeCategories_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedComponentExchangeCategories(), adaptersFactory, eResource);
return ownedComponentExchangeCategories_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ExchangeLink> */Object ownedFunctionalLinks_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ExchangeLink> */Object getOwnedFunctionalLinks() {
if (ownedFunctionalLinks_ == null)
ownedFunctionalLinks_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedFunctionalLinks(), adaptersFactory, eResource);
return ownedFunctionalLinks_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentFunctionalAllocation> */Object ownedFunctionalAllocations_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentFunctionalAllocation> */Object getOwnedFunctionalAllocations() {
if (ownedFunctionalAllocations_ == null)
ownedFunctionalAllocations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedFunctionalAllocations(), adaptersFactory, eResource);
return ownedFunctionalAllocations_;
}
private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchangeRealization> */Object ownedComponentExchangeRealizations_;
@Override
public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.fa.ComponentExchangeRealization> */Object getOwnedComponentExchangeRealizations() {
if (ownedComponentExchangeRealizations_ == null)
ownedComponentExchangeRealizations_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedComponentExchangeRealizations(), adaptersFactory, eResource);
return ownedComponentExchangeRealizations_;
}
@Override
public void destroy() {
adaptee.destroy();
}
@Override
public String getFullLabel() {
return adaptee.getFullLabel();
}
@Override
public String getLabel() {
return adaptee.getLabel();
}
@Override
public boolean hasUnnamedLabel() {
return adaptee.hasUnnamedLabel();
}
protected final static String ID_EDEFAULT = null;
protected final static String SID_EDEFAULT = null;
protected final static String NAME_EDEFAULT = null;
protected final static boolean VISIBLE_IN_DOC_EDEFAULT = true;
protected final static boolean VISIBLE_IN_LM_EDEFAULT = true;
protected final static String SUMMARY_EDEFAULT = null;
protected final static String DESCRIPTION_EDEFAULT = null;
protected final static String REVIEW_EDEFAULT = null;
@Override
public EClass eClass() {
return org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.eINSTANCE.getAbstractFunctionalStructure();
}
@Override
public Object eGet(final int featureID, final boolean resolve, final boolean coreType) {
switch (featureID) {
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_EXTENSIONS:
return getOwnedExtensions();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__ID:
return getId();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__SID:
return getSid();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__CONSTRAINTS:
return getConstraints();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_CONSTRAINTS:
return getOwnedConstraints();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__NAME:
return getName();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__INCOMING_TRACES:
return getIncomingTraces();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OUTGOING_TRACES:
return getOutgoingTraces();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__VISIBLE_IN_DOC:
return isVisibleInDoc() ? Boolean.TRUE : Boolean.FALSE;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__VISIBLE_IN_LM:
return isVisibleInLM() ? Boolean.TRUE : Boolean.FALSE;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__SUMMARY:
return getSummary();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__DESCRIPTION:
return getDescription();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__REVIEW:
return getReview();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUES:
return getOwnedPropertyValues();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_ENUMERATION_PROPERTY_TYPES:
return getOwnedEnumerationPropertyTypes();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_PROPERTY_VALUES:
return getAppliedPropertyValues();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUE_GROUPS:
return getOwnedPropertyValueGroups();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_PROPERTY_VALUE_GROUPS:
return getAppliedPropertyValueGroups();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__STATUS:
return getStatus();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__FEATURES:
return getFeatures();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_REQUIREMENTS:
return getAppliedRequirements();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_TRACES:
return getOwnedTraces();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__CONTAINED_GENERIC_TRACES:
return getContainedGenericTraces();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__CONTAINED_REQUIREMENTS_TRACES:
return getContainedRequirementsTraces();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__NAMING_RULES:
return getNamingRules();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUE_PKGS:
return getOwnedPropertyValuePkgs();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGES:
return getOwnedComponentExchanges();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGE_CATEGORIES:
return getOwnedComponentExchangeCategories();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_FUNCTIONAL_LINKS:
return getOwnedFunctionalLinks();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_FUNCTIONAL_ALLOCATIONS:
return getOwnedFunctionalAllocations();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGE_REALIZATIONS:
return getOwnedComponentExchangeRealizations();
}
return super.eGet(featureID, resolve, coreType);
}
@Override
public boolean eIsSet(final int featureID) {
switch (featureID) {
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_EXTENSIONS:
return getOwnedExtensions() != null && !getOwnedExtensions().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__ID:
return getId() != ID_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__SID:
return getSid() != SID_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__CONSTRAINTS:
return getConstraints() != null && !getConstraints().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_CONSTRAINTS:
return getOwnedConstraints() != null && !getOwnedConstraints().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__NAME:
return getName() != NAME_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__INCOMING_TRACES:
return getIncomingTraces() != null && !getIncomingTraces().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OUTGOING_TRACES:
return getOutgoingTraces() != null && !getOutgoingTraces().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__VISIBLE_IN_DOC:
return isVisibleInDoc() != VISIBLE_IN_DOC_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__VISIBLE_IN_LM:
return isVisibleInLM() != VISIBLE_IN_LM_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__SUMMARY:
return getSummary() != SUMMARY_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__DESCRIPTION:
return getDescription() != DESCRIPTION_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__REVIEW:
return getReview() != REVIEW_EDEFAULT;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUES:
return getOwnedPropertyValues() != null && !getOwnedPropertyValues().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_ENUMERATION_PROPERTY_TYPES:
return getOwnedEnumerationPropertyTypes() != null && !getOwnedEnumerationPropertyTypes().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_PROPERTY_VALUES:
return getAppliedPropertyValues() != null && !getAppliedPropertyValues().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUE_GROUPS:
return getOwnedPropertyValueGroups() != null && !getOwnedPropertyValueGroups().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_PROPERTY_VALUE_GROUPS:
return getAppliedPropertyValueGroups() != null && !getAppliedPropertyValueGroups().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__STATUS:
return getStatus() != null;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__FEATURES:
return getFeatures() != null && !getFeatures().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_REQUIREMENTS:
return getAppliedRequirements() != null && !getAppliedRequirements().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_TRACES:
return getOwnedTraces() != null && !getOwnedTraces().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__CONTAINED_GENERIC_TRACES:
return getContainedGenericTraces() != null && !getContainedGenericTraces().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__CONTAINED_REQUIREMENTS_TRACES:
return getContainedRequirementsTraces() != null && !getContainedRequirementsTraces().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__NAMING_RULES:
return getNamingRules() != null && !getNamingRules().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUE_PKGS:
return getOwnedPropertyValuePkgs() != null && !getOwnedPropertyValuePkgs().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGES:
return getOwnedComponentExchanges() != null && !getOwnedComponentExchanges().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGE_CATEGORIES:
return getOwnedComponentExchangeCategories() != null && !getOwnedComponentExchangeCategories().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_FUNCTIONAL_LINKS:
return getOwnedFunctionalLinks() != null && !getOwnedFunctionalLinks().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_FUNCTIONAL_ALLOCATIONS:
return getOwnedFunctionalAllocations() != null && !getOwnedFunctionalAllocations().isEmpty();
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGE_REALIZATIONS:
return getOwnedComponentExchangeRealizations() != null && !getOwnedComponentExchangeRealizations().isEmpty();
}
return super.eIsSet(featureID);
}
@Override
public void eSet(final int featureID, final Object newValue) {
switch (featureID) {
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_EXTENSIONS:
getOwnedExtensions().clear();
getOwnedExtensions().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__ID:
setId(
(java.lang.String)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__SID:
setSid(
(java.lang.String)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_CONSTRAINTS:
getOwnedConstraints().clear();
getOwnedConstraints().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__NAME:
setName(
(java.lang.String)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__VISIBLE_IN_DOC:
setVisibleInDoc(((java.lang.Boolean) newValue).booleanValue());
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__VISIBLE_IN_LM:
setVisibleInLM(((java.lang.Boolean) newValue).booleanValue());
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__SUMMARY:
setSummary(
(java.lang.String)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__DESCRIPTION:
setDescription(
(java.lang.String)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__REVIEW:
setReview(
(java.lang.String)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUES:
getOwnedPropertyValues().clear();
getOwnedPropertyValues().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_ENUMERATION_PROPERTY_TYPES:
getOwnedEnumerationPropertyTypes().clear();
getOwnedEnumerationPropertyTypes().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_PROPERTY_VALUES:
getAppliedPropertyValues().clear();
getAppliedPropertyValues().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUE_GROUPS:
getOwnedPropertyValueGroups().clear();
getOwnedPropertyValueGroups().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__APPLIED_PROPERTY_VALUE_GROUPS:
getAppliedPropertyValueGroups().clear();
getAppliedPropertyValueGroups().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__STATUS:
setStatus(
(org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral)
newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__FEATURES:
getFeatures().clear();
getFeatures().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_TRACES:
getOwnedTraces().clear();
getOwnedTraces().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__NAMING_RULES:
getNamingRules().clear();
getNamingRules().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_PROPERTY_VALUE_PKGS:
getOwnedPropertyValuePkgs().clear();
getOwnedPropertyValuePkgs().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGES:
getOwnedComponentExchanges().clear();
getOwnedComponentExchanges().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGE_CATEGORIES:
getOwnedComponentExchangeCategories().clear();
getOwnedComponentExchangeCategories().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_FUNCTIONAL_LINKS:
getOwnedFunctionalLinks().clear();
getOwnedFunctionalLinks().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_FUNCTIONAL_ALLOCATIONS:
getOwnedFunctionalAllocations().clear();
getOwnedFunctionalAllocations().addAll((Collection) newValue);
return;
case org.gemoc.scenario.xdsml.functionscenariomt.fa.FaPackage.ABSTRACT_FUNCTIONAL_STRUCTURE__OWNED_COMPONENT_EXCHANGE_REALIZATIONS:
getOwnedComponentExchangeRealizations().clear();
getOwnedComponentExchangeRealizations().addAll((Collection) newValue);
return;
}
super.eSet(featureID, newValue);
}
}
| epl-1.0 |
tobiasb/CodeFinder | tests/org.eclipse.recommenders.tests.codesearch.rcp.index/xtend-gen/org/eclipse/recommenders/test/codesearch/rcp/indexer/TestGeneralScenarios.java | 102942 | package org.eclipse.recommenders.test.codesearch.rcp.indexer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.recommenders.codesearch.rcp.index.Fields;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.AllDeclaredFieldNamesIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.AnnotationsIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.DeclaredFieldNamesIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.DeclaredFieldTypesIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.DeclaringTypeIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.DocumentTypeIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.FieldsReadIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.FieldsWrittenIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.FullTextIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.InstanceOfIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.ModifiersIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.ProjectNameIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.QualifiedNameIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.ResourcePathIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.SimpleNameIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.TimestampIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.UsedFieldsInFinallyIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.UsedFieldsInTryIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.UsedMethodsIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.UsedTypesIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.interfaces.IIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.interfaces.ITryCatchBlockIndexer;
import org.eclipse.recommenders.codesearch.rcp.index.indexer.visitor.CompilationUnitVisitor;
import org.eclipse.recommenders.test.codesearch.rcp.indexer.TestBase;
import org.eclipse.recommenders.tests.jdt.JavaProjectFixture;
import org.eclipse.recommenders.utils.Tuple;
import org.eclipse.xtend2.lib.StringConcatenation;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Conversions;
import org.eclipse.xtext.xbase.lib.Exceptions;
import org.junit.Ignore;
import org.junit.Test;
@SuppressWarnings("all")
public class TestGeneralScenarios extends TestBase {
@Test
public void testDocumentCounts() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
this.exercise(code, _simpleNameIndexer);
this.assertNumDocs(1);
}
@Test
public void testDocumentCounts02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
this.exercise(code, _simpleNameIndexer);
this.assertNumDocs(2);
}
@Test
public void testDocumentCounts03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.List;");
_builder.newLine();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("\t");
_builder.append("public List test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("return null;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
this.exercise(code, _simpleNameIndexer);
this.assertNumDocs(3);
}
@Test
public void testFriendlyNameIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
this.exercise(code, _simpleNameIndexer);
String _s = this.s(Fields.SIMPLE_NAME, "MyClass");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testFriendlyNameIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {}");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
this.exercise(code, _simpleNameIndexer);
String _s = this.s(Fields.SIMPLE_NAME, "test");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testFriendlyNameIndexer03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
this.exercise(code, _simpleNameIndexer);
String _s = this.s(Fields.SIMPLE_NAME, "map");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testFullyQualifiedNameIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
QualifiedNameIndexer _qualifiedNameIndexer = new QualifiedNameIndexer();
this.exercise(code, _qualifiedNameIndexer);
String _s = this.s(Fields.QUALIFIED_NAME, "LMyClass");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Ignore
@Test
public void testFullyQualifiedNameIndexer04() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("package org.test;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
QualifiedNameIndexer _qualifiedNameIndexer = new QualifiedNameIndexer();
this.exercise(code, _qualifiedNameIndexer);
String _s = this.s(Fields.QUALIFIED_NAME, "Lorg/test/MyClass");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testFullyQualifiedNameIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {}");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
QualifiedNameIndexer _qualifiedNameIndexer = new QualifiedNameIndexer();
this.exercise(code, _qualifiedNameIndexer);
String _s = this.s(Fields.QUALIFIED_NAME, "LMyClass.test()V");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testFullyQualifiedNameIndexer03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map mapInstance;");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
QualifiedNameIndexer _qualifiedNameIndexer = new QualifiedNameIndexer();
this.exercise(code, _qualifiedNameIndexer);
String _s = this.s(Fields.QUALIFIED_NAME, "LMyClass.mapInstance");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testDocumentTypeIndexerClassOnly() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
this.exercise(code, _documentTypeIndexer);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testDocumentTypeIndexerClassAndField() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
this.exercise(code, _documentTypeIndexer);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
String _s_1 = this.s(Fields.TYPE, Fields.TYPE_FIELD);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s_1);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l_1);
}
@Test
public void testDocumentTypeIndexerClassAndMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("} ");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
this.exercise(code, _documentTypeIndexer);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
String _s_1 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s_1);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l_1);
}
@Test
public void testDocumentTypeIndexerClassMethodAndTryCatch() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("if(map != null) { throw new Exception(); }");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("return null;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
this.exercise(code, _documentTypeIndexer);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
String _s_1 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s_1);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l_1);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2);
List<String> _l_2 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_2);
}
@Test
public void testUsedTypesIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.List;");
_builder.newLine();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
UsedTypesIndexer _usedTypesIndexer = new UsedTypesIndexer();
this.exercise(code, _usedTypesIndexer);
String _s = this.s(Fields.USED_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList = CollectionLiterals.<String>newArrayList(_s);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList, String.class)));
this.assertField(_l);
}
@Test
public void testUsedTypesIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.List;");
_builder.newLine();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("\t");
_builder.append("public List test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("return null;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
UsedTypesIndexer _usedTypesIndexer = new UsedTypesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_usedTypesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.USED_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_3 = this.s(Fields.USED_TYPES, "Ljava/util/List");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
}
@Test
public void testUsedTypesIndexer03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("return null;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
UsedTypesIndexer _usedTypesIndexer = new UsedTypesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_usedTypesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.USED_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_3 = this.s(Fields.USED_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
}
@Test
public void testUsedTypesIndexerNoPrimitivesStringObjectEtc() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("String f;");
_builder.newLine();
_builder.append("\t");
_builder.append("Object o1;");
_builder.newLine();
_builder.append("\t");
_builder.append("public void test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("String g;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Object o2;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
UsedTypesIndexer _usedTypesIndexer = new UsedTypesIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _usedTypesIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.USED_TYPES, "Ljava/lang/String");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertNotField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_3 = this.s(Fields.USED_TYPES, "Ljava/lang/String");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertNotField(_l_1);
String _s_4 = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_5 = this.s(Fields.USED_TYPES, "Ljava/lang/Object");
ArrayList<String> _newArrayList_3 = CollectionLiterals.<String>newArrayList(_s_4, _s_5);
List<String> _l_2 = this.l(((String[])Conversions.unwrapArray(_newArrayList_3, String.class)));
this.assertNotField(_l_2);
String _s_6 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_7 = this.s(Fields.USED_TYPES, "Ljava/lang/Object");
ArrayList<String> _newArrayList_4 = CollectionLiterals.<String>newArrayList(_s_6, _s_7);
List<String> _l_3 = this.l(((String[])Conversions.unwrapArray(_newArrayList_4, String.class)));
this.assertNotField(_l_3);
}
@Test
public void testUsedMethodsIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public List test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("String s = \"\";");
_builder.newLine();
_builder.append("\t\t");
_builder.append("s.concat(\"test\");");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
UsedMethodsIndexer _usedMethodsIndexer = new UsedMethodsIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_usedMethodsIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.USED_METHODS, "Ljava/lang/String.concat(Ljava/lang/String;)Ljava/lang/String;");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_3 = this.s(Fields.USED_METHODS, "Ljava/lang/String.concat(Ljava/lang/String;)Ljava/lang/String;");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
}
@Test
public void testUsedMethodsIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public class MyClass {\t");
_builder.newLine();
_builder.append("\t");
_builder.append("public List test() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("String s = \"\";");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("s.concat(\"test\");");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
UsedMethodsIndexer _usedMethodsIndexer = new UsedMethodsIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_usedMethodsIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.USED_METHODS, "Ljava/lang/String.concat(Ljava/lang/String;)Ljava/lang/String;");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_3 = this.s(Fields.USED_METHODS, "Ljava/lang/String.concat(Ljava/lang/String;)Ljava/lang/String;");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
String _s_4 = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_5 = this.s(Fields.USED_METHODS, "Ljava/lang/String.concat(Ljava/lang/String;)Ljava/lang/String;");
ArrayList<String> _newArrayList_3 = CollectionLiterals.<String>newArrayList(_s_4, _s_5);
List<String> _l_2 = this.l(((String[])Conversions.unwrapArray(_newArrayList_3, String.class)));
this.assertField(_l_2);
}
@Test
public void testDeclaringTypeIndexerMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void foo() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
DeclaringTypeIndexer _declaringTypeIndexer = new DeclaringTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_simpleNameIndexer, _declaringTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.SIMPLE_NAME, "foo");
String _s_1 = this.s(Fields.DECLARING_TYPE, "LMyClass");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaringTypeIndexerField() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
DeclaringTypeIndexer _declaringTypeIndexer = new DeclaringTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_simpleNameIndexer, _declaringTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.SIMPLE_NAME, "map");
String _s_1 = this.s(Fields.DECLARING_TYPE, "LMyClass");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaringTypeIndexerType() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public class SubClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
SimpleNameIndexer _simpleNameIndexer = new SimpleNameIndexer();
DeclaringTypeIndexer _declaringTypeIndexer = new DeclaringTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_simpleNameIndexer, _declaringTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.SIMPLE_NAME, "SubClass");
String _s_1 = this.s(Fields.DECLARING_TYPE, "LMyClass");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaringTypeIndexerVarUsage() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void testMethod123() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("String s;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
DeclaringTypeIndexer _declaringTypeIndexer = new DeclaringTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _declaringTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_VARUSAGE);
String _s_1 = this.s(Fields.DECLARING_TYPE, "LMyClass");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaringTypeIndexerTryCatch() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void testMethod123() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try{} catch(Exception ex){}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
DeclaringTypeIndexer _declaringTypeIndexer = new DeclaringTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _declaringTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.DECLARING_TYPE, "LMyClass");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testProjectNameIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ProjectNameIndexer _projectNameIndexer = new ProjectNameIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_projectNameIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i, "projectName");
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.PROJECT_NAME, "projectName");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testProjectNameIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void myMethod() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ProjectNameIndexer _projectNameIndexer = new ProjectNameIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_projectNameIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i, "projectName");
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.PROJECT_NAME, "projectName");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testProjectNameIndexer03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("MyClass test;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ProjectNameIndexer _projectNameIndexer = new ProjectNameIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_projectNameIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i, "projectName");
String _s = this.s(Fields.TYPE, Fields.TYPE_FIELD);
String _s_1 = this.s(Fields.PROJECT_NAME, "projectName");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testProjectNameIndexer04() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void myMethod() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) {}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ProjectNameIndexer _projectNameIndexer = new ProjectNameIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_projectNameIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i, "projectName");
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.PROJECT_NAME, "projectName");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testResourcePathIndexer() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
IWorkspace _workspace = ResourcesPlugin.getWorkspace();
JavaProjectFixture _javaProjectFixture = new JavaProjectFixture(_workspace, "projectName");
final JavaProjectFixture fixture = _javaProjectFixture;
String _string = code.toString();
final Tuple<ICompilationUnit,Set<Integer>> struct = fixture.createFileAndParseWithMarkers(_string);
final ICompilationUnit cu = struct.getFirst();
ASTNode cuParsed = TestBase.parse(cu);
CompilationUnitVisitor _compilationUnitVisitor = new CompilationUnitVisitor(this.f.index);
CompilationUnitVisitor visitor = _compilationUnitVisitor;
ResourcePathIndexer _resourcePathIndexer = new ResourcePathIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_resourcePathIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
visitor.addIndexer(_i);
cuParsed.accept(visitor);
this.f.index.commit();
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
CompilationUnit _compilationUnitFromAstNode = this.getCompilationUnitFromAstNode(cuParsed);
String _path = ResourcePathIndexer.getPath(_compilationUnitFromAstNode);
String _s_1 = this.s(Fields.RESOURCE_PATH, _path);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
} catch (Exception _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testResourcePathIndexer02() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void myMethod() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
IWorkspace _workspace = ResourcesPlugin.getWorkspace();
JavaProjectFixture _javaProjectFixture = new JavaProjectFixture(_workspace, "projectName");
final JavaProjectFixture fixture = _javaProjectFixture;
String _string = code.toString();
final Tuple<ICompilationUnit,Set<Integer>> struct = fixture.createFileAndParseWithMarkers(_string);
final ICompilationUnit cu = struct.getFirst();
ASTNode cuParsed = TestBase.parse(cu);
CompilationUnitVisitor _compilationUnitVisitor = new CompilationUnitVisitor(this.f.index);
CompilationUnitVisitor visitor = _compilationUnitVisitor;
ResourcePathIndexer _resourcePathIndexer = new ResourcePathIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_resourcePathIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
visitor.addIndexer(_i);
cuParsed.accept(visitor);
this.f.index.commit();
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
CompilationUnit _compilationUnitFromAstNode = this.getCompilationUnitFromAstNode(cuParsed);
String _path = ResourcePathIndexer.getPath(_compilationUnitFromAstNode);
String _s_1 = this.s(Fields.RESOURCE_PATH, _path);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
} catch (Exception _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testResourcePathIndexer03() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("MyClass test;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
IWorkspace _workspace = ResourcesPlugin.getWorkspace();
JavaProjectFixture _javaProjectFixture = new JavaProjectFixture(_workspace, "projectName");
final JavaProjectFixture fixture = _javaProjectFixture;
String _string = code.toString();
final Tuple<ICompilationUnit,Set<Integer>> struct = fixture.createFileAndParseWithMarkers(_string);
final ICompilationUnit cu = struct.getFirst();
ASTNode cuParsed = TestBase.parse(cu);
CompilationUnitVisitor _compilationUnitVisitor = new CompilationUnitVisitor(this.f.index);
CompilationUnitVisitor visitor = _compilationUnitVisitor;
ResourcePathIndexer _resourcePathIndexer = new ResourcePathIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_resourcePathIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
visitor.addIndexer(_i);
cuParsed.accept(visitor);
this.f.index.commit();
String _s = this.s(Fields.TYPE, Fields.TYPE_FIELD);
CompilationUnit _compilationUnitFromAstNode = this.getCompilationUnitFromAstNode(cuParsed);
String _path = ResourcePathIndexer.getPath(_compilationUnitFromAstNode);
String _s_1 = this.s(Fields.RESOURCE_PATH, _path);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
} catch (Exception _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testResourcePathIndexer04() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void myMethod() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) {}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
IWorkspace _workspace = ResourcesPlugin.getWorkspace();
JavaProjectFixture _javaProjectFixture = new JavaProjectFixture(_workspace, "projectName");
final JavaProjectFixture fixture = _javaProjectFixture;
String _string = code.toString();
final Tuple<ICompilationUnit,Set<Integer>> struct = fixture.createFileAndParseWithMarkers(_string);
final ICompilationUnit cu = struct.getFirst();
ASTNode cuParsed = TestBase.parse(cu);
CompilationUnitVisitor _compilationUnitVisitor = new CompilationUnitVisitor(this.f.index);
CompilationUnitVisitor visitor = _compilationUnitVisitor;
ResourcePathIndexer _resourcePathIndexer = new ResourcePathIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_resourcePathIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
visitor.addIndexer(_i);
cuParsed.accept(visitor);
this.f.index.commit();
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
CompilationUnit _compilationUnitFromAstNode = this.getCompilationUnitFromAstNode(cuParsed);
String _path = ResourcePathIndexer.getPath(_compilationUnitFromAstNode);
String _s_1 = this.s(Fields.RESOURCE_PATH, _path);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
} catch (Exception _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testResourcePathIndexer05() {
try {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void myMethod() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("String a = \"\";");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
IWorkspace _workspace = ResourcesPlugin.getWorkspace();
JavaProjectFixture _javaProjectFixture = new JavaProjectFixture(_workspace, "projectName");
final JavaProjectFixture fixture = _javaProjectFixture;
String _string = code.toString();
final Tuple<ICompilationUnit,Set<Integer>> struct = fixture.createFileAndParseWithMarkers(_string);
final ICompilationUnit cu = struct.getFirst();
ASTNode cuParsed = TestBase.parse(cu);
CompilationUnitVisitor _compilationUnitVisitor = new CompilationUnitVisitor(this.f.index);
CompilationUnitVisitor visitor = _compilationUnitVisitor;
ResourcePathIndexer _resourcePathIndexer = new ResourcePathIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_resourcePathIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
visitor.addIndexer(_i);
cuParsed.accept(visitor);
this.f.index.commit();
String _s = this.s(Fields.TYPE, Fields.TYPE_VARUSAGE);
CompilationUnit _compilationUnitFromAstNode = this.getCompilationUnitFromAstNode(cuParsed);
String _path = ResourcePathIndexer.getPath(_compilationUnitFromAstNode);
String _s_1 = this.s(Fields.RESOURCE_PATH, _path);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
} catch (Exception _e) {
throw Exceptions.sneakyThrow(_e);
}
}
@Test
public void testModifiersIndexerClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ModifiersIndexer _modifiersIndexer = new ModifiersIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_modifiersIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.MODIFIERS, "public");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testModifiersIndexerClass02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public abstract class MyClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ModifiersIndexer _modifiersIndexer = new ModifiersIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_modifiersIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.MODIFIERS, Fields.MODIFIER_PUBLIC);
String _s_2 = this.s(Fields.MODIFIERS, Fields.MODIFIER_ABSTRACT);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1, _s_2);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testModifiersIndexerMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void doSomethingNow123413() {}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ModifiersIndexer _modifiersIndexer = new ModifiersIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_modifiersIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.MODIFIERS, Fields.MODIFIER_PUBLIC);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testModifiersIndexerMethod02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public abstract class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void doSomethingNow123413() {}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ModifiersIndexer _modifiersIndexer = new ModifiersIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_modifiersIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.MODIFIERS, Fields.MODIFIER_PUBLIC);
String _s_2 = this.s(Fields.MODIFIERS, Fields.MODIFIER_STATIC);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1, _s_2);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testModifiersIndexerField() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("private Map map;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ModifiersIndexer _modifiersIndexer = new ModifiersIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_modifiersIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_FIELD);
String _s_1 = this.s(Fields.MODIFIERS, Fields.MODIFIER_PRIVATE);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testModifiersIndexerField02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("protected static Map map;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
ModifiersIndexer _modifiersIndexer = new ModifiersIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_modifiersIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_FIELD);
String _s_1 = this.s(Fields.MODIFIERS, Fields.MODIFIER_PROTECTED);
String _s_2 = this.s(Fields.MODIFIERS, Fields.MODIFIER_STATIC);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1, _s_2);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_3 = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_4 = this.s(Fields.MODIFIERS, Fields.MODIFIER_FINAL);
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_3, _s_4);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
}
@Test
public void testDeclaredFieldNamesClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldNamesIndexer _declaredFieldNamesIndexer = new DeclaredFieldNamesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldNamesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.DECLARED_FIELD_NAMES, "map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaredFieldNamesClassWithInitalizer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map = new HashMap();");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldNamesIndexer _declaredFieldNamesIndexer = new DeclaredFieldNamesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldNamesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.DECLARED_FIELD_NAMES, "map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaredFieldNamesMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("void doSomethingElse() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldNamesIndexer _declaredFieldNamesIndexer = new DeclaredFieldNamesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldNamesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.DECLARED_FIELD_NAMES, "map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaredFieldNamesTryCatch() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("void doSomethingElse() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) { Map map; }");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldNamesIndexer _declaredFieldNamesIndexer = new DeclaredFieldNamesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldNamesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.DECLARED_FIELD_NAMES, "map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaredFieldTypesClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldTypesIndexer _declaredFieldTypesIndexer = new DeclaredFieldTypesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldTypesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.DECLARED_FIELD_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaredFieldTypesMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("void doSomethingElse() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Map map;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldTypesIndexer _declaredFieldTypesIndexer = new DeclaredFieldTypesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldTypesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.DECLARED_FIELD_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testDeclaredFieldTypesTry() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("public final class MyClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("void doSomethingElse() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) { Map map; }");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DeclaredFieldTypesIndexer _declaredFieldTypesIndexer = new DeclaredFieldTypesIndexer();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_declaredFieldTypesIndexer, _documentTypeIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.DECLARED_FIELD_TYPES, "Ljava/util/Map");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testAllFieldNamesIndexerClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyOtherException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("private Map theMapyMap;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
AllDeclaredFieldNamesIndexer _allDeclaredFieldNamesIndexer = new AllDeclaredFieldNamesIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _allDeclaredFieldNamesIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.ALL_DECLARED_FIELD_NAMES, "theMapyMap");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_3 = this.s(Fields.ALL_DECLARED_FIELD_NAMES, "serialVersionUID");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
}
@Test
public void testAllFieldNamesIndexerClass02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyOtherException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("private Map theMapyMap;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
AllDeclaredFieldNamesIndexer _allDeclaredFieldNamesIndexer = new AllDeclaredFieldNamesIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _allDeclaredFieldNamesIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.ALL_DECLARED_FIELD_NAMES, "theMapyMap");
String _s_2 = this.s(Fields.ALL_DECLARED_FIELD_NAMES, "stackTrace");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1, _s_2);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFullTextIndexerClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MOtherException extends IOException {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FullTextIndexer _fullTextIndexer = new FullTextIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fullTextIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("public class MOtherException extends IOException {");
_builder_1.newLine();
_builder_1.append("}");
String _string = _builder_1.toString();
String _s_1 = this.s(Fields.FULL_TEXT, _string);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFullTextIndexerMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyTinyException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theEasiestMethodEver() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FullTextIndexer _fullTextIndexer = new FullTextIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fullTextIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("public static void theEasiestMethodEver(){");
_builder_1.newLine();
_builder_1.append("}");
String _string = _builder_1.toString();
String _s_1 = this.s(Fields.FULL_TEXT, _string);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFullTextIndexerTryCatch() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyRandomException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theWorstMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("//This is a comment");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FullTextIndexer _fullTextIndexer = new FullTextIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fullTextIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("catch (Exception ex) {");
_builder_1.newLine();
_builder_1.append("}");
String _string = _builder_1.toString();
String _s_1 = this.s(Fields.FULL_TEXT, _string);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFullTextIndexerField() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyOtherOtherException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("Map theWorldMap;");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theBestMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("//This is a comment");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FullTextIndexer _fullTextIndexer = new FullTextIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fullTextIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_FIELD);
StringConcatenation _builder_1 = new StringConcatenation();
_builder_1.append("Map theWorldMap;");
String _string = _builder_1.toString();
String _s_1 = this.s(Fields.FULL_TEXT, _string);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFieldsReadIndexerMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class testFieldsReadIndexerMethod extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public Map theWorldMap;");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theBestMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("MyOtherOtherException m;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Object o = m.theWorldMap;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FieldsReadIndexer _fieldsReadIndexer = new FieldsReadIndexer();
FieldsWrittenIndexer _fieldsWrittenIndexer = new FieldsWrittenIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fieldsReadIndexer, _fieldsWrittenIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.FIELDS_READ, "LtestFieldsReadIndexerMethod.theWorldMap");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_3 = this.s(Fields.FIELDS_WRITTEN, "LtestFieldsReadIndexerMethod.someObject");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertNotField(_l_1);
}
@Test
public void testFieldsReadIndexerClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class testFieldsReadIndexerClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public Object someObject = null;");
_builder.newLine();
_builder.append("\t");
_builder.append("public Testclass ob = new Testclass();");
_builder.newLine();
_builder.append("\t");
_builder.append("public Object anObject = ob.someObject;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FieldsReadIndexer _fieldsReadIndexer = new FieldsReadIndexer();
FieldsWrittenIndexer _fieldsWrittenIndexer = new FieldsWrittenIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fieldsReadIndexer, _fieldsWrittenIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.FIELDS_READ, "LtestFieldsReadIndexerClass.someObject");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFieldsReadIndexerTryCatch() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class testFieldsReadIndexerTryCatch extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public Object someObject = null;");
_builder.newLine();
_builder.append("\t");
_builder.append("public Object theWorldMap = (new Testclass()).someObject;");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theBestMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("Testclass c = new Testclass();");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("Object myObject = c.someObject;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FieldsReadIndexer _fieldsReadIndexer = new FieldsReadIndexer();
FieldsWrittenIndexer _fieldsWrittenIndexer = new FieldsWrittenIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fieldsReadIndexer, _fieldsWrittenIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.FIELDS_READ, "LtestFieldsReadIndexerTryCatch.someObject");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testFieldsWrittenIndexerMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyOtherOtherException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public Map theWorldMap;");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theBestMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("MyOtherOtherException m = null;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("m.theWorldMap = null;");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
FieldsReadIndexer _fieldsReadIndexer = new FieldsReadIndexer();
FieldsWrittenIndexer _fieldsWrittenIndexer = new FieldsWrittenIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _fieldsReadIndexer, _fieldsWrittenIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.FIELDS_WRITTEN, "LMyOtherOtherException.theWorldMap");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testUsedFieldsInTryIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyOtherOtherException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public Map theWorldMap;");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theBestMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("MyOtherOtherException m = null;");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("m.theWorldMap = null;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} finally {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
UsedFieldsInTryIndexer _usedFieldsInTryIndexer = new UsedFieldsInTryIndexer();
ArrayList<ITryCatchBlockIndexer> _newArrayList = CollectionLiterals.<ITryCatchBlockIndexer>newArrayList(_documentTypeIndexer, _usedFieldsInTryIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.USED_FIELDS_IN_TRY, "LMyOtherOtherException.theWorldMap");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testUsedFieldsInFinallyIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.Map;");
_builder.newLine();
_builder.append("import java.io.IOException;");
_builder.newLine();
_builder.append("public class MyOtherOtherException extends IOException {");
_builder.newLine();
_builder.append("\t");
_builder.append("public Map theWorldMap;");
_builder.newLine();
_builder.append("\t");
_builder.append("public static void theBestMethodEver() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} finally {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("MyOtherOtherException m = null;");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("m.theWorldMap = null;");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
UsedFieldsInFinallyIndexer _usedFieldsInFinallyIndexer = new UsedFieldsInFinallyIndexer();
ArrayList<ITryCatchBlockIndexer> _newArrayList = CollectionLiterals.<ITryCatchBlockIndexer>newArrayList(_documentTypeIndexer, _usedFieldsInFinallyIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.USED_FIELDS_IN_FINALLY, "LMyOtherOtherException.theWorldMap");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testAnnotationIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("@Deprecated");
_builder.newLine();
_builder.append("public class MyAnnotatedClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
AnnotationsIndexer _annotationsIndexer = new AnnotationsIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _annotationsIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.ANNOTATIONS, "Ljava/lang/Deprecated");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testAnnotationIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("@SuppressWarnings({\"unchecked\", \"rawtypes\"})");
_builder.newLine();
_builder.append("public class MyAnnotatedClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
AnnotationsIndexer _annotationsIndexer = new AnnotationsIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _annotationsIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.ANNOTATIONS, "Ljava/lang/SuppressWarnings");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_3 = this.s(Fields.ANNOTATIONS, "Ljava/lang/SuppressWarnings:unchecked");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
String _s_4 = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_5 = this.s(Fields.ANNOTATIONS, "Ljava/lang/SuppressWarnings:rawtypes");
ArrayList<String> _newArrayList_3 = CollectionLiterals.<String>newArrayList(_s_4, _s_5);
List<String> _l_2 = this.l(((String[])Conversions.unwrapArray(_newArrayList_3, String.class)));
this.assertField(_l_2);
}
@Test
public void testAnnotationIndexer03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("import java.util.List;");
_builder.newLine();
_builder.append("public class MyAnnotatedClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("@SuppressWarnings(\"rawtypes\")");
_builder.newLine();
_builder.append("\t");
_builder.append("public static String printLabel(List l) {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
AnnotationsIndexer _annotationsIndexer = new AnnotationsIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _annotationsIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.ANNOTATIONS, "Ljava/lang/SuppressWarnings");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
String _s_2 = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_3 = this.s(Fields.ANNOTATIONS, "Ljava/lang/SuppressWarnings:rawtypes");
ArrayList<String> _newArrayList_2 = CollectionLiterals.<String>newArrayList(_s_2, _s_3);
List<String> _l_1 = this.l(((String[])Conversions.unwrapArray(_newArrayList_2, String.class)));
this.assertField(_l_1);
}
@Test
public void testInstanceOfIndexerClass() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void operation() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Object a = new String();");
_builder.newLine();
_builder.append("\t\t");
_builder.newLine();
_builder.append("\t\t");
_builder.append("if(a instanceof Exception) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("//Somethin\'s fishy");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} ");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
InstanceOfIndexer _instanceOfIndexer = new InstanceOfIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _instanceOfIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _s_1 = this.s(Fields.INSTANCEOF_TYPES, "Ljava/lang/Exception");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testInstanceOfIndexerMethod() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void operation() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Object a = new String();");
_builder.newLine();
_builder.append("\t\t");
_builder.newLine();
_builder.append("\t\t");
_builder.append("if(a instanceof Exception) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("//Somethin\'s fishy");
_builder.newLine();
_builder.append("\t\t");
_builder.append("} ");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
InstanceOfIndexer _instanceOfIndexer = new InstanceOfIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _instanceOfIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _s_1 = this.s(Fields.INSTANCEOF_TYPES, "Ljava/lang/Exception");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testInstanceOfIndexerTryCatch() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void operation() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("Object a = new String();");
_builder.newLine();
_builder.append("\t\t");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("if(a instanceof Exception) {");
_builder.newLine();
_builder.append("\t\t\t\t");
_builder.append("//Somethin\'s fishy");
_builder.newLine();
_builder.append("\t\t\t");
_builder.append("} ");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
InstanceOfIndexer _instanceOfIndexer = new InstanceOfIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _instanceOfIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _s_1 = this.s(Fields.INSTANCEOF_TYPES, "Ljava/lang/Exception");
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertField(_l);
}
@Test
public void testTimestampIndexer() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
TimestampIndexer.updateCurrentTimestamp();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
TimestampIndexer _timestampIndexer = new TimestampIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _timestampIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_CLASS);
String _timeString = TimestampIndexer.getTimeString();
String _substring = _timeString.substring(0, 8);
String _s_1 = this.s(Fields.TIMESTAMP, _substring);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertFieldStartsWith(_l);
}
@Test
public void testTimestampIndexer02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void operation() {");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
TimestampIndexer.updateCurrentTimestamp();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
TimestampIndexer _timestampIndexer = new TimestampIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _timestampIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_METHOD);
String _timeString = TimestampIndexer.getTimeString();
String _substring = _timeString.substring(0, 8);
String _s_1 = this.s(Fields.TIMESTAMP, _substring);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertFieldStartsWith(_l);
}
@Test
public void testTimestampIndexer03() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("private String s;");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
TimestampIndexer.updateCurrentTimestamp();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
TimestampIndexer _timestampIndexer = new TimestampIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _timestampIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_FIELD);
String _timeString = TimestampIndexer.getTimeString();
String _substring = _timeString.substring(0, 8);
String _s_1 = this.s(Fields.TIMESTAMP, _substring);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertFieldStartsWith(_l);
}
@Test
public void testTimestampIndexer04() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("public class MyInstanceOfClass {");
_builder.newLine();
_builder.append("\t");
_builder.append("public void operation() {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("try {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t\t");
_builder.append("catch(Exception ex) {");
_builder.newLine();
_builder.append("\t\t");
_builder.append("}");
_builder.newLine();
_builder.append("\t");
_builder.append("}");
_builder.newLine();
_builder.append("}");
_builder.newLine();
final CharSequence code = _builder;
TimestampIndexer.updateCurrentTimestamp();
DocumentTypeIndexer _documentTypeIndexer = new DocumentTypeIndexer();
TimestampIndexer _timestampIndexer = new TimestampIndexer();
ArrayList<IIndexer> _newArrayList = CollectionLiterals.<IIndexer>newArrayList(_documentTypeIndexer, _timestampIndexer);
List<IIndexer> _i = this.i(((IIndexer[])Conversions.unwrapArray(_newArrayList, IIndexer.class)));
this.exercise(code, _i);
String _s = this.s(Fields.TYPE, Fields.TYPE_TRYCATCH);
String _timeString = TimestampIndexer.getTimeString();
String _substring = _timeString.substring(0, 8);
String _s_1 = this.s(Fields.TIMESTAMP, _substring);
ArrayList<String> _newArrayList_1 = CollectionLiterals.<String>newArrayList(_s, _s_1);
List<String> _l = this.l(((String[])Conversions.unwrapArray(_newArrayList_1, String.class)));
this.assertFieldStartsWith(_l);
}
}
| epl-1.0 |
NABUCCO/org.nabucco.framework.workflow | org.nabucco.framework.workflow.impl.service/src/main/gen/org/nabucco/framework/workflow/impl/service/crosscutting/CrosscuttingWorkflowServiceImpl.java | 5359 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.workflow.impl.service.crosscutting;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import org.nabucco.framework.base.facade.exception.service.WorkflowException;
import org.nabucco.framework.base.facade.message.ServiceRequest;
import org.nabucco.framework.base.facade.message.ServiceResponse;
import org.nabucco.framework.base.facade.message.workflow.InitWorkflowRq;
import org.nabucco.framework.base.facade.message.workflow.ProcessWorkflowRq;
import org.nabucco.framework.base.facade.message.workflow.WorkflowResultRs;
import org.nabucco.framework.base.facade.service.injection.InjectionException;
import org.nabucco.framework.base.facade.service.injection.InjectionProvider;
import org.nabucco.framework.base.impl.service.ServiceSupport;
import org.nabucco.framework.base.impl.service.maintain.PersistenceManager;
import org.nabucco.framework.base.impl.service.maintain.PersistenceManagerFactory;
import org.nabucco.framework.workflow.facade.service.crosscutting.CrosscuttingWorkflowService;
/**
* CrosscuttingWorkflowServiceImpl<p/>Workflow instance resolution service<p/>
*
* @version 1.0
* @author Nicolas Moser, PRODYNA AG, 2011-04-28
*/
public class CrosscuttingWorkflowServiceImpl extends ServiceSupport implements CrosscuttingWorkflowService {
private static final long serialVersionUID = 1L;
private static final String ID = "CrosscuttingWorkflowService";
private static Map<String, String[]> ASPECTS;
private EntityManager entityManager;
private InitWorkflowServiceHandler initWorkflowServiceHandler;
private ProcessWorkflowServiceHandler processWorkflowServiceHandler;
/** Constructs a new CrosscuttingWorkflowServiceImpl instance. */
public CrosscuttingWorkflowServiceImpl() {
super();
}
@Override
public void postConstruct() {
super.postConstruct();
InjectionProvider injector = InjectionProvider.getInstance(ID);
PersistenceManager persistenceManager = PersistenceManagerFactory.getInstance().createPersistenceManager(
this.entityManager, super.getLogger());
this.initWorkflowServiceHandler = injector.inject(InitWorkflowServiceHandler.getId());
if ((this.initWorkflowServiceHandler != null)) {
this.initWorkflowServiceHandler.setPersistenceManager(persistenceManager);
this.initWorkflowServiceHandler.setLogger(super.getLogger());
}
this.processWorkflowServiceHandler = injector.inject(ProcessWorkflowServiceHandler.getId());
if ((this.processWorkflowServiceHandler != null)) {
this.processWorkflowServiceHandler.setPersistenceManager(persistenceManager);
this.processWorkflowServiceHandler.setLogger(super.getLogger());
}
}
@Override
public void preDestroy() {
super.preDestroy();
}
@Override
public String[] getAspects(String operationName) {
if ((ASPECTS == null)) {
ASPECTS = new HashMap<String, String[]>();
}
String[] aspects = ASPECTS.get(operationName);
if ((aspects == null)) {
return ServiceSupport.NO_ASPECTS;
}
return Arrays.copyOf(aspects, aspects.length);
}
@Override
public ServiceResponse<WorkflowResultRs> initWorkflow(ServiceRequest<InitWorkflowRq> rq) throws WorkflowException {
if ((this.initWorkflowServiceHandler == null)) {
super.getLogger().error("No service implementation configured for initWorkflow().");
throw new InjectionException("No service implementation configured for initWorkflow().");
}
ServiceResponse<WorkflowResultRs> rs;
this.initWorkflowServiceHandler.init();
rs = this.initWorkflowServiceHandler.invoke(rq);
this.initWorkflowServiceHandler.finish();
return rs;
}
@Override
public ServiceResponse<WorkflowResultRs> processWorkflow(ServiceRequest<ProcessWorkflowRq> rq)
throws WorkflowException {
if ((this.processWorkflowServiceHandler == null)) {
super.getLogger().error("No service implementation configured for processWorkflow().");
throw new InjectionException("No service implementation configured for processWorkflow().");
}
ServiceResponse<WorkflowResultRs> rs;
this.processWorkflowServiceHandler.init();
rs = this.processWorkflowServiceHandler.invoke(rq);
this.processWorkflowServiceHandler.finish();
return rs;
}
}
| epl-1.0 |
lhillah/pnmlframework | pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/booleans/Equality.java | 2819 | /**
* Copyright 2009-2016 Université Paris Ouest and Sorbonne Universités,
Univ. Paris 06 - CNRS UMR 7606 (LIP6)
*
* 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
*
* Project leader / Initial Contributor:
* Lom Messan Hillah - <lom-messan.hillah@lip6.fr>
*
* Contributors:
* ${ocontributors} - <$oemails}>
*
* Mailing list:
* lom-messan.hillah@lip6.fr
*/
/**
* (C) Sorbonne Universités, UPMC Univ Paris 06, UMR CNRS 7606 (LIP6/MoVe)
* 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:
* Lom HILLAH (LIP6) - Initial models and implementation
* Rachid Alahyane (UPMC) - Infrastructure and continuous integration
* Bastien Bouzerau (UPMC) - Architecture
* Guillaume Giffo (UPMC) - Code generation refactoring, High-level API
*/
package fr.lip6.move.pnml.hlpn.booleans;
import java.nio.channels.FileChannel;
import org.apache.axiom.om.OMElement;
import org.eclipse.emf.common.util.DiagnosticChain;
import fr.lip6.move.pnml.framework.utils.IdRefLinker;
import fr.lip6.move.pnml.framework.utils.exception.InnerBuildException;
import fr.lip6.move.pnml.framework.utils.exception.InvalidIDException;
import fr.lip6.move.pnml.framework.utils.exception.VoidRepositoryException;
import fr.lip6.move.pnml.hlpn.terms.Operator;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Equality</b></em>'.
* <!-- end-user-doc -->
*
*
* @see fr.lip6.move.pnml.hlpn.booleans.BooleansPackage#getEquality()
* @model annotation="http://www.pnml.org/models/OCL inputOutputTypes='self.input.size() >= 2 and self.input->forAll{c, d | c.oclIsTypeOf(d) or d.oclIsTypeOf(c)} and self.output.oclIsKindOf(Bool)'"
* annotation="http://www.eclipse.org/emf/2002/Ecore constraints='inputOutputTypes'"
* annotation="http://www.pnml.org/models/ToPNML tag='equality' kind='son'"
* @generated
*/
public interface Equality extends Operator {
/**
* Return the string containing the pnml output
*/
@Override
public String toPNML();
/**
* set values to conform PNML document
*/
@Override
public void fromPNML(OMElement subRoot, IdRefLinker idr) throws InnerBuildException, InvalidIDException,
VoidRepositoryException;
/**
* Write the PNML xml tree of this object into file
*/
@Override
public void toPNML(FileChannel fc);
@Override
public boolean validateOCL(DiagnosticChain diagnostics);
} // Equality
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/SimpleSelectStatement.java | 1896 | /*******************************************************************************
* Copyright (c) 2006, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation
*
******************************************************************************/
package org.eclipse.persistence.jpa.jpql.parser;
/**
* <div nowrap><b>BNFL</b> <code>subquery ::= simple_select_clause subquery_from_clause [where_clause] [groupby_clause] [having_clause]</code><p>
*
* @version 2.5
* @since 2.3
* @author Pascal Filion
*/
public final class SimpleSelectStatement extends AbstractSelectStatement {
/**
* Creates a new <code>SimpleSelectStatement</code>.
*
* @param parent The parent of this expression
*/
public SimpleSelectStatement(AbstractExpression parent) {
super(parent);
}
/**
* {@inheritDoc}
*/
public void accept(ExpressionVisitor visitor) {
visitor.visit(this);
}
/**
* {@inheritDoc}
*/
@Override
protected SimpleFromClause buildFromClause() {
return new SimpleFromClause(this);
}
/**
* {@inheritDoc}
*/
@Override
protected SimpleSelectClause buildSelectClause() {
return new SimpleSelectClause(this);
}
/**
* {@inheritDoc}
*/
public JPQLQueryBNF getQueryBNF() {
return getQueryBNF(SubqueryBNF.ID);
}
/**
* {@inheritDoc}
*/
@Override
protected boolean shouldManageSpaceAfterClause() {
return false;
}
} | epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext/emf-gen/org/eclipse/xtext/Condition.java | 511 | /**
*/
package org.eclipse.xtext;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Condition</b></em>'.
* <!-- end-user-doc -->
*
*
* @see org.eclipse.xtext.XtextPackage#getCondition()
* @since 2.9
* @model
* @generated
* @noextend This interface is not intended to be extended by clients.
* @noimplement This interface is not intended to be implemented by clients.
*/
public interface Condition extends EObject {
} // Condition
| epl-1.0 |
ylussaud/M2Doc | plugins/org.obeonetwork.m2doc/src/org/obeonetwork/m2doc/element/MText.java | 1184 | /*******************************************************************************
* Copyright (c) 2017 Obeo.
* 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:
* Obeo - initial API and implementation
*
*******************************************************************************/
package org.obeonetwork.m2doc.element;
/**
* Styled text.
*
* @author <a href="mailto:yvan.lussaud@obeo.fr">Yvan Lussaud</a>
*/
public interface MText extends MElement {
/**
* Gets the text.
*
* @return the text
*/
String getText();
/**
* Sets the text.
*
* @param text
* the new text
*/
void setText(String text);
/**
* Gets the {@link MStyle}.
*
* @return the {@link MStyle}
*/
MStyle getStyle();
/**
* Set the {@link MStyle}.
*
* @param style
* the new {@link MStyle}
*/
void setStyle(MStyle style);
}
| epl-1.0 |
SK-HOLDINGS-CC/NEXCORE-UML-Modeler | nexcore.tool.uml.model/src/java/nexcore/tool/uml/model/modeldetail/impl/ModelDetailImpl.java | 5218 | /**
* Copyright (c) 2015 SK holdings Co., Ltd. All rights reserved.
* This software is the confidential and proprietary information of SK holdings.
* You shall not disclose such confidential information and shall use it only in
* accordance with the terms of the license agreement you entered into with SK holdings.
* (http://www.eclipse.org/legal/epl-v10.html)
*/
package nexcore.tool.uml.model.modeldetail.impl;
import nexcore.tool.uml.model.modeldetail.ModelDetail;
import nexcore.tool.uml.model.modeldetail.ModelDetailPackage;
import nexcore.tool.uml.model.modeldetail.ModelType;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.EAnnotationImpl;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc --> An implementation of the model object '
* <em><b>Model Detail</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>
* {@link nexcore.tool.uml.model.modeldetail.impl.ModelDetailImpl#getModelType
* <em>Model Type</em>}</li>
* </ul>
* </p>
*
* @generated
*/
/**
* <ul>
* <li>업무 그룹명 : nexcore.tool.uml.model</li>
* <li>서브 업무명 : nexcore.tool.uml.model.modeldetail.impl</li>
* <li>설 명 : ModelDetailImpl</li>
* <li>작성일 : 2015. 10. 6.</li>
* <li>작성자 : 탁희수 </li>
* </ul>
*/
public class ModelDetailImpl extends EAnnotationImpl implements ModelDetail {
/**
* The default value of the '{@link #getModelType() <em>Model Type</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getModelType()
* @generated
* @ordered
*/
protected static final ModelType MODEL_TYPE_EDEFAULT = ModelType.GENERAL;
/**
* The cached value of the '{@link #getModelType() <em>Model Type</em>}'
* attribute. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @see #getModelType()
* @generated
* @ordered
*/
protected ModelType modelType = MODEL_TYPE_EDEFAULT;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
protected ModelDetailImpl() {
super();
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
protected EClass eStaticClass() {
return ModelDetailPackage.Literals.MODEL_DETAIL;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public ModelType getModelType() {
return modelType;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
public void setModelType(ModelType newModelType) {
ModelType oldModelType = modelType;
modelType = newModelType == null ? MODEL_TYPE_EDEFAULT : newModelType;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this,
Notification.SET,
ModelDetailPackage.MODEL_DETAIL__MODEL_TYPE,
oldModelType,
modelType));
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ModelDetailPackage.MODEL_DETAIL__MODEL_TYPE:
return getModelType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ModelDetailPackage.MODEL_DETAIL__MODEL_TYPE:
setModelType((ModelType) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ModelDetailPackage.MODEL_DETAIL__MODEL_TYPE:
setModelType(MODEL_TYPE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ModelDetailPackage.MODEL_DETAIL__MODEL_TYPE:
return modelType != MODEL_TYPE_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
if (eIsProxy())
return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (ModelType: ");
result.append(modelType);
result.append(')');
return result.toString();
}
} // ModelDetailImpl
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.mdb.jms_fat/test-applications/MDBAnnEJB.jar/src/com/ibm/ws/ejbcontainer/mdb/jms/ann/ejb/SF.java | 1028 | /*******************************************************************************
* Copyright (c) 2003, 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.ejbcontainer.mdb.jms.ann.ejb;
import javax.ejb.Remote;
import javax.sql.DataSource;
@Remote
public interface SF {
/**
* Get accessor for persistent attribute: intValue
*/
public int getIntValue();
/**
* Set accessor for persistent attribute: intValue
*/
public void setIntValue(int newIntValue);
public String method1(String arg1);
// 454605
public DataSource getDataSource();
public String getStringValue();
} | epl-1.0 |
codenvy/che-core | platform-api/che-core-api-workspace/src/main/java/org/eclipse/che/api/workspace/shared/dto/WorkspaceDescriptor.java | 2235 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.workspace.shared.dto;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.dto.shared.DTO;
import com.wordnik.swagger.annotations.ApiModel;
import com.wordnik.swagger.annotations.ApiModelProperty;
import java.util.List;
import java.util.Map;
/**
* @author andrew00x
*/
@DTO
@ApiModel(value = "Information about workspace")
public interface WorkspaceDescriptor {
@ApiModelProperty(value = "Identifier of a workspace in a system", required = true)
String getId();
void setId(String id);
WorkspaceDescriptor withId(String id);
@ApiModelProperty(value = "Workspace name. It comes just after 'ws' in the workspace URL - http://codenvy.com/ws/{ws-name}", required = true)
String getName();
void setName(String name);
WorkspaceDescriptor withName(String name);
void setTemporary(boolean temporary);
@ApiModelProperty(value = "Information on whether or not the workspace is temporary", required = true, allowableValues = "true,false")
boolean isTemporary();
WorkspaceDescriptor withTemporary(boolean temporary);
@ApiModelProperty(value ="ID of an account", required = true)
String getAccountId();
void setAccountId(String accountId);
WorkspaceDescriptor withAccountId(String accountId);
@ApiModelProperty(value = "Workspace attributes, such as runner and builder life time, RAM allocation")
Map<String, String> getAttributes();
void setAttributes(Map<String, String> attributes);
WorkspaceDescriptor withAttributes(Map<String, String> attributes);
List<Link> getLinks();
void setLinks(List<Link> links);
WorkspaceDescriptor withLinks(List<Link> links);
}
| epl-1.0 |
whizzosoftware/hobson-hub-api | src/main/java/com/whizzosoftware/hobson/api/plugin/AbstractPluginManager.java | 5988 | /*
*******************************************************************************
* Copyright (c) 2016 Whizzo Software, LLC.
* 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 com.whizzosoftware.hobson.api.plugin;
import com.whizzosoftware.hobson.api.HobsonRuntimeException;
import com.whizzosoftware.hobson.api.config.ConfigurationManager;
import com.whizzosoftware.hobson.api.device.proxy.HobsonDeviceProxy;
import com.whizzosoftware.hobson.api.event.EventManager;
import com.whizzosoftware.hobson.api.event.plugin.PluginConfigurationUpdateEvent;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import com.whizzosoftware.hobson.api.property.PropertyContainerClass;
import com.whizzosoftware.hobson.api.variable.DeviceVariableContext;
import com.whizzosoftware.hobson.api.variable.DeviceVariableState;
import com.whizzosoftware.hobson.api.variable.GlobalVariable;
import com.whizzosoftware.hobson.api.variable.GlobalVariableContext;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.NotSerializableException;
import java.util.Collection;
import java.util.Map;
/**
* An abstract implementation of PluginManager.
*
* @author Dan Noguerol
*/
abstract public class AbstractPluginManager implements PluginManager {
private final Logger logger = LoggerFactory.getLogger(getClass());
abstract protected HobsonPlugin getLocalPluginInternal(PluginContext ctx);
abstract protected ConfigurationManager getConfigurationManager();
abstract protected EventManager getEventManager();
@Override
public HobsonLocalPluginDescriptor getLocalPlugin(PluginContext ctx) {
return getLocalPluginInternal(ctx).getDescriptor();
}
@Override
public PropertyContainer getLocalPluginConfiguration(PluginContext ctx) {
ConfigurationManager cfgManager = getConfigurationManager();
PropertyContainerClass configClass = getLocalPlugin(ctx).getConfigurationClass();
if (cfgManager != null && configClass != null) {
return new PropertyContainer(configClass.getContext(), cfgManager.getLocalPluginConfiguration(ctx));
} else {
return null;
}
}
@Override
public void setLocalPluginConfiguration(PluginContext ctx, Map<String,Object> config) {
try {
HobsonPlugin plugin = getLocalPluginInternal(ctx);
PropertyContainerClass pcc = plugin.getConfigurationClass();
pcc.validate(config);
getConfigurationManager().setLocalPluginConfiguration(ctx, config);
postPluginConfigurationUpdateEvent(ctx);
} catch (NotSerializableException e) {
throw new HobsonRuntimeException("Error setting plugin configuration for " + ctx + ": " + config, e);
}
}
@Override
public void setLocalPluginConfigurationProperty(PluginContext ctx, String name, Object value) {
try {
getConfigurationManager().setLocalPluginConfigurationProperty(ctx, name, value);
postPluginConfigurationUpdateEvent(ctx);
} catch (NotSerializableException e) {
throw new HobsonRuntimeException("Error setting plugin configuration property for " + ctx + ": \"" + name + "\"=\"" + value + "\"");
}
}
@Override
public Future startPluginDevice(final HobsonDeviceProxy device, final String name, final Map<String,Object> config, final Runnable runnable) {
HobsonPlugin plugin = getLocalPluginInternal(device.getContext().getPluginContext());
return plugin.getEventLoopExecutor().executeInEventLoop(new Runnable() {
@Override
public void run() {
// invoke device's onStartup callback
device.start(name, config);
// invoke follow-on
if (runnable != null) {
runnable.run();
}
}
});
}
@Override
public File getDataDirectory(PluginContext ctx) {
File f = new File(System.getProperty(ConfigurationManager.HOBSON_HOME, "."), "data");
if (!f.exists()) {
if (!f.mkdir()) {
logger.error("Error creating data directory");
}
}
return f;
}
@Override
public File getDataFile(PluginContext ctx, String filename) {
return new File(getDataDirectory(ctx), (ctx != null ? (ctx.getPluginId() + "$") : "") + filename);
}
@Override
public GlobalVariable getGlobalVariable(GlobalVariableContext gvctx) {
return null;
}
@Override
public Collection<GlobalVariable> getGlobalVariables(PluginContext pctx) {
return null;
}
@Override
public DeviceVariableState getLocalPluginDeviceVariable(DeviceVariableContext ctx) {
return getLocalPluginInternal(ctx.getPluginContext()).getDeviceVariableState(ctx.getDeviceContext().getDeviceId(), ctx.getName());
}
@Override
public boolean hasLocalPluginDeviceVariable(DeviceVariableContext ctx) {
return getLocalPluginInternal(ctx.getPluginContext()).hasDeviceVariableState(ctx.getDeviceContext().getDeviceId(), ctx.getName());
}
private void postPluginConfigurationUpdateEvent(PluginContext ctx) {
// post event
if (getEventManager() != null) {
getEventManager().postEvent(
ctx.getHubContext(),
new PluginConfigurationUpdateEvent(
System.currentTimeMillis(),
ctx,
getLocalPluginConfiguration(ctx)
)
);
}
}
}
| epl-1.0 |
liamh101/JavaUni | LabExercise9/comparestrings/src/comparestrings/CompareTest.java | 507 | package comparestrings;
public class CompareTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "Ant";
String s2 = "ant";
if (s1.compareTo(s2) < 0) { // then s1 is before s2
System.out.println(s1 + " is before " + s2);
}
else if (s1.compareTo(s2) == 0){// then s1 and s2 same
System.out.println(s1 + " is the same as " + s2);
}
else if (s1.compareTo(s2) > 0){// then s1 is after s2
System.out.println(s1 + " is after " + s2);
}
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/manual/NewObjectDeleteTest.java | 2243 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.manual;
import org.eclipse.persistence.testing.models.employee.domain.*;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.testing.framework.*;
public class NewObjectDeleteTest extends ManualVerifyTestCase {
public Employee employee;
public NewObjectDeleteTest() {
setDescription("Check the SQL to see if the new objects inserted are also deleted or not. The test case is a faliure if objects are not deleted.");
}
public void reset() {
rollbackTransaction();
getSession().getIdentityMapAccessor().initializeIdentityMaps();
}
protected void setup() {
beginTransaction();
}
protected void test() {
this.employee = (Employee)(new EmployeePopulator()).basicEmployeeExample1();
UnitOfWork uow = getSession().acquireUnitOfWork();
Employee workingCopy = (Employee)uow.registerObject(this.employee);
workingCopy.setFirstName("firstName");
uow.deleteObject(workingCopy);
uow.commit();
this.employee = (Employee)(new EmployeePopulator()).basicEmployeeExample2();
uow = getSession().acquireUnitOfWork();
UnitOfWork nuow = uow.acquireUnitOfWork();
workingCopy = (Employee)nuow.registerObject(this.employee);
workingCopy.setFirstName("firstName");
nuow.deleteObject(workingCopy);
nuow.commit();
uow.commit();
}
}
| epl-1.0 |
hms-dbmi/mallet_time | src/cc/mallet/topics/WorkerRunnable.java | 23662 | /* Copyright (C) 2005 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package cc.mallet.topics;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.*;
import java.io.*;
import java.text.NumberFormat;
import cc.mallet.types.*;
import cc.mallet.util.Randoms;
/**
* A parallel topic model runnable task.
*
* @author David Mimno, Andrew McCallum
*/
public class WorkerRunnable implements Runnable {
boolean isFinished = true;
ArrayList<TopicAssignment> data;
int startDoc, numDocs;
protected int numTopics; // Number of topics to be fit
// These values are used to encode type/topic counts as
// count/topic pairs in a single int.
protected int topicMask;
protected int topicBits;
protected int numTypes;
protected double[] alpha; // Dirichlet(alpha,alpha,...) is the distribution over topics
protected double alphaSum;
protected double beta; // Prior on per-topic multinomial distribution over words
protected double betaSum;
public static final double DEFAULT_BETA = 0.01;
protected double smoothingOnlyMass = 0.0;
protected double[] cachedCoefficients;
protected int[][] typeTopicCounts; // indexed by <feature index, topic index>
protected int[][][] typeTopicTimeCounts; //MTM - index by <feature index, topic index, time index>
protected int[] tokensPerTopic; // indexed by <topic index>
// for dirichlet estimation
protected int[] docLengthCounts; // histogram of document sizes
protected int[][] topicDocCounts; // histogram of document/topic counts, indexed by <topic index, sequence position index>
protected int[][][] topicTimeDocCounts; // histogram of document-time-topic counts, indexed by <topic index, time index, sequence position index>
boolean shouldSaveState = false;
boolean shouldBuildLocalCounts = true;
private static int numberOfTimeCluster = 15;
protected Randoms random;
public WorkerRunnable (int numTopics,
double[] alpha, double alphaSum,
double beta, Randoms random,
ArrayList<TopicAssignment> data,
int[][] typeTopicCounts,
int[][][] typeTopicTimeCounts,
int[] tokensPerTopic,
int startDoc, int numDocs) {
this.data = data;
this.numTopics = numTopics;
this.numTypes = typeTopicCounts.length;
if (Integer.bitCount(numTopics) == 1) {
// exact power of 2
topicMask = numTopics - 1;
topicBits = Integer.bitCount(topicMask);
}
else {
// otherwise add an extra bit
topicMask = Integer.highestOneBit(numTopics) * 2 - 1;
topicBits = Integer.bitCount(topicMask);
}
this.typeTopicCounts = typeTopicCounts;
this.typeTopicTimeCounts = typeTopicTimeCounts;
this.tokensPerTopic = tokensPerTopic;
this.alphaSum = alphaSum;
this.alpha = alpha;
this.beta = beta;
this.betaSum = beta * numTypes;
this.random = random;
this.startDoc = startDoc;
this.numDocs = numDocs;
cachedCoefficients = new double[ numTopics ];
//System.err.println("WorkerRunnable Thread: " + numTopics + " topics, " + topicBits + " topic bits, " +
// Integer.toBinaryString(topicMask) + " topic mask");
}
/**
* If there is only one thread, we don't need to go through
* communication overhead. This method asks this worker not
* to prepare local type-topic counts. The method should be
* called when we are using this code in a non-threaded environment.
*/
public void makeOnlyThread() {
shouldBuildLocalCounts = false;
}
public int[] getTokensPerTopic() { return tokensPerTopic; }
public int[][] getTypeTopicCounts() { return typeTopicCounts; }
public int[] getDocLengthCounts() { return docLengthCounts; }
public int[][] getTopicDocCounts() { return topicDocCounts; }
public int[][][] getTopicTimeDocCounts() { return topicTimeDocCounts; }
public void initializeAlphaStatistics(int size) {
docLengthCounts = new int[size];
topicDocCounts = new int[numTopics][size];
}
public void collectAlphaStatistics() {
shouldSaveState = true;
}
public void resetBeta(double beta, double betaSum) {
this.beta = beta;
this.betaSum = betaSum;
}
/**
* Once we have sampled the local counts, trash the
* "global" type topic counts and reuse the space to
* build a summary of the type topic counts specific to
* this worker's section of the corpus.
*/
public void buildLocalTypeTopicCounts () {
// Clear the topic totals
Arrays.fill(tokensPerTopic, 0);
// Clear the type/topic counts, only
// looking at the entries before the first 0 entry.
for (int type = 0; type < typeTopicCounts.length; type++) {
int[] topicCounts = typeTopicCounts[type];
int position = 0;
while (position < topicCounts.length &&
topicCounts[position] > 0) {
topicCounts[position] = 0;
position++;
}
}
//MTM - This is a questionable method of clearing arrays?
for (int time = 0; time < numberOfTimeCluster; time++)
{
for (int type = 0; type < typeTopicTimeCounts[time].length; type++) {
int[] topicCounts = typeTopicTimeCounts[time][type];
int position = 0;
while (position < topicCounts.length &&
topicCounts[position] > 0) {
topicCounts[position] = 0;
position++;
}
}
}
for (int doc = startDoc;
doc < data.size() && doc < startDoc + numDocs;
doc++) {
TopicAssignment document = data.get(doc);
FeatureSequence tokens = (FeatureSequence) document.instance.getData();
FeatureSequence topicSequence = (FeatureSequence) document.topicSequence;
int currentDocTimeValue = 0;
boolean validFile = false;
//MTM - This is a hack to get the current time window.
String currentDocName = document.instance.getName().toString();
Pattern p = Pattern.compile("[^/]+(?=/[^/]+$)");
Matcher m = p.matcher(currentDocName);
if (m.find()) {
try {
currentDocTimeValue = Integer.parseInt(m.group(0)) - 1;
validFile = true;
} catch (NumberFormatException e) {
System.out.println("Skipped non-conforming folder format.");
}
}
if(validFile)
{
int[] topics = topicSequence.getFeatures();
for (int position = 0; position < tokens.size(); position++) {
int topic = topics[position];
if (topic == ParallelTopicModel.UNASSIGNED_TOPIC) { continue; }
tokensPerTopic[topic]++;
// The format for these arrays is
// the topic in the rightmost bits
// the count in the remaining (left) bits.
// Since the count is in the high bits, sorting (desc)
// by the numeric value of the int guarantees that
// higher counts will be before the lower counts.
int type = tokens.getIndexAtPosition(position);
//int[] currentTypeTopicCounts = typeTopicCounts[ type ];
int[] currentTypeTopicCounts = typeTopicTimeCounts[currentDocTimeValue][ type ];
// Start by assuming that the array is either empty
// or is in sorted (descending) order.
// Here we are only adding counts, so if we find
// an existing location with the topic, we only need
// to ensure that it is not larger than its left neighbor.
int index = 0;
int currentTopic = currentTypeTopicCounts[index] & topicMask;
int currentValue;
while (currentTypeTopicCounts[index] > 0 && currentTopic != topic) {
index++;
if (index == currentTypeTopicCounts.length) {
System.out.println("overflow on type " + type);
}
currentTopic = currentTypeTopicCounts[index] & topicMask;
}
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (currentValue == 0) {
// new value is 1, so we don't have to worry about sorting
// (except by topic suffix, which doesn't matter)
currentTypeTopicCounts[index] =
(1 << topicBits) + topic;
}
else {
currentTypeTopicCounts[index] =
((currentValue + 1) << topicBits) + topic;
// Now ensure that the array is still sorted by
// bubbling this value up.
while (index > 0 &&
currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index--;
}
}
}
}
}
}
public void run () {
try {
if (! isFinished) { System.out.println("already running!"); return; }
isFinished = false;
// Initialize the smoothing-only sampling bucket
smoothingOnlyMass = 0;
// Initialize the cached coefficients, using only smoothing.
// These values will be selectively replaced in documents with
// non-zero counts in particular topics.
for (int topic=0; topic < numTopics; topic++) {
smoothingOnlyMass += alpha[topic] * beta / (tokensPerTopic[topic] + betaSum);
cachedCoefficients[topic] = alpha[topic] / (tokensPerTopic[topic] + betaSum);
}
for (int doc = startDoc;
doc < data.size() && doc < startDoc + numDocs;
doc++) {
/*
if (doc % 10000 == 0) {
System.out.println("processing doc " + doc);
}
*/
FeatureSequence tokenSequence = (FeatureSequence) data.get(doc).instance.getData();
LabelSequence topicSequence = (LabelSequence) data.get(doc).topicSequence;
//MTM - This is a hack to get the current time window.
String currentDocName = data.get(doc).instance.getName().toString();
Pattern p = Pattern.compile("[^/]+(?=/[^/]+$)");
Matcher m = p.matcher(currentDocName);
if (m.find()) {
try {
//Remove one because arrays are 0 based, therefore time groups are 0 based (unlike file system)
int currentDocTimeValue = Integer.parseInt(m.group(0)) -1;
sampleTopicsForOneDoc (tokenSequence, topicSequence, true, currentDocTimeValue);
} catch (NumberFormatException e) {
System.out.println("Skipped non-conforming folder format.");
}
}
}
if (shouldBuildLocalCounts) {
buildLocalTypeTopicCounts();
}
shouldSaveState = false;
isFinished = true;
} catch (Exception e) {
e.printStackTrace();
}
}
protected void sampleTopicsForOneDoc (FeatureSequence tokenSequence,
FeatureSequence topicSequence,
boolean readjustTopicsAndStats /* currently ignored */,
int docTime) {
//MTM - For a given document oneDocTopics[position]=Topic Assignment
int[] oneDocTopics = topicSequence.getFeatures();
int[] currentTypeTopicCounts;
int[] currentTypeTopicTimeCounts;
int type, oldTopic, newTopic;
double topicWeightsSum;
int docLength = tokenSequence.getLength();
//MTM - Number of words assigned per topic.
int[] localTopicCounts = new int[numTopics];
int[] localTopicIndex = new int[numTopics];
//MTM - populate topic counts, Number of words assigned to a topic.
for (int position = 0; position < docLength; position++) {
if (oneDocTopics[position] == ParallelTopicModel.UNASSIGNED_TOPIC) { continue; }
localTopicCounts[oneDocTopics[position]]++;
}
// Build an array that densely lists the topics that have non-zero counts.
int denseIndex = 0;
for (int topic = 0; topic < numTopics; topic++) {
if (localTopicCounts[topic] != 0) {
localTopicIndex[denseIndex] = topic;
denseIndex++;
}
}
// Record the total number of non-zero topics
int nonZeroTopics = denseIndex;
// Initialize the topic count/beta sampling bucket
double topicBetaMass = 0.0;
// Initialize cached coefficients and the topic/beta normalizing constant.
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
//MTM - Topic Number.
int topic = localTopicIndex[denseIndex];
//MTM - Number of words assigned to a topic.
int n = localTopicCounts[topic];
// initialize the normalization constant for the (B * n_{t|d}) term
topicBetaMass += beta * n / (tokensPerTopic[topic] + betaSum);
// update the coefficients for the non-zero topics
cachedCoefficients[topic] = (alpha[topic] + n) / (tokensPerTopic[topic] + betaSum);
}
double topicTermMass = 0.0;
double[] topicTermScores = new double[numTopics];
int[] topicTermIndices;
int[] topicTermValues;
int i;
double score;
// Iterate over the positions (words) in the document
for (int position = 0; position < docLength; position++) {
type = tokenSequence.getIndexAtPosition(position);
oldTopic = oneDocTopics[position];
//MTM - This needs to pull based on time.
//currentTypeTopicCounts = typeTopicCounts[type];
//currentTypeTopicTimeCounts = typeTopicTimeCounts[docTime][type];
currentTypeTopicCounts = typeTopicTimeCounts[docTime][type];
if (oldTopic != ParallelTopicModel.UNASSIGNED_TOPIC) {
// Remove this token from all counts.
// Remove this topic's contribution to the
// normalizing constants
smoothingOnlyMass -= alpha[oldTopic] * beta /
(tokensPerTopic[oldTopic] + betaSum);
topicBetaMass -= beta * localTopicCounts[oldTopic] /
(tokensPerTopic[oldTopic] + betaSum);
// Decrement the local doc/topic counts
localTopicCounts[oldTopic]--;
// Maintain the dense index, if we are deleting
// the old topic
if (localTopicCounts[oldTopic] == 0) {
// First get to the dense location associated with
// the old topic.
denseIndex = 0;
// We know it's in there somewhere, so we don't
// need bounds checking.
while (localTopicIndex[denseIndex] != oldTopic) {
denseIndex++;
}
// shift all remaining dense indices to the left.
while (denseIndex < nonZeroTopics) {
if (denseIndex < localTopicIndex.length - 1) {
localTopicIndex[denseIndex] =
localTopicIndex[denseIndex + 1];
}
denseIndex++;
}
nonZeroTopics --;
}
// Decrement the global topic count totals
tokensPerTopic[oldTopic]--;
assert(tokensPerTopic[oldTopic] >= 0) : "old Topic " + oldTopic + " below 0";
// Add the old topic's contribution back into the
// normalizing constants.
smoothingOnlyMass += alpha[oldTopic] * beta /
(tokensPerTopic[oldTopic] + betaSum);
topicBetaMass += beta * localTopicCounts[oldTopic] /
(tokensPerTopic[oldTopic] + betaSum);
// Reset the cached coefficient for this topic
cachedCoefficients[oldTopic] =
(alpha[oldTopic] + localTopicCounts[oldTopic]) /
(tokensPerTopic[oldTopic] + betaSum);
}
// Now go over the type/topic counts, decrementing
// where appropriate, and calculating the score
// for each topic at the same time.
int index = 0;
int currentTopic, currentValue;
boolean alreadyDecremented = (oldTopic == ParallelTopicModel.UNASSIGNED_TOPIC);
topicTermMass = 0.0;
while (index < currentTypeTopicCounts.length &&
currentTypeTopicCounts[index] > 0) {
currentTopic = currentTypeTopicCounts[index] & topicMask;
currentValue = currentTypeTopicCounts[index] >> topicBits;
if (! alreadyDecremented &&
currentTopic == oldTopic) {
// We're decrementing and adding up the
// sampling weights at the same time, but
// decrementing may require us to reorder
// the topics, so after we're done here,
// look at this cell in the array again.
currentValue --;
if (currentValue == 0) {
currentTypeTopicCounts[index] = 0;
}
else {
currentTypeTopicCounts[index] =
(currentValue << topicBits) + oldTopic;
}
// Shift the reduced value to the right, if necessary.
int subIndex = index;
while (subIndex < currentTypeTopicCounts.length - 1 &&
currentTypeTopicCounts[subIndex] < currentTypeTopicCounts[subIndex + 1]) {
int temp = currentTypeTopicCounts[subIndex];
currentTypeTopicCounts[subIndex] = currentTypeTopicCounts[subIndex + 1];
currentTypeTopicCounts[subIndex + 1] = temp;
subIndex++;
}
alreadyDecremented = true;
}
else {
score =
cachedCoefficients[currentTopic] * currentValue;
topicTermMass += score;
topicTermScores[index] = score;
index++;
}
}
double sample = random.nextUniform() * (smoothingOnlyMass + topicBetaMass + topicTermMass);
double origSample = sample;
// Make sure it actually gets set
newTopic = -1;
if (sample < topicTermMass) {
//topicTermCount++;
i = -1;
while (sample > 0) {
i++;
sample -= topicTermScores[i];
}
newTopic = currentTypeTopicCounts[i] & topicMask;
currentValue = currentTypeTopicCounts[i] >> topicBits;
currentTypeTopicCounts[i] = ((currentValue + 1) << topicBits) + newTopic;
// Bubble the new value up, if necessary
while (i > 0 &&
currentTypeTopicCounts[i] > currentTypeTopicCounts[i - 1]) {
int temp = currentTypeTopicCounts[i];
currentTypeTopicCounts[i] = currentTypeTopicCounts[i - 1];
currentTypeTopicCounts[i - 1] = temp;
i--;
}
}
else {
sample -= topicTermMass;
if (sample < topicBetaMass) {
//betaTopicCount++;
sample /= beta;
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
sample -= localTopicCounts[topic] /
(tokensPerTopic[topic] + betaSum);
if (sample <= 0.0) {
newTopic = topic;
break;
}
}
}
else {
//smoothingOnlyCount++;
sample -= topicBetaMass;
sample /= beta;
newTopic = 0;
sample -= alpha[newTopic] /
(tokensPerTopic[newTopic] + betaSum);
while (sample > 0.0) {
newTopic++;
sample -= alpha[newTopic] /
(tokensPerTopic[newTopic] + betaSum);
}
}
// Move to the position for the new topic,
// which may be the first empty position if this
// is a new topic for this word.
index = 0;
while (currentTypeTopicCounts[index] > 0 &&
(currentTypeTopicCounts[index] & topicMask) != newTopic) {
index++;
if (index == currentTypeTopicCounts.length) {
System.err.println("type: " + type + " new topic: " + newTopic);
for (int k=0; k<currentTypeTopicCounts.length; k++) {
System.err.print((currentTypeTopicCounts[k] & topicMask) + ":" +
(currentTypeTopicCounts[k] >> topicBits) + " ");
}
System.err.println();
}
}
// index should now be set to the position of the new topic,
// which may be an empty cell at the end of the list.
if (currentTypeTopicCounts[index] == 0) {
// inserting a new topic, guaranteed to be in
// order w.r.t. count, if not topic.
currentTypeTopicCounts[index] = (1 << topicBits) + newTopic;
}
else {
currentValue = currentTypeTopicCounts[index] >> topicBits;
currentTypeTopicCounts[index] = ((currentValue + 1) << topicBits) + newTopic;
// Bubble the increased value left, if necessary
while (index > 0 &&
currentTypeTopicCounts[index] > currentTypeTopicCounts[index - 1]) {
int temp = currentTypeTopicCounts[index];
currentTypeTopicCounts[index] = currentTypeTopicCounts[index - 1];
currentTypeTopicCounts[index - 1] = temp;
index--;
}
}
}
if (newTopic == -1) {
System.err.println("WorkerRunnable sampling error: "+ origSample + " " + sample + " " + smoothingOnlyMass + " " +
topicBetaMass + " " + topicTermMass);
newTopic = numTopics-1; // TODO is this appropriate
//throw new IllegalStateException ("WorkerRunnable: New topic not sampled.");
}
//assert(newTopic != -1);
// Put that new topic into the counts
oneDocTopics[position] = newTopic;
smoothingOnlyMass -= alpha[newTopic] * beta /
(tokensPerTopic[newTopic] + betaSum);
topicBetaMass -= beta * localTopicCounts[newTopic] /
(tokensPerTopic[newTopic] + betaSum);
localTopicCounts[newTopic]++;
// If this is a new topic for this document,
// add the topic to the dense index.
if (localTopicCounts[newTopic] == 1) {
// First find the point where we
// should insert the new topic by going to
// the end (which is the only reason we're keeping
// track of the number of non-zero
// topics) and working backwards
denseIndex = nonZeroTopics;
while (denseIndex > 0 &&
localTopicIndex[denseIndex - 1] > newTopic) {
localTopicIndex[denseIndex] =
localTopicIndex[denseIndex - 1];
denseIndex--;
}
localTopicIndex[denseIndex] = newTopic;
nonZeroTopics++;
}
tokensPerTopic[newTopic]++;
// update the coefficients for the non-zero topics
cachedCoefficients[newTopic] =
(alpha[newTopic] + localTopicCounts[newTopic]) /
(tokensPerTopic[newTopic] + betaSum);
smoothingOnlyMass += alpha[newTopic] * beta /
(tokensPerTopic[newTopic] + betaSum);
topicBetaMass += beta * localTopicCounts[newTopic] /
(tokensPerTopic[newTopic] + betaSum);
}
if (shouldSaveState) {
// Update the document-topic count histogram,
// for dirichlet estimation
docLengthCounts[ docLength ]++;
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
topicDocCounts[topic][ localTopicCounts[topic] ]++;
topicTimeDocCounts[topic][docTime][localTopicCounts[topic]]++;
}
}
// Clean up our mess: reset the coefficients to values with only
// smoothing. The next doc will update its own non-zero topics...
for (denseIndex = 0; denseIndex < nonZeroTopics; denseIndex++) {
int topic = localTopicIndex[denseIndex];
cachedCoefficients[topic] =
alpha[topic] / (tokensPerTopic[topic] + betaSum);
}
}
}
| epl-1.0 |
ossmeter/ossmeter | metric-providers/org.ossmeter.metricprovider.trans.requestreplyclassification/src/org/ossmeter/metricprovider/trans/requestreplyclassification/RequestReplyClassificationTransMetricProvider.java | 12835 | /*******************************************************************************
* Copyright (c) 2014 OSSMETER Partners.
* 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:
* Yannis Korkontzelos - Implementation.
*******************************************************************************/
package org.ossmeter.metricprovider.trans.requestreplyclassification;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.time.DurationFormatUtils;
import org.ossmeter.metricprovider.trans.requestreplyclassification.model.BugTrackerComments;
import org.ossmeter.metricprovider.trans.requestreplyclassification.model.NewsgroupArticles;
import org.ossmeter.metricprovider.trans.requestreplyclassification.model.RequestReplyClassificationTransMetric;
import org.ossmeter.platform.Date;
import org.ossmeter.platform.IMetricProvider;
import org.ossmeter.platform.ITransientMetricProvider;
import org.ossmeter.platform.MetricProviderContext;
import org.ossmeter.platform.delta.ProjectDelta;
import org.ossmeter.platform.delta.bugtrackingsystem.BugTrackingSystemComment;
import org.ossmeter.platform.delta.bugtrackingsystem.BugTrackingSystemDelta;
import org.ossmeter.platform.delta.bugtrackingsystem.BugTrackingSystemProjectDelta;
import org.ossmeter.platform.delta.bugtrackingsystem.PlatformBugTrackingSystemManager;
import org.ossmeter.platform.delta.communicationchannel.CommunicationChannelArticle;
import org.ossmeter.platform.delta.communicationchannel.CommunicationChannelDelta;
import org.ossmeter.platform.delta.communicationchannel.CommunicationChannelProjectDelta;
import org.ossmeter.platform.delta.communicationchannel.PlatformCommunicationChannelManager;
import org.ossmeter.repository.model.BugTrackingSystem;
import org.ossmeter.repository.model.CommunicationChannel;
import org.ossmeter.repository.model.Project;
import org.ossmeter.repository.model.cc.nntp.NntpNewsGroup;
import org.ossmeter.repository.model.sourceforge.Discussion;
import org.ossmeter.requestreplyclassifier.opennlptartarus.libsvm.ClassificationInstance;
import org.ossmeter.requestreplyclassifier.opennlptartarus.libsvm.Classifier;
import com.mongodb.DB;
public class RequestReplyClassificationTransMetricProvider implements ITransientMetricProvider<RequestReplyClassificationTransMetric>{
protected PlatformBugTrackingSystemManager platformBugTrackingSystemManager;
protected PlatformCommunicationChannelManager communicationChannelManager;
@Override
public String getIdentifier() {
return RequestReplyClassificationTransMetricProvider.class.getCanonicalName();
}
@Override
public boolean appliesTo(Project project) {
for (CommunicationChannel communicationChannel: project.getCommunicationChannels()) {
if (communicationChannel instanceof NntpNewsGroup) return true;
if (communicationChannel instanceof Discussion) return true;
}
return !project.getBugTrackingSystems().isEmpty();
}
@Override
public void setUses(List<IMetricProvider> uses) {
// DO NOTHING -- we don't use anything
}
@Override
public List<String> getIdentifiersOfUses() {
return Collections.emptyList();
}
@Override
public void setMetricProviderContext(MetricProviderContext context) {
this.platformBugTrackingSystemManager = context.getPlatformBugTrackingSystemManager();
this.communicationChannelManager = context.getPlatformCommunicationChannelManager();
}
@Override
public RequestReplyClassificationTransMetric adapt(DB db) {
return new RequestReplyClassificationTransMetric(db);
}
@Override
public void measure(Project project, ProjectDelta projectDelta, RequestReplyClassificationTransMetric db) {
final long startTime = System.currentTimeMillis();
long previousTime = startTime;
// System.err.println("Started " + getIdentifier());
BugTrackingSystemProjectDelta btspDelta = projectDelta.getBugTrackingSystemDelta();
clearDB(db);
Classifier classifier = new Classifier();
for (BugTrackingSystemDelta bugTrackingSystemDelta : btspDelta.getBugTrackingSystemDeltas()) {
BugTrackingSystem bugTracker = bugTrackingSystemDelta.getBugTrackingSystem();
for (BugTrackingSystemComment comment: bugTrackingSystemDelta.getComments()) {
BugTrackerComments bugTrackerComments = findBugTrackerComment(db, bugTracker, comment);
if (bugTrackerComments == null) {
bugTrackerComments = new BugTrackerComments();
bugTrackerComments.setBugTrackerId(bugTracker.getOSSMeterId());
bugTrackerComments.setBugId(comment.getBugId());
bugTrackerComments.setCommentId(comment.getCommentId());
bugTrackerComments.setDate(new Date(comment.getCreationTime()).toString());
db.getBugTrackerComments().add(bugTrackerComments);
}
prepareBugTrackerCommentInstance(classifier, bugTracker, comment);
}
db.sync();
}
previousTime = printTimeMessage(startTime, previousTime, classifier.instanceListSize(),
"prepared bug comments");
CommunicationChannelProjectDelta ccpDelta = projectDelta.getCommunicationChannelDelta();
for ( CommunicationChannelDelta communicationChannelDelta: ccpDelta.getCommunicationChannelSystemDeltas()) {
CommunicationChannel communicationChannel = communicationChannelDelta.getCommunicationChannel();
String communicationChannelName;
if (!(communicationChannel instanceof NntpNewsGroup))
communicationChannelName = communicationChannel.getUrl();
else {
NntpNewsGroup newsgroup = (NntpNewsGroup) communicationChannel;
communicationChannelName = newsgroup.getNewsGroupName();
}
for (CommunicationChannelArticle article: communicationChannelDelta.getArticles()) {
NewsgroupArticles newsgroupArticles =
findNewsgroupArticle(db, communicationChannelName, article);
if (newsgroupArticles == null) {
newsgroupArticles = new NewsgroupArticles();
newsgroupArticles.setNewsgroupName(communicationChannelName);
newsgroupArticles.setArticleNumber(article.getArticleNumber());
newsgroupArticles.setDate(new Date(article.getDate()).toString());
db.getNewsgroupArticles().add(newsgroupArticles);
}
prepareNewsgroupArticleInstance(classifier, communicationChannelName, article);
}
db.sync();
}
previousTime = printTimeMessage(startTime, previousTime, classifier.instanceListSize(),
"prepared newsgroup articles");
classifier.classify();
previousTime = printTimeMessage(startTime, previousTime, classifier.instanceListSize(),
"classifier.classify() finished");
for (BugTrackingSystemDelta bugTrackingSystemDelta : btspDelta.getBugTrackingSystemDeltas()) {
BugTrackingSystem bugTracker = bugTrackingSystemDelta.getBugTrackingSystem();
for (BugTrackingSystemComment comment: bugTrackingSystemDelta.getComments()) {
BugTrackerComments bugTrackerComments = findBugTrackerComment(db, bugTracker, comment);
String classificationResult = getBugTrackerCommentClass(classifier, bugTracker, comment);
bugTrackerComments.setClassificationResult(classificationResult);
}
db.sync();
}
previousTime = printTimeMessage(startTime, previousTime, classifier.instanceListSize(),
"stored classified bug comments");
for ( CommunicationChannelDelta communicationChannelDelta: ccpDelta.getCommunicationChannelSystemDeltas()) {
CommunicationChannel communicationChannel = communicationChannelDelta.getCommunicationChannel();
String communicationChannelName;
if (!(communicationChannel instanceof NntpNewsGroup))
communicationChannelName = communicationChannel.getUrl();
else {
NntpNewsGroup newsgroup = (NntpNewsGroup) communicationChannel;
communicationChannelName = newsgroup.getNewsGroupName();
}
for (CommunicationChannelArticle article: communicationChannelDelta.getArticles()) {
NewsgroupArticles newsgroupArticles =
findNewsgroupArticle(db, communicationChannelName, article);
String classificationResult =
getNewsgroupArticleClass(classifier, communicationChannelName, article);
newsgroupArticles.setClassificationResult(classificationResult);
}
db.sync();
}
// previousTime = printTimeMessage(startTime, previousTime, classifier.instanceListSize(),
// "stored classified newsgroup articles");
}
private long printTimeMessage(long startTime, long previousTime, int size, String message) {
long currentTime = System.currentTimeMillis();
System.err.println(time(currentTime - previousTime) + "\t" +
time(currentTime - startTime) + "\t" +
size + "\t" + message);
return currentTime;
}
private String time(long timeInMS) {
return DurationFormatUtils.formatDuration(timeInMS, "HH:mm:ss,SSS");
}
private void prepareBugTrackerCommentInstance(Classifier classifier, BugTrackingSystem bugTracker,
BugTrackingSystemComment comment) {
ClassificationInstance classificationInstance = new ClassificationInstance();
classificationInstance.setBugTrackerId(bugTracker.getOSSMeterId());
classificationInstance.setBugId(comment.getBugId());
classificationInstance.setCommentId(comment.getCommentId());
if (comment.getText() == null) {
classificationInstance.setText("");
} else {
classificationInstance.setText(comment.getText());
}
classifier.add(classificationInstance);
}
private String getBugTrackerCommentClass(Classifier classifier, BugTrackingSystem bugTracker,
BugTrackingSystemComment comment) {
ClassificationInstance classificationInstance = new ClassificationInstance();
classificationInstance.setBugTrackerId(bugTracker.getOSSMeterId());
classificationInstance.setBugId(comment.getBugId());
classificationInstance.setCommentId(comment.getCommentId());
return classifier.getClassificationResult(classificationInstance);
}
private void prepareNewsgroupArticleInstance(Classifier classifier,
String communicationChannelName, CommunicationChannelArticle article) {
ClassificationInstance classificationInstance = new ClassificationInstance();
classificationInstance.setNewsgroupName(communicationChannelName);
classificationInstance.setArticleNumber(article.getArticleNumber());
classificationInstance.setSubject(article.getSubject());
classificationInstance.setText(article.getText());
classifier.add(classificationInstance);
}
private String getNewsgroupArticleClass(Classifier classifier, String communicationChannelName,
CommunicationChannelArticle article) {
ClassificationInstance classificationInstance = new ClassificationInstance();
classificationInstance.setNewsgroupName(communicationChannelName);
classificationInstance.setArticleNumber(article.getArticleNumber());
classificationInstance.setSubject(article.getSubject());
return classifier.getClassificationResult(classificationInstance);
}
private BugTrackerComments findBugTrackerComment(RequestReplyClassificationTransMetric db,
BugTrackingSystem bugTracker, BugTrackingSystemComment comment) {
BugTrackerComments bugTrackerCommentsData = null;
Iterable<BugTrackerComments> bugTrackerCommentsIt =
db.getBugTrackerComments().
find(BugTrackerComments.BUGTRACKERID.eq(bugTracker.getOSSMeterId()),
BugTrackerComments.BUGID.eq(comment.getBugId()),
BugTrackerComments.COMMENTID.eq(comment.getCommentId()));
for (BugTrackerComments bcd: bugTrackerCommentsIt) {
bugTrackerCommentsData = bcd;
}
return bugTrackerCommentsData;
}
private NewsgroupArticles findNewsgroupArticle(RequestReplyClassificationTransMetric db,
String communicationChannelName, CommunicationChannelArticle article) {
NewsgroupArticles newsgroupArticles = null;
Iterable<NewsgroupArticles> newsgroupArticlesIt =
db.getNewsgroupArticles().
find(NewsgroupArticles.NEWSGROUPNAME.eq(communicationChannelName),
NewsgroupArticles.ARTICLENUMBER.eq(article.getArticleNumber()));
for (NewsgroupArticles nad: newsgroupArticlesIt) {
newsgroupArticles = nad;
}
return newsgroupArticles;
}
private void clearDB(RequestReplyClassificationTransMetric db) {
db.getBugTrackerComments().getDbCollection().drop();
}
@Override
public String getShortIdentifier() {
// TODO Auto-generated method stub
return "requestreplyclassification";
}
@Override
public String getFriendlyName() {
return "Request Reply Classification";
}
@Override
public String getSummaryInformation() {
return "This metric computes if each bug comment or newsgroup article is a " +
"request of a reply.";
}
}
| epl-1.0 |
occiware/Multi-Cloud-Studio | plugins/org.eclipse.cmf.occi.multicloud.aws.ec2.edit/src-gen/org/eclipse/cmf/occi/multicloud/aws/ec2/provider/M5_24xlargeItemProvider.java | 6095 | /**
* Copyright (c) 2015-2017 Obeo, Inria
* 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:
* - William Piers <william.piers@obeo.fr>
* - Philippe Merle <philippe.merle@inria.fr>
* - Faiez Zalila <faiez.zalila@inria.fr>
*/
package org.eclipse.cmf.occi.multicloud.aws.ec2.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.cmf.occi.multicloud.aws.ec2.Ec2Package;
import org.eclipse.cmf.occi.multicloud.aws.ec2.M5_24xlarge;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link org.eclipse.cmf.occi.multicloud.aws.ec2.M5_24xlarge} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class M5_24xlargeItemProvider extends GeneralpurposeItemProvider {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public M5_24xlargeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addOcciComputeMemoryPropertyDescriptor(object);
addInstanceTypePropertyDescriptor(object);
addOcciComputeCoresPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Occi Compute Memory feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOcciComputeMemoryPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_M5_24xlarge_occiComputeMemory_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_M5_24xlarge_occiComputeMemory_feature", "_UI_M5_24xlarge_type"),
Ec2Package.eINSTANCE.getM5_24xlarge_OcciComputeMemory(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Instance Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addInstanceTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_M5_24xlarge_instanceType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_M5_24xlarge_instanceType_feature", "_UI_M5_24xlarge_type"),
Ec2Package.eINSTANCE.getM5_24xlarge_InstanceType(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Occi Compute Cores feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addOcciComputeCoresPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_M5_24xlarge_occiComputeCores_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_M5_24xlarge_occiComputeCores_feature", "_UI_M5_24xlarge_type"),
Ec2Package.eINSTANCE.getM5_24xlarge_OcciComputeCores(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This returns M5_24xlarge.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/M5_24xlarge"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
Float labelValue = ((M5_24xlarge)object).getOcciComputeMemory();
String label = labelValue == null ? null : labelValue.toString();
return label == null || label.length() == 0 ?
getString("_UI_M5_24xlarge_type") :
getString("_UI_M5_24xlarge_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(M5_24xlarge.class)) {
case Ec2Package.M5_24XLARGE__OCCI_COMPUTE_MEMORY:
case Ec2Package.M5_24XLARGE__INSTANCE_TYPE:
case Ec2Package.M5_24XLARGE__OCCI_COMPUTE_CORES:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| epl-1.0 |
bradsdavis/cxml-api | src/main/java/org/cxml/catalog/ShipNoticeReleaseInfo.java | 3704 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2
// 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.09.23 at 11:07:02 AM CEST
//
package org.cxml.catalog;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"shipNoticeReferenceOrShipNoticeIDInfo",
"unitOfMeasure"
})
@XmlRootElement(name = "ShipNoticeReleaseInfo")
public class ShipNoticeReleaseInfo {
@XmlAttribute(name = "receivedQuantity", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String receivedQuantity;
@XmlElements({
@XmlElement(name = "ShipNoticeReference", required = true, type = ShipNoticeReference.class),
@XmlElement(name = "ShipNoticeIDInfo", required = true, type = ShipNoticeIDInfo.class)
})
protected List<Object> shipNoticeReferenceOrShipNoticeIDInfo;
@XmlElement(name = "UnitOfMeasure", required = true)
protected String unitOfMeasure;
/**
* Gets the value of the receivedQuantity property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReceivedQuantity() {
return receivedQuantity;
}
/**
* Sets the value of the receivedQuantity property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReceivedQuantity(String value) {
this.receivedQuantity = value;
}
/**
* Gets the value of the shipNoticeReferenceOrShipNoticeIDInfo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the shipNoticeReferenceOrShipNoticeIDInfo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getShipNoticeReferenceOrShipNoticeIDInfo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ShipNoticeReference }
* {@link ShipNoticeIDInfo }
*
*
*/
public List<Object> getShipNoticeReferenceOrShipNoticeIDInfo() {
if (shipNoticeReferenceOrShipNoticeIDInfo == null) {
shipNoticeReferenceOrShipNoticeIDInfo = new ArrayList<Object>();
}
return this.shipNoticeReferenceOrShipNoticeIDInfo;
}
/**
* Gets the value of the unitOfMeasure property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnitOfMeasure() {
return unitOfMeasure;
}
/**
* Sets the value of the unitOfMeasure property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnitOfMeasure(String value) {
this.unitOfMeasure = value;
}
}
| epl-1.0 |
abstratt/textuml | plugins/com.abstratt.mdd.frontend.core/src/com/abstratt/mdd/frontend/internal/core/ReferenceTracker.java | 5160 | /**
*
*/
package com.abstratt.mdd.frontend.internal.core;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Consumer;
import com.abstratt.mdd.core.IBasicRepository;
import com.abstratt.mdd.core.MDDCore;
import com.abstratt.mdd.core.Step;
import com.abstratt.mdd.frontend.core.InternalProblem;
import com.abstratt.mdd.frontend.core.spi.AbortedCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedStatementCompilationException;
import com.abstratt.mdd.frontend.core.spi.IDeferredReference;
import com.abstratt.mdd.frontend.core.spi.IProblemTracker;
import com.abstratt.mdd.frontend.core.spi.IReferenceTracker;
import com.abstratt.pluginutils.LogUtils;
public class ReferenceTracker implements IReferenceTracker {
private static class Stage implements Comparable<Stage> {
private Collection<IDeferredReference> references;
private Step sequence;
public Stage(Step sequence) {
this.sequence = sequence;
this.references = sequence.isOrdered() ? Collections
.synchronizedSortedSet(new TreeSet<IDeferredReference>()) : Collections
.synchronizedList(new LinkedList<IDeferredReference>());
}
public int compareTo(Stage another) {
return sequence.compareTo(another.sequence);
}
@Override
public boolean equals(Object another) {
return compareTo((Stage) another) == 0;
}
@Override
public int hashCode() {
return sequence.hashCode();
}
@Override
public String toString() {
return sequence.name() + "(" + references.size() + ")";
}
public IDeferredReference nextReference() {
if (references.isEmpty())
return null;
Iterator<IDeferredReference> iterator = references.iterator();
IDeferredReference next = iterator.next();
iterator.remove();
return next;
}
public Step getSequence() {
return sequence;
}
}
private SortedSet<Stage> stages = Collections.synchronizedSortedSet(new TreeSet<Stage>());
private IBasicRepository repository;
@Override
public void add(IDeferredReference ref, Step step) {
if (repository != null && step.compareTo(firstStage().getSequence()) < 0) {
// resolve right away
ref.resolve(this.repository);
return;
}
Stage stage = getStage(step);
stage.references.add(ref);
}
private Stage getStage(Step step) {
for (Stage stage : stages)
if (stage.sequence.compareTo(step) == 0)
return stage;
Stage newStage = new Stage(step);
stages.add(newStage);
return newStage;
}
@Override
public void resolve(IBasicRepository repository, IProblemTracker problemTracker, IStepListener stepListener) {
if (stepListener == null) {
stepListener = new IStepListener() {};
}
if (this.repository != null)
throw new IllegalStateException("Already resolving");
this.repository = repository;
try {
while (!stages.isEmpty()) {
Stage currentStage = firstStage();
stepListener.before(currentStage.getSequence());
for (IDeferredReference ref; (ref = currentStage.nextReference()) != null;) {
try {
ref.resolve(repository);
} catch (AbortedStatementCompilationException e) {
// continue with next symbol
} catch (AbortedCompilationException e) {
throw e;
} catch (RuntimeException e) {
final InternalProblem toReport = new InternalProblem(e);
problemTracker.add(toReport);
LogUtils.logError(MDDCore.PLUGIN_ID, "Unexpected exception while compiling", e);
}
// if a new reference has been added by the current
// reference to a previous stage,
// abort, as we need to resolve it first
if (firstStage().compareTo(currentStage) < 0)
break;
}
if (currentStage.references.isEmpty()) {
// once we are done with the current stage, remove it from the
// list (but might pop-up back later)
stages.remove(currentStage);
stepListener.after(currentStage.getSequence());
}
}
} finally {
this.repository = null;
}
}
private Stage firstStage() {
return stages.isEmpty() ? null : stages.first();
}
} | epl-1.0 |
ObeoNetwork/M2Doc | plugins/org.obeonetwork.m2doc.cdo/src/org/obeonetwork/m2doc/cdo/M2DocCDOUtils.java | 8898 | /*******************************************************************************
* Copyright (c) 2017 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* Obeo - initial API and implementation and/or initial documentation
* ...
*******************************************************************************/
package org.obeonetwork.m2doc.cdo;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.cdo.common.branch.CDOBranch;
import org.eclipse.emf.cdo.common.branch.CDOBranchHandler;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.net4j.CDONet4jSessionConfiguration;
import org.eclipse.emf.cdo.net4j.CDONet4jUtil;
import org.eclipse.emf.cdo.session.CDOSession;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.net4j.Net4jUtil;
import org.eclipse.net4j.connector.ConnectorException;
import org.eclipse.net4j.connector.IConnector;
import org.eclipse.net4j.tcp.TCPUtil;
import org.eclipse.net4j.util.container.ContainerUtil;
import org.eclipse.net4j.util.container.IManagedContainer;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.security.IPasswordCredentialsProvider;
import org.eclipse.net4j.util.security.PasswordCredentialsProvider;
import org.eclipse.net4j.util.ui.security.InteractiveCredentialsProvider;
import org.eclipse.swt.SWT;
/**
* A CDO utility class.
*
* @author <a href="mailto:yvan.lussaud@obeo.fr">Yvan Lussaud</a>
*/
public final class M2DocCDOUtils {
/**
* The Plug-in ID.
*/
public static final String PLUGIN_ID = "org.obeonetwork.m2doc.cdo";
/**
* The CDO server option.
*/
public static final String CDO_SERVER_OPTION = "CDOServer";
/**
* The CDO repository option.
*/
public static final String CDO_REPOSITORY_OPTION = "CDORepository";
/**
* The CDO branch option.
*/
public static final String CDO_BRANCH_OPTION = "CDOBranch";
/**
* The CDO login option.
*/
public static final String CDO_LOGIN_OPTION = "CDOLogin";
/**
* The CDO password option.
*/
public static final String CDO_PASSWORD_OPTION = "CDOPassword";
/**
* Constructor.
*/
private M2DocCDOUtils() {
// can't create instance
}
/**
* Gets a {@link IConnector} from the given description. Caller is responsible of
* {@link IConnector#close() closing} the resulting connector.
*
* @param description
* the description of the protocol host and port to use for the connection
* @return a new {@link IConnector}
*/
public static IConnector getConnector(String description) {
final IManagedContainer container = getContainer(description);
IConnector res = null;
try {
res = Net4jUtil.getConnector(container, description);
} catch (ConnectorException e) {
LifecycleUtil.deactivate(container);
throw e;
}
return res;
}
/**
* Open a new {@link CDOSession}. Caller is responsible of {@link CDOSession#close() closing} the
* resulting session.
*
* @param connector
* the {@link IConnector} to use to open the {@link CDOSession}
* @param repository
* the repository name
* @return a new {@link CDOSession}
*/
public static CDOSession openSession(IConnector connector, String repository) {
return openSession(connector, repository, null, null);
}
/**
* Open a new {@link CDOSession}. Caller is responsible of {@link CDOSession#close() closing} the
* resulting session.
*
* @param connector
* the {@link IConnector} to use to open the {@link CDOSession}
* @param repository
* the repository name
* @param login
* the user login if any, if <code>null</code> otherwise no authentication will by used
* @param password
* the user password if an, if <code>null</code> empty {@link String} will be used
* @return a new {@link CDOSession}
*/
public static CDOSession openSession(IConnector connector, String repository, String login, String password) {
final CDONet4jSessionConfiguration sessionConfiguration = CDONet4jUtil.createNet4jSessionConfiguration();
sessionConfiguration.setConnector(connector);
sessionConfiguration.setRepositoryName(repository);
if (login != null) {
final String pass;
if (password != null) {
pass = password;
} else {
pass = "";
}
sessionConfiguration.setCredentialsProvider(new PasswordCredentialsProvider(login, pass.toCharArray()));
} else {
final IPasswordCredentialsProvider credentialsProvider;
if (SWT.isLoadable()) {
credentialsProvider = new InteractiveCredentialsProvider();
} else {
credentialsProvider = new ShellCredentialsProvider();
}
sessionConfiguration.setCredentialsProvider(credentialsProvider);
}
CDOSession res = sessionConfiguration.openNet4jSession();
return res;
}
/**
* Open a {@link CDOTransaction} on the main {@link CDOBranch}. Caller is responsible of
* {@link CDOTransaction#close() closing} the resulting transaction.
*
* @param session
* the {@link CDOSession} to use to open the {@link CDOTransaction}
* @return a new {@link CDOTransaction}
*/
public static CDOTransaction openTransaction(CDOSession session) {
return openTransaction(session, null);
}
/**
* Open a {@link CDOTransaction} on the given {@link CDOBranch}. Caller is responsible of
* {@link CDOTransaction#close() closing} the resulting transaction.
*
* @param session
* the {@link CDOSession} to use to open the {@link CDOTransaction}
* @param branchName
* the branch name or <code>null</code> for the main branch
* @return a new {@link CDOTransaction}
*/
public static CDOTransaction openTransaction(CDOSession session, String branchName) {
final CDOTransaction res;
if (branchName != null) {
CDOBranch branch = session.getBranchManager().getBranch(branchName);
if (branch != null) {
res = session.openTransaction(branch);
} else {
res = session.openTransaction();
}
} else {
res = session.openTransaction();
}
return res;
}
/**
* Lists {@link CDOResource} of the given {@link CDOView}.
*
* @param view
* the {@link CDOView}
* @return the {@link List} of {@link CDOResource} from the given {@link CDOView}
*/
public static List<CDOResource> getResources(CDOView view) {
final List<CDOResource> res = new ArrayList<CDOResource>();
for (EObject eObj : view.getRootResource().eContents()) {
res.add((CDOResource) eObj);
}
return res;
}
/**
* Lists all {@link CDOBranch} for the given {@link CDOSession}.
*
* @param session
* the {@link CDOSession} to use to list {@link CDOBranch}
* @return the {@link List} of {@link CDOBranch} for the given {@link CDOSession}
*/
public static List<CDOBranch> getBranches(CDOSession session) {
final List<CDOBranch> res = new ArrayList<CDOBranch>();
session.getBranchManager().getBranches(Integer.MIN_VALUE, Integer.MAX_VALUE, new CDOBranchHandler() {
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.cdo.common.branch.CDOBranchHandler#handleBranch(org.eclipse.emf.cdo.common.branch.CDOBranch)
*/
public void handleBranch(CDOBranch branch) {
res.add(branch);
}
});
return res;
}
/**
* Gets a {@link IManagedContainer}.
*
* @param description
* the description of the protocol host and port to use for the connection
* @return a {@link IManagedContainer}
*/
private static IManagedContainer getContainer(String description) {
IManagedContainer res = ContainerUtil.createContainer();
Net4jUtil.prepareContainer(res);
CDONet4jUtil.prepareContainer(res);
TCPUtil.prepareContainer(res);
res.activate();
return res;
}
}
| epl-1.0 |
sschafer/atomic | org.allmyinfo.exception/src/org/allmyinfo/exception/ReadAccessException.java | 291 | package org.allmyinfo.exception;
import org.eclipse.jdt.annotation.NonNull;
public class ReadAccessException extends AccessException {
private static final long serialVersionUID = 1L;
@Override
public @NonNull String getTranslationKey() {
return "exception.read_access_denied";
}
}
| epl-1.0 |
smoczek/mdpm | com.lowcoupling.chartHelper/src/com/lowcoupling/charthelper/AbstractChartWithAxisBuilder.java | 1659 | /*******************************************************************************
* Copyright (c) 2006, 2010 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:
* Qi Liang (IBM Corporation)
*******************************************************************************/
package com.lowcoupling.charthelper;
import java.util.LinkedHashMap;
import java.util.Map;
import org.eclipse.birt.chart.model.component.Axis;
import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl;
/**
* Builds the chart with axis.
*
* @author Qi Liang
*/
public abstract class AbstractChartWithAxisBuilder extends AbstractChartBuilder {
/**
* Title of X axis.
*/
protected String xTitle = null;
/**
* Title of Y axis.
*/
protected String yTitle = null;
/**
* X axis.
*/
protected Axis xAxis = null;
/**
* Y axis.
*/
protected Axis yAxis = null;
/**
* Constructor.
*
* @param dataSet
* data for chart
*/
public AbstractChartWithAxisBuilder(Map<String,LinkedHashMap<String,Double>> dataSet) {
super(dataSet);
}
/*
* (non-Javadoc)
*
* @see com.ibm.examples.chart.widget.chart.AbstractChartBuilder#createChart()
*/
protected void createChart() {
chart = ChartWithAxesImpl.create();
}
}
| epl-1.0 |
ttimbul/eclipse.wst | bundles/org.eclipse.jst.jsp.ui/src/org/eclipse/jst/jsp/ui/internal/hyperlink/TaglibHyperlinkDetector.java | 17187 | /*******************************************************************************
* Copyright (c) 2006, 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 org.eclipse.jst.jsp.ui.internal.hyperlink;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
import org.eclipse.jface.text.hyperlink.IHyperlink;
import org.eclipse.jface.text.hyperlink.URLHyperlink;
import org.eclipse.jst.jsp.core.internal.contentmodel.TaglibController;
import org.eclipse.jst.jsp.core.internal.contentmodel.tld.CMElementDeclarationImpl;
import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TLDCMDocumentManager;
import org.eclipse.jst.jsp.core.internal.contentmodel.tld.TaglibTracker;
import org.eclipse.jst.jsp.core.internal.contentmodel.tld.provisional.JSP11TLDNames;
import org.eclipse.jst.jsp.core.internal.provisional.JSP11Namespace;
import org.eclipse.jst.jsp.core.internal.provisional.JSP12Namespace;
import org.eclipse.jst.jsp.core.taglib.ITLDRecord;
import org.eclipse.jst.jsp.core.taglib.ITaglibRecord;
import org.eclipse.jst.jsp.core.taglib.TaglibIndex;
import org.eclipse.jst.jsp.core.text.IJSPPartitions;
import org.eclipse.jst.jsp.ui.internal.JSPUIMessages;
import org.eclipse.jst.jsp.ui.internal.Logger;
import org.eclipse.wst.sse.core.StructuredModelManager;
import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredPartitioning;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionCollection;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
import org.eclipse.wst.sse.core.utils.StringUtils;
import org.eclipse.wst.xml.core.internal.contentmodel.CMElementDeclaration;
import org.eclipse.wst.xml.core.internal.provisional.contentmodel.CMNodeWrapper;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMAttr;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Detects hyperlinks for taglibs.
*/
public class TaglibHyperlinkDetector extends AbstractHyperlinkDetector {
private final String HTTP_PROTOCOL = "http://";//$NON-NLS-1$
private final String JAR_PROTOCOL = "jar:file:";//$NON-NLS-1$
// private String URN_TAGDIR = "urn:jsptagdir:";
private String URN_TLD = "urn:jsptld:";
private String XMLNS = "xmlns:"; //$NON-NLS-1$
static final int TAG = 1;
static final int ATTRIBUTE = 2;
static IRegion findDefinition(IDOMModel model, String searchName, int searchType) {
NodeList declarations = null;
if (searchType == TAG)
declarations = model.getDocument().getElementsByTagNameNS("*", JSP11TLDNames.TAG);
else if (searchType == ATTRIBUTE)
declarations = model.getDocument().getElementsByTagNameNS("*", JSP11TLDNames.ATTRIBUTE);
if (declarations == null || declarations.getLength() == 0) {
if (searchType == TAG)
declarations = model.getDocument().getElementsByTagName(JSP11TLDNames.TAG);
else if (searchType == ATTRIBUTE)
declarations = model.getDocument().getElementsByTagName(JSP11TLDNames.ATTRIBUTE);
}
for (int i = 0; i < declarations.getLength(); i++) {
NodeList names = model.getDocument().getElementsByTagName(JSP11TLDNames.NAME);
for (int j = 0; j < names.getLength(); j++) {
String name = getContainedText(names.item(j));
if (searchName.compareTo(name) == 0) {
int start = -1;
int end = -1;
Node caret = names.item(j).getFirstChild();
if (caret != null) {
start = ((IDOMNode) caret).getStartOffset();
}
while (caret != null) {
end = ((IDOMNode) caret).getEndOffset();
caret = caret.getNextSibling();
}
if (start > 0) {
return new Region(start, end - start);
}
}
}
}
return null;
}
private static String getContainedText(Node parent) {
NodeList children = parent.getChildNodes();
if (children.getLength() == 1) {
return children.item(0).getNodeValue().trim();
}
StringBuffer s = new StringBuffer();
Node child = parent.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
String reference = ((EntityReference) child).getNodeValue();
if (reference == null && child.getNodeName() != null) {
reference = "&" + child.getNodeName() + ";"; //$NON-NLS-1$ //$NON-NLS-2$
}
if (reference != null) {
s.append(reference.trim());
}
}
else {
s.append(child.getNodeValue().trim());
}
child = child.getNextSibling();
}
return s.toString().trim();
}
public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region, boolean canShowMultipleHyperlinks) {
IHyperlink hyperlink = null;
if (textViewer != null && region != null) {
IDocument doc = textViewer.getDocument();
if (doc != null) {
try {
// check if jsp tag/directive first
ITypedRegion partition = TextUtilities.getPartition(doc, IStructuredPartitioning.DEFAULT_STRUCTURED_PARTITIONING, region.getOffset(), false);
if (partition != null && partition.getType() == IJSPPartitions.JSP_DIRECTIVE) {
IStructuredModel sModel = null;
try {
sModel = StructuredModelManager.getModelManager().getExistingModelForRead(doc);
// check if jsp taglib directive
Node currentNode = getCurrentNode(sModel, region.getOffset());
if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) {
String baseLocationForTaglib = getBaseLocationForTaglib(doc);
if (baseLocationForTaglib != null && JSP11Namespace.ElementName.DIRECTIVE_TAGLIB.equalsIgnoreCase(currentNode.getNodeName())) {
/**
* The taglib directive itself
*/
// get the uri attribute
Attr taglibURINode = ((Element) currentNode).getAttributeNode(JSP11Namespace.ATTR_NAME_URI);
if (taglibURINode != null) {
ITaglibRecord reference = TaglibIndex.resolve(baseLocationForTaglib, taglibURINode.getValue(), false);
// when using a tagdir
// (ITaglibRecord.TAGDIR),
// there's nothing to link to
if (reference != null) {
// handle taglibs
switch (reference.getRecordType()) {
case (ITaglibRecord.TLD) : {
ITLDRecord record = (ITLDRecord) reference;
String uriString = record.getPath().toString();
IRegion hyperlinkRegion = getHyperlinkRegion(taglibURINode, region);
if (hyperlinkRegion != null) {
hyperlink = createHyperlink(uriString, hyperlinkRegion, doc, null);
}
}
break;
case (ITaglibRecord.JAR) :
case (ITaglibRecord.URL) : {
IRegion hyperlinkRegion = getHyperlinkRegion(taglibURINode, region);
if (hyperlinkRegion != null) {
hyperlink = new TaglibJarUriHyperlink(hyperlinkRegion, reference);
}
}
}
}
}
}
else if (baseLocationForTaglib != null && JSP12Namespace.ElementName.ROOT.equalsIgnoreCase(currentNode.getNodeName())) {
/**
* The jsp:root element
*/
NamedNodeMap attrs = currentNode.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
if (attr.getNodeName().startsWith(XMLNS)) {
String uri = StringUtils.strip(attr.getNodeValue());
if (uri.startsWith(URN_TLD)) {
uri = uri.substring(URN_TLD.length());
}
ITaglibRecord reference = TaglibIndex.resolve(baseLocationForTaglib, uri, false);
// when using a tagdir
// (ITaglibRecord.TAGDIR),
// there's nothing to link to
if (reference != null) {
// handle taglibs
switch (reference.getRecordType()) {
case (ITaglibRecord.TLD) : {
ITLDRecord record = (ITLDRecord) reference;
String uriString = record.getPath().toString();
IRegion hyperlinkRegion = getHyperlinkRegion(attr, region);
if (hyperlinkRegion != null) {
hyperlink = createHyperlink(uriString, hyperlinkRegion, doc, null);
}
}
break;
case (ITaglibRecord.JAR) :
case (ITaglibRecord.URL) : {
IRegion hyperlinkRegion = getHyperlinkRegion(attr, region);
if (hyperlinkRegion != null) {
hyperlink = new TaglibJarUriHyperlink(hyperlinkRegion, reference);
}
}
}
}
}
}
}
else {
/**
* Hyperlink custom tag to its TLD or tag file
*/
TLDCMDocumentManager documentManager = TaglibController.getTLDCMDocumentManager(doc);
if (documentManager != null) {
List documentTrackers = documentManager.getCMDocumentTrackers(currentNode.getPrefix(), region.getOffset());
for (int i = 0; i < documentTrackers.size(); i++) {
TaglibTracker tracker = (TaglibTracker) documentTrackers.get(i);
CMElementDeclaration decl = (CMElementDeclaration) tracker.getElements().getNamedItem(currentNode.getNodeName());
if (decl != null) {
decl = (CMElementDeclaration) ((CMNodeWrapper) decl).getOriginNode();
if (decl instanceof CMElementDeclarationImpl) {
String base = ((CMElementDeclarationImpl) decl).getLocationString();
IRegion hyperlinkRegion = getHyperlinkRegion(currentNode, region);
if (hyperlinkRegion != null) {
hyperlink = createHyperlink(base, hyperlinkRegion, doc, currentNode);
}
}
}
}
}
}
}
}
finally {
if (sModel != null)
sModel.releaseFromRead();
}
}
}
catch (BadLocationException e) {
Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e);
}
}
}
if (hyperlink != null)
return new IHyperlink[]{hyperlink};
return null;
}
/**
* Get the base location from the current model (if within workspace,
* location is relative to workspace, otherwise, file system path)
*/
private String getBaseLocationForTaglib(IDocument document) {
String baseLoc = null;
// get the base location from the current model
IStructuredModel sModel = null;
try {
sModel = StructuredModelManager.getModelManager().getExistingModelForRead(document);
if (sModel != null) {
baseLoc = sModel.getBaseLocation();
}
}
finally {
if (sModel != null) {
sModel.releaseFromRead();
}
}
return baseLoc;
}
// the below methods were copied from URIHyperlinkDetector
private IRegion getHyperlinkRegion(Node node, IRegion boundingRegion) {
IRegion hyperRegion = null;
if (node != null) {
short nodeType = node.getNodeType();
if (nodeType == Node.DOCUMENT_TYPE_NODE) {
// handle doc type node
IDOMNode docNode = (IDOMNode) node;
hyperRegion = new Region(docNode.getStartOffset(), docNode.getEndOffset() - docNode.getStartOffset());
}
else if (nodeType == Node.ATTRIBUTE_NODE) {
// handle attribute nodes
IDOMAttr att = (IDOMAttr) node;
// do not include quotes in attribute value region
int regOffset = att.getValueRegionStartOffset();
ITextRegion valueRegion = att.getValueRegion();
if (valueRegion != null) {
int regLength = valueRegion.getTextLength();
String attValue = att.getValueRegionText();
if (StringUtils.isQuoted(attValue)) {
++regOffset;
regLength = regLength - 2;
}
hyperRegion = new Region(regOffset, regLength);
}
}
if (nodeType == Node.ELEMENT_NODE) {
// Handle doc type node
IDOMNode docNode = (IDOMNode) node;
hyperRegion = getNameRegion(docNode.getFirstStructuredDocumentRegion());
if (hyperRegion == null) {
hyperRegion = new Region(docNode.getStartOffset(), docNode.getFirstStructuredDocumentRegion().getTextLength());
}
}
}
/**
* Only return a hyperlink region that overlaps the search region.
* This will help us to not underline areas not under the cursor.
*/
if (hyperRegion != null && intersects(hyperRegion, boundingRegion))
return hyperRegion;
return null;
}
private boolean intersects(IRegion hyperlinkRegion, IRegion detectionRegion) {
int hyperLinkStart = hyperlinkRegion.getOffset();
int hyperLinkEnd = hyperlinkRegion.getOffset() + hyperlinkRegion.getLength();
int detectionStart = detectionRegion.getOffset();
int detectionEnd = detectionRegion.getOffset() + detectionRegion.getLength();
return (hyperLinkStart <= detectionStart && detectionStart < hyperLinkEnd) || (hyperLinkStart <= detectionEnd && detectionEnd <= hyperLinkEnd);// ||
}
private IRegion getNameRegion(ITextRegionCollection containerRegion) {
ITextRegionList regions = containerRegion.getRegions();
ITextRegion nameRegion = null;
for (int i = 0; i < regions.size(); i++) {
ITextRegion r = regions.get(i);
if (r.getType() == DOMRegionContext.XML_TAG_NAME) {
nameRegion = r;
break;
}
}
if (nameRegion != null)
return new Region(containerRegion.getStartOffset(nameRegion), nameRegion.getTextLength());
return null;
}
/**
* Create the appropriate hyperlink
*
* @param uriString
* @param hyperlinkRegion
* @return IHyperlink
*/
private IHyperlink createHyperlink(String uriString, IRegion hyperlinkRegion, IDocument document, Node node) {
IHyperlink link = null;
if (uriString != null) {
String temp = uriString.toLowerCase();
if (temp.startsWith(HTTP_PROTOCOL)) {
// this is a URLHyperlink since this is a web address
link = new URLHyperlink(hyperlinkRegion, uriString);
}
else if (temp.startsWith(JAR_PROTOCOL)) {
// this is a URLFileHyperlink since this is a local address
try {
link = new URLFileRegionHyperlink(hyperlinkRegion, TAG, node.getLocalName(), new URL(uriString)) {
public String getHyperlinkText() {
return JSPUIMessages.CustomTagHyperlink_hyperlinkText;
}
};
}
catch (MalformedURLException e) {
Logger.log(Logger.WARNING_DEBUG, e.getMessage(), e);
}
}
else {
// try to locate the file in the workspace
IPath path = new Path(uriString);
if (path.segmentCount() > 1) {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
if (file.getType() == IResource.FILE && file.isAccessible()) {
if (node != null) {
link = new TLDFileHyperlink(file, TAG, node.getLocalName(), hyperlinkRegion) {
public String getHyperlinkText() {
return JSPUIMessages.TLDHyperlink_hyperlinkText;
}
};
}
else {
link = new WorkspaceFileHyperlink(hyperlinkRegion, file) {
public String getHyperlinkText() {
return JSPUIMessages.TLDHyperlink_hyperlinkText;
}
};
}
}
}
}
if (link == null) {
// this is an ExternalFileHyperlink since file does not exist
// in workspace
File externalFile = new File(uriString);
link = new ExternalFileHyperlink(hyperlinkRegion, externalFile) {
public String getHyperlinkText() {
return JSPUIMessages.TLDHyperlink_hyperlinkText;
}
};
}
}
return link;
}
private Node getCurrentNode(IStructuredModel model, int offset) {
// get the current node at the offset (returns either: element,
// doctype, text)
IndexedRegion inode = null;
if (model != null) {
inode = model.getIndexedRegion(offset);
if (inode == null) {
inode = model.getIndexedRegion(offset - 1);
}
}
if (inode instanceof Node) {
return (Node) inode;
}
return null;
}
}
| epl-1.0 |
jesusc/bento | tests/test-outputs/bento.sirius.tests.metamodels.output/src/fta_bdsl/impl/typeEventImpl.java | 3441 | /**
*/
package fta_bdsl.impl;
import fta_bdsl.EventType;
import fta_bdsl.Fta_bdslPackage;
import fta_bdsl.typeEvent;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>type Event</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link fta_bdsl.impl.typeEventImpl#getValue <em>Value</em>}</li>
* </ul>
*
* @generated
*/
public class typeEventImpl extends BindingAttributeImpl implements typeEvent {
/**
* The default value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected static final EventType VALUE_EDEFAULT = EventType.BASIC;
/**
* The cached value of the '{@link #getValue() <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getValue()
* @generated
* @ordered
*/
protected EventType value = VALUE_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected typeEventImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Fta_bdslPackage.Literals.TYPE_EVENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EventType getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setValue(EventType newValue) {
EventType oldValue = value;
value = newValue == null ? VALUE_EDEFAULT : newValue;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Fta_bdslPackage.TYPE_EVENT__VALUE, oldValue, value));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Fta_bdslPackage.TYPE_EVENT__VALUE:
return getValue();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Fta_bdslPackage.TYPE_EVENT__VALUE:
setValue((EventType)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Fta_bdslPackage.TYPE_EVENT__VALUE:
setValue(VALUE_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Fta_bdslPackage.TYPE_EVENT__VALUE:
return value != VALUE_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (value: ");
result.append(value);
result.append(')');
return result.toString();
}
} //typeEventImpl
| epl-1.0 |
maxeler/eclipse | eclipse.jdt.core/org.eclipse.jdt.core.tests.compiler/src/org/eclipse/jdt/core/tests/compiler/regression/JavadocTestMixed.java | 26115 | /*******************************************************************************
* Copyright (c) 2000, 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 org.eclipse.jdt.core.tests.compiler.regression;
import java.util.Map;
import junit.framework.Test;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
public class JavadocTestMixed extends JavadocTest {
String docCommentSupport = CompilerOptions.ENABLED;
String reportInvalidJavadoc = CompilerOptions.ERROR;
String reportMissingJavadocTags = CompilerOptions.ERROR;
String reportMissingJavadocComments = null;
public JavadocTestMixed(String name) {
super(name);
}
public static Class javadocTestClass() {
return JavadocTestMixed.class;
}
// Use this static initializer to specify subset for tests
// All specified tests which does not belong to the class are skipped...
static {
// TESTS_PREFIX = "testBug77602";
// TESTS_NAMES = new String[] { "testBug80910" };
// TESTS_NUMBERS = new int[] { 31, 32, 33 };
// TESTS_RANGE = new int[] { 21, 50 };
}
public static Test suite() {
return buildAllCompliancesTestSuite(javadocTestClass());
}
protected Map getCompilerOptions() {
Map options = super.getCompilerOptions();
options.put(CompilerOptions.OPTION_DocCommentSupport, this.docCommentSupport);
options.put(CompilerOptions.OPTION_ReportInvalidJavadoc, this.reportInvalidJavadoc);
if (this.reportMissingJavadocComments != null)
options.put(CompilerOptions.OPTION_ReportMissingJavadocComments, this.reportMissingJavadocComments);
else
options.put(CompilerOptions.OPTION_ReportMissingJavadocComments, this.reportInvalidJavadoc);
if (this.reportMissingJavadocTags != null)
options.put(CompilerOptions.OPTION_ReportMissingJavadocTags, this.reportMissingJavadocTags);
else
options.put(CompilerOptions.OPTION_ReportMissingJavadocTags, this.reportInvalidJavadoc);
options.put(CompilerOptions.OPTION_ReportFieldHiding, CompilerOptions.IGNORE);
options.put(CompilerOptions.OPTION_ReportSyntheticAccessEmulation, CompilerOptions.IGNORE);
options.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.ERROR);
options.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.ERROR);
options.put(CompilerOptions.OPTION_ReportRawTypeReference, CompilerOptions.IGNORE);
return options;
}
/* (non-Javadoc)
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
super.setUp();
this.docCommentSupport = CompilerOptions.ENABLED;
this.reportInvalidJavadoc = CompilerOptions.ERROR;
this.reportMissingJavadocTags = CompilerOptions.ERROR;
this.reportMissingJavadocComments = null;
}
/*
* Test missing javadoc
*/
public void test001() {
runConformTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** */\n"
+ "public class X {\n"
+ " /** */\n"
+ " public int x;\n"
+ " /** */\n"
+ " public X() {}\n"
+ " /** */\n"
+ " public void foo() {}\n"
+ "}\n" });
}
public void test002() {
runConformTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** */\n"
+ "class X {\n"
+ " /** */\n"
+ " int x;\n"
+ " /** */\n"
+ " X() {}\n"
+ " /** */\n"
+ " void foo() {}\n"
+ "}\n" });
}
public void test003() {
runConformTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** */\n"
+ "class X {\n"
+ " /** */\n"
+ " protected int x;\n"
+ " /** */\n"
+ " protected X() {}\n"
+ " /** */\n"
+ " protected void foo() {}\n"
+ "}\n" });
}
public void test004() {
runConformTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** */\n"
+ "class X {\n"
+ " /** */\n"
+ " private int x;\n"
+ " /** */\n"
+ " private X() {}\n"
+ " /** */\n"
+ " private void foo() {}\n"
+ "}\n" });
}
public void test005() {
this.reportInvalidJavadoc = CompilerOptions.IGNORE;
runConformTest(
new String[] {
"test/X.java",
"package test;\n"
+ "public class X {\n"
+ " public int x;\n"
+ "\n"
+ " public X() {}\n"
+ "\n"
+ " public void foo() {}\n"
+ "}\n" });
}
public void test006() {
this.reportMissingJavadocComments = CompilerOptions.IGNORE;
runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" String s1 = \"non-terminated;\n" +
" void foo() {}\n" +
" String s2 = \"terminated\";\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 2)\n" +
" String s1 = \"non-terminated;\n" +
" ^^^^^^^^^^^^^^^^\n" +
"String literal is not properly closed by a double-quote\n" +
"----------\n"
);
}
public void test010() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "public class X {\n"
+ " /** Field javadoc comment */\n"
+ " public int x;\n"
+ "\n"
+ " /** Constructor javadoc comment */\n"
+ " public X() {\n"
+ " }\n"
+ " /** Method javadoc comment */\n"
+ " public void foo() {\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 2)\n"
+ " public class X {\n"
+ " ^\n"
+ "Javadoc: Missing comment for public declaration\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test011() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** Class javadoc comment */\n"
+ "public class X {\n"
+ " public int x;\n"
+ "\n"
+ " /** Constructor javadoc comment */\n"
+ " public X() {\n"
+ " }\n"
+ " /** Method javadoc comment */\n"
+ " public void foo() {\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 4)\n"
+ " public int x;\n"
+ " ^\n"
+ "Javadoc: Missing comment for public declaration\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test012() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** Class javadoc comment */\n"
+ "public class X {\n"
+ " /** Field javadoc comment */\n"
+ " public int x;\n"
+ "\n"
+ " public X() {\n"
+ " }\n"
+ " /** Method javadoc comment */\n"
+ " public void foo() {\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 7)\n"
+ " public X() {\n"
+ " ^^^\n"
+ "Javadoc: Missing comment for public declaration\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test013() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/** Class javadoc comment */\n"
+ "public class X {\n"
+ " /** Field javadoc comment */\n"
+ " public int x;\n"
+ "\n"
+ " /** Constructor javadoc comment */\n"
+ " public X() {\n"
+ " }\n"
+ " public void foo(int a) {\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 10)\n"
+ " public void foo(int a) {\n"
+ " ^^^^^^^^^^\n"
+ "Javadoc: Missing comment for public declaration\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
/*
* Test mixing javadoc comments
*/
public void test021() {
runConformTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" });
}
public void test022() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Unexpected tag in class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " * @param x\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 6)\n"
+ " * @param x\n"
+ " ^^^^^\n"
+ "Javadoc: Unexpected tag\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test023() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Unexpected tag in field javadoc\n"
+ " * @throws InvalidException\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 10)\n"
+ " * @throws InvalidException\n"
+ " ^^^^^^\n"
+ "Javadoc: Unexpected tag\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test024() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Wrong tags order in constructor javadoc\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @param str Valid param tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 19)\n"
+ " * @param str Valid param tag\n"
+ " ^^^^^\n"
+ "Javadoc: Unexpected tag\n"
+ "----------\n"
+ "2. ERROR in test\\X.java (at line 22)\n"
+ " public X(String str) {\n"
+ " ^^^\n"
+ "Javadoc: Missing tag for parameter str\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test025() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Wrong param tag in method javadoc\n"
+ " * @param vector Invalid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 26)\n"
+ " * @param vector Invalid param tag\n"
+ " ^^^^^^\n"
+ "Javadoc: Parameter vector is not declared\n"
+ "----------\n"
+ "2. ERROR in test\\X.java (at line 33)\n"
+ " public String foo(java.util.Vector list) {\n"
+ " ^^^^\n"
+ "Javadoc: Missing tag for parameter list\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
public void test026() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Invalid see tag in class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Invalid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>unexpected text\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Missing throws tag in constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) throws java.io.IOException {\n"
+ " }\n"
+ "/**\n"
+ " * Missing return tag in method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 5)\n"
+ " * @see \"Test class X\n"
+ " ^^^^^^^^^^^^^\n"
+ "Javadoc: Invalid reference\n"
+ "----------\n"
+ "2. ERROR in test\\X.java (at line 10)\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>unexpected text\n"
+ " ^^^^^^^^^^^^^^^^^^\n"
+ "Javadoc: Unexpected text\n"
+ "----------\n"
+ "3. ERROR in test\\X.java (at line 22)\n"
+ " public X(String str) throws java.io.IOException {\n"
+ " ^^^^^^^^^^^^^^^^^^^\n"
+ "Javadoc: Missing tag for declared exception IOException\n"
+ "----------\n"
+ "4. ERROR in test\\X.java (at line 32)\n"
+ " public String foo(java.util.Vector list) {\n"
+ " ^^^^^^\n"
+ "Javadoc: Missing tag for return type\n"
+ "----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError);
}
/*
* Javadoc on invalid syntax
*/
public void test030() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc on invalid declaration\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "protected class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 7)\n"
+ " protected class X {\n"
+ " ^\n"
+ "Illegal modifier for the class X; only public, abstract & final are permitted\n"
+ "----------\n");
}
public void test031() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc on invalid declaration\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 12)\n"
+ " public int x\n"
+ " ^\n"
+ "Syntax error, insert \";\" to complete ClassBodyDeclarations\n"
+ "----------\n");
}
public void test032() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc on invalid declaration\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) \n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector list) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
"----------\n"
+ "1. ERROR in test\\X.java (at line 22)\n"
+ " public X(String str) \n"
+ " ^\n"
+ "Syntax error on token \")\", { expected after this token\n"
+ "----------\n");
}
public void _test033() {
runNegativeTest(
new String[] {
"test/X.java",
"package test;\n"
+ "/**\n"
+ " * Valid class javadoc\n"
+ " * @author ffr\n"
+ " * @see \"Test class X\"\n"
+ " */\n"
+ "public class X {\n"
+ "/**\n"
+ " * Valid field javadoc\n"
+ " * @see <a href=\"http://www.ibm.com\">Valid URL</a>\n"
+ " */\n"
+ " public int x;\n"
+ "\n"
+ "/**\n"
+ " * Valid constructor javadoc\n"
+ " * @param str Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public X(String str) {\n"
+ " }\n"
+ "/**\n"
+ " * Valid method javadoc on invalid declaration\n"
+ " * @param list Valid param tag\n"
+ " * @throws NullPointerException Valid throws tag\n"
+ " * @exception IllegalArgumentException Valid throws tag\n"
+ " * @return Valid return tag\n"
+ " * @see X Valid see tag\n"
+ " * @deprecated\n"
+ " */\n"
+ " public String foo(java.util.Vector ) {\n"
+ " return \"\";\n"
+ " }\n"
+ "}\n" },
this.complianceLevel < ClassFileConstants.JDK1_5
? "----------\n"
+ "1. ERROR in test\\X.java (at line 23)\n"
+ " }\n"
+ " ^\n"
+ "Syntax error, insert \"}\" to complete ClassBody\n"
+ "----------\n"
+ "2. ERROR in test\\X.java (at line 26)\n"
+ " * @param list Valid param tag\n"
+ " ^^^^\n"
+ "Javadoc: Parameter list is not declared\n"
+ "----------\n"
+ "3. ERROR in test\\X.java (at line 33)\n"
+ " public String foo(java.util.Vector ) {\n"
+ " ^^^^^^\n"
+ "Syntax error on token \"Vector\", VariableDeclaratorId expected after this token\n"
+ "----------\n"
+ "4. ERROR in test\\X.java (at line 36)\n"
+ " }\n"
+ " ^\n"
+ "Syntax error on token \"}\", delete this token\n"
+ "----------\n"
: "----------\n"
+ "1. ERROR in test\\X.java (at line 23)\n"
+ " }\n"
+ " ^\n"
+ "Syntax error, insert \"}\" to complete ClassBody\n"
+ "----------\n"
+ "2. ERROR in test\\X.java (at line 26)\n"
+ " * @param list Valid param tag\n"
+ " ^^^^\n"
+ "Javadoc: Parameter list is not declared\n"
+ "----------\n"
+ "3. ERROR in test\\X.java (at line 33)\n"
+ " public String foo(java.util.Vector ) {\n"
+ " ^\n"
+ "Syntax error on token \".\", ... expected\n"
+ "----------\n"
+ "4. ERROR in test\\X.java (at line 36)\n"
+ " }\n"
+ " ^\n"
+ "Syntax error on token \"}\", delete this token\n"
+ "----------\n");
}
public void test040() {
this.reportMissingJavadocComments = CompilerOptions.IGNORE;
runConformTest(
new String[] {
"X.java",
"public class X {\n" +
" /**\n" +
" /**\n" +
" /**\n" +
" /** \n" +
" * @param str\n" +
" * @param x\n" +
" */\n" +
" public void bar(String str, int x) {\n" +
" }\n" +
" public void foo() {\n" +
" bar(\"toto\", 0 /* block comment inline */);\n" +
" }\n" +
"}\n" });
}
public void test041() {
this.reportMissingJavadocComments = CompilerOptions.IGNORE;
runNegativeTest(
new String[] {
"X.java",
"public class X {\n" +
" /**\n" +
" * @see String\n" +
" * @see #\n" +
" * @return String\n" +
" */\n" +
" String bar() {return \"\";}\n" +
"}\n"
},
"----------\n" +
"1. ERROR in X.java (at line 4)\n" +
" * @see #\n" +
" ^\n" +
"Javadoc: Invalid reference\n" +
"----------\n",
JavacTestOptions.Excuse.EclipseWarningConfiguredAsError
);
}
}
| epl-1.0 |
qgears/opensource-utils | commons/hu.qgears.parser/src/main/java/hu/qgears/parser/util/UtilString.java | 803 | package hu.qgears.parser.util;
import java.util.List;
public class UtilString {
public static String concat(String pre, List<String> list, String delim,
String post) {
StringBuilder ret = new StringBuilder();
ret.append(pre);
boolean first = true;
for (String s : list) {
if (!first) {
ret.append(delim);
}
ret.append(s);
first = false;
}
ret.append(post);
return ret.toString();
}
public static String unescape(String str) {
String withoutquotes=str.substring(1, str.length() - 1);
StringBuilder ret=new StringBuilder();
boolean prevBackslash=false;
for(char ch:withoutquotes.toCharArray())
{
if(ch=='\\'&&!prevBackslash)
{
prevBackslash=true;
}else
{
ret.append(ch);
prevBackslash=false;
}
}
return ret.toString();
}
}
| epl-1.0 |
Achref001/My-Fashion-assistant--Android- | src/com/andy/myfashionassistant/fragments/AssitanceFragment.java | 5480 | package com.andy.myfashionassistant.fragments;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.andy.myfashionassistant.utils.Point3D;
import com.fashion.R;
import com.gc.materialdesign.views.ButtonRectangle;
@SuppressLint("NewApi")
public class AssitanceFragment extends Fragment {
static Bitmap bmp = null;
private static final int RESULT_OK = 0;
private static int CODE_IMAGE_RECHERCHE = 1;
private ButtonRectangle rechercher_imageButton;
private ImageView imageView;
private TextView rouge_textView;
private TextView vert_textView;
private TextView bleu_textView;
private TextView cadre_color;
private TextView signecouleursimilaires;
private TextView nomscouleursimilaires;
View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.activity_assistance, container, false);
rechercher_imageButton = (ButtonRectangle)rootView. findViewById(R.id.rechercher_button);
imageView = (ImageView)rootView. findViewById(R.id.imageView);
rouge_textView = (TextView)rootView. findViewById(R.id.rouge_textView);
vert_textView = (TextView)rootView. findViewById(R.id.vert_textView);
bleu_textView = (TextView)rootView. findViewById(R.id.bleu_textView);
cadre_color = (TextView)rootView. findViewById(R.id.signe_textView);
signecouleursimilaires = (TextView)rootView. findViewById(R.id.signecouleursimilaires_textView);
nomscouleursimilaires = (TextView)rootView. findViewById(R.id.nomscouleursimilaires_textView);
rechercher_imageButton.setOnClickListener(rechercherImage);
return rootView;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
}
OnClickListener rechercherImage = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
getActivity().
startActivityForResult(Intent.createChooser(intent, "Selectionner une image"),
CODE_IMAGE_RECHERCHE);
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CODE_IMAGE_RECHERCHE) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(data.getData());
traitementImage();
}
/*if (requestCode == 37 && resultCode == Activity.RESULT_OK) {
bmp = (Bitmap) data.getExtras().get("data");
((ImageButton)rootView. findViewById(R.id.image)).setImageBitmap(bmp);
traitementImage();*/
}
}
private void traitementImage() {
Bitmap image = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
long rouge = 0L;
long vert = 0L;
long bleu = 0L;
int[] pixeles = new int[image.getWidth() * image.getHeight()];
image.getPixels(pixeles, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
for (int cursor = 0; cursor < pixeles.length; cursor++) {
rouge += Color.red(pixeles[cursor]);
vert += Color.green(pixeles[cursor]);
bleu += Color.blue(pixeles[cursor]);
}
long numPixels = image.getWidth() * image.getHeight();
rouge /= numPixels;
vert /= numPixels;
bleu /= numPixels;
rouge_textView.setText("Moyenne du rouge: " + rouge);
vert_textView.setText("Moyenne du vert: " + vert);
bleu_textView.setText("Moyenne du bleu: " + bleu);
cadre_color.setBackgroundColor(Color.rgb((int)rouge, (int)vert, (int)bleu));
Point3D[] pixelesRef = {
new Point3D(255, 0, 0),
new Point3D(0, 255, 0),
new Point3D(0, 0, 255),
new Point3D(255, 255, 0),
new Point3D(0, 255, 255),
new Point3D(255, 0, 255),
new Point3D(0, 0, 0),
new Point3D(255, 255, 255)
};
Point3D pixelActuel = new Point3D(rouge, vert, bleu);
double[] distance = {
pixelActuel.distance(pixelesRef[0]),
pixelActuel.distance(pixelesRef[1]),
pixelActuel.distance(pixelesRef[2]),
pixelActuel.distance(pixelesRef[3]),
pixelActuel.distance(pixelesRef[4]),
pixelActuel.distance(pixelesRef[5]),
pixelActuel.distance(pixelesRef[6]),
pixelActuel.distance(pixelesRef[7])
};
String[] couleurs = {"rouge", "vert", "bleu",
"jaune", "turcoise", "magenta",
"noir", "blanc"};
double dist_minimum = 255;
int indice_minimum = 0;
for (int index = 0; index < distance.length; index++) {
if (distance[index] <= dist_minimum) {
indice_minimum = index;
dist_minimum = distance[index];
}
Log.i("Distance", "Distance vers " + index + ": " + distance[index]);
}
signecouleursimilaires.setBackgroundColor(Color.rgb((int)pixelesRef[indice_minimum].getX(),
(int)pixelesRef[indice_minimum].getY(),
(int)pixelesRef[indice_minimum].getZ()));
nomscouleursimilaires.setText(couleurs[indice_minimum]);
}
}
| epl-1.0 |
Jose-Badeau/boomslang-examples | boomslang.example.rcp.mail/src/boomslang/example/rcp/mail/ApplicationWorkbenchAdvisor.java | 690 | package boomslang.example.rcp.mail;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
/**
* This workbench advisor creates the window advisor, and specifies
* the perspective id for the initial window.
*/
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
@Override
public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
return new ApplicationWorkbenchWindowAdvisor(configurer);
}
@Override
public String getInitialWindowPerspectiveId() {
return Perspective.ID;
}
}
| epl-1.0 |
sazgin/elexis-3-core | ch.elexis.core.ui/src/ch/elexis/core/ui/util/viewers/PatientenListeControlFieldProvider.java | 2407 | /*******************************************************************************
* Copyright (c) 2006-2009, D. Lutz 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:
* D. Lutz - initial implementation
*
*******************************************************************************/
package ch.elexis.core.ui.util.viewers;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ch.elexis.data.Query;
import ch.rgw.tools.StringTool;
/**
* Variante des DefaultControlFieldProviders. Falls im ersten Feld ein Leerzeichen eingegeben wird,
* wird der Text vor dem Leerzeichen fürs erste Feld, der Text nach dem Leerzeichen fürs zweite Feld
* verwendet. Die restlichen Felder werden ignoriert. Ohne Leerzeichen verhält sich diese Klasse
* gleich wie der DefaultControlFieldProvider.
*
* @author Daniel Lutz <danlutz@watz.ch>
*/
public class PatientenListeControlFieldProvider extends DefaultControlFieldProvider {
public PatientenListeControlFieldProvider(CommonViewer viewer, String[] flds){
super(viewer, flds);
}
public void setQuery(Query q){
// specially handle search string with space in the first field.
// if the first field contains a space, we consider the value as
// a combination of the first field and the second field.
String field0 = null;
String field1 = null;
if (lastFiltered.length >= 2 && lastFiltered[0].contains(" ")) {
Pattern pattern = Pattern.compile("^(\\S+) +(.*)$");
Matcher matcher = pattern.matcher(lastFiltered[0]);
if (matcher.matches()) {
field0 = matcher.group(1);
field1 = matcher.group(2);
}
}
if (field0 != null && field1 != null) {
q.add(dbFields[0], "LIKE", field0 + "%", true); //$NON-NLS-1$ //$NON-NLS-2$
q.and();
q.add(dbFields[1], "LIKE", field1 + "%", true); //$NON-NLS-1$ //$NON-NLS-2$
q.and();
// remaining fields
for (int i = 2; i < fields.length; i++) {
if (!lastFiltered[i].equals(StringTool.leer)) {
q.add(dbFields[i], "LIKE", lastFiltered[i] + "%", true); //$NON-NLS-1$ //$NON-NLS-2$
q.and();
}
}
q.insertTrue();
} else {
// no space, normal behaviour
super.setQuery(q);
}
}
}
| epl-1.0 |
elelpublic/wikitext-all | src/org.eclipse.mylyn.wikitext.twiki.core/src/org/eclipse/mylyn/internal/wikitext/twiki/core/block/HorizontalRuleBlock.java | 1298 | /*******************************************************************************
* Copyright (c) 2007, 2011 David Green 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:
* David Green - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.wikitext.twiki.core.block;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.mylyn.wikitext.core.parser.markup.Block;
/**
* @author David Green
*/
public class HorizontalRuleBlock extends Block {
private static final Pattern startPattern = Pattern.compile("-{3,}\\s*"); //$NON-NLS-1$
private Matcher matcher;
@Override
public int processLineContent(String line, int offset) {
builder.charactersUnescaped("<hr/>"); //$NON-NLS-1$
setClosed(true);
return -1;
}
@Override
public boolean canStart(String line, int lineOffset) {
if (lineOffset == 0) {
matcher = startPattern.matcher(line);
return matcher.matches();
} else {
matcher = null;
return false;
}
}
}
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/dummy/AbstractDummyTestLanguageRuntimeModule.java | 4992 | /*
* generated by Xtext
*/
package org.eclipse.xtext.dummy;
import com.google.inject.Binder;
import com.google.inject.Provider;
import com.google.inject.name.Names;
import java.util.Properties;
import org.eclipse.xtext.Constants;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.dummy.parser.antlr.DummyTestLanguageAntlrTokenFileProvider;
import org.eclipse.xtext.dummy.parser.antlr.DummyTestLanguageParser;
import org.eclipse.xtext.dummy.parser.antlr.internal.InternalDummyTestLanguageLexer;
import org.eclipse.xtext.dummy.serializer.DummyTestLanguageSemanticSequencer;
import org.eclipse.xtext.dummy.serializer.DummyTestLanguageSyntacticSequencer;
import org.eclipse.xtext.dummy.services.DummyTestLanguageGrammarAccess;
import org.eclipse.xtext.parser.IParser;
import org.eclipse.xtext.parser.ITokenToStringConverter;
import org.eclipse.xtext.parser.antlr.AntlrTokenDefProvider;
import org.eclipse.xtext.parser.antlr.AntlrTokenToStringConverter;
import org.eclipse.xtext.parser.antlr.IAntlrTokenFileProvider;
import org.eclipse.xtext.parser.antlr.ITokenDefProvider;
import org.eclipse.xtext.parser.antlr.Lexer;
import org.eclipse.xtext.parser.antlr.LexerBindings;
import org.eclipse.xtext.parser.antlr.LexerProvider;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.serializer.impl.Serializer;
import org.eclipse.xtext.serializer.sequencer.ISemanticSequencer;
import org.eclipse.xtext.serializer.sequencer.ISyntacticSequencer;
import org.eclipse.xtext.service.DefaultRuntimeModule;
/**
* Manual modifications go to {@link DummyTestLanguageRuntimeModule}.
*/
@SuppressWarnings("all")
public abstract class AbstractDummyTestLanguageRuntimeModule extends DefaultRuntimeModule {
protected Properties properties = null;
@Override
public void configure(Binder binder) {
properties = tryBindProperties(binder, "org/eclipse/xtext/dummy/DummyTestLanguage.properties");
super.configure(binder);
}
public void configureLanguageName(Binder binder) {
binder.bind(String.class).annotatedWith(Names.named(Constants.LANGUAGE_NAME)).toInstance("org.eclipse.xtext.dummy.DummyTestLanguage");
}
public void configureFileExtensions(Binder binder) {
if (properties == null || properties.getProperty(Constants.FILE_EXTENSIONS) == null)
binder.bind(String.class).annotatedWith(Names.named(Constants.FILE_EXTENSIONS)).toInstance("dummytestlanguage");
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IParser> bindIParser() {
return DummyTestLanguageParser.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends ITokenToStringConverter> bindITokenToStringConverter() {
return AntlrTokenToStringConverter.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends IAntlrTokenFileProvider> bindIAntlrTokenFileProvider() {
return DummyTestLanguageAntlrTokenFileProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends Lexer> bindLexer() {
return InternalDummyTestLanguageLexer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Class<? extends ITokenDefProvider> bindITokenDefProvider() {
return AntlrTokenDefProvider.class;
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public Provider<? extends InternalDummyTestLanguageLexer> provideInternalDummyTestLanguageLexer() {
return LexerProvider.create(InternalDummyTestLanguageLexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.parser.antlr.XtextAntlrGeneratorFragment2
public void configureRuntimeLexer(Binder binder) {
binder.bind(Lexer.class)
.annotatedWith(Names.named(LexerBindings.RUNTIME))
.to(InternalDummyTestLanguageLexer.class);
}
// contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2
public ClassLoader bindClassLoaderToInstance() {
return getClass().getClassLoader();
}
// contributed by org.eclipse.xtext.xtext.generator.grammarAccess.GrammarAccessFragment2
public Class<? extends IGrammarAccess> bindIGrammarAccess() {
return DummyTestLanguageGrammarAccess.class;
}
// contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
public Class<? extends ISemanticSequencer> bindISemanticSequencer() {
return DummyTestLanguageSemanticSequencer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
public Class<? extends ISyntacticSequencer> bindISyntacticSequencer() {
return DummyTestLanguageSyntacticSequencer.class;
}
// contributed by org.eclipse.xtext.xtext.generator.serializer.SerializerFragment2
public Class<? extends ISerializer> bindISerializer() {
return Serializer.class;
}
}
| epl-1.0 |
opendaylight/yangtools | model/yang-model-ri/src/main/java/org/opendaylight/yangtools/yang/model/ri/type/AbstractConstraint.java | 2212 | /*
* Copyright (c) 2021 PANTHEON.tech, s.r.o. 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.opendaylight.yangtools.yang.model.ri.type;
import static com.google.common.base.Verify.verify;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.ImmutableRangeSet;
import com.google.common.collect.Range;
import com.google.common.collect.RangeSet;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.yang.model.api.ConstraintMetaDefinition;
/**
* Abstract base class for {@link ResolvedLengthConstraint} and {@link ResolvedRangeConstraint}.
*
* @param <T> type of constraint
*/
abstract class AbstractConstraint<T extends Number & Comparable<T>> implements ConstraintMetaDefinition {
private final ConstraintMetaDefinition meta;
private final Object ranges;
AbstractConstraint(final ConstraintMetaDefinition meta, final RangeSet<T> ranges) {
this.meta = requireNonNull(meta);
final var tmp = ranges.asRanges();
if (tmp.size() == 1) {
this.ranges = tmp.iterator().next();
} else {
this.ranges = ImmutableRangeSet.copyOf(ranges);
}
}
@Override
public final Optional<String> getDescription() {
return meta.getDescription();
}
@Override
public final Optional<String> getErrorAppTag() {
return meta.getErrorAppTag();
}
@Override
public final Optional<String> getErrorMessage() {
return meta.getErrorMessage();
}
@Override
public final Optional<String> getReference() {
return meta.getReference();
}
@SuppressWarnings("unchecked")
final @NonNull ImmutableRangeSet<T> ranges() {
if (ranges instanceof ImmutableRangeSet) {
return (ImmutableRangeSet<T>) ranges;
}
verify(ranges instanceof Range, "Unexpected range object %s", ranges);
return ImmutableRangeSet.of((Range<T>) ranges);
}
}
| epl-1.0 |
eveCSS/eveCSS | bundles/de.ptb.epics.eve.ecp1/src/de/ptb/epics/eve/ecp1/helper/statustracker/EngineStatusTracker.java | 4599 | package de.ptb.epics.eve.ecp1.helper.statustracker;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.apache.log4j.Logger;
import de.ptb.epics.eve.ecp1.client.ECP1Client;
import de.ptb.epics.eve.ecp1.client.interfaces.IConnectionStateListener;
import de.ptb.epics.eve.ecp1.client.interfaces.IEngineStatusListener;
import de.ptb.epics.eve.ecp1.types.EngineStatus;
/**
* <p>Keeps track of the engine status. Anyone interested in engine status changed
* can call the constructor giving an engine client and a listener which will be
* informed of engine status changes.</p>
*
* <p>Possible engine states are defined in {@link de.ptb.epics.eve.ecp1.types.EngineStatus}.</p>
*
* <p>{@link java.beans.PropertyChangeListener} interested in changes should listen to the {@link #ENGINE_STATUS_PROP} property.</p>
*
* <p>The connection state of the current engine status can be retrieved via {@link #isConnected()}.</p>
*
* @author Marcus Michalsky
* @since 1.28
*/
public class EngineStatusTracker implements IConnectionStateListener, IEngineStatusListener {
private static final Logger LOGGER = Logger.getLogger(EngineStatusTracker.class.getName());
public static final String ENGINE_STATUS_PROP = "currentState";
private final EngineState connected;
private final EngineState disconnected;
private final EngineState executing;
private final EngineState halted;
private final EngineState idleNoXMLLoaded;
private final EngineState idleXMLLoaded;
private final EngineState invalid;
private final EngineState loadingXML;
private final EngineState paused;
private final EngineState stopped;
private EngineState currentState;
private PropertyChangeSupport propertyChangeSupport;
public EngineStatusTracker(ECP1Client engineClient, PropertyChangeListener listener) {
this.connected = Connected.getInstance();
this.disconnected = Disconnected.getInstance();
this.executing = Executing.getInstance();
this.halted = Halted.getInstance();
this.idleNoXMLLoaded = IdleNoXMLLoaded.getInstance();
this.idleXMLLoaded = IdleXMLLoaded.getInstance();
this.invalid = Invalid.getInstance();
this.loadingXML = LoadingXML.getInstance();
this.paused = Paused.getInstance();
this.stopped = Stopped.getInstance();
this.currentState = this.disconnected;
this.propertyChangeSupport = new PropertyChangeSupport(this);
// listener must be registered before listening to the engine, to avoid missed messages
this.propertyChangeSupport.addPropertyChangeListener(listener);
engineClient.addConnectionStateListener(this);
engineClient.addEngineStatusListener(this);
LOGGER.debug("EngineStatusTracker constructed.");
}
/**
* {@inheritDoc}
*/
@Override
public void engineStatusChanged(EngineStatus engineStatus, String xmlName, int repeatCount) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Engine Status changed: " + engineStatus.toString());
}
EngineState oldState = this.currentState;
switch (engineStatus) {
case EXECUTING:
this.currentState = this.executing;
break;
case HALTED:
this.currentState = this.halted;
break;
case IDLE_NO_XML_LOADED:
this.currentState = this.idleNoXMLLoaded;
break;
case IDLE_XML_LOADED:
this.currentState = this.idleXMLLoaded;
break;
case INVALID:
this.currentState = this.invalid;
break;
case LOADING_XML:
this.currentState = this.loadingXML;
break;
case PAUSED:
this.currentState = this.paused;
break;
case STOPPED:
this.currentState = this.stopped;
break;
default:
break;
}
this.propertyChangeSupport.firePropertyChange(
EngineStatusTracker.ENGINE_STATUS_PROP,
oldState, this.currentState);
}
/**
* {@inheritDoc}
*/
@Override
public void stackConnected() {
LOGGER.debug("Engine connected");
EngineState oldState = this.currentState;
this.currentState = this.connected;
this.propertyChangeSupport.firePropertyChange(
EngineStatusTracker.ENGINE_STATUS_PROP,
oldState, this.currentState);
}
/**
* {@inheritDoc}
*/
@Override
public void stackDisconnected() {
LOGGER.debug("Engine disconnected");
EngineState oldState = this.currentState;
this.currentState = this.disconnected;
this.propertyChangeSupport.firePropertyChange(
EngineStatusTracker.ENGINE_STATUS_PROP,
oldState, this.currentState);
}
/**
* Returns whether the engine is connected
* @return <code>true</code> if the engine is connected, <code>false</code> otherwise
*/
public boolean isConnected() {
return this.currentState.isConnected();
}
} | epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/IdentificationVariableBNF.java | 1450 | /*******************************************************************************
* Copyright (c) 2006, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation
*
******************************************************************************/
package org.eclipse.persistence.jpa.jpql.parser;
/**
* The query BNF for an identification variable expression.
*
* @version 2.4
* @since 2.3
* @author Pascal Filion
*/
@SuppressWarnings("nls")
public final class IdentificationVariableBNF extends JPQLQueryBNF {
/**
* The unique identifier of this BNF rule.
*/
public static final String ID = "identification_variable";
/**
* Creates a new <code>IdentificationVariableBNF</code>.
*/
public IdentificationVariableBNF() {
super(ID);
}
/**
* {@inheritDoc}
*/
@Override
protected void initialize() {
super.initialize();
setFallbackBNFId(ID);
setFallbackExpressionFactoryId(IdentificationVariableFactory.ID);
}
} | epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | utils/eclipselink.utils.workbench/uitools/source/org/eclipse/persistence/tools/workbench/uitools/cell/AssociationTextFieldTreeCellEditor.java | 1678 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.uitools.cell;
/**
* Edit a pair of strings held by an association.
* The "key" string will used for the label text,
* the "value" string will placed in the text field.
*
* @see AssociationTextFieldTreeCellRenderer
*/
public class AssociationTextFieldTreeCellEditor extends TextFieldTreeCellEditor {
/**
* Construct a cell editor that behaves like a text field and
* looks like the specified renderer.
*/
public AssociationTextFieldTreeCellEditor(AssociationTextFieldTreeCellRenderer renderer) {
super(renderer);
}
/**
* Extend to notify the renderer that editing has stopped
* and the association's value should be updated with what
* is currently in the text editor.
*/
public boolean stopCellEditing() {
((AssociationTextFieldTreeCellRenderer) this.renderer).updateAssociationValue();
return super.stopCellEditing();
}
}
| epl-1.0 |
Genuitec/piplug-apps | com.genuitec.piplug.app.snake/src/es/org/chemi/games/snake/actions/ExpertAction.java | 1365 | /************************************************************
*
* Copyright (c) 2003 Chemi. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the MIT License
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/mit-license.html
*
************************************************************/
package es.org.chemi.games.snake.actions;
import org.eclipse.jface.action.Action;
import es.org.chemi.games.snake.SnakePlugin;
import es.org.chemi.games.snake.ui.MainView;
import es.org.chemi.games.snake.util.Constants;
public class ExpertAction extends Action {
private MainView view = null;
public ExpertAction(String label, MainView view) {
super(label);
this.view = view;
}
public void run() {
SnakePlugin.trace(this.getClass().getName(),
"Changing game mode to expert."); //$NON-NLS-1$
view.updateActionsUI(Constants.MODE_EXPERT);
view.getPreferences().setMode(Constants.MODE_EXPERT);
// Restart the game.
if (view.getPreferences().isSoundEnabled())
SnakePlugin.getResourceManager().getSound(Constants.SOUND_START)
.play();
view.getGameField().stopGame(false);
view.getGameField().resetGame();
view.getGameField().createGameField();
// view.getPauseAction().setIsGamePaused(false);
view.setFocus();
}
}
| epl-1.0 |
NABUCCO/org.nabucco.framework.exporting | org.nabucco.framework.exporting.ui.rcp/src/main/man/org/nabucco/framework/exporting/ui/rcp/browser/exportconfig/ExportConfigListViewBrowserElementHandlerImpl.java | 3065 | /*
* Copyright 2012 PRODYNA AG
*
* Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or
* http://www.nabucco.org/License.html
*
* 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.nabucco.framework.exporting.ui.rcp.browser.exportconfig;
import java.util.List;
import org.nabucco.framework.exporting.facade.datatype.ExportConfiguration;
import org.nabucco.framework.exporting.ui.rcp.browser.exportconfig.ExportConfigurationEditViewBrowserElement;
import org.nabucco.framework.exporting.ui.rcp.browser.exportconfig.ExportConfigurationListViewBrowserElement;
import org.nabucco.framework.exporting.ui.rcp.browser.exportconfig.ExportConfigurationListViewBrowserElementHandler;
import org.nabucco.framework.exporting.ui.rcp.list.exportconfig.model.ExportConfigurationListViewModel;
import org.nabucco.framework.plugin.base.model.browser.AbstractBrowserListViewHandlerImpl;
import org.nabucco.framework.plugin.base.model.browser.BrowserElement;
/**
* ExportConfigListViewBrowserElementHandlerImpl
*
* @author Christian Nicolaus, PRODYNA AG
*/
public class ExportConfigListViewBrowserElementHandlerImpl extends AbstractBrowserListViewHandlerImpl<ExportConfiguration, ExportConfigurationListViewModel, ExportConfigurationListViewBrowserElement, ExportConfigurationEditViewBrowserElement>
implements ExportConfigurationListViewBrowserElementHandler {
/**
* {@inheritDoc}
*/
@Override
public void createChildren(ExportConfigurationListViewModel viewModel,
ExportConfigurationListViewBrowserElement element) {
for (ExportConfiguration config : viewModel.getElements()) {
element.addBrowserElement(new ExportConfigurationEditViewBrowserElement(config));
}
}
@Override
public void removeChild(BrowserElement toBeRemoved,
ExportConfigurationListViewBrowserElement element) {
removeChildren((ExportConfigurationEditViewBrowserElement)toBeRemoved, element);
}
@Override
public boolean haveSameId(
ExportConfiguration exportConfig,
ExportConfigurationEditViewBrowserElement exportConfigEditViewBrowserElement) {
boolean result = false;
result = exportConfig.getId().equals(
exportConfigEditViewBrowserElement.getViewModel()
.getExportConfig().getId());
return result;
}
@Override
public void updateViewModel(List<ExportConfiguration> elements,
ExportConfigurationListViewModel viewModel) {
viewModel.setElements(elements.toArray(new ExportConfiguration[0]));
}
}
| epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/ch.elexis.base.ch.labortarif_2009/src/ch/elexis/base/ch/labortarif_2009/ui/Labor2009ControlFieldProvider.java | 2642 | /*******************************************************************************
* Copyright (c) 2009, G. Weirich and medelexis AG
* 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
*
*******************************************************************************/
package ch.elexis.base.ch.labortarif_2009.ui;
import java.time.LocalDate;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.e4.core.di.annotations.Optional;
import ch.elexis.base.ch.labortarif.LabortarifPackage;
import ch.elexis.core.model.IEncounter;
import ch.elexis.core.model.ModelPackage;
import ch.elexis.core.services.IQuery;
import ch.elexis.core.services.IQuery.COMPARATOR;
import ch.elexis.core.ui.util.CoreUiUtil;
import ch.elexis.core.ui.util.viewers.CommonViewer;
import ch.elexis.core.ui.util.viewers.DefaultControlFieldProvider;
public class Labor2009ControlFieldProvider extends DefaultControlFieldProvider {
private LocalDate filterDate;
public Labor2009ControlFieldProvider(CommonViewer viewer){
super(viewer, new String[] {
"filter=Filter"
});
CoreUiUtil.injectServicesWithContext(this);
}
@Inject
public void selectedEncounter(@Optional IEncounter encounter){
if (encounter != null) {
this.filterDate = encounter.getDate();
fireChangedEvent();
} else {
this.filterDate = null;
fireChangedEvent();
}
}
@Override
public void setQuery(IQuery<?> query){
String[] values = getValues();
if (values != null && values.length == 1) {
String filterValue = values[0];
String[] filterParts = filterValue.split(" ");
if (filterParts != null) {
for (String string : filterParts) {
if (StringUtils.isNotBlank(string)) {
if (Character.isDigit(string.charAt(0))) {
query.and(ModelPackage.Literals.ICODE_ELEMENT__CODE, COMPARATOR.LIKE,
string + "%", true);
} else {
query.and("name", COMPARATOR.LIKE, string + "%", true);
}
}
}
}
if (filterDate != null) {
query.and(LabortarifPackage.Literals.ILABOR_LEISTUNG__VALID_FROM,
COMPARATOR.LESS_OR_EQUAL, filterDate);
query.startGroup();
query.or(LabortarifPackage.Literals.ILABOR_LEISTUNG__VALID_TO, COMPARATOR.EQUALS,
null);
query.or(LabortarifPackage.Literals.ILABOR_LEISTUNG__VALID_TO,
COMPARATOR.GREATER_OR_EQUAL, filterDate);
query.andJoinGroups();
}
}
}
}
| epl-1.0 |
ossmeter/ossmeter | platform-extensions/org.ossmeter.platform.communicationchannel.zendesk/src/org/ossmeter/platform/communicationchannel/zendesk/Activator.java | 1342 | /*******************************************************************************
* Copyright (c) 2014 OSSMETER Partners.
* 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:
* Juri Di Rocco - Implementation.
* Davide Di Ruscio - Implementation
*******************************************************************************/
package org.ossmeter.platform.communicationchannel.zendesk;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.ossmeter.platform.communicationchannel.zendesk.Activator;
public class Activator implements BundleActivator {
private static BundleContext context;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
}
/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
Activator.context = null;
}
}
| epl-1.0 |
markcullen/kura_Windows | kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/bluetooth/BluetoothBeaconData.java | 395 | package org.eclipse.kura.bluetooth;
public class BluetoothBeaconData {
public String uuid;
public String address;
public int major, minor;
public int rssi;
public int txpower;
@Override
public String toString() {
return "BluetoothBeaconData [uuid=" + uuid + ", address=" + address + ", major=" + major + ", minor=" + minor
+ ", rssi=" + rssi + ", txpower=" + txpower + "]";
}
}
| epl-1.0 |
miklossy/xtext-core | org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/antlr/serializer/Bug301935ExTestLanguageSyntacticSequencer.java | 2145 | /*
* generated by Xtext
*/
package org.eclipse.xtext.parser.antlr.serializer;
import com.google.inject.Inject;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.IGrammarAccess;
import org.eclipse.xtext.RuleCall;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.parser.antlr.services.Bug301935ExTestLanguageGrammarAccess;
import org.eclipse.xtext.serializer.analysis.GrammarAlias.AbstractElementAlias;
import org.eclipse.xtext.serializer.analysis.ISyntacticSequencerPDAProvider.ISynTransition;
import org.eclipse.xtext.serializer.sequencer.AbstractSyntacticSequencer;
@SuppressWarnings("all")
public class Bug301935ExTestLanguageSyntacticSequencer extends AbstractSyntacticSequencer {
protected Bug301935ExTestLanguageGrammarAccess grammarAccess;
@Inject
protected void init(IGrammarAccess access) {
grammarAccess = (Bug301935ExTestLanguageGrammarAccess) access;
}
@Override
protected String getUnassignedRuleCallToken(EObject semanticObject, RuleCall ruleCall, INode node) {
if (ruleCall.getRule() == grammarAccess.getNLRule())
return getNLToken(semanticObject, ruleCall, node);
else if (ruleCall.getRule() == grammarAccess.getWSRule())
return getWSToken(semanticObject, ruleCall, node);
return "";
}
/**
* NL:
* WS* ('\r'? '\n') WS*;
*/
protected String getNLToken(EObject semanticObject, RuleCall ruleCall, INode node) {
if (node != null)
return getTokenText(node);
return "\n";
}
/**
* terminal WS : (' '|'\t')+;
*/
protected String getWSToken(EObject semanticObject, RuleCall ruleCall, INode node) {
if (node != null)
return getTokenText(node);
return " ";
}
@Override
protected void emitUnassignedTokens(EObject semanticObject, ISynTransition transition, INode fromNode, INode toNode) {
if (transition.getAmbiguousSyntaxes().isEmpty()) return;
List<INode> transitionNodes = collectNodes(fromNode, toNode);
for (AbstractElementAlias syntax : transition.getAmbiguousSyntaxes()) {
List<INode> syntaxNodes = getNodesFor(transitionNodes, syntax);
acceptNodes(getLastNavigableState(), syntaxNodes);
}
}
}
| epl-1.0 |
fdesco/Projet-Android | ColoCool/src/com/example/ColoCool/creationliste.java | 2657 | package com.example.ColoCool;
import com.example.projet.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class creationliste extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.creationliste);
Button fruitsetlegumes = (Button) findViewById(R.id.button2);
fruitsetlegumes.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,fruitsetlegumes.class));
}});
Button epicerie = (Button) findViewById(R.id.button3);
epicerie.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,epicerie.class));
}});
Button conserves = (Button) findViewById(R.id.button4);
conserves.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,conserves.class));
}});
Button petitdejgouter = (Button) findViewById(R.id.button5);
petitdejgouter.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,petitdejgouter.class));
}});
Button viandesetpoissons = (Button) findViewById(R.id.button6);
viandesetpoissons.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,viandesetpoissons.class));
}});
Button cremerie = (Button) findViewById(R.id.button7);
cremerie.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,cremerie.class));
}});
Button hygieneetpharmacie = (Button) findViewById(R.id.button8);
hygieneetpharmacie.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,hygieneetpharmacie.class));
}});
Button entretien = (Button) findViewById(R.id.button9);
entretien.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,entretien.class));
}});
Button menu = (Button) findViewById(R.id.button10);
menu.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
startActivity(new Intent(creationliste.this,menu.class));
}});
}} | epl-1.0 |
jmchilton/TINT | projects/TropixProteomicsCore/src/test/edu/umn/msi/tropix/proteomics/itraqquantitation/impl/MathAsserts.java | 1381 | /********************************************************************************
* Copyright (c) 2009 Regents of the University of Minnesota
*
* This Software was written at the Minnesota Supercomputing Institute
* http://msi.umn.edu
*
* All rights reserved. The following statement of license applies
* only to this file, and and not to the other files distributed with it
* or derived therefrom. This file is 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:
* Minnesota Supercomputing Institute - initial API and implementation
*******************************************************************************/
package edu.umn.msi.tropix.proteomics.itraqquantitation.impl;
public class MathAsserts {
public static void assertWithin(final double x, final double y, final double delta) {
assert Math.abs(x - y) < delta : "Expected " + x + " == " + y + " within " + delta + " [Actual difference = " + Math.abs(x - y) + "]";
}
public static void assertWithin(final double[] x, final double[] y, final double delta) {
assert x.length == y.length : " First array has length " + x.length + " second has length " + y.length;
for(int i = 0; i < x.length; i++) {
assertWithin(x[i], y[i], delta);
}
}
}
| epl-1.0 |
ttimbul/eclipse.wst | bundles/org.eclipse.wst.dtd.core/src/org/eclipse/wst/dtd/core/internal/encoding/DTDDocumentLoader.java | 3009 | /*******************************************************************************
* Copyright (c) 2001, 2006 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
* Jens Lukowski/Innoopract - initial renaming/restructuring
*
*******************************************************************************/
package org.eclipse.wst.dtd.core.internal.encoding;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.wst.dtd.core.internal.parser.DTDRegionParser;
import org.eclipse.wst.dtd.core.internal.provisional.contenttype.ContentTypeIdForDTD;
import org.eclipse.wst.dtd.core.internal.text.DTDStructuredDocumentReParser;
import org.eclipse.wst.dtd.core.internal.text.StructuredTextPartitionerForDTD;
import org.eclipse.wst.sse.core.internal.document.AbstractDocumentLoader;
import org.eclipse.wst.sse.core.internal.document.IDocumentCharsetDetector;
import org.eclipse.wst.sse.core.internal.document.StructuredDocumentFactory;
import org.eclipse.wst.sse.core.internal.encoding.ContentTypeEncodingPreferences;
import org.eclipse.wst.sse.core.internal.ltk.parser.RegionParser;
import org.eclipse.wst.sse.core.internal.provisional.document.IEncodedDocument;
import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
import org.eclipse.wst.sse.core.internal.text.BasicStructuredDocument;
public final class DTDDocumentLoader extends AbstractDocumentLoader {
public DTDDocumentLoader() {
super();
}
public IDocumentPartitioner getDefaultDocumentPartitioner() {
return new StructuredTextPartitionerForDTD();
}
public IDocumentCharsetDetector getDocumentEncodingDetector() {
if (fDocumentEncodingDetector == null) {
fDocumentEncodingDetector = new DTDDocumentCharsetDetector();
}
return fDocumentEncodingDetector;
}
public RegionParser getParser() {
return new DTDRegionParser();
}
protected String getPreferredNewLineDelimiter(IFile file) {
String delimiter = ContentTypeEncodingPreferences.getPreferredNewLineDelimiter(ContentTypeIdForDTD.ContentTypeID_DTD);
if (delimiter == null)
delimiter = super.getPreferredNewLineDelimiter(file);
return delimiter;
}
protected String getSpecDefaultEncoding() {
String enc = "UTF-8"; //$NON-NLS-1$
return enc;
}
protected IEncodedDocument newEncodedDocument() {
IStructuredDocument document = StructuredDocumentFactory.getNewStructuredDocumentInstance(getParser());
DTDStructuredDocumentReParser reParser = new DTDStructuredDocumentReParser();
reParser.setStructuredDocument(document);
if (document instanceof BasicStructuredDocument) {
((BasicStructuredDocument) document).setReParser(reParser);
}
return document;
}
}
| epl-1.0 |
nikos/informa | src/main/java/de/nava/informa/utils/NoOpEntityResolver.java | 1092 | //
// Informa -- RSS Library for Java
// Copyright (c) 2002 by Niko Schmuck
//
// 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 de.nava.informa.utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import java.io.StringReader;
/**
* An EntityResolver that resolves the DTD without actually reading
* the separate file.
*
* @author Niko Schmuck
*/
public class NoOpEntityResolver implements EntityResolver {
private static Log logger = LogFactory.getLog(NoOpEntityResolver.class);
public InputSource resolveEntity(String publicId, String systemId) {
if (logger.isDebugEnabled()) {
logger.debug("publicId: " + publicId +
", systemId: " + systemId);
}
return new InputSource(new StringReader(""));
}
}
| epl-1.0 |
opendaylight/yangtools | parser/yang-parser-rfc7950/src/test/java/org/opendaylight/yangtools/yang/stmt/EffectiveIdentityTest.java | 4868 | /*
* Copyright (c) 2016 Cisco Systems, Inc. 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.opendaylight.yangtools.yang.stmt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.opendaylight.yangtools.yang.stmt.StmtTestUtils.sourceForResource;
import com.google.common.collect.Iterables;
import java.net.URISyntaxException;
import java.util.Collection;
import org.junit.Test;
import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.parser.rfc7950.reactor.RFC7950Reactors;
import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
public class EffectiveIdentityTest {
private static final StatementStreamSource IDENTITY_TEST = sourceForResource(
"/stmt-test/identity/identity-test.yang");
private static final StatementStreamSource CYCLIC_IDENTITY_TEST = sourceForResource(
"/stmt-test/identity/cyclic-identity-test.yang");
@Test(expected = SomeModifiersUnresolvedException.class)
public void cyclicefineTest() throws SourceException, ReactorException, URISyntaxException {
CrossSourceStatementReactor.BuildAction reactor = RFC7950Reactors.defaultReactor().newBuild()
.addSources(CYCLIC_IDENTITY_TEST);
try {
reactor.buildEffective();
} catch (SomeModifiersUnresolvedException e) {
StmtTestUtils.log(e, " ");
throw e;
}
}
@Test
public void identityTest() throws SourceException, ReactorException,
URISyntaxException {
SchemaContext result = RFC7950Reactors.defaultReactor().newBuild().addSources(IDENTITY_TEST).buildEffective();
assertNotNull(result);
Module module = result.findModule("identity-test").get();
Collection<? extends IdentitySchemaNode> identities = module.getIdentities();
assertNotNull(identities);
assertEquals(4, identities.size());
IdentitySchemaNode root = null;
IdentitySchemaNode child1 = null;
IdentitySchemaNode child2 = null;
IdentitySchemaNode child12 = null;
for (IdentitySchemaNode identitySchemaNode : identities) {
switch (identitySchemaNode.getQName().getLocalName()) {
case "root-identity":
root = identitySchemaNode;
break;
case "child-identity-1":
child1 = identitySchemaNode;
break;
case "child-identity-2":
child2 = identitySchemaNode;
break;
case "child-identity-1-2":
child12 = identitySchemaNode;
break;
default:
break;
}
}
assertNotNull(root);
assertNotNull(child1);
assertNotNull(child2);
assertNotNull(child12);
assertTrue(root.getBaseIdentities().isEmpty());
Collection<? extends IdentitySchemaNode> rootDerivedIdentities = result.getDerivedIdentities(root);
assertEquals(2, rootDerivedIdentities.size());
assertTrue(rootDerivedIdentities.contains(child1));
assertTrue(rootDerivedIdentities.contains(child2));
assertFalse(rootDerivedIdentities.contains(child12));
assertFalse(child1.equals(child2));
assertTrue(root == Iterables.getOnlyElement(child1.getBaseIdentities()));
assertTrue(root == Iterables.getOnlyElement(child2.getBaseIdentities()));
assertEquals(0, result.getDerivedIdentities(child2).size());
Collection<? extends IdentitySchemaNode> child1DerivedIdentities = result.getDerivedIdentities(child1);
assertEquals(1, child1DerivedIdentities.size());
assertTrue(child1DerivedIdentities.contains(child12));
assertFalse(child1DerivedIdentities.contains(child1));
assertTrue(child1 == Iterables.getOnlyElement(child12.getBaseIdentities()));
assertTrue(child12 == child1DerivedIdentities.iterator().next());
}
}
| epl-1.0 |
sidlors/digital-booking | digital-booking-model/src/main/java/mx/com/cinepolis/digital/booking/model/CategoryTypeLanguageDO.java | 4357 | package mx.com.cinepolis.digital.booking.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* JPA entity for C_CATEGORY_TYPE_LANGUAGE
*
* @author gsegura
* @since 0.0.1
*/
@Entity
@Table(name = "C_CATEGORY_TYPE_LANGUAGE", uniqueConstraints = { @UniqueConstraint(columnNames = { "ID_CATEGORY_TYPE",
"ID_LANGUAGE" }) })
@NamedQueries({
@NamedQuery(name = "CategoryTypeLanguageDO.findAll", query = "SELECT c FROM CategoryTypeLanguageDO c"),
@NamedQuery(name = "CategoryTypeLanguageDO.findByIdCategoryTypeLanguage", query = "SELECT c FROM CategoryTypeLanguageDO c WHERE c.idCategoryTypeLanguage = :idCategoryTypeLanguage"),
@NamedQuery(name = "CategoryTypeLanguageDO.findByDsName", query = "SELECT c FROM CategoryTypeLanguageDO c WHERE c.dsName = :dsName") })
public class CategoryTypeLanguageDO extends AbstractEntity<CategoryTypeLanguageDO>
{
private static final long serialVersionUID = -2300791164367140943L;
@Id
@Column(name = "ID_CATEGORY_TYPE_LANGUAGE", nullable = false)
private Integer idCategoryTypeLanguage;
@Column(name = "DS_NAME", nullable = false, length = 160)
private String dsName;
@JoinColumn(name = "ID_LANGUAGE", referencedColumnName = "ID_LANGUAGE", nullable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private LanguageDO idLanguage;
@JoinColumn(name = "ID_CATEGORY_TYPE", referencedColumnName = "ID_CATEGORY_TYPE", nullable = false)
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private CategoryTypeDO idCategoryType;
/**
* Constructor default
*/
public CategoryTypeLanguageDO()
{
}
/**
* Constructor by idCategoryTypeLanguage
*
* @param idCategoryTypeLanguage
*/
public CategoryTypeLanguageDO( Integer idCategoryTypeLanguage )
{
this.idCategoryTypeLanguage = idCategoryTypeLanguage;
}
/**
* @return the idCategoryTypeLanguage
*/
public Integer getIdCategoryTypeLanguage()
{
return idCategoryTypeLanguage;
}
/**
* @param idCategoryTypeLanguage the idCategoryTypeLanguage to set
*/
public void setIdCategoryTypeLanguage( Integer idCategoryTypeLanguage )
{
this.idCategoryTypeLanguage = idCategoryTypeLanguage;
}
/**
* @return the dsName
*/
public String getDsName()
{
return dsName;
}
/**
* @param dsName the dsName to set
*/
public void setDsName( String dsName )
{
this.dsName = dsName;
}
/**
* @return the idLanguage
*/
public LanguageDO getIdLanguage()
{
return idLanguage;
}
/**
* @param idLanguage the idLanguage to set
*/
public void setIdLanguage( LanguageDO idLanguage )
{
this.idLanguage = idLanguage;
}
/**
* @return the idCategoryType
*/
public CategoryTypeDO getIdCategoryType()
{
return idCategoryType;
}
/**
* @param idCategoryType the idCategoryType to set
*/
public void setIdCategoryType( CategoryTypeDO idCategoryType )
{
this.idCategoryType = idCategoryType;
}
@Override
public int hashCode()
{
int hash = 0;
hash += (idCategoryTypeLanguage != null ? idCategoryTypeLanguage.hashCode() : 0);
return hash;
}
@Override
public boolean equals( Object object )
{
// TODO: Warning - this method won't work in the case the id fields are not set
if( !(object instanceof CategoryTypeLanguageDO) )
{
return false;
}
CategoryTypeLanguageDO other = (CategoryTypeLanguageDO) object;
if( (this.idCategoryTypeLanguage == null && other.idCategoryTypeLanguage != null)
|| (this.idCategoryTypeLanguage != null && !this.idCategoryTypeLanguage.equals( other.idCategoryTypeLanguage )) )
{
return false;
}
return true;
}
@Override
public String toString()
{
return "mx.com.cinepolis.digital.booking.model.CategoryTypeLanguageDO[ idCategoryTypeLanguage="
+ idCategoryTypeLanguage + " ]";
}
@Override
public int compareTo( CategoryTypeLanguageDO other )
{
return this.idCategoryTypeLanguage.compareTo( other.idCategoryTypeLanguage );
}
}
| epl-1.0 |
debabratahazra/OptimaLA | Optima/com.ose.dbgserver/src/com/ose/dbgserver/protocol/DBGGetProcessFullInfoReply.java | 7295 | /*
This module was generated automatically from /vobs/ose5/core_ext/dbgserver/private/dbgserverinterface.stl.
DO NOT EDIT THIS FILE
*/
package com.ose.dbgserver.protocol;
import java.io.*;
public class DBGGetProcessFullInfoReply extends Message implements dbgserverinterfaceConstants{
public int pid;
public int bid;
public int parent;
public int userId;
public short procType;
public short status;
public short priority;
public short signalsInQueue;
public int entryPoint;
public int createTimeTick;
public int createTimeUTick;
public int fsemValue;
public int stackSize;
public int lineNumber;
public int signalBuffers;
public int wantedSignals[];
public String processName;
public String fileName;
public String CPURegisters;
public DBGGetProcessFullInfoReply(int _pid, int _bid, int _parent, int _userId, short _procType, short _status, short _priority, short _signalsInQueue, int _entryPoint, int _createTimeTick, int _createTimeUTick, int _fsemValue, int _stackSize, int _lineNumber, int _signalBuffers, int _wantedSignals[], String _processName, String _fileName, String _CPURegisters) {
pid = _pid;
bid = _bid;
parent = _parent;
userId = _userId;
procType = _procType;
status = _status;
priority = _priority;
signalsInQueue = _signalsInQueue;
entryPoint = _entryPoint;
createTimeTick = _createTimeTick;
createTimeUTick = _createTimeUTick;
fsemValue = _fsemValue;
stackSize = _stackSize;
lineNumber = _lineNumber;
signalBuffers = _signalBuffers;
wantedSignals = _wantedSignals;
processName = _processName;
fileName = _fileName;
CPURegisters = _CPURegisters;
}
public DBGGetProcessFullInfoReply(DataInputStream _s) throws IOException { signalNo = 32962; read(_s);}
public final void sendMessage(DataOutputStream _s) throws IOException { write(_s, this.pid, this.bid, this.parent, this.userId, this.procType, this.status, this.priority, this.signalsInQueue, this.entryPoint, this.createTimeTick, this.createTimeUTick, this.fsemValue, this.stackSize, this.lineNumber, this.signalBuffers, this.wantedSignals, this.processName, this.fileName, this.CPURegisters);}
public final static void write(DataOutputStream _s, int _pid, int _bid, int _parent, int _userId, short _procType, short _status, short _priority, short _signalsInQueue, int _entryPoint, int _createTimeTick, int _createTimeUTick, int _fsemValue, int _stackSize, int _lineNumber, int _signalBuffers, int _wantedSignals[], String _processName, String _fileName, String _CPURegisters ) throws IOException {
int _i;
int _processNameSize=_processName.length()+1;
int _fileNameSize=_fileName.length()+1;
int _CPURegistersSize=_CPURegisters.length()+1;
_s.writeInt(DBGGETPROCESSFULLINFOREPLY);
int _size=60
+4+(((_wantedSignals.length*4) & 3) == 0 ? (_wantedSignals.length*4) : ((_wantedSignals.length*4) + 4 - ((_wantedSignals.length*4)&3)))
+4+((_processNameSize & 3) == 0 ? _processNameSize : (_processNameSize + 4 - (_processNameSize&3)))
+4+((_fileNameSize & 3) == 0 ? _fileNameSize : (_fileNameSize + 4 - (_fileNameSize&3)))
+4+_CPURegistersSize
;
_s.writeInt(_size);
_s.writeInt(_pid);
_s.writeInt(_bid);
_s.writeInt(_parent);
_s.writeInt(_userId);
_s.writeShort(_procType);
_s.writeShort(_status);
_s.writeShort(_priority);
_s.writeShort(_signalsInQueue);
_s.writeInt(_entryPoint);
_s.writeInt(_createTimeTick);
_s.writeInt(_createTimeUTick);
_s.writeInt(_fsemValue);
_s.writeInt(_stackSize);
_s.writeInt(_lineNumber);
_s.writeInt(_signalBuffers);
int _dynSize=60;
int _bytes2Skip;
// write wantedSignals
_bytes2Skip=4-_dynSize&3;
for(_i=0;_i<_bytes2Skip;_i++) _s.writeByte(0);
_dynSize+=_bytes2Skip;
_s.writeInt((_wantedSignals.length*4));
_dynSize+=(_wantedSignals.length*4);
for(_i = 0 ; _i < _wantedSignals.length ; _i++)
_s.writeInt(_wantedSignals[_i]);
// write processName
_bytes2Skip=4-_dynSize&3;
for(_i=0;_i<_bytes2Skip;_i++) _s.writeByte(0);
_dynSize+=_bytes2Skip;
_s.writeInt(_processNameSize);
_dynSize+=_processNameSize;
_s.writeBytes(_processName);
_s.writeByte(0);
// write fileName
_bytes2Skip=4-_dynSize&3;
for(_i=0;_i<_bytes2Skip;_i++) _s.writeByte(0);
_dynSize+=_bytes2Skip;
_s.writeInt(_fileNameSize);
_dynSize+=_fileNameSize;
_s.writeBytes(_fileName);
_s.writeByte(0);
// write CPURegisters
_bytes2Skip=4-_dynSize&3;
for(_i=0;_i<_bytes2Skip;_i++) _s.writeByte(0);
_dynSize+=_bytes2Skip;
_s.writeInt(_CPURegistersSize);
_dynSize+=_CPURegistersSize;
_s.writeBytes(_CPURegisters);
_s.writeByte(0);
}
public final void read(DataInputStream _s) throws IOException {
int _i;
int _size=_s.readInt();
pid=_s.readInt();
bid=_s.readInt();
parent=_s.readInt();
userId=_s.readInt();
procType=_s.readShort();
status=_s.readShort();
priority=_s.readShort();
signalsInQueue=_s.readShort();
entryPoint=_s.readInt();
createTimeTick=_s.readInt();
createTimeUTick=_s.readInt();
fsemValue=_s.readInt();
stackSize=_s.readInt();
lineNumber=_s.readInt();
signalBuffers=_s.readInt();
int _dynSize=60;
int _bytes2Skip;
// read wantedSignals
_bytes2Skip=4-_dynSize&3;
if(_bytes2Skip!=0) {_s.skipBytes(_bytes2Skip);_dynSize+=_bytes2Skip;}
_size=_s.readInt();
_dynSize+=_size;
_size/=4;
wantedSignals=new int[_size];
for(_i = 0 ; _i < _size ; _i++)
wantedSignals[_i]=_s.readInt();
// read processName
_bytes2Skip=4-_dynSize&3;
if(_bytes2Skip!=0) {_s.skipBytes(_bytes2Skip);_dynSize+=_bytes2Skip;}
_size=_s.readInt();
_dynSize+=_size;
byte _processName[] = new byte[_size];
_s.readFully(_processName, 0, _size);
processName=new String(_processName, 0,0, _processName.length-1);
// read fileName
_bytes2Skip=4-_dynSize&3;
if(_bytes2Skip!=0) {_s.skipBytes(_bytes2Skip);_dynSize+=_bytes2Skip;}
_size=_s.readInt();
_dynSize+=_size;
byte _fileName[] = new byte[_size];
_s.readFully(_fileName, 0, _size);
fileName=new String(_fileName, 0,0, _fileName.length-1);
// read CPURegisters
_bytes2Skip=4-_dynSize&3;
if(_bytes2Skip!=0) {_s.skipBytes(_bytes2Skip);_dynSize+=_bytes2Skip;}
_size=_s.readInt();
_dynSize+=_size;
byte _CPURegisters[] = new byte[_size];
_s.readFully(_CPURegisters, 0, _size);
CPURegisters=new String(_CPURegisters, 0,0, _CPURegisters.length-1);
}
}
| epl-1.0 |
adolfosbh/cs2as | org.xtext.example.delphi/emf-gen/org/xtext/example/delphi/astm/impl/IdentifierReferenceImpl.java | 1048 | /**
*/
package org.xtext.example.delphi.astm.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.jdt.annotation.NonNull;
import org.xtext.example.delphi.astm.AstmPackage;
import org.xtext.example.delphi.astm.IdentifierReference;
import org.xtext.example.delphi.astm.util.Visitor;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Identifier Reference</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class IdentifierReferenceImpl extends NameReferenceImpl implements IdentifierReference {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IdentifierReferenceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return AstmPackage.Literals.IDENTIFIER_REFERENCE;
}
/**
* {@inheritDoc}
* @generated
*/
@Override
public <R> R accept(@NonNull Visitor<R> visitor) {
return visitor.visitIdentifierReference(this);
}
} //IdentifierReferenceImpl
| epl-1.0 |
fujaba/BeAST | de.uks.beast.model/src/model/impl/ControlCenterImpl.java | 4682 | /**
*/
package model.impl;
import java.util.Collection;
import model.ControlCenter;
import model.HadoopMaster;
import model.ModelPackage;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectResolvingEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Control Center</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link model.impl.ControlCenterImpl#getMasterNodes <em>Master Nodes</em>}</li>
* <li>{@link model.impl.ControlCenterImpl#getName <em>Name</em>}</li>
* </ul>
*
* @generated
*/
public class ControlCenterImpl extends MinimalEObjectImpl.Container implements ControlCenter
{
/**
* The cached value of the '{@link #getMasterNodes() <em>Master Nodes</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMasterNodes()
* @generated
* @ordered
*/
protected EList<HadoopMaster> masterNodes;
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = "controlCenter";
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* This is true if the Name attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean nameESet;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ControlCenterImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return ModelPackage.Literals.CONTROL_CENTER;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<HadoopMaster> getMasterNodes()
{
if (masterNodes == null)
{
masterNodes = new EObjectResolvingEList<HadoopMaster>(HadoopMaster.class, this, ModelPackage.CONTROL_CENTER__MASTER_NODES);
}
return masterNodes;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName()
{
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetName()
{
return nameESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case ModelPackage.CONTROL_CENTER__MASTER_NODES:
return getMasterNodes();
case ModelPackage.CONTROL_CENTER__NAME:
return getName();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case ModelPackage.CONTROL_CENTER__MASTER_NODES:
getMasterNodes().clear();
getMasterNodes().addAll((Collection<? extends HadoopMaster>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case ModelPackage.CONTROL_CENTER__MASTER_NODES:
getMasterNodes().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case ModelPackage.CONTROL_CENTER__MASTER_NODES:
return masterNodes != null && !masterNodes.isEmpty();
case ModelPackage.CONTROL_CENTER__NAME:
return isSetName();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString()
{
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
if (nameESet) result.append(name); else result.append("<unset>");
result.append(')');
return result.toString();
}
} //ControlCenterImpl
| epl-1.0 |
opendaylight/yangtools | common/util/src/test/java/org/opendaylight/yangtools/util/DurationStatisticsTrackerTest.java | 3541 | /*
* Copyright (c) 2014 Brocade Communications Systems, Inc. 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.opendaylight.yangtools.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit tests for DurationStatsTracker.
*
* @author Thomas Pantelis
*/
public class DurationStatisticsTrackerTest {
@Test
public void test() {
DurationStatisticsTracker tracker = DurationStatisticsTracker.createConcurrent();
tracker.addDuration(10000);
assertEquals("getTotalDurations", 1, tracker.getTotalDurations());
assertEquals("getAverageDuration", 10000.0, tracker.getAverageDuration(), 0.1);
assertEquals("getLongestDuration", 10000, tracker.getLongestDuration());
assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
tracker.addDuration(30000);
assertEquals("getTotalDurations", 2, tracker.getTotalDurations());
assertEquals("getAverageDuration", 20000.0, tracker.getAverageDuration(), 0.1);
assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
verifyDisplayableString("getDisplayableAverageDuration",
tracker.getDisplayableAverageDuration(), "20.0");
verifyDisplayableString("getDisplayableLongestDuration",
tracker.getDisplayableLongestDuration(), "30.0");
verifyDisplayableString("getDisplayableShortestDuration",
tracker.getDisplayableShortestDuration(), "10.0");
tracker.addDuration(10000);
assertEquals("getTotalDurations", 3, tracker.getTotalDurations());
assertEquals("getAverageDuration", 16666.0, tracker.getAverageDuration(), 1.0);
assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
tracker.addDuration(5000);
assertEquals("getTotalDurations", 4, tracker.getTotalDurations());
assertEquals("getAverageDuration", 13750.0, tracker.getAverageDuration(), 1.0);
assertEquals("getLongestDuration", 30000, tracker.getLongestDuration());
assertEquals("getShortestDuration", 5000, tracker.getShortestDuration());
tracker.reset();
assertEquals("getTotalDurations", 0, tracker.getTotalDurations());
assertEquals("getAverageDuration", 0.0, tracker.getAverageDuration(), 0.1);
assertEquals("getLongestDuration", 0, tracker.getLongestDuration());
assertEquals("getShortestDuration", 0, tracker.getShortestDuration());
tracker.addDuration(10000);
assertEquals("getTotalDurations", 1, tracker.getTotalDurations());
assertEquals("getAverageDuration", 10000.0, tracker.getAverageDuration(), 0.1);
assertEquals("getLongestDuration", 10000, tracker.getLongestDuration());
assertEquals("getShortestDuration", 10000, tracker.getShortestDuration());
}
private static void verifyDisplayableString(final String name, final String actual, final String expPrefix) {
assertTrue(name + " starts with " + expPrefix + ". Actual: " + actual,
actual.startsWith(expPrefix));
}
}
| epl-1.0 |
agentlab/org.glassfish.jersey | plugins/org.glassfish.jersey.client/src/main/java/org/glassfish/jersey/client/ClientProperties.java | 18724 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2012-2014 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* http://glassfish.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.jersey.client;
import java.util.Map;
import org.glassfish.jersey.CommonProperties;
import org.glassfish.jersey.internal.util.PropertiesClass;
import org.glassfish.jersey.internal.util.PropertiesHelper;
import org.glassfish.jersey.internal.util.PropertyAlias;
/**
* Jersey client implementation configuration properties.
*
* @author Marek Potociar (marek.potociar at oracle.com)
* @author Libor Kramolis (libor.kramolis at oracle.com)
*/
@PropertiesClass
public final class ClientProperties {
/**
* Automatic redirection. A value of {@code true} declares that the client
* will automatically redirect to the URI declared in 3xx responses.
*
* The value MUST be an instance convertible to {@link java.lang.Boolean}.
* <p />
* The default value is {@code true}.
* <p />
* The name of the configuration property is <tt>{@value}</tt>.
*/
public static final String FOLLOW_REDIRECTS = "jersey.config.client.followRedirects";
/**
* Read timeout interval, in milliseconds.
*
* The value MUST be an instance convertible to {@link java.lang.Integer}. A
* value of zero (0) is equivalent to an interval of infinity.
*
* <p />
* The default value is infinity (0).
* <p />
* The name of the configuration property is <tt>{@value}</tt>.
*/
public static final String READ_TIMEOUT = "jersey.config.client.readTimeout";
/**
* Connect timeout interval, in milliseconds.
*
* The value MUST be an instance convertible to {@link java.lang.Integer}. A
* value of zero (0) is equivalent to an interval of infinity.
* <p />
* The default value is infinity (0).
* <p />
* The name of the configuration property is <tt>{@value}</tt>.
*/
public static final String CONNECT_TIMEOUT = "jersey.config.client.connectTimeout";
/**
* The value MUST be an instance convertible to {@link java.lang.Integer}.
* <p />
* The property defines the size of the chunk in bytes. The property does not enable
* chunked encoding (it is controlled by {@link #REQUEST_ENTITY_PROCESSING} property).
* <p />
* A default value is not set and is {@link org.glassfish.jersey.client.spi.Connector connector}
* implementation-specific.
* <p />
* The name of the configuration property is <tt>{@value}</tt>.
*/
public static final String CHUNKED_ENCODING_SIZE = "jersey.config.client.chunkedEncodingSize";
/**
* Asynchronous thread pool size.
*
* The value MUST be an instance of {@link java.lang.Integer}.
* <p>
* If the property is absent then thread pool used for async requests will
* be initialized as default cached thread pool, which creates new thread
* for every new request, see {@link java.util.concurrent.Executors}. When a
* value > 0 is provided, the created cached thread pool limited to that
* number of threads will be utilized. Zero or negative values will be ignored.
* </p>
* <p>
* Note that the property is ignored if a custom {@link org.glassfish.jersey.spi.RequestExecutorProvider}
* is configured in the client runtime.
* </p>
* <p>
* A default value is not set.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
*/
public static final String ASYNC_THREADPOOL_SIZE = "jersey.config.client.async.threadPoolSize";
/**
* If {@link org.glassfish.jersey.client.filter.EncodingFilter} is
* registered, this property indicates the value of Content-Encoding
* property the filter should be adding.
*
* <p>The value MUST be an instance of {@link String}.</p>
* <p>The default value is {@code null}.</p>
* <p>The name of the configuration property is <tt>{@value}</tt>.</p>
*/
public static final String USE_ENCODING = "jersey.config.client.useEncoding";
/**
* If {@code true} then disable auto-discovery on the client.
* <p>
* By default auto-discovery on client is automatically enabled if global
* property
* {@value org.glassfish.jersey.CommonProperties#FEATURE_AUTO_DISCOVERY_DISABLE}
* is not disabled. If set then the client property value overrides the
* global property value.
* <p>
* The default value is {@code false}.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
* <p>This constant is an alias for {@link CommonProperties#FEATURE_AUTO_DISCOVERY_DISABLE_CLIENT}.</p>
*
* @see org.glassfish.jersey.CommonProperties#FEATURE_AUTO_DISCOVERY_DISABLE
*/
@PropertyAlias
public static final String FEATURE_AUTO_DISCOVERY_DISABLE = CommonProperties.FEATURE_AUTO_DISCOVERY_DISABLE_CLIENT;
/**
* An integer value that defines the buffer size used to buffer client-side
* request entity in order to determine its size and set the value of HTTP
* <tt>{@value javax.ws.rs.core.HttpHeaders#CONTENT_LENGTH}</tt> header.
* <p>
* If the entity size exceeds the configured buffer size, the buffering
* would be cancelled and the entity size would not be determined. Value
* less or equal to zero disable the buffering of the entity at all.
* </p>
* This property can be used on the client side to override the outbound
* message buffer size value - default or the global custom value set using
* the
* {@value org.glassfish.jersey.CommonProperties#OUTBOUND_CONTENT_LENGTH_BUFFER}
* global property.
* <p>
* The default value is
* <tt>8192</tt>.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
* <p>This constant is an alias for {@link CommonProperties#OUTBOUND_CONTENT_LENGTH_BUFFER_CLIENT}.</p>
*
* @since 2.2
*/
@PropertyAlias
public static final String OUTBOUND_CONTENT_LENGTH_BUFFER = CommonProperties.OUTBOUND_CONTENT_LENGTH_BUFFER_CLIENT;
/**
* If {@code true} then disable configuration of Json Processing (JSR-353)
* feature on client.
* <p>
* By default Json Processing on client is automatically enabled if global
* property
* {@value org.glassfish.jersey.CommonProperties#JSON_PROCESSING_FEATURE_DISABLE}
* is not disabled. If set then the client property value overrides the
* global property value.
* <p>
* The default value is {@code false}.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
* <p>This constant is an alias for {@link CommonProperties#JSON_PROCESSING_FEATURE_DISABLE_CLIENT}.</p>
*
* @see org.glassfish.jersey.CommonProperties#JSON_PROCESSING_FEATURE_DISABLE
*/
@PropertyAlias
public static final String JSON_PROCESSING_FEATURE_DISABLE = CommonProperties.JSON_PROCESSING_FEATURE_DISABLE_CLIENT;
/**
* If {@code true} then disable META-INF/services lookup on client.
* <p>
* By default Jersey lookups SPI implementations described by
* META-INF/services/* files. Then you can register appropriate provider
* classes by {@link javax.ws.rs.core.Application}.
* </p>
* <p>
* The default value is {@code false}.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
* <p>This constant is an alias for {@link CommonProperties#METAINF_SERVICES_LOOKUP_DISABLE_CLIENT}.</p>
*
* @see org.glassfish.jersey.CommonProperties#METAINF_SERVICES_LOOKUP_DISABLE
*/
@PropertyAlias
public static final String METAINF_SERVICES_LOOKUP_DISABLE = CommonProperties.METAINF_SERVICES_LOOKUP_DISABLE_CLIENT;
/**
* If {@code true} then disable configuration of MOXy Json feature on
* client.
* <p>
* By default MOXy Json on client is automatically enabled if global
* property
* {@value org.glassfish.jersey.CommonProperties#MOXY_JSON_FEATURE_DISABLE}
* is not disabled. If set then the client property value overrides the
* global property value.
* </p>
* <p>
* The default value is {@code false}.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
* <p>This constant is an alias for {@link CommonProperties#MOXY_JSON_FEATURE_DISABLE_CLIENT}.</p>
*
* @see org.glassfish.jersey.CommonProperties#MOXY_JSON_FEATURE_DISABLE
* @since 2.1
*/
@PropertyAlias
public static final String MOXY_JSON_FEATURE_DISABLE = CommonProperties.MOXY_JSON_FEATURE_DISABLE_CLIENT;
/**
* If {@code true}, the strict validation of HTTP specification compliance
* will be suppressed.
* <p>
* By default, Jersey client runtime performs certain HTTP compliance checks
* (such as which HTTP methods can facilitate non-empty request entities
* etc.) in order to fail fast with an exception when user tries to
* establish a communication non-compliant with HTTP specification. Users
* who need to override these compliance checks and avoid the exceptions
* being thrown by Jersey client runtime for some reason, can set this
* property to {@code true}. As a result, the compliance issues will be
* merely reported in a log and no exceptions will be thrown.
* </p>
* <p>
* Note that the property suppresses the Jersey layer exceptions. Chances
* are that the non-compliant behavior will cause different set of
* exceptions being raised in the underlying I/O connector layer.
* </p>
* <p>
* This property can be configured in a client runtime configuration or
* directly on an individual request. In case of conflict, request-specific
* property value takes precedence over value configured in the runtime
* configuration.
* </p>
* <p>
* The default value is {@code false}.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
*
* @since 2.2
*/
public static final String SUPPRESS_HTTP_COMPLIANCE_VALIDATION =
"jersey.config.client.suppressHttpComplianceValidation";
/**
* The property defines the size of digest cache in the
* {@link org.glassfish.jersey.client.authentication.HttpAuthenticationFeature#digest()} digest filter}.
* Cache contains authentication
* schemes for different request URIs.
* <p\>
* The value MUST be an instance of {@link java.lang.Integer} and it must be
* higher or equal to 1.
* </p>
* <p>
* The default value is {@code 1000}.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
*
* @since 2.3
*/
public static final String DIGESTAUTH_URI_CACHE_SIZELIMIT = "jersey.config.client.digestAuthUriCacheSizeLimit";
// TODO Need to implement support for PROXY-* properties in other connectors
/**
* The property defines a URI of a HTTP proxy the client connector should use.
* <p>
* If the port component of the URI is absent then a default port of {@code 8080} is assumed.
* If the property absent then no proxy will be utilized.
* </p>
* <p>The value MUST be an instance of {@link String}.</p>
* <p>The default value is {@code null}.</p>
* <p>The name of the configuration property is <tt>{@value}</tt>.</p>
*
* @since 2.5
*/
public static final String PROXY_URI = "jersey.config.client.proxy.uri";
/**
* The property defines a user name which will be used for HTTP proxy authentication.
* <p>
* The property is ignored if no {@link #PROXY_URI HTTP proxy URI} has been set.
* If the property absent then no proxy authentication will be utilized.
* </p>
* <p>The value MUST be an instance of {@link String}.</p>
* <p>The default value is {@code null}.</p>
* <p>The name of the configuration property is <tt>{@value}</tt>.</p>
*
* @since 2.5
*/
public static final String PROXY_USERNAME = "jersey.config.client.proxy.username";
/**
* The property defines a user password which will be used for HTTP proxy authentication.
* <p>
* The property is ignored if no {@link #PROXY_URI HTTP proxy URI} has been set.
* If the property absent then no proxy authentication will be utilized.
* </p>
* <p>The value MUST be an instance of {@link String}.</p>
* <p>The default value is {@code null}.</p>
* <p>The name of the configuration property is <tt>{@value}</tt>.</p>
*
* @since 2.5
*/
public static final String PROXY_PASSWORD = "jersey.config.client.proxy.password";
/**
* The property specified how the entity should be serialized to the output stream by the
* {@link org.glassfish.jersey.client.spi.Connector connector}; if the buffering
* should be used or the entity is streamed in chunked encoding.
* <p>
* The value MUST be an instance of {@link String} or an enum value {@link RequestEntityProcessing} in the case
* of programmatic definition of the property. Allowed values are:
* <ul>
* <li><b>{@code BUFFERED}</b>: the entity will be buffered and content length will be send in Content-length header.</li>
* <li><b>{@code CHUNKED}</b>: chunked encoding will be used and entity will be streamed.</li>
* </ul>
* </p>
* <p>
* Default value is {@code CHUNKED}. However, due to limitations some connectors can define different
* default value (usually if the chunked encoding cannot be properly supported on the {@code Connector}).
* This detail should be specified in the javadoc of particular connector. For example, {@link HttpUrlConnector}
* use buffering as the default mode.
* </p>
* <p>
* The name of the configuration property is <tt>{@value}</tt>.
* </p>
* @since 2.5
*/
public static final String REQUEST_ENTITY_PROCESSING = "jersey.config.client.request.entity.processing";
private ClientProperties() {
// prevents instantiation
}
/**
* Get the value of the specified property.
*
* If the property is not set or the real value type is not compatible with
* {@code defaultValue} type, the specified {@code defaultValue} is returned. Calling this method is equivalent to calling
* {@code ClientProperties.getValue(properties, key, defaultValue, (Class<T>) defaultValue.getClass())}
*
* @param properties Map of properties to get the property value from.
* @param key Name of the property.
* @param defaultValue Default value if property is not registered
* @param <T> Type of the property value.
* @return Value of the property or {@code null}.
*
* @since 2.8
*/
public static <T> T getValue(final Map<String, ?> properties, final String key, final T defaultValue) {
return PropertiesHelper.getValue(properties, key, defaultValue, null);
}
/**
* Get the value of the specified property.
*
* If the property is not set or the real value type is not compatible with the specified value type,
* returns {@code defaultValue}.
*
* @param properties Map of properties to get the property value from.
* @param key Name of the property.
* @param defaultValue Default value if property is not registered
* @param type Type to retrieve the value as.
* @param <T> Type of the property value.
* @return Value of the property or {@code null}.
*
* @since 2.8
*/
public static <T> T getValue(final Map<String, ?> properties, final String key, final T defaultValue, final Class<T> type) {
return PropertiesHelper.getValue(properties, key, defaultValue, type, null);
}
/**
* Get the value of the specified property.
*
* If the property is not set or the actual property value type is not compatible with the specified type, the method will
* return {@code null}.
*
* @param properties Map of properties to get the property value from.
* @param key Name of the property.
* @param type Type to retrieve the value as.
* @param <T> Type of the property value.
* @return Value of the property or {@code null}.
*
* @since 2.8
*/
public static <T> T getValue(final Map<String, ?> properties, final String key, final Class<T> type) {
return PropertiesHelper.getValue(properties, key, type, null);
}
}
| epl-1.0 |
amozzhuhin/blacksphere | edu.nops.blacksphere.core/src/edu/nops/blacksphere/core/device/elements/LedMatrixElement.java | 3605 | package edu.nops.blacksphere.core.device.elements;
import java.util.Arrays;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
public class LedMatrixElement extends AbstractChipElement {
@Override
protected void init() {
super.init();
firedRows = new boolean[8];
firedColumns = new boolean[8];
}
public static final String FUNCTION_NAME = "DPY"; //$NON-NLS-1$
public static final String NAME_PREFIX = "HG"; //$NON-NLS-1$
@Override
public String getFunctionName() {
return FUNCTION_NAME;
}
@Override
public String getNamePrefix() {
return NAME_PREFIX;
}
public static final int PIN_A0 = 1;
public static final int PIN_A1 = 2;
public static final int PIN_A2 = 3;
public static final int PIN_A3 = 4;
public static final int PIN_A4 = 5;
public static final int PIN_A5 = 6;
public static final int PIN_A6 = 7;
public static final int PIN_A7 = 8;
public static final int PIN_K0 = 9;
public static final int PIN_K1 = 10;
public static final int PIN_K2 = 11;
public static final int PIN_K3 = 12;
public static final int PIN_K4 = 13;
public static final int PIN_K5 = 14;
public static final int PIN_K6 = 15;
public static final int PIN_K7 = 16;
public static final int PIN_E = 17;
public static String[] PIN_NAMES = {
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
"K0", "K1", "K2", "K3", "K4", "K5", "K6", "K7", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
"~E" //$NON-NLS-1$
};
public static int[][] INPUT_PIN_SECTIONS = {
{PIN_A0, PIN_A1, PIN_A2, PIN_A3, PIN_A4, PIN_A5, PIN_A6, PIN_A7},
{PIN_K0, PIN_K1, PIN_K2, PIN_K3, PIN_K4, PIN_K5, PIN_K6, PIN_K7},
{PIN_E}
};
@Override
public int getPinCount() {
return PIN_NAMES.length;
}
@Override
public String getPinName(int index) {
return PIN_NAMES[index-1];
}
@Override
public int[][] getInputPinSections() {
return INPUT_PIN_SECTIONS;
}
@Override
public boolean hasFace() {
return true;
}
@XStreamOmitField
private boolean[] firedRows;
@XStreamOmitField
private boolean[] firedColumns;
public static final String FIRED_ROWS_PROP = "ledmatrix.firedRows"; //$NON-NLS-1$
public static final String FIRED_COLUMNS_PROP = "ledmatrix.firedColumns"; //$NON-NLS-1$
public boolean[] getFiredColumns() {
return firedColumns;
}
public void setFiredColumns(boolean[] firedColumns) {
boolean[] oldFiredColumns = this.firedColumns;
this.firedColumns = firedColumns;
if (!Arrays.equals(oldFiredColumns, firedColumns))
firePropertyChange(FIRED_COLUMNS_PROP, oldFiredColumns, firedColumns);
}
public boolean[] getFiredRows() {
return firedRows;
}
public void setFiredRows(boolean[] firedRows) {
boolean[] oldFiredRows = this.firedRows;
this.firedRows = firedRows;
if (!Arrays.equals(oldFiredRows, firedRows))
firePropertyChange(FIRED_ROWS_PROP, oldFiredRows, firedRows);
}
@Override
protected void doRefresh() {
super.doRefresh();
if (!getLogicInputValue(PIN_E)) {
boolean[] rows = new boolean[8];
for (int i = PIN_K0; i <= PIN_K7; i++)
rows[i-PIN_K0] = !getLogicInputValue(i);
setFiredRows(rows);
boolean[] cols = new boolean[8];
for (int i = PIN_A0; i <= PIN_A7; i++)
cols[i-PIN_A0] = getLogicInputValue(i);
setFiredColumns(cols);
} else {
boolean[] hidden = new boolean[8];
for (int i = 0; i < hidden.length; i++)
hidden[i] = false;
setFiredColumns(hidden);
setFiredRows(hidden);
}
}
}
| epl-1.0 |
andreamargheri/FACPL | XACML2FACPL/src/it/unifi/xacmlToFacpl/jaxb/MissingAttributeDetailType.java | 5851 | /*******************************************************************************
* Copyright (c) 2016 Andrea Margheri
* 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:
* Andrea Margheri
*******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// 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: 2013.01.22 at 04:37:38 PM CET
//
package it.unifi.xacmlToFacpl.jaxb;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for MissingAttributeDetailType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="MissingAttributeDetailType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}AttributeValue" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attribute name="Category" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="AttributeId" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="DataType" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
* <attribute name="Issuer" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MissingAttributeDetailType", propOrder = {
"attributeValue"
})
public class MissingAttributeDetailType {
@XmlElement(name = "AttributeValue")
protected List<AttributeValueType> attributeValue;
@XmlAttribute(name = "Category", required = true)
@XmlSchemaType(name = "anyURI")
protected String category;
@XmlAttribute(name = "AttributeId", required = true)
@XmlSchemaType(name = "anyURI")
protected String attributeId;
@XmlAttribute(name = "DataType", required = true)
@XmlSchemaType(name = "anyURI")
protected String dataType;
@XmlAttribute(name = "Issuer")
protected String issuer;
/**
* Gets the value of the attributeValue property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the attributeValue property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAttributeValue().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AttributeValueType }
*
*
*/
public List<AttributeValueType> getAttributeValue() {
if (attributeValue == null) {
attributeValue = new ArrayList<AttributeValueType>();
}
return this.attributeValue;
}
/**
* Gets the value of the category property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCategory() {
return category;
}
/**
* Sets the value of the category property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCategory(String value) {
this.category = value;
}
/**
* Gets the value of the attributeId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAttributeId() {
return attributeId;
}
/**
* Sets the value of the attributeId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAttributeId(String value) {
this.attributeId = value;
}
/**
* Gets the value of the dataType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataType() {
return dataType;
}
/**
* Sets the value of the dataType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataType(String value) {
this.dataType = value;
}
/**
* Gets the value of the issuer property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIssuer() {
return issuer;
}
/**
* Sets the value of the issuer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIssuer(String value) {
this.issuer = value;
}
}
| epl-1.0 |
dejanb/hono | adapters/mqtt-vertx-base/src/test/java/org/eclipse/hono/adapter/mqtt/AbstractVertxBasedMqttProtocolAdapterTest.java | 34686 | /*******************************************************************************
* Copyright (c) 2016, 2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* 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.eclipse.hono.adapter.mqtt;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.net.HttpURLConnection;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import org.apache.qpid.proton.message.Message;
import org.eclipse.hono.client.ClientErrorException;
import org.eclipse.hono.client.HonoClient;
import org.eclipse.hono.client.MessageSender;
import org.eclipse.hono.client.RegistrationClient;
import org.eclipse.hono.client.TenantClient;
import org.eclipse.hono.config.ProtocolAdapterProperties;
import org.eclipse.hono.service.auth.device.Device;
import org.eclipse.hono.service.auth.device.DeviceCredentials;
import org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider;
import org.eclipse.hono.service.auth.device.UsernamePasswordCredentials;
import org.eclipse.hono.service.command.CommandConnection;
import org.eclipse.hono.util.EventConstants;
import org.eclipse.hono.util.RegistrationConstants;
import org.eclipse.hono.util.ResourceIdentifier;
import org.eclipse.hono.util.TelemetryConstants;
import org.eclipse.hono.util.TenantConstants;
import org.eclipse.hono.util.TenantObject;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.mqtt.MqttAuth;
import io.vertx.mqtt.MqttEndpoint;
import io.vertx.mqtt.MqttServer;
import io.vertx.mqtt.messages.MqttPublishMessage;
import io.vertx.proton.ProtonDelivery;
/**
* Verifies behavior of {@link AbstractVertxBasedMqttProtocolAdapter}.
*
*/
@RunWith(VertxUnitRunner.class)
public class AbstractVertxBasedMqttProtocolAdapterTest {
private static final String ADAPTER_TYPE = "mqtt";
private static Vertx vertx = Vertx.vertx();
/**
* Global timeout for all test cases.
*/
@Rule
public Timeout globalTimeout = new Timeout(2, TimeUnit.SECONDS);
private HonoClient tenantServiceClient;
private HonoClient credentialsServiceClient;
private HonoClient messagingClient;
private HonoClient deviceRegistrationServiceClient;
private RegistrationClient regClient;
private TenantClient tenantClient;
private HonoClientBasedAuthProvider usernamePasswordAuthProvider;
private ProtocolAdapterProperties config;
private MqttAdapterMetrics metrics;
private CommandConnection commandConnection;
private Context context;
/**
* Creates clients for the needed micro services and sets the configuration to enable the insecure port.
*/
@Before
@SuppressWarnings("unchecked")
public void setup() {
context = mock(Context.class);
doAnswer(invocation -> {
final Handler<Void> handler = invocation.getArgument(0);
handler.handle(null);
return null;
}).when(context).runOnContext(any(Handler.class));
config = new ProtocolAdapterProperties();
config.setInsecurePortEnabled(true);
metrics = mock(MqttAdapterMetrics.class);
regClient = mock(RegistrationClient.class);
final JsonObject result = new JsonObject().put(RegistrationConstants.FIELD_ASSERTION, "token");
when(regClient.assertRegistration(anyString(), (String) any(), (SpanContext) any())).thenReturn(Future.succeededFuture(result));
tenantClient = mock(TenantClient.class);
when(tenantClient.get(anyString(), (SpanContext) any())).thenAnswer(invocation -> {
return Future.succeededFuture(TenantObject.from(invocation.getArgument(0), true));
});
tenantServiceClient = mock(HonoClient.class);
when(tenantServiceClient.connect(any(Handler.class))).thenReturn(Future.succeededFuture(tenantServiceClient));
when(tenantServiceClient.getOrCreateTenantClient()).thenReturn(Future.succeededFuture(tenantClient));
credentialsServiceClient = mock(HonoClient.class);
when(credentialsServiceClient.connect(any(Handler.class)))
.thenReturn(Future.succeededFuture(credentialsServiceClient));
messagingClient = mock(HonoClient.class);
when(messagingClient.connect(any(Handler.class))).thenReturn(Future.succeededFuture(messagingClient));
when(messagingClient.getOrCreateEventSender(anyString())).thenReturn(Future.succeededFuture(mock(MessageSender.class)));
when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(mock(MessageSender.class)));
deviceRegistrationServiceClient = mock(HonoClient.class);
when(deviceRegistrationServiceClient.connect(any(Handler.class)))
.thenReturn(Future.succeededFuture(deviceRegistrationServiceClient));
when(deviceRegistrationServiceClient.getOrCreateRegistrationClient(anyString()))
.thenReturn(Future.succeededFuture(regClient));
commandConnection = mock(CommandConnection.class);
when(commandConnection.connect(any(Handler.class))).thenReturn(Future.succeededFuture(commandConnection));
usernamePasswordAuthProvider = mock(HonoClientBasedAuthProvider.class);
}
/**
* Cleans up fixture.
*/
@AfterClass
public static void shutDown() {
vertx.close();
}
private static MqttContext newMqttContext(final MqttPublishMessage message, final MqttEndpoint endpoint) {
final MqttContext result = new MqttContext(message, endpoint);
final Span currentSpan = mock(Span.class);
when(currentSpan.context()).thenReturn(mock(SpanContext.class));
result.put(AbstractVertxBasedMqttProtocolAdapter.KEY_CURRENT_SPAN, currentSpan);
return result;
}
/**
* Verifies that an MQTT server is bound to the insecure port during startup and connections to required services
* have been established.
*
* @param ctx The helper to use for running async tests on vertx.
*/
@SuppressWarnings("unchecked")
@Test
public void testStartup(final TestContext ctx) {
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
final Async startup = ctx.async();
final Future<Void> startupTracker = Future.future();
startupTracker.setHandler(ctx.asyncAssertSuccess(s -> {
startup.complete();
}));
adapter.start(startupTracker);
startup.await();
verify(server).listen(any(Handler.class));
verify(server).endpointHandler(any(Handler.class));
}
// TODO: startup fail test
/**
* Verifies that a connection attempt from a device is refused if the adapter is not connected to all of the
* services it depends on.
*/
@Test
public void testEndpointHandlerFailsWithoutConnect() {
// GIVEN an endpoint
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
adapter.handleEndpointConnection(endpoint);
verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
}
/**
* Verifies that an adapter that is configured to not require devices to authenticate, accepts connections from
* devices not providing any credentials.
*/
@Test
public void testEndpointHandlerAcceptsUnauthenticatedDevices() {
// GIVEN an adapter that does not require devices to authenticate
config.setAuthenticationRequired(false);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
// WHEN a device connects without providing credentials
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
adapter.handleEndpointConnection(endpoint);
// THEN the connection is established
verify(endpoint).accept(false);
}
/**
* Verifies that an adapter rejects a connection attempt from a device that belongs to a tenant for which the
* adapter is disabled.
*/
@Test
public void testEndpointHandlerRejectsDeviceOfDisabledTenant() {
// GIVEN an adapter
final MqttServer server = getMqttServer(false);
// which is disabled for tenant "my-tenant"
final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
myTenantConfig.addAdapterConfiguration(new JsonObject()
.put(TenantConstants.FIELD_ADAPTERS_TYPE, ADAPTER_TYPE)
.put(TenantConstants.FIELD_ENABLED, false));
when(tenantClient.get(eq("my-tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(myTenantConfig));
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
// WHEN a device of "my-tenant" tries to connect
final MqttAuth deviceCredentials = new MqttAuth("device@my-tenant", "irrelevant");
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.auth()).thenReturn(deviceCredentials);
adapter.handleEndpointConnection(endpoint);
// THEN the connection is not established
verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
}
/**
* Verifies that an adapter that is configured to require devices to authenticate, rejects connections from devices
* not providing any credentials.
*/
@Test
public void testEndpointHandlerRejectsUnauthenticatedDevices() {
// GIVEN an adapter that does require devices to authenticate
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
// WHEN a device connects without providing any credentials
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
adapter.handleEndpointConnection(endpoint);
// THEN the connection is refused
verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
}
/**
* Verifies that an adapter retrieves credentials on record for a device connecting to the adapter.
*/
@SuppressWarnings("unchecked")
@Test
public void testEndpointHandlerRetrievesCredentialsOnRecord() {
// GIVEN an adapter requiring devices to authenticate endpoint
final MqttServer server = getMqttServer(false);
config.setAuthenticationRequired(true);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
adapter.handleEndpointConnection(endpoint);
verify(usernamePasswordAuthProvider).authenticate(any(UsernamePasswordCredentials.class), any(Handler.class));
}
/**
* Verifies that on successful authentication the adapter sets appropriate message and close handlers on the client
* endpoint.
*/
@SuppressWarnings({ "unchecked" })
@Test
public void testAuthenticatedMqttAdapterCreatesMessageHandlersForAuthenticatedDevices() {
// GIVEN an adapter
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
doAnswer(invocation -> {
final Handler<AsyncResult<Device>> resultHandler = invocation.getArgument(1);
resultHandler.handle(Future.succeededFuture(new Device("DEFAULT_TENANT", "4711")));
return null;
}).when(usernamePasswordAuthProvider).authenticate(any(DeviceCredentials.class), any(Handler.class));
// WHEN a device tries to connect with valid credentials
final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
adapter.handleEndpointConnection(endpoint);
// THEN the device's logical ID is successfully established and corresponding handlers
// are registered
final ArgumentCaptor<DeviceCredentials> credentialsCaptor = ArgumentCaptor.forClass(DeviceCredentials.class);
verify(usernamePasswordAuthProvider).authenticate(credentialsCaptor.capture(), any(Handler.class));
assertThat(credentialsCaptor.getValue().getAuthId(), is("sensor1"));
verify(endpoint).accept(false);
verify(endpoint).publishHandler(any(Handler.class));
verify(endpoint).closeHandler(any(Handler.class));
}
/**
* Verifies that the adapter registers message handlers on client connections when device authentication is
* disabled.
*/
@SuppressWarnings("unchecked")
@Test
public void testUnauthenticatedMqttAdapterCreatesMessageHandlersForAllDevices() {
// GIVEN an adapter that does not require devices to authenticate
config.setAuthenticationRequired(false);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
// WHEN a device connects that does not provide any credentials
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
adapter.handleEndpointConnection(endpoint);
// THEN the connection is established and handlers are registered
verify(usernamePasswordAuthProvider, never()).authenticate(any(DeviceCredentials.class), any(Handler.class));
verify(endpoint).publishHandler(any(Handler.class));
verify(endpoint).closeHandler(any(Handler.class));
verify(endpoint).accept(false);
}
/**
* Verifies that the adapter does not forward a message published by a device if the device's registration status
* cannot be asserted.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadTelemetryMessageFailsForUnknownDevice(final TestContext ctx) {
// GIVEN an adapter
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
givenAQoS0TelemetrySender();
// WHEN an unknown device publishes a telemetry message
when(regClient.assertRegistration(eq("unknown"), any(), any())).thenReturn(
Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_NOT_FOUND)));
final MessageSender sender = mock(MessageSender.class);
when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(sender));
adapter.uploadTelemetryMessage(
newMqttContext(mock(MqttPublishMessage.class), mock(MqttEndpoint.class)),
"my-tenant",
"unknown",
Buffer.buffer("test")).setHandler(ctx.asyncAssertFailure(t -> {
// THEN the message has not been sent downstream
verify(sender, never()).send(any(Message.class));
// because the device's registration status could not be asserted
ctx.assertEquals(HttpURLConnection.HTTP_NOT_FOUND,
((ClientErrorException) t).getErrorCode());
}));
}
/**
* Verifies that the adapter does not forward a message published by a device if the device belongs to a tenant for
* which the adapter has been disabled.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadTelemetryMessageFailsForDisabledTenant(final TestContext ctx) {
// GIVEN an adapter
final MqttServer server = getMqttServer(false);
// which is disabled for tenant "my-tenant"
final TenantObject myTenantConfig = TenantObject.from("my-tenant", true);
myTenantConfig.addAdapterConfiguration(new JsonObject()
.put(TenantConstants.FIELD_ADAPTERS_TYPE, ADAPTER_TYPE)
.put(TenantConstants.FIELD_ENABLED, false));
when(tenantClient.get(eq("my-tenant"), (SpanContext) any())).thenReturn(Future.succeededFuture(myTenantConfig));
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final MessageSender sender = mock(MessageSender.class);
when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(sender));
// WHEN a device of "my-tenant" publishes a telemetry message
adapter.uploadTelemetryMessage(
newMqttContext(mock(MqttPublishMessage.class), mock(MqttEndpoint.class)),
"my-tenant",
"the-device",
Buffer.buffer("test")).setHandler(ctx.asyncAssertFailure(t -> {
// THEN the message has not been sent downstream
verify(sender, never()).send(any(Message.class));
// because the tenant is not enabled
ctx.assertEquals(HttpURLConnection.HTTP_FORBIDDEN,
((ClientErrorException) t).getErrorCode());
}));
}
/**
* Verifies that the adapter waits for an event being settled and accepted by a downstream peer before sending a
* PUBACK package to the device.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadEventMessageSendsPubAckOnSuccess(final TestContext ctx) {
// GIVEN an adapter with a downstream event consumer
final Future<ProtonDelivery> outcome = Future.future();
givenAnEventSenderForOutcome(outcome);
testUploadQoS1MessageSendsPubAckOnSuccess(outcome, (adapter, mqttContext) -> {
adapter.uploadEventMessage(mqttContext, "my-tenant", "4712", mqttContext.message().payload())
.setHandler(ctx.asyncAssertSuccess());
});
}
/**
* Verifies that the adapter waits for a QoS 1 telemetry message being settled
* and accepted by a downstream peer before sending a PUBACK package to the device.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadTelemetryMessageSendsPubAckOnSuccess(final TestContext ctx) {
// GIVEN an adapter with a downstream telemetry consumer
final Future<ProtonDelivery> outcome = Future.future();
givenAQoS1TelemetrySender(outcome);
testUploadQoS1MessageSendsPubAckOnSuccess(outcome, (adapter, mqttContext) -> {
// WHEN forwarding a telemetry message that has been published with QoS 1
adapter.uploadTelemetryMessage(mqttContext, "my-tenant", "4712", mqttContext.message().payload())
.setHandler(ctx.asyncAssertSuccess());
});
}
private void testUploadQoS1MessageSendsPubAckOnSuccess(
final Future<ProtonDelivery> outcome,
final BiConsumer<AbstractVertxBasedMqttProtocolAdapter<?>, MqttContext> upload) {
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
// WHEN a device publishes a message using QoS 1
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
final Buffer payload = Buffer.buffer("some payload");
final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
when(messageFromDevice.messageId()).thenReturn(5555555);
when(messageFromDevice.payload()).thenReturn(payload);
final MqttContext context = newMqttContext(messageFromDevice, endpoint);
upload.accept(adapter, context);
// THEN the device does not receive a PUBACK
verify(endpoint, never()).publishAcknowledge(anyInt());
// until the message has been settled and accepted
outcome.complete(mock(ProtonDelivery.class));
verify(endpoint).publishAcknowledge(5555555);
}
/**
* Verifies that the adapter does not send a PUBACK package to the device if an event message has not been accepted
* by the peer.
*
* @param ctx The vert.x test context.
*/
@Test
public void testOnUnauthenticatedMessageDoesNotSendPubAckOnFailure(final TestContext ctx) {
// GIVEN an adapter with a downstream event consumer
final Future<ProtonDelivery> outcome = Future.future();
givenAnEventSenderForOutcome(outcome);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
// WHEN a device publishes an event
final Buffer payload = Buffer.buffer("some payload");
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
when(messageFromDevice.messageId()).thenReturn(5555555);
final MqttContext context = newMqttContext(messageFromDevice, endpoint);
adapter.uploadEventMessage(context, "my-tenant", "4712", payload).setHandler(ctx.asyncAssertFailure());
// and the peer rejects the message
outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
// THEN the device has not received a PUBACK
verify(endpoint, never()).publishAcknowledge(anyInt());
}
/**
*
* Verifies that the adapter will accept uploading messages to standard as well
* as shortened topic names.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadMessageSupportsShortAndLongEndpointNames(final TestContext ctx) {
// GIVEN an adapter with downstream telemetry & event consumers
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
givenAQoS1TelemetrySender(Future.succeededFuture(mock(ProtonDelivery.class)));
givenAnEventSenderForOutcome(Future.succeededFuture(mock(ProtonDelivery.class)));
// WHEN a device publishes events and telemetry messages
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
final Buffer payload = Buffer.buffer("some payload");
final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
when(messageFromDevice.messageId()).thenReturn(5555555);
when(messageFromDevice.payload()).thenReturn(payload);
final MqttContext context = newMqttContext(messageFromDevice, endpoint);
ResourceIdentifier resourceId = ResourceIdentifier.from("telemetry", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("event", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("t", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("e", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("unknown", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertFailure());
}
private void forceClientMocksToConnected() {
when(tenantServiceClient.isConnected()).thenReturn(Future.succeededFuture());
when(messagingClient.isConnected()).thenReturn(Future.succeededFuture());
when(deviceRegistrationServiceClient.isConnected()).thenReturn(Future.succeededFuture());
when(credentialsServiceClient.isConnected()).thenReturn(Future.succeededFuture());
}
private MqttEndpoint getMqttEndpointAuthenticated(final String username, final String password) {
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.auth()).thenReturn(new MqttAuth(username, password));
return endpoint;
}
private MqttEndpoint getMqttEndpointAuthenticated() {
return getMqttEndpointAuthenticated("sensor1@DEFAULT_TENANT", "test");
}
@SuppressWarnings("unchecked")
private static MqttServer getMqttServer(final boolean startupShouldFail) {
final MqttServer server = mock(MqttServer.class);
when(server.actualPort()).thenReturn(0, 1883);
when(server.endpointHandler(any(Handler.class))).thenReturn(server);
when(server.listen(any(Handler.class))).then(invocation -> {
final Handler<AsyncResult<MqttServer>> handler = invocation.getArgument(0);
if (startupShouldFail) {
handler.handle(Future.failedFuture("MQTT server intentionally failed to start"));
} else {
handler.handle(Future.succeededFuture(server));
}
return server;
});
return server;
}
private AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> getAdapter(final MqttServer server) {
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = new AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties>() {
@Override
protected String getTypeName() {
return ADAPTER_TYPE;
}
@Override
protected Future<Void> onPublishedMessage(final MqttContext ctx) {
final ResourceIdentifier topic = ResourceIdentifier.fromString(ctx.message().topicName());
return uploadTelemetryMessage(ctx, topic.getTenantId(), topic.getResourceId(), ctx.message().payload());
}
};
adapter.setConfig(config);
adapter.setMetrics(metrics);
adapter.setTenantServiceClient(tenantServiceClient);
adapter.setHonoMessagingClient(messagingClient);
adapter.setRegistrationServiceClient(deviceRegistrationServiceClient);
adapter.setCredentialsServiceClient(credentialsServiceClient);
adapter.setCommandConnection(commandConnection);
adapter.setUsernamePasswordAuthProvider(usernamePasswordAuthProvider);
if (server != null) {
adapter.setMqttInsecureServer(server);
adapter.init(vertx, context);
}
return adapter;
}
private void givenAnEventSenderForOutcome(final Future<ProtonDelivery> outcome) {
final MessageSender sender = mock(MessageSender.class);
when(sender.getEndpoint()).thenReturn(EventConstants.EVENT_ENDPOINT);
when(sender.send(any(Message.class), (SpanContext) any())).thenReturn(outcome);
when(sender.sendAndWaitForOutcome(any(Message.class), (SpanContext) any())).thenReturn(outcome);
when(messagingClient.getOrCreateEventSender(anyString())).thenReturn(Future.succeededFuture(sender));
}
private void givenAQoS0TelemetrySender() {
final MessageSender sender = mock(MessageSender.class);
when(sender.getEndpoint()).thenReturn(TelemetryConstants.TELEMETRY_ENDPOINT);
when(sender.send(any(Message.class), (SpanContext) any())).thenReturn(Future.succeededFuture(mock(ProtonDelivery.class)));
when(sender.sendAndWaitForOutcome(any(Message.class), (SpanContext) any())).thenThrow(new UnsupportedOperationException());
when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(sender));
}
private void givenAQoS1TelemetrySender(final Future<ProtonDelivery> outcome) {
final MessageSender sender = mock(MessageSender.class);
when(sender.getEndpoint()).thenReturn(TelemetryConstants.TELEMETRY_ENDPOINT);
when(sender.send(any(Message.class), (SpanContext) any())).thenThrow(new UnsupportedOperationException());
when(sender.sendAndWaitForOutcome(any(Message.class), (SpanContext) any())).thenReturn(outcome);
when(messagingClient.getOrCreateTelemetrySender(anyString())).thenReturn(Future.succeededFuture(sender));
}
/**
* Verify that a missing password rejects the connection.
* <p>
* The connection must be rejected with the code {@link MqttConnectReturnCode#CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD}.
*/
@Test
public void testMissingPassword() {
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final MqttEndpoint endpoint = getMqttEndpointAuthenticated("foo", null);
adapter.handleEndpointConnection(endpoint);
verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
}
/**
* Verify that a missing username rejects the connection.
* <p>
* The connection must be rejected with the code {@link MqttConnectReturnCode#CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD}.
*/
@Test
public void testMissingUsername() {
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final MqttEndpoint endpoint = getMqttEndpointAuthenticated(null, "bar");
adapter.handleEndpointConnection(endpoint);
verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);
}
/**
* Verifies the connection metrics for authenticated connections.
* <p>
* This test should check if the metrics receive a call to increment and decrement when a connection is being
* established and then closed.
*/
@SuppressWarnings("unchecked")
@Test
public void testConnectionMetrics() {
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
doAnswer(invocation -> {
final Handler<AsyncResult<Device>> resultHandler = invocation.getArgument(1);
resultHandler.handle(Future.succeededFuture(new Device("DEFAULT_TENANT", "4711")));
return null;
}).when(usernamePasswordAuthProvider).authenticate(any(DeviceCredentials.class), any(Handler.class));
final AtomicReference<Handler<Void>> closeHandlerRef = new AtomicReference<>();
final MqttEndpoint endpoint = getMqttEndpointAuthenticated();
doAnswer(invocation -> {
closeHandlerRef.set(invocation.getArgument(0));
return endpoint;
}).when(endpoint).closeHandler(any(Handler.class));
adapter.handleEndpointConnection(endpoint);
verify(metrics).incrementMqttConnections("DEFAULT_TENANT");
closeHandlerRef.get().handle(null);
verify(metrics).decrementMqttConnections("DEFAULT_TENANT");
}
/**
* Verifies the connection metrics for unauthenticated connections.
* <p>
* This test should check if the metrics receive a call to increment and decrement when a connection is being
* established and then closed.
*/
@SuppressWarnings("unchecked")
@Test
public void testUnauthenticatedConnectionMetrics() {
config.setAuthenticationRequired(false);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
forceClientMocksToConnected();
final AtomicReference<Handler<Void>> closeHandlerRef = new AtomicReference<>();
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
doAnswer(invocation -> {
closeHandlerRef.set(invocation.getArgument(0));
return endpoint;
}).when(endpoint).closeHandler(any(Handler.class));
adapter.handleEndpointConnection(endpoint);
verify(metrics).incrementUnauthenticatedMqttConnections();
closeHandlerRef.get().handle(null);
verify(metrics).decrementUnauthenticatedMqttConnections();
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | sdo/eclipselink.sdo.test/src/org/eclipse/persistence/testing/sdo/helper/jaxbhelper/identity/IdentityProject.java | 2208 | /*******************************************************************************
* Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* bdoughan - Feb 3/2009 - 1.1 - Initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.jaxbhelper.identity;
import org.eclipse.persistence.oxm.NamespaceResolver;
import org.eclipse.persistence.oxm.XMLDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
import org.eclipse.persistence.oxm.schema.XMLSchemaClassPathReference;
import org.eclipse.persistence.platform.xml.XMLSchemaReference;
import org.eclipse.persistence.sessions.Project;
public class IdentityProject extends Project {
public IdentityProject() {
super();
this.addDescriptor(getRootDescriptor());
}
private XMLDescriptor getRootDescriptor() {
XMLDescriptor xmlDescriptor = new XMLDescriptor();
xmlDescriptor.setJavaClass(Root.class);
xmlDescriptor.setDefaultRootElement("tns:root");
XMLSchemaClassPathReference schemaReference = new XMLSchemaClassPathReference();
schemaReference.setSchemaContext("/tns:root-type");
schemaReference.setType(XMLSchemaReference.COMPLEX_TYPE);
xmlDescriptor.setSchemaReference(schemaReference);
NamespaceResolver namespaceResolver = new NamespaceResolver();
namespaceResolver.put("tns", "urn:identity");
xmlDescriptor.setNamespaceResolver(namespaceResolver);
XMLDirectMapping nameMapping = new XMLDirectMapping();
nameMapping.setAttributeName("name");
nameMapping.setXPath("tns:name/text()");
return xmlDescriptor;
}
}
| epl-1.0 |
ubc-cs-spl/command-recommender | plugins/ca.ubc.cs.commandrecommender.usagedata.gathering/src/ca/ubc/cs/commandrecommender/usagedata/gathering/contextwriters/ContextWriter.java | 1045 | package ca.ubc.cs.commandrecommender.usagedata.gathering.contextwriters;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class ContextWriter implements ActionListener, IContextWriter {
protected static final int DELAY = 10000; // ten seconds in milliseconds
protected Timer timer;
private static final ActiveEditorCapture aec = new ActiveEditorCapture();
private static final ScreenCapture tsc = new ScreenCapture();
private boolean captureToggle;
private static ContextWriter instance;
public static ContextWriter getInstance() {
if (instance == null) {
instance = new ContextWriter();
}
return instance;
}
private ContextWriter() {
timer = new Timer(DELAY, this);
timer.start();
captureToggle = false;
}
public void switchCaptureMode(boolean captureModeVal) {
captureToggle = captureModeVal;
}
public void actionPerformed(ActionEvent e) {
if (captureToggle) {
tsc.captureScreenContext();
} else {
aec.captureEditorContext();
}
}
}
| epl-1.0 |
debrief/debrief | org.mwc.cmap.legacy/src/MWC/Utilities/ReaderWriter/XML/Features/ChartBoundsHandler.java | 5578 |
package MWC.Utilities.ReaderWriter.XML.Features;
/*******************************************************************************
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2020, Deep Blue C Technology Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* 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.
*******************************************************************************/
import java.awt.Color;
import MWC.GenericData.WorldLocation;
import MWC.Utilities.ReaderWriter.XML.PlottableExporter;
import MWC.Utilities.ReaderWriter.XML.Util.ColourHandler;
import MWC.Utilities.ReaderWriter.XML.Util.FontHandler;
import MWC.Utilities.ReaderWriter.XML.Util.LocationHandler;
abstract public class ChartBoundsHandler extends MWC.Utilities.ReaderWriter.XML.MWCXMLReader
implements PlottableExporter {
private static final String CHART_REFERENCE = "ChartReference";
private static final String FILE_NAME = "FileName";
private static final String BOTTOM_RIGHT = "BottomRight";
private static final String TOP_LEFT = "TopLeft";
/**
* class which contains list of textual representations of label locations
*/
static final MWC.GUI.Properties.LocationPropertyEditor lp = new MWC.GUI.Properties.LocationPropertyEditor();
/**
* and define the strings used to describe the shape
*
*/
private static final String LABEL_VISIBLE = "LabelVisible";
private static final String SHAPE_VISIBLE = "Visible";
private static final String LABEL_LOCATION = "LabelLocation";
private static final String LABEL_TEXT = "Label";
String _myType = null;
String _label = null;
java.awt.Font _font = null;
Integer _theLocation = null;
boolean _isVisible = false;
boolean _labelVisible = true;
private WorldLocation _tl;
private WorldLocation _br;
private Color _col;
protected String _filename;
public ChartBoundsHandler() {
// inform our parent what type of class we are
super(CHART_REFERENCE);
addHandler(new LocationHandler(TOP_LEFT) {
@Override
public void setLocation(final WorldLocation res) {
_tl = res;
}
});
addHandler(new LocationHandler(BOTTOM_RIGHT) {
@Override
public void setLocation(final WorldLocation res) {
_br = res;
}
});
addHandler(new FontHandler() {
@Override
public void setFont(final java.awt.Font font) {
_font = font;
}
});
addAttributeHandler(new HandleAttribute(LABEL_TEXT) {
@Override
public void setValue(final String name, final String value) {
_label = fromXML(value);
}
});
addHandler(new ColourHandler() {
@Override
public void setColour(final Color res) {
_col = res;
}
});
addAttributeHandler(new HandleAttribute(LABEL_LOCATION) {
@Override
public void setValue(final String name, final String val) {
lp.setAsText(val);
_theLocation = (Integer) lp.getValue();
}
});
addAttributeHandler(new HandleAttribute(FILE_NAME) {
@Override
public void setValue(final String name, final String val) {
_filename = val;
}
});
addAttributeHandler(new HandleBooleanAttribute(SHAPE_VISIBLE) {
@Override
public void setValue(final String name, final boolean value) {
_isVisible = value;
}
});
addAttributeHandler(new HandleBooleanAttribute(LABEL_VISIBLE) {
@Override
public void setValue(final String name, final boolean value) {
_labelVisible = value;
}
});
}
abstract public void addPlottable(MWC.GUI.Plottable plottable);
@Override
public void elementClosed() {
final MWC.GUI.Shapes.ChartBoundsWrapper sw = new MWC.GUI.Shapes.ChartBoundsWrapper(_label, _tl, _br, _col,
_filename);
if (_theLocation != null) {
sw.setLabelLocation(_theLocation);
}
sw.setVisible(_isVisible);
sw.setLabelVisible(_labelVisible);
addPlottable(sw);
// reset the local parameters
_label = null;
_theLocation = null;
_isVisible = true;
_filename = null;
}
@Override
public void exportThisPlottable(final MWC.GUI.Plottable plottable, final org.w3c.dom.Element parent,
final org.w3c.dom.Document doc) {
// output the shape related stuff first
final org.w3c.dom.Element theShape = doc.createElement(CHART_REFERENCE);
final MWC.GUI.Shapes.ChartBoundsWrapper sw = (MWC.GUI.Shapes.ChartBoundsWrapper) plottable;
// put the parameters into the parent
theShape.setAttribute(LABEL_TEXT, toXML(sw.getName()));
theShape.setAttribute(FILE_NAME, sw.getFileName());
lp.setValue(sw.getLabelLocation());
theShape.setAttribute(LABEL_LOCATION, lp.getAsText());
theShape.setAttribute(SHAPE_VISIBLE, writeThis(sw.getVisible()));
theShape.setAttribute(LABEL_VISIBLE, writeThis(sw.getLabelVisible()));
// output the colour for the shape
MWC.Utilities.ReaderWriter.XML.Util.ColourHandler.exportColour(sw.getShape().getColor(), theShape, doc);
// and the rectangle corners
LocationHandler.exportLocation(sw.getShape().getCorner_TopLeft(), TOP_LEFT, theShape, doc);
LocationHandler.exportLocation(sw.getShape().getCornerBottomRight(), BOTTOM_RIGHT, theShape, doc);
// add ourselves to the output
parent.appendChild(theShape);
}
} | epl-1.0 |
earnou/rcptraining | com.sii.restaurant.edit/src/com/sii/restaurant/restaurant/provider/RestaurantEditPlugin.java | 1890 | /**
*/
package com.sii.restaurant.restaurant.provider;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.common.util.ResourceLocator;
/**
* This is the central singleton for the Restaurant edit plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public final class RestaurantEditPlugin extends EMFPlugin {
/**
* Keep track of the singleton.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final RestaurantEditPlugin INSTANCE = new RestaurantEditPlugin();
/**
* Keep track of the singleton.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static Implementation plugin;
/**
* Create the instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RestaurantEditPlugin() {
super
(new ResourceLocator [] {
});
}
/**
* Returns the singleton instance of the Eclipse plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the singleton instance.
* @generated
*/
@Override
public ResourceLocator getPluginResourceLocator() {
return plugin;
}
/**
* Returns the singleton instance of the Eclipse plugin.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the singleton instance.
* @generated
*/
public static Implementation getPlugin() {
return plugin;
}
/**
* The actual implementation of the Eclipse <b>Plugin</b>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static class Implementation extends EclipsePlugin {
/**
* Creates an instance.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Implementation() {
super();
// Remember the static instance.
//
plugin = this;
}
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/io.openliberty.opentracing.3.x_fat/test-applications/mpOpenTracing/src/io/openliberty/opentracing/internal/test/mpot/POJO.java | 998 | /*******************************************************************************
* 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 io.openliberty.opentracing.internal.test.mpot;
import jakarta.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.opentracing.Traced;
/**
* POJO to test Traced annotation.
*/
@ApplicationScoped
@Traced
public class POJO {
/**
* Method that we expect to be Traced implicitly.
*/
public void annotatedClassMethodImplicitlyTraced() {
System.out.println("Called annotatedClassMethodImplicitlyTraced");
}
}
| epl-1.0 |
debrief/debrief | org.mwc.cmap.legacy/src/MWC/GenericData/WorldPath.java | 14058 |
package MWC.GenericData;
/*******************************************************************************
* Debrief - the Open Source Maritime Analysis Application
* http://debrief.info
*
* (C) 2000-2020, Deep Blue C Technology Ltd
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html)
*
* 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.
*******************************************************************************/
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;
public final class WorldPath implements java.io.Serializable {
//////////////////////////////////////////////////////////////////////////////////////////////////
// testing for this class
//////////////////////////////////////////////////////////////////////////////////////////////////
static public final class PathTest extends junit.framework.TestCase {
static public final String TEST_ALL_TEST_TYPE = "UNIT";
public PathTest(final String val) {
super(val);
}
private void showPath(final WorldPath path) {
final Vector<WorldLocation> pts = path._myPoints;
for (int i = 0; i < pts.size(); i++) {
final WorldLocation location = pts.elementAt(i);
System.out.println("" + location.getLong() + ", " + location.getLat() + ", " + location.getDepth());
}
}
public final void testBreakPath() {
final WorldLocation loc1 = new WorldLocation(0, 0, 0);
final WorldLocation loc2 = new WorldLocation(0, 2, 0);
final WorldLocation loc3 = new WorldLocation(0, 0, 4);
final WorldLocation loc4 = new WorldLocation(0, 0, 8);
final WorldLocation loc5 = new WorldLocation(0, 3, 4);
final WorldPath newPath = new WorldPath(new WorldLocation[] { loc1, loc2, loc3, loc4, loc5 });
final WorldPath brokenDownPath = newPath.breakIntoStraightSections(2);
assertEquals("broken down into wrong number of sections - is it implemented even?", 2,
brokenDownPath.size(), 0);
}
public void testBreakSections() {
final WorldPath thePath = new WorldPath(
new WorldLocation[] { new WorldLocation(0, 0, 0), new WorldLocation(2, 1, 0),
new WorldLocation(3, 4, 0), new WorldLocation(2, 5, 0), new WorldLocation(0, 6, 0) });
final int PATH_LENGTH = 8;
final WorldPath brokenPath = thePath.breakIntoStraightSections(PATH_LENGTH);
// get some checks in
assertEquals("path not of correct length", PATH_LENGTH, brokenPath.size());
assertEquals("doesn't finish at correct point", thePath._myPoints.lastElement(),
brokenPath._myPoints.lastElement());
showPath(thePath);
showPath(brokenPath);
}
public void testBreakSections2() {
final WorldPath thePath = new WorldPath(new WorldLocation[] {
new WorldLocation.LocalLocation(new WorldDistance(0, WorldDistance.NM),
new WorldDistance(0, WorldDistance.NM), 0),
new WorldLocation.LocalLocation(new WorldDistance(20, WorldDistance.NM),
new WorldDistance(25, WorldDistance.NM), 0),
new WorldLocation.LocalLocation(new WorldDistance(40, WorldDistance.NM),
new WorldDistance(30, WorldDistance.NM), 0),
new WorldLocation.LocalLocation(new WorldDistance(60, WorldDistance.NM),
new WorldDistance(40, WorldDistance.NM), 0)
});
final int PATH_LENGTH = 8;
final WorldPath brokenPath = thePath.breakIntoStraightSections(PATH_LENGTH);
// get some checks in
assertEquals("path not of correct length", PATH_LENGTH, brokenPath.size());
assertEquals("doesn't finish at correct point", thePath._myPoints.lastElement(),
brokenPath._myPoints.lastElement());
showPath(thePath);
showPath(brokenPath);
}
public final void testMovement() {
final WorldLocation w1 = new WorldLocation(1, 1, 1);
final WorldLocation w2 = new WorldLocation(2, 2, 2);
final WorldLocation w3 = new WorldLocation(3, 3, 3);
final WorldLocation w4 = new WorldLocation(4, 4, 4);
final WorldLocation w5 = new WorldLocation(5, 5, 5);
final WorldPath path = new WorldPath();
path.addPoint(w1);
// check the area
WorldArea ar = path.getBounds();
assertTrue("area updated", ar.equals(new WorldArea(w1, w1)));
path.addPoint(w2);
assertTrue("area changed", !(ar.equals(path.getBounds())));
path.addPoint(w3);
path.addPoint(w4);
// add duff point
path.addPoint(null);
// check they're all there
assertEquals("all points loaded", 4, path._myPoints.size());
// check the area
ar = path.getBounds();
assertTrue("full area contained", ar.equals(new WorldArea(w1, w4)));
assertEquals("found fourth item", w4, path.getLocationAt(3));
// move up
path.moveUpward(w4);
assertEquals("found third in fourth slot item", w3, path.getLocationAt(3));
// move invalid upwards
path.moveUpward(w5);
// move first upwards
path.moveUpward(w1);
assertEquals("first item still in slot", w1, path.getLocationAt(0));
// move last downwards
path.moveDownward(w3);
assertEquals("last item still in slot", w3, path.getLocationAt(3));
// move invalid downwards
path.moveDownward(w5);
// remove invalid
path.remove(w5);
assertEquals("still contains 4", 4, path.size());
// remove others
path.remove(w3);
assertEquals("dropped to 3", 3, path.size());
// move first upwards
path.moveUpward(w1);
assertEquals("first item still in slot", w1, path.getLocationAt(0));
// move last downwards
path.moveDownward(w4);
assertEquals("last item still in slot", w4, path.getLocationAt(2));
path.remove(w2);
path.remove(w1);
path.moveUpward(w4);
path.moveDownward(w4);
path.remove(w4);
path.moveUpward(w4);
ar = path.getBounds();
assertEquals("empty area with no points", null, ar);
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
//////////////////////////////////////////////////////////////////////
// Member Variables
//////////////////////////////////////////////////////////////////////
/**
* our points
*/
Vector<WorldLocation> _myPoints;
/**
* the area we cover
*/
private WorldArea _myBounds;
//////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////
public WorldPath() {
_myPoints = new Vector<WorldLocation>(0, 1);
}
public WorldPath(final WorldLocation[] path) {
_myPoints = new Vector<WorldLocation>(path.length, 1);
for (int i = 0; i < path.length; i++) {
_myPoints.add(new WorldLocation(path[i]));
}
refreshBounds();
}
public WorldPath(final WorldPath path) {
_myPoints = new Vector<WorldLocation>(path.size(), 1);
for (int i = 0; i < path.size(); i++) {
_myPoints.add(new WorldLocation(path.getLocationAt(i)));
}
refreshBounds();
}
/**
* copy the other path into ourselves
*
* @param destinations path to copy
*/
public void add(final WorldPath destinations) {
for (int i = 0; i < destinations.size(); i++) {
addPoint(new WorldLocation(destinations.getLocationAt(i)));
}
}
/**
* add this location
*/
public final void addPoint(final WorldLocation loc) {
// check it's not null
if (loc == null)
return;
_myPoints.addElement(loc);
// update the bounds
refreshBounds();
}
/**
* break the provided path into a number of straight legs
*
* @param numStops the number of legs to break down
* @return broken down path
*/
public WorldPath breakIntoStraightSections(final int numStops) {
final double leg_length = getTotalDistance().getValueIn(WorldDistance.DEGS) / numStops;
double needed = leg_length;
int thisSection = 1;
int thisLeg = 0;
WorldVector sep = getSeparation(thisLeg);
double currentBearing = sep.getBearing();
double leg_remaining = sep.getRange();
final WorldPath res = new WorldPath();
WorldLocation lastOrigin = _myPoints.firstElement();
while (thisSection < numStops) {
// ok, is there enough left in this leg to finish off a point?
if (leg_remaining >= needed) {
// ok, we can mark off this point, and move on to the next
// consume a little more
leg_remaining -= needed;
// create this intermediate point
final WorldLocation newLoc = lastOrigin.add(new WorldVector(currentBearing, needed, 0));
res.addPoint(new WorldLocation(newLoc));
thisSection++;
needed = leg_length;
lastOrigin = newLoc;
} else {
// or do we need to move onto the next path point?
// ok, use up the remaining distance
needed -= leg_remaining;
// ok, move on to the next point.
thisLeg++;
sep = getSeparation(thisLeg);
currentBearing = sep.getBearing();
leg_remaining = sep.getRange();
lastOrigin = _myPoints.elementAt(thisLeg);
}
}
// ok, dropped out. just use the last point as the final one
res.addPoint(new WorldLocation(_myPoints.lastElement()));
//
//
// // do some funny processing just to make use of getTotalDistance.
// WorldDistance totalLen = getTotalDistance();
// if (totalLen != null)
// totalLen = null;
//
//
// // @@ hack - we should be calculating this stuff.
// WorldPath res = new WorldPath(this);
return res;
}
/**
* equality operator
*/
@Override
public final boolean equals(final Object obj) {
if (obj == null)
return false;
final WorldPath other = (WorldPath) obj;
boolean equals = true;
// how long is our list
final int num = _myPoints.size();
// see if they are the same size
if (other.size() != num) {
// different lengths, cannot be equals
equals = false;
} else {
// so they're the same length
for (int i = 0; i < num; i++) {
//
if (!_myPoints.elementAt(i).equals(other._myPoints.elementAt(i))) {
// hey, they're different!
equals = false;
break;
}
}
}
return equals;
}
/**
* get the bounds of the area
*/
public final WorldArea getBounds() {
return _myBounds;
}
/**
* get the indicated location
*/
public final WorldLocation getLocationAt(final int i) {
return _myPoints.elementAt(i);
}
//////////////////////////////////////////////////////////////////////
// Member methods
//////////////////////////////////////////////////////////////////////
/**
* get the list of locations
*/
public final Collection<WorldLocation> getPoints() {
return _myPoints;
}
private WorldVector getSeparation(final int thisLeg) {
final WorldLocation lasPoint = _myPoints.elementAt(thisLeg);
final WorldLocation nextPoint = _myPoints.elementAt(thisLeg + 1);
final WorldVector sep = nextPoint.subtract(lasPoint);
return sep;
}
/**
* calculate the total distance covered by this path
*
* @return total distance
*/
private WorldDistance getTotalDistance() {
double degs = 0d;
WorldLocation lastLocation = null;
for (final Iterator<WorldLocation> iterator = _myPoints.iterator(); iterator.hasNext();) {
final WorldLocation thisPoint = iterator.next();
if (lastLocation != null) {
final double thisDegs = thisPoint.rangeFrom(lastLocation);
degs += thisDegs;
}
lastLocation = thisPoint;
}
// and convert the elapsed distance back
final WorldDistance res = new WorldDistance(degs, WorldDistance.DEGS);
return res; // To change body of created methods use File | Settings | File Templates.
}
/**
* get the index of a particular point
*
*/
public int indexOf(final WorldLocation loc) {
return _myPoints.indexOf(loc);
}
/**
* put this location in at the indicated point
*
* @param loc
* @param index
*/
public void insertPointAt(final WorldLocation loc, final int index) {
_myPoints.insertElementAt(loc, index);
}
/**
* move the indicated point down the list by one
*/
public final void moveDownward(final WorldLocation point) {
final int index = _myPoints.indexOf(point);
if (index != -1) {
// ok, at least it's in the list, now remove it
_myPoints.remove(point);
// produce the new index
final int newIndex = Math.min(_myPoints.size(), index + 1);
// and put it in
_myPoints.insertElementAt(point, newIndex);
}
}
/**
* move the indicate point up the list by one
*/
public final void moveUpward(final WorldLocation point) {
final int index = _myPoints.indexOf(point);
if (index != -1) {
// ok, at least it's in the list, now remove it
_myPoints.remove(point);
// produce the new index
final int newIndex = Math.max(0, index - 1);
// and put it in
_myPoints.insertElementAt(point, newIndex);
}
}
/**
* refresh the area covered
*/
public final void refreshBounds() {
WorldArea res = null;
final Iterator<WorldLocation> it = _myPoints.iterator();
while (it.hasNext()) {
final WorldLocation nx = it.next();
if (res == null)
res = new WorldArea(nx, nx);
else
res.extend(nx);
}
_myBounds = res;
}
/**
* remove the indicated point from the list
*/
public final void remove(final WorldLocation point) {
_myPoints.remove(point);
refreshBounds();
}
/**
* the length of the list
*/
public final int size() {
return _myPoints.size();
}
@Override
public String toString() {
return getPoints().size() + " Points";
}
/***************************************************************
* main method, to test this class
***************************************************************/
} | epl-1.0 |
rmcilroy/HeraJVM | rvm/src/org/jikesrvm/runtime/VM_SysCall.java | 14280 | /*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Common Public License (CPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/cpl1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.jikesrvm.runtime;
import org.jikesrvm.apt.annotations.GenerateImplementation;
import org.jikesrvm.apt.annotations.SysCallTemplate;
import org.jikesrvm.scheduler.VM_Processor;
import org.vmmagic.pragma.Uninterruptible;
import org.vmmagic.unboxed.Address;
import org.vmmagic.unboxed.Extent;
import org.vmmagic.unboxed.Offset;
/**
* Support for lowlevel (ie non-JNI) invocation of C functions with
* static addresses.
*
* All methods of this class have the following signature:
* <pre>
* public abstract <TYPE> NAME(<args to pass to sysNAME via native calling convention>)
* </pre>
* which will call the corresponding method in system call trampoline
* with the added function address from the boot image.
* <p>
* NOTE: From the standpoint of the rest of the VM, an invocation
* to a method of VM_SysCall is uninterruptible.
* <p>
* NOTE: There must be a matching field NAMEIP in VM_BootRecord.java
* for each method declared here.
*/
@Uninterruptible
@GenerateImplementation(generatedClass = "org.jikesrvm.runtime.VM_SysCallImpl")
public abstract class VM_SysCall {
public static final VM_SysCall sysCall = VM_SysCallUtil.getImplementation(VM_SysCall.class);
// lowlevel write to console
@SysCallTemplate
public abstract void sysConsoleWriteChar(char v);
@SysCallTemplate
public abstract void sysConsoleWriteInteger(int value, int hexToo);
@SysCallTemplate
public abstract void sysConsoleWriteLong(long value, int hexToo);
@SysCallTemplate
public abstract void sysConsoleWriteDouble(double value, int postDecimalDigits);
// startup/shutdown
@SysCallTemplate
public abstract void sysExit(int value);
@SysCallTemplate
public abstract int sysArg(int argno, byte[] buf, int buflen);
// misc. info on the process -- used in startup/shutdown
@SysCallTemplate
public abstract int sysGetenv(byte[] varName, byte[] buf, int limit);
// memory
@SysCallTemplate
public abstract void sysCopy(Address dst, Address src, Extent cnt);
@SysCallTemplate
public abstract Address sysMalloc(int length);
@SysCallTemplate
public abstract Address sysCalloc(int length);
@SysCallTemplate
public abstract void sysFree(Address location);
@SysCallTemplate
public abstract void sysZero(Address dst, Extent cnt);
@SysCallTemplate
public abstract void sysZeroPages(Address dst, int cnt);
@SysCallTemplate
public abstract void sysSyncCache(Address address, int size);
/*
* Interface to performance counters
*/
@SysCallTemplate
public abstract void sysPerfCtrInit(int metric);
@SysCallTemplate
public abstract void sysPerfCtrRead(byte[] name);
@SysCallTemplate
public abstract long sysPerfCtrReadMetric();
@SysCallTemplate
public abstract long sysPerfCtrReadCycles();
// files
@SysCallTemplate
public abstract int sysStat(byte[] name, int kind);
@SysCallTemplate
public abstract int sysReadByte(int fd);
@SysCallTemplate
public abstract int sysWriteByte(int fd, int data);
@SysCallTemplate
public abstract int sysReadBytes(int fd, Address buf, int cnt);
@SysCallTemplate
public abstract int sysWriteBytes(int fd, Address buf, int cnt);
@SysCallTemplate
public abstract int sysBytesAvailable(int fd);
@SysCallTemplate
public abstract int sysSyncFile(int fd);
@SysCallTemplate
public abstract int sysSetFdCloseOnExec(int fd);
@SysCallTemplate
public abstract int sysAccess(byte[] name, int kind);
// mmap - memory mapping
@SysCallTemplate
public abstract Address sysMMap(Address start, Extent length, int protection, int flags, int fd, Offset offset);
@SysCallTemplate
public abstract Address sysMMapErrno(Address start, Extent length, int protection, int flags, int fd, Offset offset);
@SysCallTemplate
public abstract int sysMProtect(Address start, Extent length, int prot);
@SysCallTemplate
public abstract int sysGetPageSize();
// threads
@SysCallTemplate
public abstract int sysNumProcessors();
/**
* Create a virtual processor (aka "unix kernel thread", "pthread").
* @param jtoc register values to use for thread startup
* @param pr
* @param ip
* @param fp
* @return virtual processor's o/s handle
*/
@SysCallTemplate
public abstract int sysVirtualProcessorCreate(Address jtoc, Address pr, Address ip, Address fp);
/**
* Bind execution of current virtual processor to specified physical cpu.
* @param cpuid physical cpu id (0, 1, 2, ...)
*/
@SysCallTemplate
public abstract void sysVirtualProcessorBind(int cpuid);
@SysCallTemplate
public abstract void sysVirtualProcessorYield();
/**
* Start interrupt generator for thread timeslicing.
* The interrupt will be delivered to whatever virtual processor happens
* to be running when the timer expires.
*/
@SysCallTemplate
public abstract void sysVirtualProcessorEnableTimeSlicing(int timeSlice);
@SysCallTemplate
public abstract int sysPthreadSelf();
@SysCallTemplate
public abstract void sysPthreadSetupSignalHandling();
@SysCallTemplate
public abstract int sysPthreadSignal(int pthread);
@SysCallTemplate
public abstract void sysPthreadExit();
@SysCallTemplate
public abstract int sysPthreadJoin(int pthread);
@SysCallTemplate
public abstract int sysStashVmProcessorInPthread(VM_Processor vmProcessor);
// arithmetic
@SysCallTemplate
public abstract long sysLongDivide(long x, long y);
@SysCallTemplate
public abstract long sysLongRemainder(long x, long y);
@SysCallTemplate
public abstract float sysLongToFloat(long x);
@SysCallTemplate
public abstract double sysLongToDouble(long x);
@SysCallTemplate
public abstract int sysFloatToInt(float x);
@SysCallTemplate
public abstract int sysDoubleToInt(double x);
@SysCallTemplate
public abstract long sysFloatToLong(float x);
@SysCallTemplate
public abstract long sysDoubleToLong(double x);
@SysCallTemplate
public abstract double sysDoubleRemainder(double x, double y);
/**
* Used to parse command line arguments that are
* doubles and floats early in booting before it
* is safe to call Float.valueOf or Double.valueOf.
*
* This aborts in case of errors, with an appropriate error message.
*
* NOTE: this does not support the full Java spec of parsing a string
* into a float.
* @param buf a null terminated byte[] that can be parsed
* by strtof()
* @return the floating-point value produced by the call to strtof() on buf.
*/
@SysCallTemplate
public abstract float sysPrimitiveParseFloat(byte[] buf);
/**
* Used to parse command line arguments that are
* bytes and ints early in booting before it
* is safe to call Byte.parseByte or Integer.parseInt.
*
* This aborts in case of errors, with an appropriate error message.
*
* @param buf a null terminated byte[] that can be parsed
* by strtol()
* @return the int value produced by the call to strtol() on buf.
*/
@SysCallTemplate
public abstract int sysPrimitiveParseInt(byte[] buf);
/** Parse memory sizes passed as command-line arguments.
*/
@SysCallTemplate
public abstract long sysParseMemorySize(byte[] sizeName, byte[] sizeFlag, byte[] defaultFactor, int roundTo,
byte[] argToken, byte[] subArg);
// time
@SysCallTemplate
public abstract long sysCurrentTimeMillis();
@SysCallTemplate
public abstract long sysNanoTime();
@SysCallTemplate
public abstract void sysNanosleep(long howLongNanos);
// shared libraries
@SysCallTemplate
public abstract Address sysDlopen(byte[] libname);
@SysCallTemplate
public abstract Address sysDlsym(Address libHandler, byte[] symbolName);
// network
@SysCallTemplate
public abstract int sysNetSocketCreate(int isStream);
@SysCallTemplate
public abstract int sysNetSocketPort(int fd);
@SysCallTemplate
public abstract int sysNetSocketSndBuf(int fd);
@SysCallTemplate
public abstract int sysNetSocketFamily(int fd);
@SysCallTemplate
public abstract int sysNetSocketLocalAddress(int fd);
@SysCallTemplate
public abstract int sysNetSocketBind(int fd, int family, int localAddress, int localPort);
@SysCallTemplate
public abstract int sysNetSocketConnect(int fd, int family, int remoteAddress, int remotePort);
@SysCallTemplate
public abstract int sysNetSocketListen(int fd, int backlog);
@SysCallTemplate
public abstract int sysNetSocketAccept(int fd, java.net.SocketImpl connectionObject);
@SysCallTemplate
public abstract int sysNetSocketLinger(int fd, int enable, int timeout);
@SysCallTemplate
public abstract int sysNetSocketNoDelay(int fd, int enable);
@SysCallTemplate
public abstract int sysNetSocketNoBlock(int fd, int enable);
@SysCallTemplate
public abstract int sysNetSocketClose(int fd);
@SysCallTemplate
public abstract int sysNetSocketShutdown(int fd, int how);
@SysCallTemplate
public abstract int sysNetSelect(int[] allFds, int rc, int wc, int ec);
// process management
@SysCallTemplate
public abstract void sysWaitPids(Address pidArray, Address exitStatusArray, int numPids);
// system startup pthread sync. primitives
@SysCallTemplate
public abstract void sysCreateThreadSpecificDataKeys();
@SysCallTemplate
public abstract void sysInitializeStartupLocks(int howMany);
@SysCallTemplate
public abstract void sysWaitForVirtualProcessorInitialization();
@SysCallTemplate
public abstract void sysWaitForMultithreadingStart();
// system calls for alignment checking
@SysCallTemplate
public abstract void sysEnableAlignmentChecking();
@SysCallTemplate
public abstract void sysDisableAlignmentChecking();
@SysCallTemplate
public abstract void sysReportAlignmentChecking();
@SysCallTemplate
public abstract Address gcspyDriverAddStream(Address driver, int id);
@SysCallTemplate
public abstract void gcspyDriverEndOutput(Address driver);
@SysCallTemplate
public abstract void gcspyDriverInit(Address driver, int id, Address serverName, Address driverName, Address title,
Address blockInfo, int tileNum, Address unused, int mainSpace);
@SysCallTemplate
public abstract void gcspyDriverInitOutput(Address driver);
@SysCallTemplate
public abstract void gcspyDriverResize(Address driver, int size);
@SysCallTemplate
public abstract void gcspyDriverSetTileNameRange(Address driver, int i, Address start, Address end);
@SysCallTemplate
public abstract void gcspyDriverSetTileName(Address driver, int i, Address start, long value);
@SysCallTemplate
public abstract void gcspyDriverSpaceInfo(Address driver, Address info);
@SysCallTemplate
public abstract void gcspyDriverStartComm(Address driver);
@SysCallTemplate
public abstract void gcspyDriverStream(Address driver, int id, int len);
@SysCallTemplate
public abstract void gcspyDriverStreamByteValue(Address driver, byte value);
@SysCallTemplate
public abstract void gcspyDriverStreamShortValue(Address driver, short value);
@SysCallTemplate
public abstract void gcspyDriverStreamIntValue(Address driver, int value);
@SysCallTemplate
public abstract void gcspyDriverSummary(Address driver, int id, int len);
@SysCallTemplate
public abstract void gcspyDriverSummaryValue(Address driver, int value);
@SysCallTemplate
public abstract void gcspyIntWriteControl(Address driver, int id, int tileNum);
@SysCallTemplate
public abstract Address gcspyMainServerAddDriver(Address addr);
@SysCallTemplate
public abstract void gcspyMainServerAddEvent(Address server, int event, Address name);
@SysCallTemplate
public abstract Address gcspyMainServerInit(int port, int len, Address name, int verbose);
@SysCallTemplate
public abstract int gcspyMainServerIsConnected(Address server, int event);
@SysCallTemplate
public abstract Address gcspyMainServerOuterLoop();
@SysCallTemplate
public abstract void gcspyMainServerSafepoint(Address server, int event);
@SysCallTemplate
public abstract void gcspyMainServerSetGeneralInfo(Address server, Address info);
@SysCallTemplate
public abstract void gcspyMainServerStartCompensationTimer(Address server);
@SysCallTemplate
public abstract void gcspyMainServerStopCompensationTimer(Address server);
@SysCallTemplate
public abstract void gcspyStartserver(Address server, int wait, Address serverOuterLoop);
@SysCallTemplate
public abstract void gcspyStreamInit(Address stream, int id, int dataType, Address name, int minValue, int maxValue,
int zeroValue, int defaultValue, Address pre, Address post, int presentation,
int paintStyle, int maxStreamIndex, int red, int green, int blue);
@SysCallTemplate
public abstract void gcspyFormatSize(Address buffer, int size);
@SysCallTemplate
public abstract int gcspySprintf(Address str, Address format, Address value);
@SysCallTemplate
public abstract int sysVirtualSubArchProcessorBind(Address procObj, int ProcId);
@SysCallTemplate
public abstract int migrateToSubArch(int retType, int procAffinity, int methodTocOffset,
int methodSubArchOffset, Address paramsStart, int paramsLength);
@SysCallTemplate
public abstract int subArchCheckStatus(int[] allSubArchThrdStatus, int count);
@SysCallTemplate
public abstract int subArchGetIntReturn(int threadId);
@SysCallTemplate
public abstract float subArchGetFloatReturn(int threadId);
@SysCallTemplate
public abstract long subArchGetLongReturn(int threadId);
@SysCallTemplate
public abstract double subArchGetDoubleReturn(int threadId);
@SysCallTemplate
public abstract Address subArchGetRefReturn(int threadId);
}
| epl-1.0 |
frawla/NBR | NBR-core/src/main/java/org/frawla/nbr/core/controller/ERCController.java | 941 | package org.frawla.nbr.core.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.frawla.nbr.core.business.Importer;
import org.frawla.nbr.core.business.NBRparser;
public class ERCController
{
private final Map<String, String> resultsMap;
public ERCController(final List<String> selectedFileList)
{
assert null != selectedFileList : "Parameter 'selectedFileList' of method 'ERCController' must not be null";
final Importer importer = new Importer(selectedFileList);
/** key: File Name. */
Map<String, String> rawFileContentMap = importer.getFileContentMap();
resultsMap = new HashMap<String, String>(rawFileContentMap.size());
rawFileContentMap.forEach((k, v) -> resultsMap.put(k, NBRparser.getResult(rawFileContentMap.get(k))));
}
public void export(final IExporter exporter)
{
exporter.export(resultsMap);
}
} | epl-1.0 |
kaloyan-raev/che | ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/workspace/perspectives/project/ProjectPerspective.java | 3774 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* 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:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.workspace.perspectives.project;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.ide.api.notification.NotificationManager;
import org.eclipse.che.ide.api.parts.EditorPartStack;
import org.eclipse.che.ide.api.parts.PartStack;
import org.eclipse.che.ide.api.parts.ProjectExplorerPart;
import org.eclipse.che.ide.workspace.PartStackPresenterFactory;
import org.eclipse.che.ide.workspace.PartStackViewFactory;
import org.eclipse.che.ide.workspace.WorkBenchControllerFactory;
import org.eclipse.che.ide.workspace.perspectives.general.AbstractPerspective;
import org.eclipse.che.ide.workspace.perspectives.general.PerspectiveViewImpl;
import javax.validation.constraints.NotNull;
import static org.eclipse.che.ide.api.parts.PartStackType.EDITING;
import static org.eclipse.che.ide.api.parts.PartStackType.INFORMATION;
import static org.eclipse.che.ide.api.parts.PartStackType.NAVIGATION;
import static org.eclipse.che.ide.api.parts.PartStackType.TOOLING;
/**
* General-purpose, displaying all the PartStacks in a default manner:
* Navigation at the left side;
* Tooling at the right side;
* Information at the bottom of the page;
* Editors in the center.
*
* @author Nikolay Zamosenchuk
* @author Dmitry Shnurenko
*/
@Singleton
public class ProjectPerspective extends AbstractPerspective {
public final static String PROJECT_PERSPECTIVE_ID = "Project Perspective";
@Inject
public ProjectPerspective(PerspectiveViewImpl view,
EditorPartStack editorPartStackPresenter,
PartStackPresenterFactory stackPresenterFactory,
PartStackViewFactory partViewFactory,
WorkBenchControllerFactory controllerFactory,
ProjectExplorerPart projectExplorerPart,
NotificationManager notificationManager,
EventBus eventBus) {
super(PROJECT_PERSPECTIVE_ID, view, stackPresenterFactory, partViewFactory, controllerFactory, eventBus);
notificationManager.addRule(PROJECT_PERSPECTIVE_ID);
partStacks.put(EDITING, editorPartStackPresenter);
addPart(notificationManager, INFORMATION);
addPart(projectExplorerPart, NAVIGATION);
}
/** {@inheritDoc} */
@Override
public void go(@NotNull AcceptsOneWidget container) {
PartStack navigatorPanel = getPartStack(NAVIGATION);
PartStack editorPanel = getPartStack(EDITING);
PartStack toolPanel = getPartStack(TOOLING);
PartStack infoPanel = getPartStack(INFORMATION);
if (navigatorPanel == null || editorPanel == null || toolPanel == null || infoPanel == null) {
return;
}
infoPanel.updateStack();
navigatorPanel.go(view.getNavigationPanel());
editorPanel.go(view.getEditorPanel());
toolPanel.go(view.getToolPanel());
infoPanel.go(view.getInformationPanel());
container.setWidget(view);
openActivePart(NAVIGATION);
restoreState();
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/eclipselink.extension.oracle.test/src/org/eclipse/persistence/testing/tests/nonJDBC/joNijiNoTestSet.java | 10763 | package org.eclipse.persistence.testing.tests.nonJDBC;
// javase imports
import java.io.FileInputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.Properties;
import java.util.Vector;
import org.w3c.dom.Document;
// JUnit imports
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
// EclipseLink imports
import org.eclipse.persistence.internal.helper.NonSynchronizedVector;
import org.eclipse.persistence.internal.sessions.factories.ObjectPersistenceWorkbenchXMLProject;
import org.eclipse.persistence.oxm.XMLContext;
import org.eclipse.persistence.oxm.XMLMarshaller;
import org.eclipse.persistence.platform.database.jdbc.JDBCTypes;
import org.eclipse.persistence.platform.database.oracle.plsql.OraclePLSQLTypes;
import org.eclipse.persistence.platform.database.oracle.plsql.PLSQLStoredProcedureCall;
import org.eclipse.persistence.queries.DataReadQuery;
import org.eclipse.persistence.sessions.DatabaseRecord;
import org.eclipse.persistence.sessions.DatabaseSession;
import org.eclipse.persistence.sessions.Project;
import org.eclipse.persistence.sessions.Session;
import org.eclipse.persistence.sessions.factories.XMLProjectReader;
// Domain imports
import static org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.buildTestProject;
import static org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.buildWorkbenchXMLProject;
import static org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.CONSTANT_PROJECT_BUILD_VERSION;
import static org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.comparer;
import static org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.TEST_DOT_PROPERTIES_KEY;
import static org.eclipse.persistence.testing.tests.nonJDBC.NonJDBCTestHelper.xmlParser;
/*
N == Non-JDBC type
j == JDBC type
i - IN parameter
o - OUT parameter
io - INOUT parameter
*/
public class joNijiNoTestSet {
// testsuite fixture(s)
static ObjectPersistenceWorkbenchXMLProject workbenchXMLProject;
static Project project = null;
@BeforeClass
public static void setUpProjects() {
try {
Properties p = new Properties();
String testPropertiesPath = System.getProperty(TEST_DOT_PROPERTIES_KEY);
p.load(new FileInputStream(testPropertiesPath));
project = buildTestProject(p);
workbenchXMLProject = buildWorkbenchXMLProject();
}
catch (Exception e) {
fail("error setting up Project's database properties " + e.getMessage());
}
}
@Test
public void writeToXml() {
// PROCEDURE JONIJINO(X OUT VARCHAR, Y IN PLS_INTEGER, Z IN NUMBER, AA OUT BOOLEAN)
PLSQLStoredProcedureCall call = new PLSQLStoredProcedureCall();
call.setProcedureName("joNijiNo");
call.addNamedOutputArgument("X", JDBCTypes.VARCHAR_TYPE, 5);
call.addNamedArgument("Y", OraclePLSQLTypes.PLSQLInteger);
call.addNamedArgument("Z", JDBCTypes.NUMERIC_TYPE, 22, 2);
call.addNamedOutputArgument("AA", OraclePLSQLTypes.PLSQLBoolean);
DataReadQuery query = new DataReadQuery();
query.addArgument("Y", Integer.class);
query.addArgument("Z", BigDecimal.class);
query.setCall(call);
project.getDescriptor(Empty.class).getQueryManager().addQuery("joNijiNo", query);
Project projectToXml = (Project)project.clone();
// trim off login 'cause it changes under test - this way, a comparison
// can be done to a control document
projectToXml.setDatasourceLogin(null);
XMLContext context = new XMLContext(workbenchXMLProject);
XMLMarshaller marshaller = context.createMarshaller();
Document doc = marshaller.objectToXML(projectToXml);
Document controlDoc = xmlParser.parse(new StringReader(JONIJINO_PROJECT_XML));
assertTrue("control document not same as instance document",
comparer.isNodeEqual(controlDoc, doc));
}
public static final String JONIJINO_PROJECT_XML =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<eclipselink:object-persistence version=\"" + CONSTANT_PROJECT_BUILD_VERSION + "\"" + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns:eclipselink=\"http://xmlns.oracle.com/ias/xsds/eclipselink\">" +
"<eclipselink:name>nonJDBCTestProject</eclipselink:name>" +
"<eclipselink:class-mapping-descriptors>" +
"<eclipselink:class-mapping-descriptor xsi:type=\"eclipselink:relational-class-mapping-descriptor\">" +
"<eclipselink:class>org.eclipse.persistence.testing.tests.nonJDBC.Empty</eclipselink:class>" +
"<eclipselink:alias>Empty</eclipselink:alias>" +
"<eclipselink:primary-key>" +
"<eclipselink:field table=\"EMPTY\" name=\"ID\" xsi:type=\"eclipselink:column\"/>" +
"</eclipselink:primary-key>" +
"<eclipselink:events xsi:type=\"eclipselink:event-policy\"/>" +
"<eclipselink:querying xsi:type=\"eclipselink:query-policy\">" +
"<eclipselink:queries>" +
"<eclipselink:query name=\"joNijiNo\" xsi:type=\"eclipselink:data-read-query\">" +
"<eclipselink:arguments>" +
"<eclipselink:argument name=\"Y\">" +
"<eclipselink:type>java.lang.Integer</eclipselink:type>" +
"</eclipselink:argument>" +
"<eclipselink:argument name=\"Z\">" +
"<eclipselink:type>java.math.BigDecimal</eclipselink:type>" +
"</eclipselink:argument>" +
"</eclipselink:arguments>" +
"<eclipselink:maintain-cache>false</eclipselink:maintain-cache>" +
"<eclipselink:call xsi:type=\"eclipselink:plsql-stored-procedure-call\">" +
"<eclipselink:procedure-name>joNijiNo</eclipselink:procedure-name>" +
"<eclipselink:arguments>" +
"<eclipselink:argument xsi:type=\"eclipselink:jdbc-type\" type-name=\"VARCHAR_TYPE\">" +
"<eclipselink:name>X</eclipselink:name>" +
"<eclipselink:index>0</eclipselink:index>" +
"<eclipselink:direction>OUT</eclipselink:direction>" +
"<eclipselink:length>5</eclipselink:length>" +
"</eclipselink:argument>" +
"<eclipselink:argument xsi:type=\"eclipselink:plsql-type\" type-name=\"PLSQLInteger\">" +
"<eclipselink:name>Y</eclipselink:name>" +
"<eclipselink:index>1</eclipselink:index>" +
"</eclipselink:argument>" +
"<eclipselink:argument xsi:type=\"eclipselink:jdbc-type\" type-name=\"NUMERIC_TYPE\">" +
"<eclipselink:name>Z</eclipselink:name>" +
"<eclipselink:index>2</eclipselink:index>" +
"<eclipselink:precision>22</eclipselink:precision>" +
"<eclipselink:scale>2</eclipselink:scale>" +
"</eclipselink:argument>" +
"<eclipselink:argument xsi:type=\"eclipselink:plsql-type\" type-name=\"PLSQLBoolean\">" +
"<eclipselink:name>AA</eclipselink:name>" +
"<eclipselink:index>3</eclipselink:index>" +
"<eclipselink:direction>OUT</eclipselink:direction>" +
"</eclipselink:argument>" +
"</eclipselink:arguments>" +
"</eclipselink:call>" +
"<eclipselink:container xsi:type=\"eclipselink:list-container-policy\">" +
"<eclipselink:collection-type>java.util.Vector</eclipselink:collection-type>" +
"</eclipselink:container>" +
"</eclipselink:query>" +
"</eclipselink:queries>" +
"</eclipselink:querying>" +
"<eclipselink:attribute-mappings>" +
"<eclipselink:attribute-mapping xsi:type=\"eclipselink:direct-mapping\">" +
"<eclipselink:attribute-name>id</eclipselink:attribute-name>" +
"<eclipselink:field table=\"EMPTY\" name=\"ID\" xsi:type=\"eclipselink:column\"/>" +
"</eclipselink:attribute-mapping>" +
"</eclipselink:attribute-mappings>" +
"<eclipselink:descriptor-type>independent</eclipselink:descriptor-type>" +
"<eclipselink:instantiation/>" +
"<eclipselink:copying xsi:type=\"eclipselink:instantiation-copy-policy\"/>" +
"<eclipselink:tables>" +
"<eclipselink:table name=\"EMPTY\"/>" +
"</eclipselink:tables>" +
"</eclipselink:class-mapping-descriptor>" +
"</eclipselink:class-mapping-descriptors>" +
"</eclipselink:object-persistence>";
@Test
public void readFromXml() {
Project projectFromXML = XMLProjectReader.read(new StringReader(JONIJINO_PROJECT_XML),
this.getClass().getClassLoader());
projectFromXML.setDatasourceLogin(project.getDatasourceLogin());
project = projectFromXML;
}
@SuppressWarnings("unchecked")
@Test
public void runQuery() {
Session s = project.createDatabaseSession();
s.dontLogMessages();
((DatabaseSession)s).login();
Object o = null;
Vector queryArgs = new NonSynchronizedVector();
queryArgs.add(Integer.valueOf(100));
queryArgs.add(Integer.valueOf(101));
boolean worked = false;
String msg = null;
try {
o = s.executeQuery("joNijiNo", Empty.class, queryArgs);
worked = true;
}
catch (Exception e) {
msg = e.getMessage();
}
assertTrue("invocation joNijiNo failed: " + msg, worked);
Vector results = (Vector)o;
DatabaseRecord record = (DatabaseRecord)results.get(0);
String y = (String)record.get("X");
assertTrue("wrong y value", y.equals("test"));
Integer aa = (Integer)record.get("AA");
assertTrue("wrong aa value", aa.intValue() == 1);
((DatabaseSession)s).logout();
}
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/t24/core/com.odcgroup.t24.enquiry.model/src-gen/com/odcgroup/t24/enquiry/enquiry/TargetMapping.java | 2386 | /**
*/
package com.odcgroup.t24.enquiry.enquiry;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Target Mapping</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link com.odcgroup.t24.enquiry.enquiry.TargetMapping#getFromField <em>From Field</em>}</li>
* <li>{@link com.odcgroup.t24.enquiry.enquiry.TargetMapping#getToField <em>To Field</em>}</li>
* </ul>
* </p>
*
* @see com.odcgroup.t24.enquiry.enquiry.EnquiryPackage#getTargetMapping()
* @model
* @generated
*/
public interface TargetMapping extends EObject
{
/**
* Returns the value of the '<em><b>From Field</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>From Field</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>From Field</em>' attribute.
* @see #setFromField(String)
* @see com.odcgroup.t24.enquiry.enquiry.EnquiryPackage#getTargetMapping_FromField()
* @model
* @generated
*/
String getFromField();
/**
* Sets the value of the '{@link com.odcgroup.t24.enquiry.enquiry.TargetMapping#getFromField <em>From Field</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>From Field</em>' attribute.
* @see #getFromField()
* @generated
*/
void setFromField(String value);
/**
* Returns the value of the '<em><b>To Field</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>To Field</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>To Field</em>' attribute.
* @see #setToField(String)
* @see com.odcgroup.t24.enquiry.enquiry.EnquiryPackage#getTargetMapping_ToField()
* @model
* @generated
*/
String getToField();
/**
* Sets the value of the '{@link com.odcgroup.t24.enquiry.enquiry.TargetMapping#getToField <em>To Field</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>To Field</em>' attribute.
* @see #getToField()
* @generated
*/
void setToField(String value);
} // TargetMapping
| epl-1.0 |
SmithRWORNL/january | org.eclipse.january.form/src/org/eclipse/january/form/MasterDetailsPair.java | 8010 | /*******************************************************************************
* Copyright (c) 2012, 2016 UT-Battelle, LLC.
* 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:
* Initial API and implementation and/or initial documentation - Jay Jay Billings,
* Jordan H. Deyton, Dasha Gorin, Alexander J. McCaskey, Taylor Patterson,
* Claire Saunders, Matthew Wang, Anna Wojtowicz
*******************************************************************************/
package org.eclipse.january.form;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* <p>
* The MasterDetailsPair class is used by the MasterDetailsComponent to keep
* track of "masters" and "details" without having to store them in two separate
* arrays. It simply allows one master value, a string, to be stored beside one
* details DataComponent. A list of these pairs may also be used to set the
* templates for the MasterDetailsComponent.
* </p>
* <p>
* A MasterDetailsPair is an ICEObject and is both uniquely identifiable and
* persistent. However, it only overloads ICEObject.loadFromXML(), not copy(),
* equals(), hashcode() or clone().
* </p>
*
* @author Jay Jay Billings
*/
@XmlRootElement(name = "MasterDetailsPair")
public class MasterDetailsPair extends ICEObject {
/**
* <p>
* The "master" value in this pair.
* </p>
*
*/
private String master;
/**
* <p>
* The "details" DataComponent for the master in this pair.
* </p>
*
*/
private DataComponent details;
/**
* <p>
* This is a unique id for the master details pair. This is originally
* inserted to allow master details component to have ids and to keep
* ICEObject's ids for database manipulation.
* </p>
*
*/
private Integer masterDetailsPairId;
/**
* <p>
* Creates a hash number from the current object.
* </p>
*
* @return <p>
* A hashcode value.
* </p>
*/
@Override
public int hashCode() {
// Local Declarations
int hash = 8;
// Compute the hashcode
hash = 31 * super.hashCode();
hash = 31 * hash + (null == this.details ? 0 : this.details.hashCode());
hash = 31 * hash + (null == this.master ? 0 : this.master.hashCode());
hash = 31 * hash + this.masterDetailsPairId;
return hash;
}
/**
* <p>
* An operation that checks to see if the current object equals the other
* object. Returns true if equal. False otherwise.
* </p>
*
* @param otherObject
* <p>
* The other object to be checked for equality.
* </p>
* @return <p>
* True if equal to otherObject. False otherwise.
* </p>
*/
@Override
public boolean equals(Object otherObject) {
// Local Declarations
boolean retVal = false;
MasterDetailsPair other;
// Check the MasterDetailsPair, null and base type check first. Note
// that the
// instanceof operator must be used because subclasses of
// MasterDetailsPair
// can be anonymous.
if (otherObject != null && (otherObject instanceof MasterDetailsPair)) {
// See if they are the same reference on the heap
if (this == otherObject) {
retVal = true;
} else {
other = (MasterDetailsPair) otherObject;
// Check each member value
retVal = (this.uniqueId == other.uniqueId)
&& (this.objectName.equals(other.objectName))
&& (this.objectDescription
.equals(other.objectDescription))
&& (this.details.equals(other.details))
&& (this.master.equals(other.master))
&& (this.masterDetailsPairId == other.masterDetailsPairId);
}
}
return retVal;
}
/**
* <p>
* An operation that copies the object passed into the current object.
* </p>
*
* @param otherMasterDetailsPair
* <p>
* A MasterDetailsPair object to be copied.
* </p>
*/
public void copy(MasterDetailsPair otherMasterDetailsPair) {
// Return if object is null
if (otherMasterDetailsPair == null) {
return;
}
// Copy contents of super
super.copy(otherMasterDetailsPair);
// Copy id
this.masterDetailsPairId = otherMasterDetailsPair.masterDetailsPairId;
// copy master
this.master = otherMasterDetailsPair.master;
// copy details (DataComponent) - clone it.
this.details = (DataComponent) otherMasterDetailsPair.details.clone();
}
/**
* <p>
* Deep copies current object and returns a newly instantiated object.
* </p>
*
* @return <p>
* A deep cloned MasterDetailsPair.
* </p>
*/
@Override
public Object clone() {
// create a new instance of MasterDetailsComponent and copy contents
MasterDetailsPair master = new MasterDetailsPair();
master.copy(this);
return master;
}
/**
* <p>
* This operation returns the master value of this pair or null if it has
* not been set.
* </p>
*
* @return <p>
* The string that describes the value of the master that is
* associated with the details.
* </p>
*/
@XmlAttribute
public String getMaster() {
return this.master;
}
/**
* <p>
* This operation sets the master value of this pair.
* </p>
*
* @param masterValue
* <p>
* The string that describes the value of the master that is
* associated with the details.
* </p>
*/
public void setMaster(String masterValue) {
// Do not set if null
if (masterValue != null) {
this.master = masterValue;
}
}
/**
* <p>
* This operation returns the details DataComponent of this pair or null if
* it has not been set.
* </p>
*
* @return <p>
* The DataComponent that contains the detailed parameters
* associated with the master.
* </p>
*/
@XmlElement(name = "Details")
public DataComponent getDetails() {
return this.details;
}
/**
* <p>
* This operation sets the details DataComponent for this pair.
* </p>
*
* @param detailsComp
* <p>
* The DataComponent that contains the detailed parameters
* associated with the master.
* </p>
*/
public void setDetails(DataComponent detailsComp) {
// if not null, set
if (detailsComp != null) {
this.details = detailsComp;
}
}
/**
* <p>
* Returns the value of the attribute masterDetailsPairId.
* </p>
*
* @return <p>
* A return value representing the integer for the
* masterDetailsPairId.
* </p>
*/
@XmlAttribute()
public Integer getMasterDetailsPairId() {
return this.masterDetailsPairId;
}
/**
* <p>
* Sets the masterDetailsPairId. Must be a non negative number.
* </p>
*
* @param id
* <p>
* An id to be set to masterDetailsPairId.
* </p>
*/
public void setMasterDetailsPairId(Integer id) {
// If the id is not negative, set
if (id >= 0 && id != null) {
this.masterDetailsPairId = id;
}
}
/**
* <p>
* The constructor.
* </p>
*
*/
public MasterDetailsPair() {
this.masterDetailsPairId = 0;
}
/**
* <p>
* An alternative constructor in which the master and details pieces can be
* specified to immediately initialize the pair.
* </p>
*
* @param masterValue
* <p>
* The string that describes the value of the master that is
* associated with the details.
* </p>
* @param detailsComp
* <p>
* The DataComponent that contains the detailed parameters
* associated with the master.
* </p>
*/
public MasterDetailsPair(String masterValue, DataComponent detailsComp) {
this.master = masterValue;
this.details = detailsComp;
this.masterDetailsPairId = 0;
}
} | epl-1.0 |
mazbrili/SWTSwing | src/swtswing/org/eclipse/swt/accessibility/ACC.java | 3272 | /*******************************************************************************
* Copyright (c) 2000, 2004 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 org.eclipse.swt.accessibility;
/**
* Class ACC contains all the constants used in defining an
* Accessible object.
*
* @since 2.0
*/
public class ACC {
public static final int STATE_NORMAL = 0x00000000;
public static final int STATE_SELECTED = 0x00000002;
public static final int STATE_SELECTABLE = 0x00200000;
public static final int STATE_MULTISELECTABLE = 0x1000000;
public static final int STATE_FOCUSED = 0x00000004;
public static final int STATE_FOCUSABLE = 0x00100000;
public static final int STATE_PRESSED = 0x8;
public static final int STATE_CHECKED = 0x10;
public static final int STATE_EXPANDED = 0x200;
public static final int STATE_COLLAPSED = 0x400;
public static final int STATE_HOTTRACKED = 0x80;
public static final int STATE_BUSY = 0x800;
public static final int STATE_READONLY = 0x40;
public static final int STATE_INVISIBLE = 0x8000;
public static final int STATE_OFFSCREEN = 0x10000;
public static final int STATE_SIZEABLE = 0x20000;
public static final int STATE_LINKED = 0x400000;
public static final int ROLE_CLIENT_AREA = 0xa;
public static final int ROLE_WINDOW = 0x9;
public static final int ROLE_MENUBAR = 0x2;
public static final int ROLE_MENU = 0xb;
public static final int ROLE_MENUITEM = 0xc;
public static final int ROLE_SEPARATOR = 0x15;
public static final int ROLE_TOOLTIP = 0xd;
public static final int ROLE_SCROLLBAR = 0x3;
public static final int ROLE_DIALOG = 0x12;
public static final int ROLE_LABEL = 0x29;
public static final int ROLE_PUSHBUTTON = 0x2b;
public static final int ROLE_CHECKBUTTON = 0x2c;
public static final int ROLE_RADIOBUTTON = 0x2d;
public static final int ROLE_COMBOBOX = 0x2e;
public static final int ROLE_TEXT = 0x2a;
public static final int ROLE_TOOLBAR = 0x16;
public static final int ROLE_LIST = 0x21;
public static final int ROLE_LISTITEM = 0x22;
public static final int ROLE_TABLE = 0x18;
public static final int ROLE_TABLECELL = 0x1d;
public static final int ROLE_TABLECOLUMNHEADER = 0x19;
/** @deprecated use ROLE_TABLECOLUMNHEADER */
public static final int ROLE_TABLECOLUMN = ROLE_TABLECOLUMNHEADER;
public static final int ROLE_TABLEROWHEADER = 0x1a;
public static final int ROLE_TREE = 0x23;
public static final int ROLE_TREEITEM = 0x24;
public static final int ROLE_TABFOLDER = 0x3c;
public static final int ROLE_TABITEM = 0x25;
public static final int ROLE_PROGRESSBAR = 0x30;
public static final int ROLE_SLIDER = 0x33;
public static final int ROLE_LINK = 0x1e;
public static final int CHILDID_SELF = -1;
public static final int CHILDID_NONE = -2;
public static final int CHILDID_MULTIPLE = -3;
public static final int TEXT_INSERT = 0;
public static final int TEXT_DELETE = 1;
}
| epl-1.0 |
andre-santos-pt/eclipse-feature-editor | pt.iscte.eclipse.featureeditor/src/pt/iscte/eclipse/featureeditor/PluginList.java | 7009 | package pt.iscte.eclipse.featureeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TableColumn;
import pt.iscte.eclipse.featureeditor.model.FeatureSelection;
import pt.iscte.eclipse.featureeditor.model.FeatureSet;
class PluginList extends Composite {
private FeatureSet set;
private FeatureSelection selection;
private CheckboxTableViewer table;
private Label totalLabel;
private Label featLabel;
private Label featAbsLabel;
private Label depthLabel;
PluginList(Composite parent) {
super(parent, SWT.NONE);
createPanelFields(this);
createPanel(this);
}
void setInput(FeatureSet set, FeatureSelection selection) {
Assert.isNotNull(set);
Assert.isNotNull(selection);
this.set = set;
this.selection = selection;
table.setInput(set.getPlugins());
updatePanelFields();
selection.addObserver(new Observer() {
@Override
public void update(Observable o, Object arg) {
boolean check = ((FeatureSelection) o).isPluginSelected((String) arg);
table.setChecked((String) arg, check);
}
});
}
private ViewerFilter filter = new ViewerFilter() {
@Override
public boolean select(Viewer viewer, Object parentElement, Object element) {
return selection.isPluginSelected((String) element);
}
};
void createPanel(Composite parent) {
setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, true));
setLayout(new GridLayout(1, false));
totalLabel = new Label(this, SWT.NONE);
featLabel = new Label(this, SWT.NONE);
featAbsLabel = new Label(this, SWT.NONE);
depthLabel = new Label(this, SWT.NONE);
final Button checkOnlySelected = new Button(this, SWT.CHECK);
checkOnlySelected.setText("Show only selected plugins");
checkOnlySelected.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if(checkOnlySelected.getSelection())
table.addFilter(filter);
else
table.removeFilter(filter);
}
});
table = CheckboxTableViewer.newCheckList(this, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL | SWT.FULL_SELECTION);
table.getControl().setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true));
table.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
System.out.println(event);
}
});
TableViewerColumn pluginColumn = new TableViewerColumn(table, SWT.NONE);
{
TableColumn c = pluginColumn.getColumn();
c.setWidth(250);
c.setResizable(false);
c.setMoveable(false);
pluginColumn.setLabelProvider(new ColumnLabelProvider() {
@Override
public String getText(Object element) {
return element.toString();
}
});
}
table.setContentProvider(new ArrayContentProvider());
// table.setContentProvider(new IStructuredContentProvider() {
//
// // FeatureSet set;
// @Override
// public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// // set = (FeatureSet) newInput;
// //
// // if(set != null) {
// // set.addObserver(new Observer() {
// //
// // @Override
// // public void update(Observable o, Object arg) {
// // boolean check = ((FeatureSet) o).isPluginSelected((String) arg);
// // pluginTable.setChecked((String) arg, check);
// // }
// // });
// // }
// }
//
// @Override
// public Object[] getElements(Object inputElement) {
// return set.getPlugins().toArray();
// }
//
// @Override
// public void dispose() {
//
// }
// });
table.addCheckStateListener(new ICheckStateListener() {
@Override
public void checkStateChanged(CheckStateChangedEvent event) {
String plugin = (String) event.getElement();
if(event.getChecked())
selection.selectPlugin(plugin);
else
selection.unselectPlugin(plugin);
}
});
table.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel = (IStructuredSelection) event.getSelection();
List<String> selection = new ArrayList<String>(sel.size());
Iterator<String> iterator = sel.iterator();
while(iterator.hasNext())
selection.add(iterator.next());
for(SelectionListener l : listeners)
l.selectionChanged(selection);
}
});
}
private void createPanelFields(Composite panel) {
totalLabel = new Label(panel, SWT.NONE);
featLabel = new Label(panel, SWT.NONE);
featAbsLabel = new Label(panel, SWT.NONE);
depthLabel = new Label(panel, SWT.NONE);
}
private void updatePanelFields() {
totalLabel.setText("Plugins: " + set.getPlugins().size());
int concreteFeaturesCount = set.totalConcreteFeatures();
featLabel.setText("Concrete Features: " + concreteFeaturesCount);
int abstractFeaturesCount = set.totalAbstractFeatures();
featAbsLabel.setText("Abstract Features: " + abstractFeaturesCount);
depthLabel.setText("Depth: " + set.getDepth());
}
public void select(String pluginId) {
Assert.isNotNull(pluginId);
IStructuredSelection selection = new StructuredSelection(pluginId);
table.setSelection(selection);
}
public void select(Set<String> pluginIds) {
Assert.isNotNull(pluginIds);
IStructuredSelection selection = new StructuredSelection(pluginIds.toArray());
table.setSelection(selection);
}
public void addSelectionListener(SelectionListener listener) {
Assert.isNotNull(listener);
listeners.add(listener);
}
public void removeSelectionListener(SelectionListener listener) {
Assert.isNotNull(listener);
listeners.remove(listener);
}
private List<SelectionListener> listeners = new ArrayList<PluginList.SelectionListener>();
interface SelectionListener {
void selectionChanged(List<String> selectedPlugins);
}
}
| epl-1.0 |
kenkieo/figure.to.itch | src/com/example/com/demo/bean/Frame.java | 2772 | package com.example.com.demo.bean;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import com.example.com.demo.utils.Constants;
import com.example.com.demo.utils.Point;
public class Frame {
public RectF mRectC = new RectF();
public RectF mRectL = new RectF();
public Rect mRect = new Rect();
public RectF mRealRect = new RectF();
/*********************自身旋转用到*********************/
public float mDrawableDegreesC;
public float mDrawableDegreesL;
public float mDrawableDegreesP;
public Matrix mMenuMatrix = new Matrix();//菜单参数
public Drawable mDrawable;
public Matrix mMatrix = new Matrix();//自身参数
public boolean mMirror;//是否反转
public float mCurrentDegrees;//当前角度(对应中心点)
public float mLastDegrees;//最终角度
public int mColor = 0x00000000;//颜色
public int mAlpha = 255;//透明度
public Point mPointC = new Point();//当前位移
public Point mPointP = new Point();//前一位移:记录在touch down的时候
public float mScaleC = 1;
public float mScaleP;
public int mPosition;
public boolean mMirrorByYAxis;
public static final void clone(Frame srcFrame, Frame dstFrame){
dstFrame.mRectC.set(srcFrame.mRectC);
dstFrame.mRectL.set(srcFrame.mRectL);
dstFrame.mDrawableDegreesC = srcFrame.mDrawableDegreesC;
dstFrame.mDrawableDegreesL = srcFrame.mDrawableDegreesL;
dstFrame.mDrawableDegreesP = srcFrame.mDrawableDegreesP;
dstFrame.mDrawable = srcFrame.mDrawable;
dstFrame.mMirror = srcFrame.mMirror;
dstFrame.mColor = srcFrame.mColor;
dstFrame.mAlpha = srcFrame.mAlpha;
dstFrame.mPointC.set(srcFrame.mPointC);
dstFrame.mPointP.set(srcFrame.mPointP);
dstFrame.mScaleC = srcFrame.mScaleC;
dstFrame.mScaleP = srcFrame.mScaleP;
}
public static final void cloneSecond(Frame srcFrame, Frame dstFrame){
dstFrame.mRectC.set(srcFrame.mRectC);
dstFrame.mRectL.set(srcFrame.mRectL);
if(srcFrame.mPosition % 2 != 0){
dstFrame.mDrawableDegreesC = Constants.DEGRESS - srcFrame.mDrawableDegreesC;
dstFrame.mDrawableDegreesL = Constants.DEGRESS - srcFrame.mDrawableDegreesL;
dstFrame.mDrawableDegreesP = Constants.DEGRESS - srcFrame.mDrawableDegreesP;
}else{
dstFrame.mDrawableDegreesC = srcFrame.mDrawableDegreesC;
dstFrame.mDrawableDegreesL = srcFrame.mDrawableDegreesL;
dstFrame.mDrawableDegreesP = srcFrame.mDrawableDegreesP;
}
dstFrame.mDrawable = srcFrame.mDrawable;
dstFrame.mColor = srcFrame.mColor;
dstFrame.mAlpha = srcFrame.mAlpha;
dstFrame.mScaleC = srcFrame.mScaleC;
dstFrame.mScaleP = srcFrame.mScaleP;
}
}
| epl-1.0 |
Bitub/step | org.buildingsmart.mvd.tmvd/src/org/buildingsmart/mvd/tmvd/converter/UUIDValueConverter.java | 897 | package org.buildingsmart.mvd.tmvd.converter;
import java.util.UUID;
import org.eclipse.xtext.conversion.IValueConverter;
import org.eclipse.xtext.conversion.ValueConverterException;
import org.eclipse.xtext.nodemodel.INode;
import org.eclipse.xtext.util.Strings;
public class UUIDValueConverter implements IValueConverter<UUID>
{
@Override
public UUID toValue(String string, INode node) throws ValueConverterException
{
if (Strings.isEmpty(string))
throw new ValueConverterException("Couldn't convert empty string to an UUID value.", node, null);
try {
return UUID.fromString(string);
}
catch (IllegalArgumentException e) {
throw new ValueConverterException("Couldn't convert " + string + " to an UUID value.", node, e);
}
}
@Override
public String toString(UUID value) throws ValueConverterException
{
return value.toString();
}
}
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/forceupdate/FUVLTimestampLockInCacheTest.java | 9722 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.tests.forceupdate;
import org.eclipse.persistence.sessions.*;
import org.eclipse.persistence.exceptions.*;
import org.eclipse.persistence.expressions.*;
import org.eclipse.persistence.testing.framework.*;
import org.eclipse.persistence.testing.models.forceupdate.*;
/**
Scenario:
Two threads(here we use two UOWs to simulate two threads) read in the same emplyee
object. The first thread updates employee's address(relationship) and commits. The
second thread updates the emplyee's salary(non-relationship attribute based on
where the emplyee lives)and commits. No exception is thrown but the updated salary
is invalid. If the first thread forces update the version value of the employee, an
optimistic lock exception is thrown in the second thread.
(Timestamp locking stores in the cache)
Test 1: (Correctly use method forceUpdateToVersionField())
UOW1 updates employee's address,
calls forceUpdateToVersionField(Object cloneFromUOW1,true) and commits.
UOW2 updates the employee's salary and commits.
The test verified an optimistic lock exception is thrown in UOW2.
Test 2: (forceUpdateToVersionField() doesn't effect read-only UOW)
UOW1 updates employee's address,
calls forceUpdateToVersionField(Object cloneFromUOW1,true) and commits.
UOW2 has only read-operation and commits.
The test verified no optimistic lock exception is thrown in UOW2.
Test 3: (Test method removeForceUpdateToVersionField())
UOW1 updates employee's address,
calls forceUpdateToVersionField(cloneFromUOW1,true),COMMIT&RESUMEs.
It calls removeForceUpdateToVersionField(cloneFromUOW1),
updates employee's address again and commits.
UOW2 reads employee after the first commit of UOW1,updates the emplyee's salary
and commits.
The test verified no optimistic lock exception is thrown in UOW2.
Test 4: (Demonstrate the result when no using forceUpdateToVersionField())
UOW1 updates employee's address, commits.
UOW2 updates the employee's salary and commits.
The test verified no optimistic lock exception is thrown in UOW2.
*/
public class FUVLTimestampLockInCacheTest extends TransactionalTestCase {
boolean exceptionCaught = false;
int testnumber;
public FUVLTimestampLockInCacheTest(int anInt) {
testnumber = anInt;
setName(getName() + "(Test" + anInt + ")");
switch (testnumber) {
case 1:
setDescription("Correctly use method forceUpdateToVersionField()");
break;
case 2:
setDescription("forceUpdateToVersionField() doesn't effect read-only UOW");
break;
case 3:
setDescription("Test method removeForceUpdateToVersionField()");
break;
case 4:
setDescription("Demonstrate the result when no using forceUpdateToVersionField()");
break;
default:
break;
}
}
public void test() {
switch (testnumber) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test3();
break;
case 4:
test4();
break;
default:
break;
}
}
public void test1() {
UnitOfWork uow1, uow2;
ExpressionBuilder bldr = new ExpressionBuilder();
Expression exp1 = bldr.get("firstName").equal("Bob");
Expression exp2 = bldr.get("lastName").equal("Smith");
Expression exp = exp1.and(exp2);
EmployeeTLIC emp = (EmployeeTLIC)getSession().readObject(EmployeeTLIC.class, exp);
uow1 = getSession().acquireUnitOfWork();
uow2 = getSession().acquireUnitOfWork();
EmployeeTLIC clone1 = (EmployeeTLIC)uow1.registerObject(emp);
EmployeeTLIC clone2 = (EmployeeTLIC)uow2.registerObject(emp);
uow1.forceUpdateToVersionField(clone1, true);
clone1.getAddress().setStreet("4 Hutton Centre,Suite 900");
clone1.getAddress().setCity("Santa Ana");
clone1.getAddress().setProvince("CA");
clone1.getAddress().setCountry("USA");
clone1.getAddress().setPostalCode("92797");
uow1.commit();
clone2.setSalary(clone2.getSalary() + 200);
try {
uow2.commit();
} catch (OptimisticLockException exception) {
exceptionCaught = true;
}
}
public void test2() {
UnitOfWork uow1, uow2;
ExpressionBuilder bldr = new ExpressionBuilder();
Expression exp1 = bldr.get("firstName").equal("Bob");
Expression exp2 = bldr.get("lastName").equal("Smith");
Expression exp = exp1.and(exp2);
EmployeeTLIC emp = (EmployeeTLIC)getSession().readObject(EmployeeTLIC.class, exp);
uow1 = getSession().acquireUnitOfWork();
uow2 = getSession().acquireUnitOfWork();
EmployeeTLIC clone1 = (EmployeeTLIC)uow1.registerObject(emp);
EmployeeTLIC clone2 = (EmployeeTLIC)uow2.registerObject(emp);
uow1.forceUpdateToVersionField(clone1, true);
clone1.getAddress().setStreet("4 Hutton Centre,Suite 900");
clone1.getAddress().setCity("Santa Ana");
clone1.getAddress().setProvince("CA");
clone1.getAddress().setCountry("USA");
clone1.getAddress().setPostalCode("92797");
uow1.commit();
// uow2 has only read-operation here
//...
try {
uow2.commit();
} catch (OptimisticLockException exception) {
exceptionCaught = true;
}
}
public void test3() {
UnitOfWork uow1, uow2;
ExpressionBuilder bldr = new ExpressionBuilder();
Expression exp1 = bldr.get("firstName").equal("Bob");
Expression exp2 = bldr.get("lastName").equal("Smith");
Expression exp = exp1.and(exp2);
EmployeeTLIC emp = (EmployeeTLIC)getSession().readObject(EmployeeTLIC.class, exp);
uow1 = getSession().acquireUnitOfWork();
EmployeeTLIC clone1 = (EmployeeTLIC)uow1.registerObject(emp);
uow1.forceUpdateToVersionField(clone1, true);
clone1.getAddress().setStreet("100 Young Street");
clone1.getAddress().setCity("Toronto");
clone1.getAddress().setProvince("ON");
clone1.getAddress().setCountry("CANADA");
clone1.getAddress().setPostalCode("K489Y7");
uow1.commitAndResume();
uow1.removeForceUpdateToVersionField(clone1);
uow2 = getSession().acquireUnitOfWork();
EmployeeTLIC clone2 = (EmployeeTLIC)uow2.registerObject(emp);
clone1.getAddress().setStreet("4 Hutton Centre,Suite 900");
clone1.getAddress().setCity("Santa Ana");
clone1.getAddress().setProvince("CA");
clone1.getAddress().setCountry("USA");
clone1.getAddress().setPostalCode("92797");
uow1.commit();
clone2.setSalary(clone2.getSalary() + 200);
try {
uow2.commit();
} catch (OptimisticLockException exception) {
exceptionCaught = true;
}
}
public void test4() {
UnitOfWork uow1, uow2;
ExpressionBuilder bldr = new ExpressionBuilder();
Expression exp1 = bldr.get("firstName").equal("Bob");
Expression exp2 = bldr.get("lastName").equal("Smith");
Expression exp = exp1.and(exp2);
EmployeeTLIC emp = (EmployeeTLIC)getSession().readObject(EmployeeTLIC.class, exp);
uow1 = getSession().acquireUnitOfWork();
uow2 = getSession().acquireUnitOfWork();
EmployeeTLIC clone1 = (EmployeeTLIC)uow1.registerObject(emp);
EmployeeTLIC clone2 = (EmployeeTLIC)uow2.registerObject(emp);
clone1.getAddress().setStreet("4 Hutton Centre,Suite 900");
clone1.getAddress().setCity("Santa Ana");
clone1.getAddress().setProvince("CA");
clone1.getAddress().setCountry("USA");
clone1.getAddress().setPostalCode("92797");
uow1.commit();
clone2.setSalary(clone2.getSalary() + 200);
try {
uow2.commit();
} catch (OptimisticLockException exception) {
exceptionCaught = true;
}
}
protected void verify() {
switch (testnumber) {
case 1:
if (!exceptionCaught)
throw new TestErrorException("No Optimistic Lock exception was thrown");
break;
case 2:
case 3:
case 4:
if (exceptionCaught)
throw new TestErrorException("Optimistic Lock exception should not have been thrown");
break;
default:
break;
}
}
}
| epl-1.0 |
parzonka/prm4j | src/test/java/prm4j/api/SymbolTest.java | 953 | /*
* Copyright (c) 2012, 2013 Mateusz Parzonka
* 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:
* Mateusz Parzonka - initial API and implementation
*/
package prm4j.api;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import prm4j.AbstractTest;
public class SymbolTest extends AbstractTest {
@Test
public void getParameterIndices_UnsafeMapIterator() throws Exception {
FSM_SafeMapIterator fsm = new FSM_SafeMapIterator();
assertArrayEquals(array(0), fsm.updateMap.getParameterMask());
assertArrayEquals(array(0, 1), fsm.createColl.getParameterMask());
assertArrayEquals(array(1, 2), fsm.createIter.getParameterMask());
assertArrayEquals(array(2), fsm.useIter.getParameterMask());
}
}
| epl-1.0 |
stzilli/kapua | service/api/src/test/java/org/eclipse/kapua/KapuaEntityExistsExceptionTest.java | 2293 | /*******************************************************************************
* Copyright (c) 2020, 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;
import org.eclipse.kapua.model.id.KapuaId;
import org.eclipse.kapua.model.id.KapuaIdImpl;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.math.BigInteger;
@Category(JUnitTests.class)
public class KapuaEntityExistsExceptionTest extends Assert {
Throwable[] throwables;
KapuaId[] ids;
@Before
public void initialize() {
throwables = new Throwable[]{new Throwable(), null};
ids = new KapuaId[]{new KapuaIdImpl(BigInteger.ONE), null};
}
@Test
public void kapuaEntityExistsExceptionTest() {
for (Throwable throwable : throwables) {
for (KapuaId id : ids) {
KapuaEntityExistsException kapuaEntityExistsException = new KapuaEntityExistsException(throwable, id);
assertEquals("Expected and actual values should be the same.", KapuaErrorCodes.ENTITY_ALREADY_EXISTS, kapuaEntityExistsException.getCode());
assertEquals("Expected and actual values should be the same.", id, kapuaEntityExistsException.getId());
assertEquals("Expected and actual values should be the same.", throwable, kapuaEntityExistsException.getCause());
assertEquals("Expected and actual values should be the same.", "Error: ", kapuaEntityExistsException.getMessage());
}
}
}
@Test(expected = KapuaEntityExistsException.class)
public void throwingExceptionTest() {
for (Throwable throwable : throwables) {
for (KapuaId id : ids) {
throw new KapuaEntityExistsException(throwable, id);
}
}
}
}
| epl-1.0 |
simon33-2/triplea | test/games/strategy/engine/data/ITestDelegateBridge.java | 889 | package games.strategy.engine.data;
import games.strategy.engine.delegate.IDelegateBridge;
import games.strategy.engine.gamePlayer.IRemotePlayer;
import games.strategy.engine.random.IRandomSource;
import games.strategy.triplea.ui.display.ITripleADisplay;
/**
* Not for actual use, suitable for testing. Never returns messages, but can get
* random and implements changes immediately.
*/
public interface ITestDelegateBridge extends IDelegateBridge {
/**
* Changing the player has the effect of commiting the current transaction.
* Player is initialized to the player specified in the xml data.
*/
void setPlayerID(PlayerID aPlayer);
void setStepName(String name);
void setStepName(String name, boolean doNotChangeSequence);
void setRandomSource(IRandomSource randomSource);
void setRemote(IRemotePlayer remote);
void setDisplay(ITripleADisplay display);
}
| gpl-2.0 |
w7cook/batch-javac | src/share/classes/com/sun/source/tree/CompilationUnitTree.java | 2038 | /*
* 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.source.tree;
import java.util.List;
import javax.tools.JavaFileObject;
import com.sun.source.tree.LineMap;
/**
* Represents the abstract syntax tree for compilation units (source files) and
* package declarations (package-info.java).
*
* @jls sections 7.3, and 7.4
*
* @author Peter von der Ahé
* @since 1.6
*/
public interface CompilationUnitTree extends Tree {
List<? extends AnnotationTree> getPackageAnnotations();
ExpressionTree getPackageName();
List<? extends ImportTree> getImports();
List<? extends Tree> getTypeDecls();
JavaFileObject getSourceFile();
/**
* Gets the line map for this compilation unit, if available. Returns null if
* the line map is not available.
*
* @return the line map for this compilation unit
*/
LineMap getLineMap();
}
| gpl-2.0 |
maciek123/travel-assistance | HealthTravelAssistant/mobile/src/main/java/com/hta/travelassistant/model/SleepEntry.java | 440 | package com.hta.travelassistant.model;
import org.joda.time.DateTime;
import org.joda.time.Duration;
public class SleepEntry {
private DateTime startTime;
private Duration duration;
public SleepEntry(DateTime startTime, Duration duration) {
this.startTime = startTime;
this.duration = duration;
}
public DateTime getStartTime() {
return startTime;
}
public Duration getDuration() {
return duration;
}
}
| gpl-2.0 |
Krakitos/AndroIUT | src/com/iutdijon/androiut2/mail/adapters/MailDisplayAdapter.java | 1491 | package com.iutdijon.androiut2.mail.adapters;
import java.util.HashMap;
import javax.mail.Flags.Flag;
import javax.mail.Message;
import javax.mail.Part;
import android.os.AsyncTask;
import android.os.Bundle;
import com.iutdijon.androiut2.mail.activities.MailReaderActivity;
import com.iutdijon.androiut2.mail.services.EmailUtils;
/**
* Classe permettant de récupérer de manière asynchrone le contenu du message dont on souhaite afficher le contenu
* @author Morgan Funtowicz
*
*/
public class MailDisplayAdapter extends AsyncTask<Message, Void, Bundle>{
public MailDisplayAdapter(){
}
@Override
protected Bundle doInBackground(Message... params) {
Bundle mail_data = new Bundle();
Message email = params[0];
try {
//On annonce au serveur qu'on a vu le message
email.setFlag(Flag.SEEN, true);
HashMap<String, Part> attachments = EmailUtils.getAttachments(email);
String[] attachments_name;
if(attachments != null){
attachments_name = new String[attachments.size()];
mail_data.putStringArray("attachment", attachments.keySet().toArray(attachments_name));
MailReaderActivity.attachments = attachments;
}
mail_data.putString("sender", EmailUtils.parseSenderAddress(email.getFrom()[0].toString()));
mail_data.putString("subject", email.getSubject());
mail_data.putString("content", EmailUtils.extractMessage(email));
} catch (Exception e) {
e.printStackTrace();
}
return mail_data;
}
}
| gpl-2.0 |
callakrsos/Gargoyle | VisualFxVoEditor/src/main/java/com/kyj/fx/voeditor/visual/loder/SCMInitLoader.java | 571 | /********************************
* 프로젝트 : VisualFxVoEditor
* 패키지 : com.kyj.fx.voeditor.visual.component.scm
* 작성일 : 2016. 4. 3.
* 작성자 : KYJ
*******************************/
package com.kyj.fx.voeditor.visual.loder;
import java.util.List;
import com.kyj.fx.commons.memory.ResourceLoader;
import com.kyj.fx.voeditor.visual.component.scm.SVNItem;
/**
* SCM
*
* @author KYJ
*
*/
public interface SCMInitLoader {
public static final String REPOSITORIES = ResourceLoader.SVN_REPOSITORIES;
<T extends SVNItem> List<T> load();
}
| gpl-2.0 |
algo3-2015-fiuba/algocraft | src/juego/razas/unidades/protoss/Scout.java | 528 | package juego.razas.unidades.protoss;
import juego.costos.Costos;
import juego.decoradores.Escudo;
import juego.decoradores.Vida;
import juego.estrategias.MovimientoVolador;
import juego.razas.ataques.Ataques;
import juego.razas.unidades.UnidadAtaque;
public class Scout extends UnidadAtaque {
public Scout() {
super();
this.vida = new Escudo(new Vida(150), 100);
this.costos = new Costos(300,150,9,3);
this.ataques = new Ataques(8,14,4,4);
this.estrategiaDeMovimiento = new MovimientoVolador(3,7);
}
}
| gpl-2.0 |
FearlessTobi/HPUM-1.7 | src/main/java/snidgert/harrypottermod/mobs/Dementor.java | 3690 | package snidgert.harrypottermod.mobs;
import net.minecraft.client.model.*;
import net.minecraft.entity.*;
public class Dementor extends ModelBase
{
ModelRenderer Head;
ModelRenderer BodyTop;
ModelRenderer BodyBase;
ModelRenderer ArmR;
ModelRenderer ArmL;
ModelRenderer HeadCape;
ModelRenderer ArmRCape;
ModelRenderer ArmLCape;
public Dementor() {
super.textureWidth = 128;
super.textureHeight = 64;
(this.Head = new ModelRenderer(this, 0, 0)).addBox(-3.5f, -7.0f, -3.5f, 7, 7, 7);
this.Head.setRotationPoint(0.0f, 0.0f, 0.0f);
this.Head.setTextureSize(128, 64);
this.Head.mirror = true;
this.setRotation(this.Head, 0.0f, 0.0f, 0.0f);
(this.BodyTop = new ModelRenderer(this, 24, 16)).addBox(-4.0f, 0.0f, -2.0f, 8, 12, 4);
this.BodyTop.setRotationPoint(0.0f, 0.0f, 1.0f);
this.BodyTop.setTextureSize(128, 64);
this.BodyTop.mirror = true;
this.setRotation(this.BodyTop, 0.0f, 0.0f, 0.0f);
(this.BodyBase = new ModelRenderer(this, 0, 16)).addBox(-4.0f, 0.0f, -2.0f, 8, 10, 4);
this.BodyBase.setRotationPoint(0.0f, 11.6f, 1.0f);
this.BodyBase.setTextureSize(128, 64);
this.BodyBase.mirror = true;
this.setRotation(this.BodyBase, 0.1745329f, 0.0f, 0.0f);
(this.ArmR = new ModelRenderer(this, 48, 16)).addBox(-3.5f, -1.0f, -1.5f, 3, 12, 3);
this.ArmR.setRotationPoint(-3.5f, 2.0f, 1.0f);
this.ArmR.setTextureSize(128, 64);
this.ArmR.mirror = true;
this.setRotation(this.ArmR, -1.308997f, 0.0f, 0.0f);
(this.ArmL = new ModelRenderer(this, 48, 16)).addBox(0.5f, -1.0f, -1.5f, 3, 12, 3);
this.ArmL.setRotationPoint(3.5f, 2.0f, 1.0f);
this.ArmL.setTextureSize(128, 64);
this.ArmL.mirror = true;
this.setRotation(this.ArmL, -1.308997f, 0.0f, 0.0f);
(this.HeadCape = new ModelRenderer(this, 28, 0)).addBox(-4.0f, -8.0f, -4.0f, 8, 8, 8);
this.HeadCape.setRotationPoint(0.0f, 0.1f, 0.0f);
this.HeadCape.setTextureSize(128, 64);
this.HeadCape.mirror = true;
this.setRotation(this.HeadCape, 0.0f, 0.0f, 0.0f);
(this.ArmRCape = new ModelRenderer(this, 61, 16)).addBox(-4.0f, -2.0f, -2.0f, 4, 12, 4);
this.ArmRCape.setRotationPoint(-3.5f, 2.0f, 1.0f);
this.ArmRCape.setTextureSize(128, 64);
this.ArmRCape.mirror = true;
this.setRotation(this.ArmRCape, -1.308997f, 0.0f, 0.0f);
(this.ArmLCape = new ModelRenderer(this, 61, 16)).addBox(0.0f, -2.0f, -2.0f, 4, 12, 4);
this.ArmLCape.setRotationPoint(3.5f, 2.0f, 1.0f);
this.ArmLCape.setTextureSize(128, 64);
this.ArmLCape.mirror = true;
this.setRotation(this.ArmLCape, -1.308997f, 0.0f, 0.0f);
}
@Override
public void render(final Entity entity, final float f, final float f1, final float f2, final float f3, final float f4, final float f5) {
super.render(entity, f, f1, f2, f3, f4, f5);
this.setRotationAngles(f, f1, f2, f3, f4, f5);
this.Head.render(f5);
this.BodyTop.render(f5);
this.BodyBase.render(f5);
this.ArmR.render(f5);
this.ArmL.render(f5);
this.HeadCape.render(f5);
this.ArmRCape.render(f5);
this.ArmLCape.render(f5);
}
private void setRotation(final ModelRenderer model, final float x, final float y, final float z) {
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
public void setRotationAngles(final float f, final float f1, final float f2, final float f3, final float f4, final float f5) {
}
}
| gpl-2.0 |
sungsoo/esper | esper/src/main/java/com/espertech/esper/dataflow/core/DataFlowConfigurationStateServiceImpl.java | 1864 | /*
* *************************************************************************************
* 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.dataflow.core;
import com.espertech.esper.client.dataflow.EPDataFlowSavedConfiguration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class DataFlowConfigurationStateServiceImpl implements DataFlowConfigurationStateService {
private final Map<String, EPDataFlowSavedConfiguration> savedConfigs = new HashMap<String, EPDataFlowSavedConfiguration>();
public boolean exists(String savedConfigName) {
return savedConfigs.containsKey(savedConfigName);
}
public void add(EPDataFlowSavedConfiguration savedConfiguration) {
savedConfigs.put(savedConfiguration.getSavedConfigurationName(), savedConfiguration);
}
public String[] getSavedConfigNames() {
Set<String> names = savedConfigs.keySet();
return names.toArray(new String[names.size()]);
}
public EPDataFlowSavedConfiguration getSavedConfig(String savedConfigName) {
return savedConfigs.get(savedConfigName);
}
public EPDataFlowSavedConfiguration removePrototype(String savedConfigName) {
return savedConfigs.remove(savedConfigName);
}
}
| gpl-2.0 |
MapYou/MapYou | Project/workspace/MapYou/src/it/mapyou/controller/parsing/ParsingUser.java | 1871 | /**
*
*/
package it.mapyou.controller.parsing;
import java.util.ArrayList;
import java.util.List;
import it.mapyou.model.User;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* @author mapyou (mapyouu@gmail.com)
*
*/
public class ParsingUser implements ParserInterface<User> {
@Override
public User parseFromJsonObject(JSONObject json) throws Exception {
User user= new User();
JSONArray jsonArr= json.getJSONArray("User");
for(int i=0; i<jsonArr.length(); i++){
json=jsonArr.getJSONObject(i);
user.setNickname(json.getString("nickname"));
user.setEmail(json.getString("email"));
user.setModelID(json.getInt("id"));
}
return user;
}
@Override
public User parseFromJsonArray(JSONArray jsonArr) throws Exception {
User user= new User();
JSONObject json = null;
for(int i=0; i<jsonArr.length(); i++){
json = jsonArr.getJSONObject(i);
user.setNickname(json.getString("nickname"));
user.setEmail(json.getString("email"));
user.setModelID(json.getInt("id"));
}
return user;
}
/* (non-Javadoc)
* @see it.mapyou.controller.parsing.ParserInterface#parseListFromJsonObject(org.json.JSONObject)
*/
@Override
public List<User> parseListFromJsonObject(JSONObject o) throws Exception {
List<User> u= new ArrayList<User>();
JSONArray jsonArray = o.getJSONArray("Users");
for(int i=0; i<jsonArray.length(); i++){
o = jsonArray.getJSONObject(i);
User user = new User();
user.setNickname(o.getString("nickname"));
user.setEmail(o.getString("email"));
user.setModelID(o.getInt("id"));
u.add(user);
}
return u;
}
/* (non-Javadoc)
* @see it.mapyou.controller.parsing.ParserInterface#parseListFromJsonArray(org.json.JSONArray)
*/
@Override
public List<User> parseListFromJsonArray(JSONArray o) throws Exception {
// TODO Auto-generated method stub
return null;
}
}
| gpl-2.0 |
hemoye/doIT | src/com/jsu/doIT/vo/CoursecommentVO.java | 954 | package com.jsu.doIT.vo;
public class CoursecommentVO implements java.io.Serializable {
private static final long serialVersionUID = 1477008165249891981L;
private Integer commentId;
private String commentInfo;
private Integer agreeNumber;
public CoursecommentVO() {
}
public CoursecommentVO(String commentInfo) {
this.commentInfo = commentInfo;
}
public CoursecommentVO(String commentInfo, Integer agreeNumber) {
this.commentInfo = commentInfo;
this.agreeNumber = agreeNumber;
}
public Integer getCommentId() {
return this.commentId;
}
public void setCommentId(Integer commentId) {
this.commentId = commentId;
}
public String getCommentInfo() {
return this.commentInfo;
}
public void setCommentInfo(String commentInfo) {
this.commentInfo = commentInfo;
}
public Integer getAgreeNumber() {
return this.agreeNumber;
}
public void setAgreeNumber(Integer agreeNumber) {
this.agreeNumber = agreeNumber;
}
} | gpl-2.0 |
gcoulby/AccountsManagerPlus | gui/windows/AddAccountWindow.java | 16498 | /**
* Package for GUI Window
*/
package gui.windows;
import gui.Constants;
import gui.components.Row;
import gui.components.Toolbar;
import gui.components.VerticalStrut;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import model.AccountHandler;
/**
* Class for building the slide in panel which is
* used for adding accounts to the system and the
* database tables.
* @author Barber, Coulby
*
*/
public class AddAccountWindow extends JPanel
{
// Buttons
private JButton trdAccountBtn = new JButton("Trade Account");
private JButton trdAccountBtn2 = new JButton("Trade Account");
private JButton perAccountBtn = new JButton("Personal Account");
private JButton perAccountBtn2 = new JButton("Personal Account");
private JButton submitBtnPer = new JButton("Submit");
private JButton submitBtnTrd = new JButton("Submit");
private JButton cancelBtnPer = new JButton("Cancel");
private JButton cancelBtnTrd = new JButton("Cancel");
private static String currentForm = "";
// Form Fields
private JLabel trdFirstNameLabel = new JLabel("First Name: " + addSpace(16));
private JTextField trdFirstNameField = new JTextField(20);
private JLabel perFirstNameLabel = new JLabel("First Name: " + addSpace(16));
private JTextField perFirstNameField = new JTextField(20);
private JLabel trdSurnameLabel = new JLabel("Surname: " + addSpace(19));
private JTextField trdSurnameField = new JTextField(20);
private JLabel perSurnameLabel = new JLabel("Surname: " + addSpace(19));
private JTextField perSurnameField = new JTextField(20);
private JLabel vatNoLabel = new JLabel("VAT Number: " + addSpace(13));
private JTextField vatNoField = new JTextField(20);
private JLabel phoneLabel = new JLabel("Phone Number: " + addSpace(9));
private JTextField phoneField = new JTextField(20);
private JLabel credCardTypeLabel = new JLabel("Credit Card Type: " + addSpace(6));
private JComboBox<String> credCardTypeField = new JComboBox<String>(new String[]
{ "AMEX", "MCard", "VISA" });
private JLabel credCardNoLabel = new JLabel("Credit Card Number: ");
private JTextField creditCardNoField = new JTextField(20);
private CardLayout cardLayout = new CardLayout();
private JPanel forms = new JPanel();
private JLabel trdTitleLabel = new JLabel("Trade Account");
private JLabel perTitleLabel = new JLabel("Personal Account");
private final JFrame frame;
/**
* Constructor for AddAccountWindow.
* Creates a JPanel calls the init() method and
* adds the components to the panel
* @param frame The parent JFrame for this window to be added to.
*/
public AddAccountWindow(JFrame frame)
{
this.frame = frame;
init();
add(new JPanel(), BorderLayout.NORTH); // Add a little space to the top
add(forms, BorderLayout.CENTER);
}
/**
* Initialises the Constructor, builds the cards and sets action commands
* @author Barber, Coulby
*/
private void init()
{
setVisible(false);
setBorder(BorderFactory.createLoweredBevelBorder());
buildCards();
setLayout(new BorderLayout());
setActionListeners();
cancelBtnPer.setActionCommand("Plus");
cancelBtnTrd.setActionCommand("Plus");
submitBtnPer.setActionCommand("SubmitPer");
submitBtnTrd.setActionCommand("SubmitTrd");
trdTitleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
perTitleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
}
/**
* Sets the action listeners for all the buttons to use the BtnListener Class
* Allows switching between the card layouts
* @author Carr
*/
private void setActionListeners()
{
trdAccountBtn.addActionListener(new FormListener());
trdAccountBtn2.addActionListener(new FormListener());
perAccountBtn.addActionListener(new FormListener());
perAccountBtn2.addActionListener(new FormListener());
submitBtnPer.addActionListener(new FormListener());
submitBtnTrd.addActionListener(new FormListener());
Toolbar.getTrdButton().addActionListener(new BtnListener());
Toolbar.getPerButton().addActionListener(new BtnListener());
}
/**
* Set the CardLayout Panel and add the forms to the cards for switching
* @author Barber, Coulby
*/
public void buildCards()
{
forms.setLayout(cardLayout);
forms.add("Trade Account", new Form(true));
forms.add("Personal Account", new Form(false));
}
/**
* The Class for building the Form Slide in Panel
* @author Barber, Carr, Coulby
*/
class Form extends JPanel
{
private GridLayout grid = new GridLayout(5, 1);
private JPanel gridPanel = new JPanel(grid);
/**
* Method for building the forms to be added to the add account panel
* @author Barber, Coulby
* @param isTradeAccount A boolean to determine which form to show
*/
public Form(boolean isTradeAccount)
{
setLayout(new BorderLayout());
new VerticalStrut(4, grid, this);
if (isTradeAccount)
{
add(Constants.label(Constants.TRD_ICON_LRG), BorderLayout.NORTH);
gridPanel.add(new Row(trdTitleLabel, FlowLayout.CENTER, false));
gridPanel.add(new Row(trdAccountBtn, perAccountBtn, FlowLayout.CENTER, false));
gridPanel.add(new Row(trdFirstNameLabel, trdFirstNameField, FlowLayout.LEFT, false));
gridPanel.add(new Row(trdSurnameLabel, trdSurnameField, FlowLayout.LEFT, false));
gridPanel.add(new Row(vatNoLabel, vatNoField, FlowLayout.LEFT, false));
gridPanel.add(new Row(phoneLabel, phoneField, FlowLayout.LEFT, false));
gridPanel.add(new Row(cancelBtnTrd, submitBtnTrd, FlowLayout.CENTER, false));
}
else
{
add(Constants.label(Constants.PER_ICON_LRG), BorderLayout.NORTH);
gridPanel.add(new Row(perTitleLabel, FlowLayout.CENTER, false));
gridPanel.add(new Row(trdAccountBtn2, perAccountBtn2, FlowLayout.CENTER, false));
gridPanel.add(new Row(perFirstNameLabel, perFirstNameField, FlowLayout.LEFT, false));
gridPanel.add(new Row(perSurnameLabel, perSurnameField, FlowLayout.LEFT, false));
gridPanel.add(new Row(credCardTypeLabel, credCardTypeField, FlowLayout.LEFT, false));
gridPanel.add(new Row(credCardNoLabel, creditCardNoField, FlowLayout.LEFT, false));
gridPanel.add(new Row(cancelBtnPer, submitBtnPer, FlowLayout.CENTER, false));
}
new VerticalStrut(4, grid, this);
add(gridPanel, BorderLayout.CENTER);
}
}
/**
* A getter to return the current form
* @author Carr
*/
public static String getCurrentForm()
{
return currentForm;
}
/**
* A setter to add an action listener to the 'Cancel' button from another class
* @author Carr
* @param listener the ActionListener that will listen to the button
*/
public void addCancelListener(ActionListener listener)
{
cancelBtnPer.addActionListener(listener);
cancelBtnTrd.addActionListener(listener);
}
/**
* A setter to add an action listener to the 'Trade Account' button from another class
* @author Carr
* @param listener the ActionListener that will listen to the button
*/
public void addTradeListener(ActionListener listener)
{
trdAccountBtn.addActionListener(listener);
trdAccountBtn2.addActionListener(listener);
}
/**
* A setter to add an action listener to the 'Personal Account' button from another class
* @author Carr
* @param listener the ActionListener that will listen to the button
*/
public void addPersonalListener(ActionListener listener)
{
perAccountBtn.addActionListener(listener);
perAccountBtn2.addActionListener(listener);
}
/**
* Creates a String of white space to pad out the form
* @author Barber, Coulby
* @param numberOfSpaces The Number of white spaces to add
* @return str String of empty space
*/
public String addSpace(int numberOfSpaces)
{
String str = "";
for (int i = 0; i < numberOfSpaces; i++)
{
str += " ";
}
return str;
}
/**
* Checks to see if all the Text fields have a value.
* @author Barber, Coulby
* @param field1 First Text Field
* @param field2 Second Text Field
* @param field3 Third Text Field
* @param field4 Forth Text Field
* @return boolean
*/
private boolean errorHandling(String field1, String field2, String field3, String field4)
{
return (!field1.equals("") && !field2.equals("") && !field3.equals("") && !field4.equals("")) ? true : false;
}
/**
* Does error handling to ensure the number entered into the VAT field
* is either 8 characters in length starting with "GB" or 6 characters
* in length and does NOT start with "GB"
* @author Barber, Coulby
* @return String A String of 8 characters in length; starting with GB
*/
private String vatStringErrorHandling()
{
String vatString = null;
if (vatNoField.getText().substring(0, 2).equalsIgnoreCase("GB"))
{
vatString = vatNoField.getText().substring(2);
}
else
{
vatString = vatNoField.getText();
if (vatString.length() != 6)
{
JOptionPane.showMessageDialog(frame,
"VAT Number must start with GB and be 8 characters long e.g. GB123456",
"Invalid Value", JOptionPane.ERROR_MESSAGE);
return null;
}
}
return "GB" + vatString;
}
/**
* Returns a boolean based on whether the value entered into the
* phone number field is 11 characters long.
* @author Barber, Coulby
* @return boolean
*/
private boolean phoneStringErrorHandling()
{
if (phoneField.getText().length() != 11)
{
JOptionPane.showMessageDialog(frame,
"Phone number must be 11 digits long!",
"Invalid Value", JOptionPane.ERROR_MESSAGE);
return false;
}
else
{
return true;
}
}
/**
* Returns a boolean based on whether the value entered into the
* credit card field is 16 characters long.
* @author Barber, Coulby
* @return boolean
*/
private boolean credCardErrorHandling()
{
if (creditCardNoField.getText().length() != 16)
{
JOptionPane.showMessageDialog(frame,
"Phone number must be 16 digits long!",
"Invalid Value", JOptionPane.ERROR_MESSAGE);
return false;
}
else
{
return true;
}
}
/**
* Inner Class: BtnListener is an ActionListener for buttons in other windows
* such as Toolbar, or MenuBar. Used to switch between CardLayouts.
* @author Barber, Coulby
*/
class BtnListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
cardLayout.show(forms, e.getActionCommand().substring(0, e.getActionCommand().length() - 1));
currentForm = e.getActionCommand().substring(0, e.getActionCommand().length() - 1);
}
}
/**
* This Action Listener handles a lot of the functionality of this class
* When a form is submitted the form is ran through a series of error handling
* methods and if all the methods come back true the Table is updated and the
* Account is added to the database.
* This Listener also handles which form to show, depending on what form navigation
* button is pressed.
* @author Barber, Coulby
*/
class FormListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().substring(0, 3).equals("Sub"))
{
if (e.getActionCommand().substring(6, 9).equals("Trd"))
{
boolean noEmptyFields = errorHandling
(
trdFirstNameField.getText(),
trdSurnameField.getText(),
vatNoField.getText(),
phoneField.getText()
);
if (noEmptyFields)
{
String vatString = vatStringErrorHandling();
boolean phoneOK = phoneStringErrorHandling();
if (vatString != null && phoneOK)
{
AccountHandler.addTradeAccount
(
trdFirstNameField.getText(),
trdSurnameField.getText(),
vatString,
phoneField.getText()
);
MainFrame.getTrdAccountWindow().updateStatusBar(AccountHandler.getNoOfTradeAccounts());
trdFirstNameField.setText("");
trdSurnameField.setText("");
vatNoField.setText("");
phoneField.setText("");
}
}
else
{
JOptionPane.showMessageDialog(frame,
"All fields must have a value!",
"Invalid Form Submission", JOptionPane.ERROR_MESSAGE);
}
}
else
{
boolean noEmptyFields = errorHandling
(
perFirstNameField.getText(),
perSurnameField.getText(),
credCardTypeField.getSelectedItem().toString(),
creditCardNoField.getText()
);
if (noEmptyFields)
{
if (credCardErrorHandling())
{
AccountHandler.addPersonalAccount
(
perFirstNameField.getText(),
perSurnameField.getText(),
credCardTypeField.getSelectedItem().toString(),
creditCardNoField.getText()
);
MainFrame.getPerAccountWindow().updateStatusBar(AccountHandler.getNoOfPersonalAccounts());
perFirstNameField.setText("");
perSurnameField.setText("");
credCardTypeField.setSelectedIndex(0);
creditCardNoField.setText("");
}
}
else
{
JOptionPane.showMessageDialog(frame,
"All fields must have a value!",
"Invalid Form Submission", JOptionPane.ERROR_MESSAGE);
}
}
MainFrame.getAllAccountWindow().updateStatusBar();
AccountHandler.updateTable();
}
else
{
cardLayout.show(forms, e.getActionCommand());
currentForm = e.getActionCommand();
}
}
}
} | gpl-2.0 |
karianna/jdk8_tl | jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/handler/SOAPMessageContextImpl.java | 4699 | /*
* Copyright (c) 1997, 2010, 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.ws.handler;
import com.sun.xml.internal.ws.api.message.Header;
import com.sun.xml.internal.ws.api.message.Message;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.message.saaj.SAAJFactory;
import com.sun.xml.internal.ws.api.WSBinding;
import com.sun.xml.internal.ws.api.SOAPVersion;
import com.sun.xml.internal.ws.message.saaj.SAAJMessage;
import javax.xml.bind.JAXBContext;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Implementation of {@link SOAPMessageContext}. This class is used at runtime
* to pass to the handlers for processing soap messages.
*
* @see MessageContextImpl
*
* @author WS Development Team
*/
public class SOAPMessageContextImpl extends MessageUpdatableContext implements SOAPMessageContext {
private Set<String> roles;
private SOAPMessage soapMsg = null;
private WSBinding binding;
public SOAPMessageContextImpl(WSBinding binding, Packet packet,Set<String> roles) {
super(packet);
this.binding = binding;
this.roles = roles;
}
public SOAPMessage getMessage() {
if(soapMsg == null) {
try {
Message m = packet.getMessage();
soapMsg = m != null ? m.readAsSOAPMessage() : null;
} catch (SOAPException e) {
throw new WebServiceException(e);
}
}
return soapMsg;
}
public void setMessage(SOAPMessage soapMsg) {
try {
this.soapMsg = soapMsg;
} catch(Exception e) {
throw new WebServiceException(e);
}
}
void setPacketMessage(Message newMessage){
if(newMessage != null) {
packet.setMessage(newMessage);
soapMsg = null;
}
}
protected void updateMessage() {
//Check if SOAPMessage has changed, if so construct new one,
// Packet are handled through MessageContext
if(soapMsg != null) {
packet.setMessage(SAAJFactory.create(soapMsg));
soapMsg = null;
}
}
public Object[] getHeaders(QName header, JAXBContext jaxbContext, boolean allRoles) {
SOAPVersion soapVersion = binding.getSOAPVersion();
List<Object> beanList = new ArrayList<Object>();
try {
Iterator<Header> itr = packet.getMessage().getHeaders().getHeaders(header,false);
if(allRoles) {
while(itr.hasNext()) {
beanList.add(itr.next().readAsJAXB(jaxbContext.createUnmarshaller()));
}
} else {
while(itr.hasNext()) {
Header soapHeader = itr.next();
//Check if the role is one of the roles on this Binding
String role = soapHeader.getRole(soapVersion);
if(getRoles().contains(role)) {
beanList.add(soapHeader.readAsJAXB(jaxbContext.createUnmarshaller()));
}
}
}
return beanList.toArray();
} catch(Exception e) {
throw new WebServiceException(e);
}
}
public Set<String> getRoles() {
return roles;
}
}
| gpl-2.0 |
thirdy/durian | durian/src/main/java/qic/ui/extra/MultiLineTableCellRenderer.java | 4273 | package qic.ui.extra;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableCellRenderer;
import org.apache.commons.lang3.StringUtils;
import com.porty.swing.table.model.BeanPropertyTableModel;
import qic.SearchPageScraper.SearchResultItem;
/**
* Multiline Table Cell Renderer.
*/
public class MultiLineTableCellRenderer extends JTextArea implements TableCellRenderer {
private static final long serialVersionUID = 1L;
private List<List<Integer>> rowColHeight = new ArrayList<List<Integer>>();
private static final EmptyBorder EMPTY_BORDER = new EmptyBorder(1, 2, 1, 2);
private Color bgColor;
private Color guildColor;
private Color corruptedColor;
private Color autoHighlightColor;
private BeanPropertyTableModel<SearchResultItem> model;
public MultiLineTableCellRenderer(BeanPropertyTableModel<SearchResultItem> model, Color bgColor, Color guildColor, Color corruptedColor, Color autoHighlightColor) {
setLineWrap(true);
setWrapStyleWord(true);
setOpaque(true);
this.bgColor = bgColor;
this.guildColor = guildColor;
this.corruptedColor=corruptedColor;
this.autoHighlightColor = autoHighlightColor;
this.model = model;
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(bgColor != null ? bgColor : table.getBackground());
if (!model.getData().isEmpty()) {
SearchResultItem item = model.getData().get(row);
if (item.newInAutomated()) {
setBackground(autoHighlightColor);
} else if (item.guildItem()) {
setBackground(guildColor);
}
if(item.corrupted) {
this.setForeground(corruptedColor);
}
}
}
setFont(table.getFont());
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
if (table.isCellEditable(row, column)) {
setForeground(UIManager.getColor("Table.focusCellForeground"));
setBackground(UIManager.getColor("Table.focusCellBackground"));
}
} else {
setBorder(EMPTY_BORDER);
}
if (value != null) {
if (value instanceof List) {
@SuppressWarnings("rawtypes")
List list = (List) value;
String s = StringUtils.join(list, System.lineSeparator());
setText(s);
} else {
setText(value.toString());
}
} else {
setText("");
}
adjustRowHeight(table, row, column);
return this;
}
/**
* Calculate the new preferred height for a given row, and sets the height on the table.
*/
private void adjustRowHeight(JTable table, int row, int column) {
//The trick to get this to work properly is to set the width of the column to the
//textarea. The reason for this is that getPreferredSize(), without a width tries
//to place all the text in one line. By setting the size with the with of the column,
//getPreferredSize() returnes the proper height which the row should have in
//order to make room for the text.
int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
setSize(new Dimension(cWidth, 1000));
int prefH = getPreferredSize().height;
while (rowColHeight.size() <= row) {
rowColHeight.add(new ArrayList<Integer>(column));
}
List<Integer> colHeights = rowColHeight.get(row);
while (colHeights.size() <= column) {
colHeights.add(0);
}
colHeights.set(column, prefH);
int maxH = prefH;
for (Integer colHeight : colHeights) {
if (colHeight > maxH) {
maxH = colHeight;
}
}
if (table.getRowHeight(row) < maxH) {
table.setRowHeight(row, maxH);
}
}
} | gpl-2.0 |
nextgis/nextgismobile | src/com/nextgis/mobile/datasource/GeoEnvelope.java | 6847 | /******************************************************************************
* Project: NextGIS mobile
* Purpose: Mobile GIS for Android.
* Author: Dmitry Baryshnikov (aka Bishop), polimax@mail.ru
******************************************************************************
* Copyright (C) 2014 NextGIS
*
* 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, see <http://www.gnu.org/licenses/>.
****************************************************************************/
package com.nextgis.mobile.datasource;
import org.json.JSONException;
import org.json.JSONObject;
import static com.nextgis.mobile.util.Constants.*;
public class GeoEnvelope implements JSONStore{
protected double mMinX;
protected double mMaxX;
protected double mMinY;
protected double mMaxY;
public GeoEnvelope(){
mMinX = 0;
mMaxX = 0;
mMinY = 0;
mMaxY = 0;
}
public GeoEnvelope(double minX, double maxX, double minY, double maxY){
mMinX = minX;
mMaxX = maxX;
mMinY = minY;
mMaxY = maxY;
}
public GeoEnvelope(final GeoEnvelope env){
mMinX = env.mMinX;
mMaxX = env.mMaxX;
mMinY = env.mMinY;
mMaxY = env.mMaxY;
}
public void setMin(double x, double y){
mMinX = x;
mMinY = y;
}
public void setMax(double x, double y){
mMaxX = x;
mMaxY = y;
}
public void setMinX(double x){
mMinX = x;
}
public void setMaxX(double x){
mMaxX = x;
}
public void setMinY(double y){
mMinY = y;
}
public void setMaxY(double y){
mMaxY = y;
}
public final double getMinX(){
return mMinX;
}
public final double getMinY(){
return mMinY;
}
public final double getMaxX(){
return mMaxX;
}
public final double getMaxY(){
return mMaxY;
}
public final boolean isInit(){
return mMinX != 0 || mMinY != 0 || mMaxX != 0 || mMaxY != 0;
}
public final GeoPoint getCenter(){
double x = mMinX + width() / 2.0;
double y = mMinY + height() / 2.0;
return new GeoPoint(x, y);
}
public final double width(){
return mMaxX - mMinX;
}
public final double height(){
return mMaxY - mMinY;
}
public void adjust(double ratio){
double w = width() / 2.0;
double h = height() / 2.0;
double centerX = mMinX + w;
double centerY = mMinY + h;
double envRatio = w / h;
if(envRatio == ratio)
return;
if(ratio > envRatio) //increase width
{
w = h * ratio;
mMaxX = centerX + w;
mMinX = centerX - w;
}
else //increase height
{
h = w / ratio;
mMaxY = centerY + h;
mMinY = centerY - h;
}
}
public void merge( final GeoEnvelope other ) {
if( isInit() ){
mMinX = Math.min(mMinX, other.mMinX);
mMaxX = Math.max(mMaxX, other.mMaxX);
mMinY = Math.min(mMinY, other.mMinY);
mMaxY = Math.max(mMaxY, other.mMaxY);
}
else{
mMinX = other.mMinX;
mMaxX = other.mMaxX;
mMinY = other.mMinY;
mMaxY = other.mMaxY;
}
}
public void merge( double dfX, double dfY ) {
if( isInit() ){
mMinX = Math.min(mMinX, dfX);
mMaxX = Math.max(mMaxX, dfX);
mMinY = Math.min(mMinY, dfY);
mMaxY = Math.max(mMaxY, dfY);
}
else{
mMinX = mMaxX = dfX;
mMinY = mMaxY = dfY;
}
}
public void intersect( final GeoEnvelope other ) {
if(intersects(other)){
if( isInit() )
{
mMinX = Math.max(mMinX, other.mMinX);
mMaxX = Math.min(mMaxX, other.mMaxX);
mMinY = Math.max(mMinY, other.mMinY);
mMaxY = Math.min(mMaxY, other.mMaxY);
}
else{
mMinX = other.mMinX;
mMaxX = other.mMaxX;
mMinY = other.mMinY;
mMaxY = other.mMaxY;
}
}
else{
mMinX = 0;
mMaxX = 0;
mMinY = 0;
mMaxY = 0;
}
}
public final boolean intersects(final GeoEnvelope other){
return mMinX <= other.mMaxX && mMaxX >= other.mMinX && mMinY <= other.mMaxY && mMaxY >= other.mMinY;
}
public final boolean contains(final GeoEnvelope other){
return mMinX <= other.mMinX && mMinY <= other.mMinY && mMaxX >= other.mMaxX && mMaxY >= other.mMaxY;
}
public final boolean contains(final GeoPoint pt){
return mMinX <= pt.getX() && mMinY <= pt.getY() && mMaxX >= pt.getX() && mMaxY >= pt.getY();
}
public void offset(double x, double y) {
mMinX += x;
mMaxX += x;
mMinY += y;
mMaxY += y;
}
public void scale(double scale) {
mMaxX = mMinX + width() * scale;
mMaxY = mMinY + height() * scale;
}
public void fix(){
if(mMinX > mMaxX){
double tmp = mMinX;
mMinX = mMaxX;
mMaxX = tmp;
}
if(mMinY > mMaxY){
double tmp = mMinY;
mMinY = mMaxY;
mMaxY = tmp;
}
}
public String toString(){
return "MinX: " + mMinX + ", MinY: " + mMinY + ", MaxX: " + mMaxX + ", MaxY: " + mMaxY;
}
@Override
public JSONObject toJSON() throws JSONException{
JSONObject oJSONBBox = new JSONObject();
oJSONBBox.put(JSON_BBOX_MINX_KEY, getMinX());
oJSONBBox.put(JSON_BBOX_MINY_KEY, getMinY());
oJSONBBox.put(JSON_BBOX_MAXX_KEY, getMaxX());
oJSONBBox.put(JSON_BBOX_MAXY_KEY, getMaxY());
return oJSONBBox;
}
@Override
public void fromJSON(JSONObject jsonObject) throws JSONException{
setMinX(jsonObject.getDouble(JSON_BBOX_MINX_KEY));
setMinY(jsonObject.getDouble(JSON_BBOX_MINY_KEY));
setMaxX(jsonObject.getDouble(JSON_BBOX_MAXX_KEY));
setMaxY(jsonObject.getDouble(JSON_BBOX_MAXY_KEY));
}
}
| gpl-2.0 |
klst-com/metasfresh | de.metas.commission/test/unit/java/de/metas/commission/modelvalidator/SponsorValidatorTests.java | 2122 | package de.metas.commission.modelvalidator;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Verifications;
import org.adempiere.util.Services;
import org.compiere.model.MBPartner;
import org.compiere.model.ModelValidator;
import org.junit.Before;
import org.junit.Test;
import de.metas.adempiere.test.POTest;
import de.metas.commission.interfaces.I_C_BPartner;
import de.metas.commission.model.MCSponsor;
import de.metas.commission.model.MCSponsorSalesRep;
public final class SponsorValidatorTests {
private static final String SPONSOR_NO = "1234";
private static final int BPARTNER_ID = 25;
private static final int SPONSOR_ID = 35;
@Mocked
MBPartner bPartner;
@Mocked
MCSponsor sponsor;
@Mocked
MCSponsorSalesRep sponsorSalesRep;
@Mocked
Services unused = null;
/**
* A new sponsor and ssr is created for a new bPartner
*/
@Test
public void bPartnerNew() {
new NonStrictExpectations() {
{
MCSponsor.createNewForCustomer(bPartner);
returns(sponsor);
}
};
new SponsorValidator().bPartnerChange(bPartner,
ModelValidator.TYPE_AFTER_NEW);
new Verifications() {
{
MCSponsor.createNewForCustomer(bPartner);
}
};
}
@Test
public void bVendorNewNoParentSponsorId() {
new NonStrictExpectations() {
{
bPartner.get_ValueAsInt(I_C_BPartner.COLUMNNAME_C_Sponsor_Parent_ID);
returns(0);
bPartner.isCustomer();
returns(false);
bPartner.isSalesRep();
returns(false);
}
};
new SponsorValidator().modelChange(bPartner,
ModelValidator.TYPE_AFTER_NEW);
new Verifications() {
{
MCSponsor.createNewForCustomer(bPartner);
}
};
}
@Mocked
MCSponsorSalesRep ssr;
@Before
public void setUp() {
new NonStrictExpectations() {
{
bPartner.getCtx();
returns(POTest.CTX);
bPartner.getC_BPartner_ID();
returns(BPARTNER_ID);
bPartner.get_TrxName();
returns(POTest.TRX_NAME);
bPartner.getValue();
returns(SPONSOR_NO);
sponsor.getC_Sponsor_ID();
returns(SPONSOR_ID);
sponsor.get_TrxName();
returns(POTest.TRX_NAME);
}
};
}
} | gpl-2.0 |
pachuc/dijjer | src/dijjer/io/store/Block.java | 1764 | /*
* Dijjer - A Peer to Peer HTTP Cache
* Copyright (C) 2004,2005 Change.Tv, Inc
*
* 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 dijjer.io.store;
import dijjer.util.VeryLongInteger;
public class Block {
public static final String VERSION = "$Id$";
private int _recordNumber;
private long _lastAccessTime;
private VeryLongInteger _key;
public Block(int recordNum, VeryLongInteger key, long accessTime) {
_recordNumber = recordNum;
_key = key;
_lastAccessTime = accessTime;
}
public int getRecordNumber() {
return _recordNumber;
}
public void setRecordNumber(int newRecNo) {
_recordNumber = newRecNo;
}
public VeryLongInteger getKey() {
return _key;
}
public long lastAccessTime() {
return _lastAccessTime;
}
public String toString() {
return "key: " + _key + " lastAccess: " + _lastAccessTime + " rec: " + _recordNumber;
}
public long getLastAccessTime() {
return _lastAccessTime;
}
public void setLastAccessTime(long accessTime) {
_lastAccessTime = accessTime;
}
public void setKey(VeryLongInteger key) {
_key = key;
}
}
| gpl-2.0 |
TheDarkEra/TheDarkEra | src/java/com/thedarkera/entity/EntityDaedricArrow.java | 19561 | package com.thedarkera.entity;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IProjectile;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.play.server.S2BPacketChangeGameState;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
public class EntityDaedricArrow extends Entity implements IProjectile {
private int field_145791_d = -1;
private int field_145792_e = -1;
private int field_145789_f = -1;
private Block field_145790_g;
private int inData;
private boolean inGround;
public int canBePickedUp;
public int arrowShake;
public Entity shootingEntity;
private int ticksInGround;
private int ticksInAir;
private double damage = 2.0D;
private int knockbackStrength;
public EntityDaedricArrow(World world) {
super(world);
renderDistanceWeight = 10.0D;
setSize(0.5F, 0.5F);
}
@SideOnly(Side.CLIENT)
public boolean canRenderOnFire()
{
return this.isBurning();
}
public EntityDaedricArrow(World p_i1754_1_, double p_i1754_2_,
double p_i1754_4_, double p_i1754_6_) {
super(p_i1754_1_);
renderDistanceWeight = 10.0D;
setSize(0.5F, 0.5F);
setPosition(p_i1754_2_, p_i1754_4_, p_i1754_6_);
yOffset = 0.0F;
setInvisible(false);
}
public EntityDaedricArrow(World p_i1755_1_, EntityLivingBase p_i1755_2_,
EntityLivingBase p_i1755_3_, float p_i1755_4_, float p_i1755_5_) {
super(p_i1755_1_);
renderDistanceWeight = 10.0D;
shootingEntity = p_i1755_2_;
if (p_i1755_2_ instanceof EntityPlayer) {
canBePickedUp = 1;
}
posY = p_i1755_2_.posY + (double) p_i1755_2_.getEyeHeight()
- 0.10000000149011612D;
double d0 = p_i1755_3_.posX - p_i1755_2_.posX;
double d1 = p_i1755_3_.boundingBox.minY
+ (double) (p_i1755_3_.height / 3.0F) - posY;
double d2 = p_i1755_3_.posZ - p_i1755_2_.posZ;
double d3 = (double) MathHelper.sqrt_double(d0 * d0 + d2 * d2);
if (d3 >= 1.0E-7D) {
float f2 = (float) (Math.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F;
float f3 = (float) (-(Math.atan2(d1, d3) * 180.0D / Math.PI));
double d4 = d0 / d3;
double d5 = d2 / d3;
setLocationAndAngles(p_i1755_2_.posX + d4, posY, p_i1755_2_.posZ
+ d5, f2, f3);
yOffset = 0.0F;
float f4 = (float) d3 * 0.2F;
setThrowableHeading(d0, d1 + (double) f4, d2, p_i1755_4_,
p_i1755_5_);
}
}
public EntityDaedricArrow(World p_i1756_1_, EntityLivingBase p_i1756_2_,
float p_i1756_3_) {
super(p_i1756_1_);
renderDistanceWeight = 10.0D;
shootingEntity = p_i1756_2_;
if (p_i1756_2_ instanceof EntityPlayer) {
canBePickedUp = 1;
}
setSize(0.5F, 0.5F);
setLocationAndAngles(p_i1756_2_.posX, p_i1756_2_.posY
+ (double) p_i1756_2_.getEyeHeight(), p_i1756_2_.posZ,
p_i1756_2_.rotationYaw, p_i1756_2_.rotationPitch);
posX -= (double) (MathHelper
.cos(rotationYaw / 180.0F * (float) Math.PI) * 0.16F);
posY -= 0.10000000149011612D;
posZ -= (double) (MathHelper
.sin(rotationYaw / 180.0F * (float) Math.PI) * 0.16F);
setPosition(posX, posY, posZ);
yOffset = 0.0F;
motionX = (double) (-MathHelper.sin(rotationYaw / 180.0F
* (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F
* (float) Math.PI));
motionZ = (double) (MathHelper.cos(rotationYaw / 180.0F
* (float) Math.PI) * MathHelper.cos(rotationPitch / 180.0F
* (float) Math.PI));
motionY = (double) (-MathHelper.sin(rotationPitch / 180.0F
* (float) Math.PI));
setThrowableHeading(motionX, motionY, motionZ, p_i1756_3_ * 1.5F, 1.0F);
}
protected void entityInit() {
dataWatcher.addObject(16, Byte.valueOf((byte) 0));
}
/**
* Similar to setArrowHeading, it's point the throwable entity to a x, y, z
* direction.
*/
public void setThrowableHeading(double p_70186_1_, double p_70186_3_,
double p_70186_5_, float p_70186_7_, float p_70186_8_) {
float f2 = MathHelper.sqrt_double(p_70186_1_ * p_70186_1_ + p_70186_3_
* p_70186_3_ + p_70186_5_ * p_70186_5_);
p_70186_1_ /= (double) f2;
p_70186_3_ /= (double) f2;
p_70186_5_ /= (double) f2;
p_70186_1_ += rand.nextGaussian()
* (double) (rand.nextBoolean() ? -1 : 1)
* 0.007499999832361937D * (double) p_70186_8_;
p_70186_3_ += rand.nextGaussian()
* (double) (rand.nextBoolean() ? -1 : 1)
* 0.007499999832361937D * (double) p_70186_8_;
p_70186_5_ += rand.nextGaussian()
* (double) (rand.nextBoolean() ? -1 : 1)
* 0.007499999832361937D * (double) p_70186_8_;
p_70186_1_ *= (double) p_70186_7_;
p_70186_3_ *= (double) p_70186_7_;
p_70186_5_ *= (double) p_70186_7_;
motionX = p_70186_1_;
motionY = p_70186_3_;
motionZ = p_70186_5_;
float f3 = MathHelper.sqrt_double(p_70186_1_ * p_70186_1_ + p_70186_5_
* p_70186_5_);
prevRotationYaw = rotationYaw = (float) (Math.atan2(p_70186_1_,
p_70186_5_) * 180.0D / Math.PI);
prevRotationPitch = rotationPitch = (float) (Math.atan2(p_70186_3_,
(double) f3) * 180.0D / Math.PI);
ticksInGround = 0;
}
/**
* Sets the position and rotation. Only difference from the other one is no
* bounding on the rotation. Args: posX, posY, posZ, yaw, pitch
*/
@SideOnly(Side.CLIENT)
public void setPositionAndRotation2(double p_70056_1_, double p_70056_3_,
double p_70056_5_, float p_70056_7_, float p_70056_8_,
int p_70056_9_) {
setPosition(p_70056_1_, p_70056_3_, p_70056_5_);
setRotation(p_70056_7_, p_70056_8_);
}
/**
* Sets the velocity to the args. Args: x, y, z
*/
@SideOnly(Side.CLIENT)
public void setVelocity(double p_70016_1_, double p_70016_3_,
double p_70016_5_) {
motionX = p_70016_1_;
motionY = p_70016_3_;
motionZ = p_70016_5_;
if (prevRotationPitch == 0.0F && prevRotationYaw == 0.0F) {
float f = MathHelper.sqrt_double(p_70016_1_ * p_70016_1_
+ p_70016_5_ * p_70016_5_);
prevRotationYaw = rotationYaw = (float) (Math.atan2(p_70016_1_,
p_70016_5_) * 180.0D / Math.PI);
prevRotationPitch = rotationPitch = (float) (Math.atan2(p_70016_3_,
(double) f) * 180.0D / Math.PI);
prevRotationPitch = rotationPitch;
prevRotationYaw = rotationYaw;
setLocationAndAngles(posX, posY, posZ, rotationYaw, rotationPitch);
ticksInGround = 0;
}
}
/**
* Called to update the entity's position/logic.
*/
@SuppressWarnings("rawtypes")
public void onUpdate() {
super.onUpdate();
if (prevRotationPitch == 0.0F && prevRotationYaw == 0.0F) {
float f = MathHelper.sqrt_double(motionX * motionX + motionZ
* motionZ);
prevRotationYaw = rotationYaw = (float) (Math.atan2(motionX,
motionZ) * 180.0D / Math.PI);
prevRotationPitch = rotationPitch = (float) (Math.atan2(motionY,
(double) f) * 180.0D / Math.PI);
}
Block block = worldObj.getBlock(field_145791_d, field_145792_e,
field_145789_f);
if (block.getMaterial() != Material.air) {
block.setBlockBoundsBasedOnState(worldObj, field_145791_d,
field_145792_e, field_145789_f);
AxisAlignedBB axisalignedbb = block
.getCollisionBoundingBoxFromPool(worldObj, field_145791_d,
field_145792_e, field_145789_f);
if (axisalignedbb != null
&& axisalignedbb.isVecInside(Vec3.createVectorHelper(posX,
posY, posZ))) {
inGround = true;
}
}
if (arrowShake > 0) {
--arrowShake;
}
if (inGround) {
int j = worldObj.getBlockMetadata(field_145791_d, field_145792_e,
field_145789_f);
if (block == field_145790_g && j == inData) {
++ticksInGround;
if (ticksInGround == 1200) {
setDead();
}
} else {
inGround = false;
motionX *= (double) (rand.nextFloat() * 0.2F);
motionY *= (double) (rand.nextFloat() * 0.2F);
motionZ *= (double) (rand.nextFloat() * 0.2F);
ticksInGround = 0;
ticksInAir = 0;
}
} else {
++ticksInAir;
Vec3 vec31 = Vec3.createVectorHelper(posX, posY, posZ);
Vec3 vec3 = Vec3.createVectorHelper(posX + motionX, posY + motionY,
posZ + motionZ);
MovingObjectPosition movingobjectposition = worldObj.func_147447_a(
vec31, vec3, false, true, false);
vec31 = Vec3.createVectorHelper(posX, posY, posZ);
vec3 = Vec3.createVectorHelper(posX + motionX, posY + motionY, posZ
+ motionZ);
if (movingobjectposition != null) {
vec3 = Vec3.createVectorHelper(
movingobjectposition.hitVec.xCoord,
movingobjectposition.hitVec.yCoord,
movingobjectposition.hitVec.zCoord);
}
Entity entity = null;
List list = worldObj.getEntitiesWithinAABBExcludingEntity(
this,
boundingBox.addCoord(motionX, motionY, motionZ).expand(
1.0D, 1.0D, 1.0D));
double d0 = 0.0D;
int i;
float f1;
for (i = 0; i < list.size(); ++i) {
Entity entity1 = (Entity) list.get(i);
if (entity1.canBeCollidedWith()
&& (entity1 != shootingEntity || ticksInAir >= 5)) {
f1 = 0.3F;
AxisAlignedBB axisalignedbb1 = entity1.boundingBox.expand(
(double) f1, (double) f1, (double) f1);
MovingObjectPosition movingobjectposition1 = axisalignedbb1
.calculateIntercept(vec31, vec3);
if (movingobjectposition1 != null) {
double d1 = vec31
.distanceTo(movingobjectposition1.hitVec);
if (d1 < d0 || d0 == 0.0D) {
entity = entity1;
d0 = d1;
}
}
}
}
if (entity != null) {
movingobjectposition = new MovingObjectPosition(entity);
}
if (movingobjectposition != null
&& movingobjectposition.entityHit != null
&& movingobjectposition.entityHit instanceof EntityPlayer) {
EntityPlayer entityplayer = (EntityPlayer) movingobjectposition.entityHit;
if (entityplayer.capabilities.disableDamage
|| shootingEntity instanceof EntityPlayer
&& !((EntityPlayer) shootingEntity)
.canAttackPlayer(entityplayer)) {
movingobjectposition = null;
}
}
float f2;
float f4;
if (movingobjectposition != null) {
if (movingobjectposition.entityHit != null) {
f2 = MathHelper.sqrt_double(motionX * motionX + motionY
* motionY + motionZ * motionZ);
int k = MathHelper.ceiling_double_int((double) f2 * damage);
if (getIsCritical()) {
k += rand.nextInt(k / 2 + 2);
}
DamageSource damagesource = null;
if (shootingEntity == null) {
damagesource = DamageSource.causeThrownDamage(this,
this);
} else {
damagesource = DamageSource.causeThrownDamage(this,
shootingEntity);
}
if (isBurning()
&& !(movingobjectposition.entityHit instanceof EntityEnderman)) {
movingobjectposition.entityHit.setFire(5);
}
if (movingobjectposition.entityHit.attackEntityFrom(
damagesource, (float) k)) {
if (movingobjectposition.entityHit instanceof EntityLivingBase) {
EntityLivingBase entitylivingbase = (EntityLivingBase) movingobjectposition.entityHit;
if (!worldObj.isRemote) {
entitylivingbase
.setArrowCountInEntity(entitylivingbase
.getArrowCountInEntity() + 1);
}
if (knockbackStrength > 0) {
f4 = MathHelper.sqrt_double(motionX * motionX
+ motionZ * motionZ);
if (f4 > 0.0F) {
movingobjectposition.entityHit
.addVelocity(
motionX
* (double) knockbackStrength
* 0.6000000238418579D
/ (double) f4,
0.1D,
motionZ
* (double) knockbackStrength
* 0.6000000238418579D
/ (double) f4);
}
}
if (shootingEntity != null
&& shootingEntity instanceof EntityLivingBase) {
EnchantmentHelper.func_151384_a(
entitylivingbase, shootingEntity);
EnchantmentHelper.func_151385_b(
(EntityLivingBase) shootingEntity,
entitylivingbase);
}
if (shootingEntity != null
&& movingobjectposition.entityHit != shootingEntity
&& movingobjectposition.entityHit instanceof EntityPlayer
&& shootingEntity instanceof EntityPlayerMP) {
((EntityPlayerMP) shootingEntity).playerNetServerHandler
.sendPacket(new S2BPacketChangeGameState(
6, 0.0F));
}
}
playSound("random.bowhit", 1.0F,
1.2F / (rand.nextFloat() * 0.2F + 0.9F));
if (!(movingobjectposition.entityHit instanceof EntityEnderman)) {
setDead();
}
} else {
motionX *= -0.10000000149011612D;
motionY *= -0.10000000149011612D;
motionZ *= -0.10000000149011612D;
rotationYaw += 180.0F;
prevRotationYaw += 180.0F;
ticksInAir = 0;
}
} else {
field_145791_d = movingobjectposition.blockX;
field_145792_e = movingobjectposition.blockY;
field_145789_f = movingobjectposition.blockZ;
field_145790_g = worldObj.getBlock(field_145791_d,
field_145792_e, field_145789_f);
inData = worldObj.getBlockMetadata(field_145791_d,
field_145792_e, field_145789_f);
motionX = (double) ((float) (movingobjectposition.hitVec.xCoord - posX));
motionY = (double) ((float) (movingobjectposition.hitVec.yCoord - posY));
motionZ = (double) ((float) (movingobjectposition.hitVec.zCoord - posZ));
f2 = MathHelper.sqrt_double(motionX * motionX + motionY
* motionY + motionZ * motionZ);
posX -= motionX / (double) f2 * 0.05000000074505806D;
posY -= motionY / (double) f2 * 0.05000000074505806D;
posZ -= motionZ / (double) f2 * 0.05000000074505806D;
playSound("random.bowhit", 1.0F,
1.2F / (rand.nextFloat() * 0.2F + 0.9F));
inGround = true;
arrowShake = 7;
setIsCritical(false);
if (field_145790_g.getMaterial() != Material.air) {
field_145790_g.onEntityCollidedWithBlock(worldObj,
field_145791_d, field_145792_e, field_145789_f,
this);
}
}
}
if (getIsCritical()) {
for (i = 0; i < 4; ++i) {
worldObj.spawnParticle("crit", posX + motionX * (double) i
/ 4.0D, posY + motionY * (double) i / 4.0D, posZ
+ motionZ * (double) i / 4.0D, -motionX,
-motionY + 0.2D, -motionZ);
}
}
posX += motionX;
posY += motionY;
posZ += motionZ;
f2 = MathHelper.sqrt_double(motionX * motionX + motionZ * motionZ);
rotationYaw = (float) (Math.atan2(motionX, motionZ) * 180.0D / Math.PI);
for (rotationPitch = (float) (Math.atan2(motionY, (double) f2) * 180.0D / Math.PI); rotationPitch
- prevRotationPitch < -180.0F; prevRotationPitch -= 360.0F) {
;
}
while (rotationPitch - prevRotationPitch >= 180.0F) {
prevRotationPitch += 360.0F;
}
while (rotationYaw - prevRotationYaw < -180.0F) {
prevRotationYaw -= 360.0F;
}
while (rotationYaw - prevRotationYaw >= 180.0F) {
prevRotationYaw += 360.0F;
}
rotationPitch = prevRotationPitch
+ (rotationPitch - prevRotationPitch) * 0.2F;
rotationYaw = prevRotationYaw + (rotationYaw - prevRotationYaw)
* 0.2F;
float f3 = 0.99F;
f1 = 0.05F;
if (isInWater()) {
for (int l = 0; l < 4; ++l) {
f4 = 0.25F;
worldObj.spawnParticle("bubble", posX - motionX
* (double) f4, posY - motionY * (double) f4, posZ
- motionZ * (double) f4, motionX, motionY, motionZ);
}
f3 = 0.8F;
}
if (isWet()) {
extinguish();
}
motionX *= (double) f3;
motionY *= (double) f3;
motionZ *= (double) f3;
motionY -= (double) f1;
setPosition(posX, posY, posZ);
func_145775_I();
}
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound p_70014_1_) {
p_70014_1_.setShort("xTile", (short) field_145791_d);
p_70014_1_.setShort("yTile", (short) field_145792_e);
p_70014_1_.setShort("zTile", (short) field_145789_f);
p_70014_1_.setShort("life", (short) ticksInGround);
p_70014_1_.setByte("inTile",
(byte) Block.getIdFromBlock(field_145790_g));
p_70014_1_.setByte("inData", (byte) inData);
p_70014_1_.setByte("shake", (byte) arrowShake);
p_70014_1_.setByte("inGround", (byte) (inGround ? 1 : 0));
p_70014_1_.setByte("pickup", (byte) canBePickedUp);
p_70014_1_.setDouble("damage", damage);
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound p_70037_1_) {
field_145791_d = p_70037_1_.getShort("xTile");
field_145792_e = p_70037_1_.getShort("yTile");
field_145789_f = p_70037_1_.getShort("zTile");
ticksInGround = p_70037_1_.getShort("life");
field_145790_g = Block.getBlockById(p_70037_1_.getByte("inTile") & 255);
inData = p_70037_1_.getByte("inData") & 255;
arrowShake = p_70037_1_.getByte("shake") & 255;
inGround = p_70037_1_.getByte("inGround") == 1;
if (p_70037_1_.hasKey("damage", 99)) {
damage = p_70037_1_.getDouble("damage");
}
if (p_70037_1_.hasKey("pickup", 99)) {
canBePickedUp = p_70037_1_.getByte("pickup");
} else if (p_70037_1_.hasKey("player", 99)) {
canBePickedUp = p_70037_1_.getBoolean("player") ? 1 : 0;
}
}
/**
* Called by a player entity when they collide with an entity
*/
public void onCollideWithPlayer(EntityPlayer p_70100_1_) {
if (!worldObj.isRemote && inGround && arrowShake <= 0) {
boolean flag = canBePickedUp == 1 || canBePickedUp == 2
&& p_70100_1_.capabilities.isCreativeMode;
if (canBePickedUp == 1
&& !p_70100_1_.inventory
.addItemStackToInventory(new ItemStack(Items.arrow,
1))) {
flag = false;
}
if (flag) {
playSound(
"random.pop",
0.2F,
((rand.nextFloat() - rand.nextFloat()) * 0.7F + 1.0F) * 2.0F);
p_70100_1_.onItemPickup(this, 1);
setDead();
}
}
}
/**
* returns if this entity triggers Block.onEntityWalking on the blocks they
* walk on. used for spiders and wolves to prevent them from trampling crops
*/
protected boolean canTriggerWalking() {
return false;
}
@SideOnly(Side.CLIENT)
public float getShadowSize() {
return 0.0F;
}
public void setDamage(double p_70239_1_) {
damage = p_70239_1_;
}
public double getDamage() {
return damage;
}
/**
* Sets the amount of knockback the arrow applies when it hits a mob.
*/
public void setKnockbackStrength(int p_70240_1_) {
knockbackStrength = p_70240_1_;
}
/**
* If returns false, the item will not inflict any damage against entities.
*/
public boolean canAttackWithItem() {
return false;
}
/**
* Whether the arrow has a stream of critical hit particles flying behind
* it.
*/
public void setIsCritical(boolean p_70243_1_) {
byte b0 = dataWatcher.getWatchableObjectByte(16);
if (p_70243_1_) {
dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1)));
} else {
dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2)));
}
}
/**
* Whether the arrow has a stream of critical hit particles flying behind
* it.
*/
public boolean getIsCritical() {
byte b0 = dataWatcher.getWatchableObjectByte(16);
return (b0 & 1) != 0;
}
} | gpl-2.0 |
mackaiver/streams-dim | src/main/java/dim/DimService.java | 20225 | package dim;
import java.util.Date;
public class DimService extends MutableMemory implements DataEncoder, DimServiceUpdateHandler
{
int service_id;
String service_name;
int published, curr_size;
String format;
Format itsFormat;
DimDataOffsets items;
public DimService(String theServiceName)
{
published = 0;
service_name = theServiceName;
curr_size = 0;
format = "";
items = new DimDataOffsets();
}
public DimService()
{
published = 0;
service_name = "";
curr_size = 0;
format = "";
items = new DimDataOffsets();
}
public String getFormatStr()
{
return format;
}
public void setName(String theServiceName)
{
service_name = theServiceName;
}
public DimService(String theServiceName, boolean theData)
{
service_name = theServiceName;
setSize(1);
this.copyBoolean(theData);
service_id = Server.addService(theServiceName, "C", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, byte theData)
{
service_name = theServiceName;
setSize(1);
this.copyByte(theData);
service_id = Server.addService(theServiceName, "C", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, short theData)
{
service_name = theServiceName;
setSize(2);
this.copyShort(theData);
service_id = Server.addService(theServiceName, "S", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, int theData)
{
service_name = theServiceName;
setSize(4);
this.copyInt(theData);
service_id = Server.addService(theServiceName, "I", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, float theData)
{
service_name = theServiceName;
setSize(4);
this.copyFloat(theData);
service_id = Server.addService(theServiceName, "F", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, double theData)
{
service_name = theServiceName;
setSize(8);
this.copyDouble(theData);
service_id = Server.addService(theServiceName, "D", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, long theData)
{
service_name = theServiceName;
setSize(8);
this.copyLong(theData);
service_id = Server.addService(theServiceName, "X", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, String theData)
{
service_name = theServiceName;
setSize(theData.length()+1);
this.copyString(theData);
service_id = Server.addService(theServiceName, "C", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, boolean[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromBooleanArray(theData, 0, size);
service_id = Server.addService(theServiceName, "C", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, byte[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromByteArray(theData, 0, size);
service_id = Server.addService(theServiceName, "C", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, short[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromShortArray(theData, 0, size/2);
service_id = Server.addService(theServiceName, "S", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, int[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromIntArray(theData, 0, size/4);
service_id = Server.addService(theServiceName, "I", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, float[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromFloatArray(theData, 0, size/4);
service_id = Server.addService(theServiceName, "F", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, double[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromDoubleArray(theData, 0, size/8);
service_id = Server.addService(theServiceName, "D", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, long[] theData)
{
service_name = theServiceName;
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromLongArray(theData, 0, size/8);
service_id = Server.addService(theServiceName, "X", this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public DimService(String theServiceName, DimService src)
{
service_name = theServiceName;
int size = src.getDataSize();
setSize(size);
this.copyFromMemory(src);
service_id = Server.addService(theServiceName, src.getFormatStr(), this);
published = 1;
itsFormat = null;
// theDataStore = null;
}
public void finalize()
{
removeService();
}
public void removeService()
{
if(service_id != 0)
Server.removeService(service_id);
}
public Memory encodeData()
{
serviceUpdateHandler();
return this;
}
public void updateService(String theData)
{
this.setSize(theData.length()+1);
this.copyString(theData);
Server.updateService(service_id);
}
public void updateService(boolean theData)
{
this.setSize(1);
this.copyBoolean(theData);
Server.updateService(service_id);
}
public void updateService(byte theData)
{
this.setSize(1);
this.copyByte(theData);
Server.updateService(service_id);
}
public void updateService(short theData)
{
this.setSize(2);
this.copyShort(theData);
Server.updateService(service_id);
}
public void updateService(int theData)
{
this.setSize(4);
this.copyInt(theData);
Server.updateService(service_id);
}
public void updateService(float theData)
{
this.setSize(4);
this.copyFloat(theData);
Server.updateService(service_id);
}
public void updateService(double theData)
{
this.setSize(8);
this.copyDouble(theData);
Server.updateService(service_id);
}
public void updateService(long theData)
{
this.setSize(8);
this.copyLong(theData);
Server.updateService(service_id);
}
public void updateService(boolean[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromBooleanArray(theData, 0, size);
Server.updateService(service_id);
}
public void updateService(byte[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromByteArray(theData, 0, size);
Server.updateService(service_id);
}
public void updateService(short[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromShortArray(theData, 0, size/2);
Server.updateService(service_id);
}
public void updateService(int[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromIntArray(theData, 0, size/4);
Server.updateService(service_id);
}
public void updateService(float[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromFloatArray(theData, 0, size/4);
Server.updateService(service_id);
}
public void updateService(double[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromDoubleArray(theData, 0, size/8);
Server.updateService(service_id);
}
public void updateService(long[] theData)
{
int size = Sizeof.sizeof(theData);
setSize(size);
this.copyFromLongArray(theData, 0, size/8);
Server.updateService(service_id);
}
public void updateService(DimService src)
{
int size = src.getDataSize();
setSize(size);
this.copyFromMemory(src);
Server.updateService(service_id);
}
int do_setup_format(int offset, char type, int num)
{
char last;
if(published == 0)
{
if(items.findOffset(offset) != -1)
return 1;
items.addOffset(offset, type, num);
if(format != "")
{
if(format.lastIndexOf(':') < format.lastIndexOf(';'))
{
last = format.charAt(format.length()-1);
if(last != type)
{
System.out.println(
"JDIM: Dynamic Item must be at the end");
return 0;
}
else
return 1;
}
format += ";";
}
format += type;
if(num != 0)
format += ":"+num;
return 1;
}
else
{
int index;
if((index = items.findOffset(offset)) == -1)
{
if((type == 'C') && (num == 0))
return 1;
else
{
System.out.println("JDIM: Offset "+offset+" not found ");
return 0;
}
}
// char ntype = itsFormat.getType();
// int nnum = itsFormat.getNum();
char ntype = items.getType(index);
int nnum = items.getSize(index);
if(ntype != type)
{
System.out.println("JDIM: Expected "+ntype+" found "+type);
return 0;
}
if((nnum != num) && (nnum != 0) && (num != 0))
{
// if(nnum)
System.out.println("JDIM: Expected "+nnum+" items, found "+num);
// else
// System.out.println("JDIM: Expected "+nnum+" items, found "+num);
// return 0;
}
if(nnum == 0)
return 1;
return nnum;
}
}
/*
public int do_set_data_size(char type, int len, int size)
{
int index, offset, old_size;
if(do_setup_format(type,len) == 0)
return -1;
offset = curr_size;
curr_size += size;
setSize(curr_size);
setDataStoreOffset(offset);
return offset;
}
*/
public int do_setup_data(char type, int len, int size, int offset)
{
int index, new_offset, old_size;
new_offset = offset;
if(offset == -1)
{
new_offset = curr_size;
curr_size += size;
setSize(curr_size);
}
else if((type == 'C') && (len == 0))
{
curr_size = getAllocatedSize();
if(offset + size > curr_size)
setSize(offset+size);
}
if(do_setup_format(new_offset, type,len) == 0)
return -1;
setDataStoreOffset(new_offset);
return new_offset;
}
public int setBoolean(boolean theData)
{
int offset;
offset = do_setup_data('C', 1, 1, -1);
if(offset != -1)
copyBoolean(theData);
return offset;
}
public int setBoolean(boolean theData, int theOffset)
{
int offset;
offset = do_setup_data('C', 1, 1, theOffset);
if(offset != -1)
copyBoolean(theData);
return offset;
}
public int setByte(byte theData)
{
int offset;
offset = do_setup_data('C', 1, 1, -1);
if(offset != -1)
copyByte(theData);
return offset;
}
public int setByte(byte theData, int theOffset)
{
int offset;
offset = do_setup_data('C', 1, 1, theOffset);
if(offset != -1)
copyByte(theData);
return offset;
}
public int setShort(short theData)
{
int offset;
offset = do_setup_data('S', 1, 2, -1);
if(offset != -1)
copyShort(theData);
return offset;
}
public int setShort(short theData, int theOffset)
{
int offset;
offset = do_setup_data('S', 1, 2, theOffset);
if(offset != -1)
copyShort(theData);
return offset;
}
public int setInt(int theData)
{
int offset;
offset = do_setup_data('I', 1, 4, -1);
if(offset != -1)
copyInt(theData);
return offset;
}
public int setInt(int theData, int theOffset)
{
int offset;
offset = do_setup_data('I', 1, 4, theOffset);
if(offset != -1)
copyInt(theData);
return offset;
}
public int setFloat(float theData)
{
int offset;
offset = do_setup_data('F', 1, 4, -1);
if(offset != -1)
copyFloat(theData);
return offset;
}
public int setFloat(float theData, int theOffset)
{
int offset;
offset = do_setup_data('F', 1, 4, theOffset);
if(offset != -1)
copyFloat(theData);
return offset;
}
public int setDouble(double theData)
{
int offset;
offset = do_setup_data('D', 1, 8, -1);
if(offset != -1)
copyDouble(theData);
return offset;
}
public int setDouble(double theData, int theOffset)
{
int offset;
offset = do_setup_data('D', 1, 8, theOffset);
if(offset != -1)
copyDouble(theData);
return offset;
}
public int setLong(long theData)
{
int offset;
offset = do_setup_data('X', 1, 8, -1);
if(offset != -1)
copyLong(theData);
return offset;
}
public int setLong(long theData, int theOffset)
{
int offset;
offset = do_setup_data('X', 1, 8, theOffset);
if(offset != -1)
copyLong(theData);
return offset;
}
public int setString(int max_size, String theData)
{
int offset;
offset = do_setup_data('C', max_size, max_size, -1);
if(offset != -1)
copyString(theData);
return offset;
}
public int setString(String theData)
{
int offset;
offset = do_setup_data('C', 0, theData.length()+1, -1);
if(offset != -1)
copyString(theData);
return offset;
}
public int setString(String theData, int theOffset)
{
int offset;
offset = do_setup_data('C', 0, theData.length()+1, theOffset);
if(offset != -1)
copyString(theData);
return offset;
}
/*
public int setString(String theData)
{
// return theDataStore.setString(theData);
int max_size;
if(published == 0)
max_size = do_setup_format('C',theData.length());
else
max_size = do_setup_format('C',0);
if(max_size == 0)
return 0;
itsLast = 1;
int offset = curr_size;
curr_size += max_size;
setSize(curr_size);
setDataStoreOffset(offset);
// if(do_setup_data('I', 1, 4, "") == 0)
// return 0;
this.copyString(theData);
return 1;
}
*/
public int setBooleanArray(boolean theData[])
{
int size = Sizeof.sizeof(theData);
int len = size;
int offset;
offset = do_setup_data('C', len, size, -1);
if(offset != -1)
copyFromBooleanArray(theData);
return offset;
}
public int setBooleanArray(boolean theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size;
int offset;
offset = do_setup_data('C', len, size, theOffset);
if(offset != -1)
copyFromBooleanArray(theData);
return offset;
}
public int setByteArray(byte theData[])
{
int size = Sizeof.sizeof(theData);
int len = size;
int offset;
offset = do_setup_data('C', len, size, -1);
if(offset != -1)
copyFromByteArray(theData);
return offset;
}
public int setByteArray(byte theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size;
int offset;
offset = do_setup_data('C', len, size, theOffset);
if(offset != -1)
copyFromByteArray(theData);
return offset;
}
public int setShortArray(short theData[])
{
int size = Sizeof.sizeof(theData);
int len = size/2;
int offset;
offset = do_setup_data('S', len, size, -1);
if(offset != -1)
copyFromShortArray(theData);
return offset;
}
public int setShortArray(short theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size/2;
int offset;
offset = do_setup_data('S', len, size, theOffset);
if(offset != -1)
copyFromShortArray(theData);
return offset;
}
public int setIntArray(int theData[])
{
int size = Sizeof.sizeof(theData);
int len = size/4;
int offset;
offset = do_setup_data('I', len, size, -1);
if(offset != -1)
copyFromIntArray(theData);
return offset;
}
public int setIntArray(int theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size/4;
int offset;
offset = do_setup_data('I', len, size, theOffset);
if(offset != -1)
copyFromIntArray(theData);
return offset;
}
public int setFloatArray(float theData[])
{
int size = Sizeof.sizeof(theData);
int len = size/4;
int offset;
offset = do_setup_data('F', len, size, -1);
if(offset != -1)
copyFromFloatArray(theData);
return offset;
}
public int setFloatArray(float theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size/4;
int offset;
offset = do_setup_data('F', len, size, theOffset);
if(offset != -1)
copyFromFloatArray(theData);
return offset;
}
public int setDoubleArray(double theData[])
{
int size = Sizeof.sizeof(theData);
int len = size/8;
int offset;
offset = do_setup_data('D', len, size, -1);
if(offset != -1)
copyFromDoubleArray(theData);
return offset;
}
public int setDoubleArray(double theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size/8;
int offset;
offset = do_setup_data('D', len, size, theOffset);
if(offset != -1)
copyFromDoubleArray(theData);
return offset;
}
public int setLongArray(long theData[])
{
int size = Sizeof.sizeof(theData);
int len = size/8;
int offset;
offset = do_setup_data('X', len, size, -1);
if(offset != -1)
copyFromLongArray(theData);
return offset;
}
public int setLongArray(long theData[], int theOffset)
{
int size = Sizeof.sizeof(theData);
int len = size/8;
int offset;
offset = do_setup_data('X', len, size, theOffset);
if(offset != -1)
copyFromLongArray(theData);
return offset;
}
public int setStringArray(String theData[])
{
int size = 0;
int len = theData.length;
int offset, i;
for(i = 0; i < len; i++)
{
size += theData[i].length()+1;
}
offset = do_setup_data('C', 0, size, -1);
if(offset != -1)
{
for(i = 0; i < len; i++)
copyString(theData[i]);
}
return offset;
}
public int setStringArray(String theData[], int theOffset)
{
int size = 0;
int len = theData.length;
int offset, i;
for(i = 0; i < len; i++)
{
size += theData[i].length()+1;
}
offset = do_setup_data('C', 0, size, theOffset);
if(offset != -1)
{
for(i = 0; i < len; i++)
copyString(theData[i]);
}
return offset;
}
public void updateService()
{
if(published == 0)
{
itsFormat = new Format(format, 1);
service_id = Server.addService(service_name, itsFormat.getFormat(), this);
published = 1;
}
else
{
if(itsFormat != null)
{
itsFormat.reset();
}
Server.updateService(service_id);
}
curr_size = 0;
}
public void selectiveUpdateService()
{
int client_id = DimServer.getClientId();
Server.selectiveUpdateService(service_id, client_id);
}
public void selectiveUpdateService(int[] client_ids)
{
Server.selectiveUpdateService(service_id, client_ids);
}
public void selectiveUpdateService(int client_id)
{
Server.selectiveUpdateService(service_id, client_id);
}
public static native void setQuality(int serviceId, int quality);
public static native void setTimestamp(int serviceId, int secs, int millisecs);
public void setQuality(int quality)
{
setQuality(service_id, quality);
}
public void setTimestamp(Date tstamp)
{
int secs, millisecs;
long total, aux;
total = tstamp.getTime();
aux = total % 1000;
millisecs = (int)aux;
aux = total / 1000;
secs = (int)aux;
setTimestamp(service_id, secs, millisecs);
}
public void serviceUpdateHandler() {}
}
interface DimServiceUpdateHandler
{
void serviceUpdateHandler();
}
| gpl-2.0 |
Alariel91/VIDEOPLAYER-VLC | PracticaVLC/src/com/mony/gui/HiloTiempo.java | 1528 | package com.mony.gui;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.SwingWorker;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
public class HiloTiempo extends SwingWorker <Void,Integer> {
private int tamano;
private int tiempo;
private JSlider barraProgreso;
private EmbeddedMediaPlayerComponent mediaPlayer;
private JLabel tiempoTotal;
private JLabel tiempoTranscurrido;
public HiloTiempo(JSlider barraProgreso, EmbeddedMediaPlayerComponent mediaPlayer,JLabel tiempoTranscurrido,JLabel tiempoTotal){
this.mediaPlayer=mediaPlayer;
this.barraProgreso=barraProgreso;
this.tiempoTotal=tiempoTotal;
this.tiempoTranscurrido=tiempoTranscurrido;
}
@Override
protected Void doInBackground() throws Exception {
while(mediaPlayer.getMediaPlayer().getLength()==0){
Thread.sleep(100);
}
this.tamano= (int) mediaPlayer.getMediaPlayer().getLength();
barraProgreso.setMaximum(tamano);
int segundostotal = tamano / 1000;
int minutostotal = segundostotal / 60;
segundostotal = segundostotal - (minutostotal*60);
this.tiempoTotal.setText(String.valueOf(minutostotal+ ":" + segundostotal));
for(int i=0; i<=this.tamano; i++){
tiempo = (int) mediaPlayer.getMediaPlayer().getTime();
}
barraProgreso.setValue(tiempo);
int segundos = tiempo / 1000;
int minutos = segundos / 60;
segundos = segundos - (minutos*60);
this.tiempoTranscurrido.setText(String.valueOf(minutos +":" +segundos));
return null;
}
}
| gpl-2.0 |