repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ModelWriter/Source
plugins/org.eclipse.mylyn.docs.intent.mapping.emf/src-gen/org/eclipse/mylyn/docs/intent/mapping/IEMFBaseElement.java
914
/** * Copyright (c) 2015 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 and/or initial documentation * ... * */ package org.eclipse.mylyn.docs.intent.mapping; import org.eclipse.emf.ecore.EObject; import org.eclipse.mylyn.docs.intent.mapping.base.IMappingElement; /** * <!-- begin-user-doc --> A representation of the model object '<em><b>IBase Element</b></em>'. <!-- * end-user-doc --> * * @see org.eclipse.mylyn.docs.intent.mapping.MappingPackage#getIBaseElement() * @model interface="true" abstract="true" * @generated NOT */ public interface IEMFBaseElement extends EObject, IMappingElement { } // IEMFBaseElement
epl-1.0
digitaldan/smarthome
bundles/io/org.eclipse.smarthome.io.rest.core/src/main/java/org/eclipse/smarthome/io/rest/core/internal/RESTCoreActivator.java
1460
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.io.rest.core.internal; import org.eclipse.smarthome.io.rest.core.JSONResponse; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * Extension of the default OSGi bundle activator * * @author Kai Kreuzer - Initial contribution and API */ public class RESTCoreActivator implements BundleActivator { private static BundleContext context; private ServiceRegistration<JSONResponse.ExceptionMapper> mExcMapper; /** * Called whenever the OSGi framework starts our bundle */ @Override public void start(BundleContext bc) throws Exception { context = bc; mExcMapper = bc.registerService(JSONResponse.ExceptionMapper.class, new JSONResponse.ExceptionMapper(), null); } /** * Called whenever the OSGi framework stops our bundle */ @Override public void stop(BundleContext context) throws Exception { context = null; mExcMapper.unregister(); } public static BundleContext getBundleContext() { return context; } }
epl-1.0
forge/furnace
container/src/main/java/org/jboss/forge/furnace/impl/modules/ModuleSpecProvider.java
1187
/* * Copyright 2014 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.furnace.impl.modules; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; import org.jboss.modules.ModuleSpec; /** * A {@link ModuleSpecProvider} is used by {@link AddonModuleLoader} to provide {@link ModuleSpec} instances based on a * given {@link ModuleIdentifier} * * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> */ public interface ModuleSpecProvider { /** * Returns a {@link ModuleSpec} instance given a {@link ModuleIdentifier} * * @param loader the {@link ModuleLoader} used to load the returned {@link ModuleSpec} * @param id the {@link ModuleIdentifier} of the loaded {@link ModuleSpec} * @return the {@link ModuleSpec} associated with this {@link ModuleIdentifier}, <code>null</code> if the * {@link ModuleIdentifier} does not apply to this {@link ModuleSpecProvider} */ ModuleSpec get(ModuleLoader loader, ModuleIdentifier id); ModuleIdentifier getId(); }
epl-1.0
taimos/openhab
bundles/core/org.openhab.core.jsr223/src/main/java/org/openhab/core/jsr223/internal/engine/scriptmanager/Script.java
4873
package org.openhab.core.jsr223.internal.engine.scriptmanager; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.openhab.core.jsr223.internal.engine.RuleExecutionRunnable; import org.openhab.core.jsr223.internal.shared.ChangedEventTrigger; import org.openhab.core.jsr223.internal.shared.CommandEventTrigger; import org.openhab.core.jsr223.internal.shared.Event; import org.openhab.core.jsr223.internal.shared.EventTrigger; import org.openhab.core.jsr223.internal.shared.Openhab; import org.openhab.core.jsr223.internal.shared.Rule; import org.openhab.core.jsr223.internal.shared.RuleSet; import org.openhab.core.jsr223.internal.shared.ShutdownTrigger; import org.openhab.core.jsr223.internal.shared.StartupTrigger; import org.openhab.core.jsr223.internal.shared.TimerTrigger; import org.openhab.core.jsr223.internal.shared.TriggerType; import org.openhab.core.library.types.DateTimeType; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.HSBType; import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OpenClosedType; import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.PointType; import org.openhab.core.library.types.StopMoveType; import org.openhab.core.library.types.StringType; import org.openhab.core.library.types.UpDownType; import org.openhab.core.types.Command; import org.openhab.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Script holds information about a script-file. Furthermore it feeds information and objects to the Jsr223 * Script-Engine to allow interoperability with openHAB. * * @author Simon Merschjohann * @since 1.7.0 */ public class Script { static private final Logger logger = LoggerFactory.getLogger(Script.class); ArrayList<Rule> rules = new ArrayList<Rule>(); private ScriptManager scriptManager; private ScriptEngine engine; private String fileName; public Script(ScriptManager scriptManager, File file) throws FileNotFoundException, ScriptException, NoSuchMethodException { this.scriptManager = scriptManager; this.fileName = file.getName(); loadScript(file); } public void loadScript(File file) throws FileNotFoundException, ScriptException, NoSuchMethodException { logger.info("Loading Script " + file.getName()); String extension = getFileExtension(file); ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByExtension(extension); if (engine != null) { initializeSciptGlobals(); engine.eval(new FileReader(file)); Invocable inv = (Invocable) engine; RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules"); rules.addAll(ruleSet.getRules()); } } private void initializeSciptGlobals() { engine.put("RuleSet", RuleSet.class); engine.put("Rule", Rule.class); engine.put("State", State.class); engine.put("Command", Command.class); engine.put("ChangedEventTrigger", ChangedEventTrigger.class); engine.put("CommandEventTrigger", CommandEventTrigger.class); engine.put("Event", Event.class); engine.put("EventTrigger", EventTrigger.class); engine.put("ShutdownTrigger", ShutdownTrigger.class); engine.put("StartupTrigger", StartupTrigger.class); engine.put("TimerTrigger", TimerTrigger.class); engine.put("TriggerType", TriggerType.class); engine.put("ItemRegistry", scriptManager.getItemRegistry()); engine.put("DateTime", org.joda.time.DateTime.class); engine.put("oh", Openhab.class); // default types, TODO: auto import would be nice engine.put("DateTimeType", DateTimeType.class); engine.put("DecimalType", DecimalType.class); engine.put("HSBType", HSBType.class); engine.put("IncreaseDecreaseType", IncreaseDecreaseType.class); engine.put("OnOffType", OnOffType.class); engine.put("OpenClosedType", OpenClosedType.class); engine.put("PercentType", PercentType.class); engine.put("PointType", PointType.class); engine.put("StopMoveType", StopMoveType.class); engine.put("UpDownType", UpDownType.class); engine.put("StringType", StringType.class); } private String getFileExtension(File file) { String extension = null; if (file.getName().contains(".")) { String name = file.getName(); extension = name.substring(name.lastIndexOf('.') + 1, name.length()); } return extension; } public List<Rule> getRules() { return this.rules; } public void executeRule(Rule rule, Event event) { Thread t = new Thread(new RuleExecutionRunnable(rule, event)); t.start(); } public String getFileName() { return fileName; } }
epl-1.0
MasteringJava/Swing
MyTrafficLamp/src/MyTrafficLamp/view/ShowPanel.java
714
package MyTrafficLamp.view; import java.awt.Graphics; import javax.swing.JPanel; import MyTrafficLamp.entities.Ground; import MyTrafficLamp.entities.TrafficLamp; /** * ÏÔÊ¾Ãæ°åÀà<BR> * ¸ºÔðÏÔʾ³öµØÃæ¡¢ÐźŵÆ<BR> * * @author Asdf * @version 1.0 10/12/13 * */ public class ShowPanel extends JPanel { /** * */ private static final long serialVersionUID = 1L; private TrafficLamp[] trafficLamps; private Ground ground; public ShowPanel(TrafficLamp[] trafficLamps, Ground ground) { this.trafficLamps = trafficLamps; this.ground = ground; } @Override public void paint(Graphics g) { super.paint(g); ground.drawMe(g); for (TrafficLamp tl : trafficLamps) tl.drawMe(g); } }
epl-1.0
georgeerhan/openhab2-addons
addons/binding/org.openhab.binding.oceanic/src/main/java/org/openhab/binding/oceanic/OceanicBindingConstants.java
12997
/** * Copyright (c) 2010-2017 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.oceanic; import java.io.InvalidClassException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.eclipse.smarthome.core.library.types.DateTimeType; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.StringType; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.types.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link OceanicBinding} class defines common constants, which are used * across the whole binding. * * @author Karel Goderis - Initial contribution */ public class OceanicBindingConstants { public static final String BINDING_ID = "oceanic"; // List of all Thing Type UIDs public final static ThingTypeUID THING_TYPE_SOFTENER = new ThingTypeUID(BINDING_ID, "softener"); // List of all Channel ids public enum OceanicChannelSelector { getSRN("serial", StringType.class, ValueSelectorType.GET, true), getMAC("mac", StringType.class, ValueSelectorType.GET, true), getDNA("name", StringType.class, ValueSelectorType.GET, true), getSCR("type", StringType.class, ValueSelectorType.GET, true) { @Override public String convertValue(String value) { int index = Integer.valueOf(value); String convertedValue = value; switch (index) { case 0: convertedValue = "Single"; break; case 1: convertedValue = "Double Alternative"; break; case 2: convertedValue = "Triple Alternative"; break; case 3: convertedValue = "Double Parallel"; break; case 4: convertedValue = "Triple Parallel"; break; case 5: convertedValue = "Single Filter"; break; case 6: convertedValue = "Double Filter"; break; case 7: convertedValue = "Triple Filter"; break; default: break; } return convertedValue; } }, getALM("alarm", StringType.class, ValueSelectorType.GET, false) { @Override public String convertValue(String value) { int index = Integer.valueOf(value); String convertedValue = value; switch (index) { case 0: convertedValue = "No Alarm"; break; case 1: convertedValue = "Lack of salt during regeneration"; break; case 2: convertedValue = "Water pressure too low"; break; case 3: convertedValue = "Water pressure too high"; break; case 4: convertedValue = "Pressure sensor failure"; break; case 5: convertedValue = "Camshaft failure"; break; default: break; } return convertedValue; } }, getNOT("alert", StringType.class, ValueSelectorType.GET, false) { @Override public String convertValue(String value) { int index = Integer.valueOf(value); String convertedValue = value; switch (index) { case 0: convertedValue = "No Alert"; break; case 1: convertedValue = "Imminent lack of salt"; break; default: break; } return convertedValue; } }, getFLO("totalflow", DecimalType.class, ValueSelectorType.GET, false), getRES("reserve", DecimalType.class, ValueSelectorType.GET, false), getCYN("cycle", StringType.class, ValueSelectorType.GET, false), getCYT("endofcycle", StringType.class, ValueSelectorType.GET, false), getRTI("endofregeneration", StringType.class, ValueSelectorType.GET, false), getWHU("hardnessunit", StringType.class, ValueSelectorType.GET, false) { @Override public String convertValue(String value) { int index = Integer.valueOf(value); String convertedValue = value; switch (index) { case 0: convertedValue = "dH"; break; case 1: convertedValue = "fH"; break; case 2: convertedValue = "e"; break; case 3: convertedValue = "mg CaCO3/l"; break; case 4: convertedValue = "ppm"; break; case 5: convertedValue = "mmol/l"; break; case 6: convertedValue = "mval/l"; break; default: break; } return convertedValue; } }, getIWH("inlethardness", DecimalType.class, ValueSelectorType.GET, false), getOWH("outlethardness", DecimalType.class, ValueSelectorType.GET, false), getRG1("cylinderstate", StringType.class, ValueSelectorType.GET, false) { @Override public String convertValue(String value) { int index = Integer.valueOf(value); String convertedValue = value; switch (index) { case 0: convertedValue = "No regeneration"; break; case 1: convertedValue = "Paused"; break; case 2: convertedValue = "Regeneration"; break; default: break; } return convertedValue; } }, setSV1("salt", DecimalType.class, ValueSelectorType.SET, false), getSV1("salt", DecimalType.class, ValueSelectorType.GET, false), setSIR("regeneratenow", OnOffType.class, ValueSelectorType.SET, false), setSDR("regeneratelater", OnOffType.class, ValueSelectorType.SET, false), setSMR("multiregenerate", OnOffType.class, ValueSelectorType.SET, false), getMOF("consumptionmonday", DecimalType.class, ValueSelectorType.GET, false), getTUF("consumptiontuesday", DecimalType.class, ValueSelectorType.GET, false), getWEF("consumptionwednesday", DecimalType.class, ValueSelectorType.GET, false), getTHF("consumptionthursday", DecimalType.class, ValueSelectorType.GET, false), getFRF("consumptionfriday", DecimalType.class, ValueSelectorType.GET, false), getSAF("consumptionsaturday", DecimalType.class, ValueSelectorType.GET, false), getSUF("consumptionsunday", DecimalType.class, ValueSelectorType.GET, false), getTOF("consumptiontoday", DecimalType.class, ValueSelectorType.GET, false), getYEF("consumptionyesterday", DecimalType.class, ValueSelectorType.GET, false), getCWF("consumptioncurrentweek", DecimalType.class, ValueSelectorType.GET, false), getLWF("consumptionlastweek", DecimalType.class, ValueSelectorType.GET, false), getCMF("consumptioncurrentmonth", DecimalType.class, ValueSelectorType.GET, false), getLMF("consumptionlastmonth", DecimalType.class, ValueSelectorType.GET, false), getCOF("consumptioncomplete", DecimalType.class, ValueSelectorType.GET, false), getUWF("consumptionuntreated", DecimalType.class, ValueSelectorType.GET, false), getTFO("consumptionpeaklevel", DecimalType.class, ValueSelectorType.GET, false), getPRS("pressure", DecimalType.class, ValueSelectorType.GET, false), getMXP("maxpressure", DecimalType.class, ValueSelectorType.GET, false), getMNP("minpressure", DecimalType.class, ValueSelectorType.GET, false), getMXF("maxflow", DecimalType.class, ValueSelectorType.GET, false), getLAR("lastgeneration", DateTimeType.class, ValueSelectorType.GET, false) { @Override public String convertValue(String value) { final SimpleDateFormat IN_DATE_FORMATTER = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); final SimpleDateFormat OUT_DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); Date date = null; String convertedValue = null; try { date = IN_DATE_FORMATTER.parse(value); convertedValue = OUT_DATE_FORMATTER.format(date); } catch (ParseException fpe) { throw new IllegalArgumentException(value + " is not in a valid format.", fpe); } return convertedValue; } }, getNOR("normalregenerations", DecimalType.class, ValueSelectorType.GET, false), getSRE("serviceregenerations", DecimalType.class, ValueSelectorType.GET, false), getINR("incompleteregenerations", DecimalType.class, ValueSelectorType.GET, false), getTOR("allregenerations", DecimalType.class, ValueSelectorType.GET, false); static final Logger logger = LoggerFactory.getLogger(OceanicChannelSelector.class); private final String text; private Class<? extends Type> typeClass; private ValueSelectorType typeValue; private boolean isProperty; private OceanicChannelSelector(final String text, Class<? extends Type> typeClass, ValueSelectorType typeValue, boolean isProperty) { this.text = text; this.typeClass = typeClass; this.typeValue = typeValue; this.isProperty = isProperty; } @Override public String toString() { return text; } public Class<? extends Type> getTypeClass() { return typeClass; } public ValueSelectorType getTypeValue() { return typeValue; } public boolean isProperty() { return isProperty; } /** * Procedure to convert selector string to value selector class. * * @param valueSelectorText * selector string e.g. RawData, Command, Temperature * @return corresponding selector value. * @throws InvalidClassException * Not valid class for value selector. */ public static OceanicChannelSelector getValueSelector(String valueSelectorText, ValueSelectorType valueSelectorType) throws IllegalArgumentException { for (OceanicChannelSelector c : OceanicChannelSelector.values()) { if (c.text.equals(valueSelectorText) && c.typeValue == valueSelectorType) { return c; } } throw new IllegalArgumentException("Not valid value selector"); } public static ValueSelectorType getValueSelectorType(String valueSelectorText) throws IllegalArgumentException { for (OceanicChannelSelector c : OceanicChannelSelector.values()) { if (c.text.equals(valueSelectorText)) { return c.typeValue; } } throw new IllegalArgumentException("Not valid value selector"); } public String convertValue(String value) { return value; } public enum ValueSelectorType { GET, SET } } }
epl-1.0
bradsdavis/windup
rules-java/src/test/java/org/jboss/windup/rules/apps/java/service/TypeReferenceServiceTest.java
4560
package org.jboss.windup.rules.apps.java.service; import java.util.Map; import javax.inject.Inject; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.forge.arquillian.AddonDependency; import org.jboss.forge.arquillian.Dependencies; import org.jboss.forge.arquillian.archive.ForgeArchive; import org.jboss.forge.furnace.repositories.AddonDependencyEntry; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.windup.graph.GraphContext; import org.jboss.windup.graph.GraphContextFactory; import org.jboss.windup.graph.model.ProjectModel; import org.jboss.windup.graph.model.resource.FileModel; import org.jboss.windup.reporting.model.InlineHintModel; import org.jboss.windup.reporting.service.InlineHintService; import org.jboss.windup.rules.apps.java.scan.ast.JavaTypeReferenceModel; import org.jboss.windup.rules.apps.java.scan.ast.TypeReferenceLocation; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(Arquillian.class) public class TypeReferenceServiceTest { @Deployment @Dependencies({ @AddonDependency(name = "org.jboss.windup.config:windup-config"), @AddonDependency(name = "org.jboss.windup.graph:windup-graph"), @AddonDependency(name = "org.jboss.windup.reporting:windup-reporting"), @AddonDependency(name = "org.jboss.windup.rules.apps:rules-base"), @AddonDependency(name = "org.jboss.windup.rules.apps:rules-java"), @AddonDependency(name = "org.jboss.forge.furnace.container:cdi") }) public static ForgeArchive getDeployment() { ForgeArchive archive = ShrinkWrap.create(ForgeArchive.class) .addBeansXML() .addAsAddonDependencies( AddonDependencyEntry.create("org.jboss.windup.config:windup-config"), AddonDependencyEntry.create("org.jboss.windup.graph:windup-graph"), AddonDependencyEntry.create("org.jboss.windup.reporting:windup-reporting"), AddonDependencyEntry.create("org.jboss.windup.rules.apps:rules-base"), AddonDependencyEntry.create("org.jboss.windup.rules.apps:rules-java"), AddonDependencyEntry.create("org.jboss.forge.furnace.container:cdi") ); return archive; } @Inject private GraphContextFactory factory; @Test public void testGetPackageUseFrequencies() throws Exception { try (GraphContext context = factory.create()) { Assert.assertNotNull(context); TypeReferenceService typeReferenceService = new TypeReferenceService(context); ProjectModel projectModel = fillData(context); Map<String, Integer> data = typeReferenceService.getPackageUseFrequencies(projectModel, 2, false); Assert.assertEquals(1, data.size()); Assert.assertEquals("com.example.*", data.keySet().iterator().next()); Assert.assertEquals(Integer.valueOf(2), data.values().iterator().next()); } } private ProjectModel fillData(GraphContext context) { InlineHintService inlineHintService = new InlineHintService(context); TypeReferenceService typeReferenceService = new TypeReferenceService(context); FileModel f1 = context.getFramed().addVertex(null, FileModel.class); f1.setFilePath("/f1"); FileModel f2 = context.getFramed().addVertex(null, FileModel.class); f2.setFilePath("/f2"); JavaTypeReferenceModel t1 = typeReferenceService.createTypeReference(f1, TypeReferenceLocation.ANNOTATION, 0, 2, 2, "com.example.Class1"); JavaTypeReferenceModel t2 = typeReferenceService.createTypeReference(f1, TypeReferenceLocation.ANNOTATION, 0, 2, 2, "com.example.Class1"); InlineHintModel b1 = inlineHintService.create(); InlineHintModel b1b = inlineHintService.create(); b1.setFile(f1); b1.setFileLocationReference(t1); b1b.setFile(f1); b1b.setFileLocationReference(t2); ProjectModel projectModel = context.getFramed().addVertex(null, ProjectModel.class); projectModel.addFileModel(f1); f1.setProjectModel(projectModel); projectModel.addFileModel(f2); f2.setProjectModel(projectModel); return projectModel; } }
epl-1.0
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/discovery/EcobeeDiscoveryService.java
7591
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.ecobee.internal.discovery; import static org.openhab.binding.ecobee.internal.EcobeeBindingConstants.*; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.ecobee.internal.dto.thermostat.RemoteSensorDTO; import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO; import org.openhab.binding.ecobee.internal.handler.EcobeeAccountBridgeHandler; import org.openhab.binding.ecobee.internal.handler.EcobeeThermostatBridgeHandler; import org.openhab.core.config.discovery.AbstractDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link EcobeeDiscoveryService} is responsible for discovering the Ecobee * thermostats that are associated with the Ecobee Account, as well as the sensors * are associated with the Ecobee thermostats. * * @author Mark Hilbush - Initial contribution */ @NonNullByDefault public class EcobeeDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { private final Logger logger = LoggerFactory.getLogger(EcobeeDiscoveryService.class); private @NonNullByDefault({}) EcobeeAccountBridgeHandler bridgeHandler; private @Nullable Future<?> discoveryJob; public EcobeeDiscoveryService() { super(SUPPORTED_THERMOSTAT_AND_SENSOR_THING_TYPES_UIDS, 8, true); } @Override public void setThingHandler(@Nullable ThingHandler handler) { if (handler instanceof EcobeeAccountBridgeHandler) { this.bridgeHandler = (EcobeeAccountBridgeHandler) handler; } } @Override public @Nullable ThingHandler getThingHandler() { return bridgeHandler; } @Override public void activate() { super.activate(null); } @Override public void deactivate() { super.deactivate(); } @Override public Set<ThingTypeUID> getSupportedThingTypes() { return SUPPORTED_THERMOSTAT_AND_SENSOR_THING_TYPES_UIDS; } @Override protected void startBackgroundDiscovery() { logger.debug("EcobeeDiscovery: Starting background discovery job"); Future<?> localDiscoveryJob = discoveryJob; if (localDiscoveryJob == null || localDiscoveryJob.isCancelled()) { discoveryJob = scheduler.scheduleWithFixedDelay(this::backgroundDiscover, DISCOVERY_INITIAL_DELAY_SECONDS, DISCOVERY_INTERVAL_SECONDS, TimeUnit.SECONDS); } } @Override protected void stopBackgroundDiscovery() { logger.debug("EcobeeDiscovery: Stopping background discovery job"); Future<?> localDiscoveryJob = discoveryJob; if (localDiscoveryJob != null) { localDiscoveryJob.cancel(true); discoveryJob = null; } } @Override public void startScan() { logger.debug("EcobeeDiscovery: Starting discovery scan"); discover(); } private void backgroundDiscover() { if (!bridgeHandler.isBackgroundDiscoveryEnabled()) { return; } discover(); } private void discover() { if (bridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) { logger.debug("EcobeeDiscovery: Skipping discovery because Account Bridge thing is not ONLINE"); return; } logger.debug("EcobeeDiscovery: Discovering Ecobee devices"); discoverThermostats(); discoverSensors(); } private synchronized void discoverThermostats() { logger.debug("EcobeeDiscovery: Discovering thermostats"); for (ThermostatDTO thermostat : bridgeHandler.getRegisteredThermostats()) { String name = thermostat.name; String identifier = thermostat.identifier; if (identifier != null && name != null) { ThingUID thingUID = new ThingUID(UID_THERMOSTAT_BRIDGE, bridgeHandler.getThing().getUID(), identifier); thingDiscovered(createThermostatDiscoveryResult(thingUID, identifier, name)); logger.debug("EcobeeDiscovery: Thermostat '{}' and name '{}' added with UID '{}'", identifier, name, thingUID); } } } private DiscoveryResult createThermostatDiscoveryResult(ThingUID thermostatUID, String identifier, String name) { Map<String, Object> properties = new HashMap<>(); properties.put(CONFIG_THERMOSTAT_ID, identifier); return DiscoveryResultBuilder.create(thermostatUID).withProperties(properties) .withRepresentationProperty(CONFIG_THERMOSTAT_ID).withBridge(bridgeHandler.getThing().getUID()) .withLabel(String.format("Ecobee Thermostat %s", name)).build(); } private synchronized void discoverSensors() { List<Thing> thermostatThings = bridgeHandler.getThing().getThings(); if (thermostatThings.size() == 0) { logger.debug("EcobeeDiscovery: Skipping sensor discovery because there are no thermostat things"); return; } logger.debug("EcobeeDiscovery: Discovering sensors"); for (Thing thermostat : thermostatThings) { EcobeeThermostatBridgeHandler thermostatHandler = (EcobeeThermostatBridgeHandler) thermostat.getHandler(); if (thermostatHandler != null) { String thermostatId = thermostatHandler.getThermostatId(); logger.debug("EcobeeDiscovery: Discovering sensors for thermostat '{}'", thermostatId); for (RemoteSensorDTO sensor : thermostatHandler.getSensors()) { ThingUID bridgeUID = thermostatHandler.getThing().getUID(); ThingUID sensorUID = new ThingUID(UID_SENSOR_THING, bridgeUID, sensor.id.replace(":", "-")); thingDiscovered(createSensorDiscoveryResult(sensorUID, bridgeUID, sensor)); logger.debug("EcobeeDiscovery: Sensor for '{}' with id '{}' and name '{}' added with UID '{}'", thermostatId, sensor.id, sensor.name, sensorUID); } } } } private DiscoveryResult createSensorDiscoveryResult(ThingUID sensorUID, ThingUID bridgeUID, RemoteSensorDTO sensor) { Map<String, Object> properties = new HashMap<>(); properties.put(CONFIG_SENSOR_ID, sensor.id); return DiscoveryResultBuilder.create(sensorUID).withProperties(properties) .withRepresentationProperty(CONFIG_SENSOR_ID).withBridge(bridgeUID) .withLabel(String.format("Ecobee Sensor %s", sensor.name)).build(); } }
epl-1.0
jesusc/anatlyzer
experiments/anatlyzer.experiments/src/anatlyzer/experiments/configuration/ExperimentConfigurationReader.java
808
package anatlyzer.experiments.configuration; import java.io.StringReader; import com.esotericsoftware.yamlbeans.YamlException; import com.esotericsoftware.yamlbeans.YamlReader; /** * Reads a configuration file for an experiment, with the following format: * * <pre> * projects: * my.project1.atl * another.projectname * * </pre> * * @author jesus * */ public class ExperimentConfigurationReader { public ExperimentConfigurationReader() { } public static ExperimentConfiguration parseFromText(String text) { YamlReader reader = new YamlReader(new StringReader(text)); ExperimentConfigurationSerializer.configure(reader.getConfig()); try { return reader.read(ExperimentConfiguration.class); } catch (YamlException e) { throw new RuntimeException(e); } } }
epl-1.0
alexVengrovsk/che
plugins/plugin-maven/che-plugin-maven-server/src/main/java/org/eclipse/che/plugin/maven/server/MavenServerManager.java
8873
/******************************************************************************* * 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.plugin.maven.server; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.eclipse.che.plugin.maven.server.execution.CommandLine; import org.eclipse.che.plugin.maven.server.execution.JavaParameters; import org.eclipse.che.plugin.maven.server.execution.ProcessExecutor; import org.eclipse.che.plugin.maven.server.execution.ProcessHandler; import org.eclipse.che.plugin.maven.server.rmi.RmiClient; import org.eclipse.che.plugin.maven.server.rmi.RmiObjectWrapper; import org.eclipse.che.maven.data.MavenModel; import org.eclipse.che.maven.server.MavenRemoteServer; import org.eclipse.che.maven.server.MavenServer; import org.eclipse.che.maven.server.MavenServerDownloadListener; import org.eclipse.che.maven.server.MavenServerLogger; import org.eclipse.che.maven.server.MavenSettings; import org.eclipse.che.maven.server.MavenTerminal; import org.eclipse.che.rmi.RmiObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import java.io.File; import java.rmi.NoSuchObjectException; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; /** * @author Evgen Vidolob */ @Singleton public class MavenServerManager extends RmiObjectWrapper<MavenRemoteServer> { private static final Logger LOG = LoggerFactory.getLogger(MavenServerManager.class); private static final String MAVEN_SERVER_MAIN = "org.eclipse.che.maven.server.MavenServerMain"; private RmiClient<MavenRemoteServer> client; private RmiLogger rmiLogger = new RmiLogger(); private RmiMavenServerDownloadListener rmiDownloadListener = new RmiMavenServerDownloadListener(); private boolean loggerExported; private boolean listenerExported; private String mavenServerPath; private File localRepository; @Inject public MavenServerManager(@Named("che.maven.server.path") String mavenServerPath) { this.mavenServerPath = mavenServerPath; client = new RmiClient<MavenRemoteServer>(MavenRemoteServer.class) { @Override protected ProcessExecutor getExecutor() { return createExecutor(); } }; } private static void addDirToClasspath(List<String> classPath, File dir) { File[] jars = dir.listFiles((dir1, name) -> { return name.endsWith(".jar"); }); if (jars == null) { return; } for (File jar : jars) { classPath.add(jar.getAbsolutePath()); } } private ProcessExecutor createExecutor() { return () -> { JavaParameters parameters = buildMavenServerParameters(); CommandLine command = parameters.createCommand(); return new ProcessHandler(command.createProcess()); }; } public MavenServerWrapper createMavenServer() { return new MavenServerWrapper() { @Override protected MavenServer create() throws RemoteException { MavenSettings mavenSettings = new MavenSettings(); //TODO add more user settings mavenSettings.setMavenHome(new File(System.getenv("M2_HOME"))); mavenSettings.setGlobalSettings(new File(System.getProperty("user.home"), ".m2/settings.xml")); mavenSettings.setLoggingLevel(MavenTerminal.LEVEL_INFO); if (localRepository != null) { mavenSettings.setLocalRepository(localRepository); } return MavenServerManager.this.getOrCreateWrappedObject().createServer(mavenSettings); } }; } /** * For test use only. Sets the path to local maven repository * * @param localRepository */ public void setLocalRepository(File localRepository) { this.localRepository = localRepository; } public MavenModel interpolateModel(MavenModel model, File projectDir) { return perform(() -> getOrCreateWrappedObject().interpolateModel(model, projectDir)); } @PreDestroy public void shutdown() { client.stopAll(false); cleanUp(); } @Override protected MavenRemoteServer create() throws RemoteException { MavenRemoteServer server; try { server = client.acquire(this, ""); } catch (Exception e) { throw new RemoteException("Can't start maven server", e); } if(!loggerExported) { Remote loggerRemote = UnicastRemoteObject.exportObject(rmiLogger, 0); if (!(loggerExported = loggerRemote != null)) { throw new RemoteException("Can't export logger"); } } if(!listenerExported) { Remote listenerRemote = UnicastRemoteObject.exportObject(rmiDownloadListener, 0); if (!(listenerExported = listenerRemote != null)) { throw new RemoteException("Can't export download listener"); } } server.configure(rmiLogger, rmiDownloadListener); return server; } @Override protected synchronized void cleanUp() { super.cleanUp(); if (loggerExported) { try { UnicastRemoteObject.unexportObject(rmiLogger, true); } catch (NoSuchObjectException e) { LOG.error("Can't unexport RMI logger", e); } loggerExported = false; } if (listenerExported) { try { UnicastRemoteObject.unexportObject(rmiDownloadListener, true); } catch (NoSuchObjectException e) { LOG.error("Can't unexport RMI artifact download listener", e); } listenerExported = false; } } public JavaParameters buildMavenServerParameters() { JavaParameters parameters = new JavaParameters(); parameters.setJavaExecutable("java"); parameters.setWorkingDirectory(System.getProperty("java.io.tmpdir")); parameters.setMainClassName(MAVEN_SERVER_MAIN); //TODO read and set MAVEN_OPTS system properties List<String> classPath = new ArrayList<>(); addDirToClasspath(classPath, new File(mavenServerPath)); String mavenHome = System.getenv("M2_HOME"); addDirToClasspath(classPath, new File(mavenHome, "lib")); File bootDir = new File(mavenHome, "boot"); File[] classworlds = bootDir.listFiles((dir, name) -> { return name.contains("classworlds"); }); if (classworlds != null) { for (File file : classworlds) { classPath.add(file.getAbsolutePath()); } } parameters.getClassPath().addAll(classPath); parameters.getVmParameters().add("-Xmx512m"); return parameters; } private <T> T perform(RunnableRemoteWithResult<T> runnable) { RemoteException exception = null; for (int i = 0; i < 2; i++) { try { return runnable.perform(); } catch (RemoteException e) { exception = e; onError(); } } throw new RuntimeException(exception); } private interface RunnableRemoteWithResult<T> { T perform() throws RemoteException; } private class RmiLogger extends RmiObject implements MavenServerLogger { @Override public void info(Throwable t) throws RemoteException { LOG.info(t.getMessage(), t); } @Override public void warning(Throwable t) throws RemoteException { LOG.warn(t.getMessage(), t); } @Override public void error(Throwable t) throws RemoteException { LOG.error(t.getMessage(), t); } } private class RmiMavenServerDownloadListener extends RmiObject implements MavenServerDownloadListener { @Override public void artifactDownloaded(File file, String relativePath) throws RemoteException { System.out.println("On download - " + relativePath); //todo notify browser about that } } }
epl-1.0
debabratahazra/DS
designstudio/components/workbench/ui/com.odcgroup.translation.ui/src/main/java/com/odcgroup/translation/ui/internal/views/richtext/RichTextToolbar.java
5414
package com.odcgroup.translation.ui.internal.views.richtext; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import com.odcgroup.translation.ui.TranslationUICore; class RichTextToolbar { private ToolBar toolBar; private Map<ActionHandler, ComboViewer> comboViewers = new HashMap<ActionHandler, ComboViewer>(); private void createButton(final ButtonAction action) { final ToolItem item = new ToolItem(toolBar, action.getStyle()); item.setImage(createImage(action.getImageName())); item.setToolTipText(action.getTooltip()); item.setData(action.getHandler()); item.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { if (action.getHandler() != null) { boolean selected = ((ToolItem)e.widget).getSelection(); action.getHandler().updateStyle(selected); } updateToolbar(); } }); item.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { item.getImage().dispose(); } }); } private void createDropDownCombo(final DropDownAction action) { ToolItem sep = new ToolItem(toolBar, SWT.SEPARATOR); sep.setData(action.getHandler()); Composite composite = new Composite(toolBar, SWT.NONE); GridLayout layout = new GridLayout(1, false); layout.marginWidth = layout.marginHeight = 1; composite.setLayout(layout); Combo combo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER); combo.setToolTipText(action.getToolTip()); ComboViewer mComboViewer = new ComboViewer(combo); mComboViewer .addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { String selection = (String) ((IStructuredSelection) event .getSelection()).getFirstElement(); action.getHandler().updateStyle(selection); } }); mComboViewer.setContentProvider(ArrayContentProvider.getInstance()); mComboViewer.setInput(action.getValues()); mComboViewer.setSelection(new StructuredSelection(action.getSelection())); comboViewers.put(action.getHandler(), mComboViewer); combo.setEnabled(true); sep.setWidth(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x); // control.getSize().x); sep.setControl(composite); } private Image createImage(String name) { return TranslationUICore.getImageDescriptor("icons/" + name + ".png") .createImage(); } private void createSeparator() { new ToolItem(toolBar, SWT.SEPARATOR); } private void createToolItems(RichTextAction... actions) { for (RichTextAction action : actions) { int style = action.getStyle(); if ((style & SWT.PUSH) != 0) { createButton((ButtonAction)action); } else if ((style & SWT.CHECK) != 0) { createButton((ButtonAction)action); } else if ((style & SWT.DROP_DOWN) != 0) { createDropDownCombo((DropDownAction)action); } else if ((style & SWT.SEPARATOR) != 0) { createSeparator(); } } } private void disposeAll() { // TODO do we need to dispose something ????? } public void setActions(RichTextAction[] actions) { createToolItems(actions); } public void setEnabled(boolean enabled) { toolBar.setEnabled(enabled); } public boolean isEnabled() { return toolBar.isEnabled(); } public void updateToolbar() { for (ToolItem item : toolBar.getItems()) { Object data = item.getData(); if (data != null) { if (data instanceof FontHandler) { // combo box FontHandler handler = ((FontHandler)data); ComboViewer cv = comboViewers.get(handler); if (cv != null) { String selection = handler.getSelection(); IStructuredSelection ss = ((IStructuredSelection)cv.getSelection()); String currentSelection = (String)ss.getFirstElement(); //System.out.println("size current:"+currentSelection+" new:"+selection); if (!currentSelection.equals(selection)) { cv.setSelection(new StructuredSelection(selection)); } } } else if (data instanceof ActionHandler) { // button item.setSelection(((ActionHandler) data).isStyleSelected(item .getSelection())); } } } } public RichTextToolbar(Composite parent, RichTextAction... actions) { toolBar = new ToolBar(parent, SWT.FLAT | SWT.WRAP ); GridData spec = new GridData(); spec.horizontalAlignment = GridData.FILL; spec.grabExcessHorizontalSpace = true; spec.grabExcessVerticalSpace = false; toolBar.setLayoutData(spec); toolBar.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { disposeAll(); } }); } }
epl-1.0
koentsje/forge-furnace
proxy/src/main/java/org/jboss/forge/furnace/proxy/ClassLoaderAdapterCallback.java
31773
/* * Copyright 2012 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.furnace.proxy; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.forge.furnace.exception.ContainerException; import org.jboss.forge.furnace.proxy.javassist.util.proxy.MethodFilter; import org.jboss.forge.furnace.proxy.javassist.util.proxy.MethodHandler; import org.jboss.forge.furnace.proxy.javassist.util.proxy.Proxy; import org.jboss.forge.furnace.proxy.javassist.util.proxy.ProxyFactory; import org.jboss.forge.furnace.proxy.javassist.util.proxy.ProxyObject; import org.jboss.forge.furnace.util.Assert; import org.jboss.forge.furnace.util.ClassLoaders; /** * @author <a href="mailto:lincolnbaxter@gmail.com">Lincoln Baxter, III</a> */ public class ClassLoaderAdapterCallback implements MethodHandler, ForgeProxy { private static final Logger log = Logger.getLogger(ClassLoaderAdapterCallback.class.getName()); private static final ClassLoader JAVASSIST_LOADER = ProxyObject.class.getClassLoader(); private final Object delegate; private final ClassLoader initialCallingLoader; private final ClassLoader delegateLoader; private final Callable<Set<ClassLoader>> whitelist; private ClassLoader getCallingLoader() { ClassLoader callingLoader = ClassLoaderInterceptor.getCurrentloader(); if (callingLoader == null) callingLoader = initialCallingLoader; return callingLoader; } public ClassLoaderAdapterCallback(Callable<Set<ClassLoader>> whitelist, ClassLoader callingLoader, ClassLoader delegateLoader, Object delegate) { Assert.notNull(whitelist, "ClassLoader whitelist must not be null"); Assert.notNull(callingLoader, "Calling loader must not be null."); Assert.notNull(delegateLoader, "Delegate loader must not be null."); Assert.notNull(delegate, "Delegate must not be null."); this.whitelist = whitelist; this.initialCallingLoader = callingLoader; this.delegateLoader = delegateLoader; this.delegate = delegate; } @Override public Object invoke(final Object obj, final Method thisMethod, final Method proceed, final Object[] args) throws Throwable { return ClassLoaders.executeIn(delegateLoader, new Callable<Object>() { @Override public Object call() throws Exception { try { if (thisMethod.getDeclaringClass().equals(getCallingLoader().loadClass(ForgeProxy.class.getName()))) { if (thisMethod.getName().equals("getDelegate")) return ClassLoaderAdapterCallback.this.getDelegate(); if (thisMethod.getName().equals("getHandler")) return ClassLoaderAdapterCallback.this.getHandler(); } } catch (Exception e) { } Method delegateMethod = getDelegateMethod(thisMethod); List<Object> parameterValues = enhanceParameterValues(args, delegateMethod); AccessibleObject.setAccessible(new AccessibleObject[] { delegateMethod }, true); try { Object[] parameterValueArray = parameterValues.toArray(); Object result = delegateMethod.invoke(delegate, parameterValueArray); return enhanceResult(thisMethod, result); } catch (InvocationTargetException e) { if (e.getCause() instanceof Exception) throw enhanceException(delegateMethod, (Exception) e.getCause()); throw enhanceException(delegateMethod, e); } } private Method getDelegateMethod(final Method proxy) throws ClassNotFoundException, NoSuchMethodException { Method delegateMethod = null; try { List<Class<?>> parameterTypes = translateParameterTypes(proxy); delegateMethod = delegate.getClass().getMethod(proxy.getName(), parameterTypes.toArray(new Class<?>[parameterTypes.size()])); } catch (ClassNotFoundException e) { method: for (Method m : delegate.getClass().getMethods()) { String methodName = proxy.getName(); String delegateMethodName = m.getName(); if (methodName.equals(delegateMethodName)) { Class<?>[] methodParameterTypes = proxy.getParameterTypes(); Class<?>[] delegateParameterTypes = m.getParameterTypes(); if (methodParameterTypes.length == delegateParameterTypes.length) { for (int i = 0; i < methodParameterTypes.length; i++) { Class<?> methodType = methodParameterTypes[i]; Class<?> delegateType = delegateParameterTypes[i]; if (!methodType.getName().equals(delegateType.getName())) { continue method; } } delegateMethod = m; break; } } } if (delegateMethod == null) throw e; } return delegateMethod; } }); } private Object enhanceResult(final Method method, Object result) throws Exception { if (result != null) { Class<?> unwrappedResultType = Proxies.unwrap(result).getClass(); ClassLoader callingLoader = getCallingLoader(); if (getCallingLoader().equals(delegateLoader)) callingLoader = getInitialCallingLoader(); ClassLoader resultInstanceLoader = delegateLoader; if (!ClassLoaders.containsClass(delegateLoader, unwrappedResultType)) { resultInstanceLoader = Proxies.unwrapProxyTypes(unwrappedResultType, getCallingLoader(), delegateLoader, unwrappedResultType.getClassLoader()).getClassLoader(); // FORGE-928: java.util.ArrayList.class.getClassLoader() returns null if (resultInstanceLoader == null) { resultInstanceLoader = getClass().getClassLoader(); } } Class<?> returnType = method.getReturnType(); if (Class.class.equals(returnType)) { Class<?> resultClassValue = (Class<?>) result; try { result = callingLoader.loadClass(Proxies.unwrapProxyClassName(resultClassValue)); } catch (ClassNotFoundException e) { try { // If all else fails, try the whitelist loaders. result = loadClassFromWhitelist(Proxies.unwrapProxyClassName(resultClassValue)); } catch (ClassNotFoundException e3) { // Oh well. } if (result == null) { /* * No way, here is the original class and god bless you :) Also unwrap any proxy types since we don't * know about this object, there is no reason to pass a proxied class type. */ result = Proxies.unwrapProxyTypes(resultClassValue); } } return result; } else if (returnTypeNeedsEnhancement(returnType, result, unwrappedResultType)) { result = stripClassLoaderAdapters(result); Class<?>[] resultHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(result.getClass(), callingLoader, delegateLoader, resultInstanceLoader)); Class<?>[] returnTypeHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(returnType, callingLoader, delegateLoader, resultInstanceLoader)); if (!Modifier.isFinal(returnType.getModifiers())) { if (Object.class.equals(returnType) && !Object.class.equals(result)) { result = enhance(whitelist, callingLoader, resultInstanceLoader, method, result, resultHierarchy); } else { if (returnTypeHierarchy.length == 0) { returnTypeHierarchy = new Class[] { returnType }; } Object delegateObject = result; if (result instanceof ForgeProxy) { if ((((ForgeProxy) result).getHandler() instanceof ClassLoaderAdapterCallback)) { ClassLoaderAdapterCallback handler = (ClassLoaderAdapterCallback) ((ForgeProxy) result) .getHandler(); if (handler.getCallingLoader().equals(getCallingLoader()) && handler.getDelegateLoader().equals(getDelegateLoader())) { delegateObject = stripClassLoaderAdapters(result); } } } result = enhance(whitelist, callingLoader, resultInstanceLoader, method, delegateObject, mergeHierarchies(returnTypeHierarchy, resultHierarchy)); } } else { if (result.getClass().isEnum()) result = enhanceEnum(callingLoader, result); else result = enhance(whitelist, callingLoader, resultInstanceLoader, method, returnTypeHierarchy); } } } return result; } private Object stripClassLoaderAdapters(Object value) { while (Proxies.isForgeProxy(value)) { Object handler = Proxies.getForgeProxyHandler(value); if (handler.getClass().getName().equals(ClassLoaderAdapterCallback.class.getName())) value = Proxies.unwrapOnce(value); else break; } return value; } private Exception enhanceException(final Method method, final Exception exception) { Exception result = exception; try { if (exception != null) { Class<?> unwrappedExceptionType = Proxies.unwrap(exception).getClass(); ClassLoader exceptionLoader = delegateLoader; if (!ClassLoaders.containsClass(delegateLoader, unwrappedExceptionType)) { exceptionLoader = Proxies.unwrapProxyTypes(unwrappedExceptionType, getCallingLoader(), delegateLoader, unwrappedExceptionType.getClassLoader()).getClassLoader(); if (exceptionLoader == null) { exceptionLoader = getClass().getClassLoader(); } } if (exceptionNeedsEnhancement(exception)) { Class<?>[] exceptionHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(getCallingLoader(), Proxies.unwrapProxyTypes(exception.getClass(), getCallingLoader(), delegateLoader, exceptionLoader)); if (!Modifier.isFinal(unwrappedExceptionType.getModifiers())) { result = enhance(whitelist, getCallingLoader(), exceptionLoader, method, exception, exceptionHierarchy); result.initCause(exception); result.setStackTrace(exception.getStackTrace()); } } } } catch (Exception e) { log.log(Level.WARNING, "Could not enhance exception for passing through ClassLoader boundary. Exception type [" + exception.getClass().getName() + "], Caller [" + getCallingLoader() + "], Delegate [" + delegateLoader + "]"); return exception; } return result; } @SuppressWarnings({ "unchecked", "rawtypes" }) private Object enhanceEnum(ClassLoader loader, Object instance) { try { Class<Enum> callingType = (Class<Enum>) loader.loadClass(instance.getClass().getName()); return Enum.valueOf(callingType, ((Enum) instance).name()); } catch (ClassNotFoundException e) { throw new ContainerException( "Could not enhance instance [" + instance + "] of type [" + instance.getClass() + "]", e); } } @SuppressWarnings("unchecked") private Class<?>[] mergeHierarchies(Class<?>[] left, Class<?>[] right) { for (Class<?> type : right) { boolean found = false; for (Class<?> existing : left) { if (type.equals(existing)) { found = true; break; } } if (!found) { if (type.isInterface()) left = Arrays.append(left, type); else if (left.length == 0 || left[0].isInterface()) left = Arrays.prepend(left, type); } } return left; } @SuppressWarnings("unchecked") private boolean exceptionNeedsEnhancement(Exception exception) { Class<? extends Exception> exceptionType = exception.getClass(); Class<? extends Exception> unwrappedExceptionType = (Class<? extends Exception>) Proxies.unwrap(exception).getClass(); if (Proxies.isPassthroughType(unwrappedExceptionType)) { return false; } if (unwrappedExceptionType.getClassLoader() != null && !exceptionType.getClassLoader().equals(getCallingLoader())) { if (ClassLoaders.containsClass(getCallingLoader(), exceptionType)) { return false; } } return true; } private boolean returnTypeNeedsEnhancement(Class<?> methodReturnType, Object returnValue, Class<?> unwrappedReturnValueType) { if (Proxies.isPassthroughType(unwrappedReturnValueType)) { return false; } else if (!Object.class.equals(methodReturnType) && Proxies.isPassthroughType(methodReturnType)) { return false; } if (unwrappedReturnValueType.getClassLoader() != null && !unwrappedReturnValueType.getClassLoader().equals(getCallingLoader())) { if (ClassLoaders.containsClass(getCallingLoader(), unwrappedReturnValueType) && ClassLoaders.containsClass(getCallingLoader(), methodReturnType)) { return false; } } return true; } private static boolean whitelistContainsAll(Callable<Set<ClassLoader>> whitelist, ClassLoader... classLoaders) { try { Set<ClassLoader> set = whitelist.call(); for (ClassLoader classLoader : classLoaders) { if (!set.contains(classLoader)) return false; } return true; } catch (Exception e) { throw new RuntimeException("Could not retrieve ClassLoader whitelist from callback [" + whitelist + "].", e); } } private Class<?> loadClassFromWhitelist(String typeName) throws ClassNotFoundException { Class<?> result; Set<ClassLoader> loaders; try { loaders = whitelist.call(); } catch (Exception e) { throw new RuntimeException("Could not retrieve ClassLoader whitelist from callback [" + whitelist + "].", e); } for (ClassLoader loader : loaders) { try { result = loader.loadClass(typeName); return result; } catch (Exception e) { // next! } } throw new ClassNotFoundException(typeName); } private List<Object> enhanceParameterValues(final Object[] args, Method delegateMethod) throws Exception { List<Object> parameterValues = new ArrayList<>(); for (int i = 0; i < delegateMethod.getParameterTypes().length; i++) { final Class<?> delegateParameterType = delegateMethod.getParameterTypes()[i]; final Object parameterValue = args[i]; parameterValues.add(enhanceSingleParameterValue(delegateMethod, delegateParameterType, stripClassLoaderAdapters(parameterValue))); } return parameterValues; } private Object enhanceSingleParameterValue(final Method delegateMethod, final Class<?> delegateParameterType, final Object parameterValue) throws Exception { if (parameterValue != null) { if (parameterValue instanceof Class<?>) { Class<?> paramClassValue = (Class<?>) parameterValue; Class<?> loadedClass = null; try { loadedClass = delegateLoader.loadClass(Proxies.unwrapProxyClassName(paramClassValue)); } catch (ClassNotFoundException e) { try { // If all else fails, try the whitelist loaders. loadedClass = loadClassFromWhitelist(Proxies.unwrapProxyClassName(paramClassValue)); } catch (ClassNotFoundException e3) { // Oh well. } if (loadedClass == null) { /* * No way, here is the original class and god bless you :) Also unwrap any proxy types since we don't * know about this object, there is no reason to pass a proxied class type. */ loadedClass = Proxies.unwrapProxyTypes(paramClassValue); } } return loadedClass; } else { Object unwrappedValue = stripClassLoaderAdapters(parameterValue); if (delegateParameterType.isAssignableFrom(unwrappedValue.getClass()) && !Proxies.isLanguageType(unwrappedValue.getClass()) && (!isEquals(delegateMethod) || (isEquals(delegateMethod) && ClassLoaders.containsClass( delegateLoader, unwrappedValue.getClass())))) { // https://issues.jboss.org/browse/FORGE-939 return unwrappedValue; } else { Class<?> unwrappedValueType = Proxies.unwrapProxyTypes(unwrappedValue.getClass(), delegateMethod .getDeclaringClass().getClassLoader(), getCallingLoader(), delegateLoader, unwrappedValue.getClass() .getClassLoader()); ClassLoader valueDelegateLoader = delegateLoader; ClassLoader methodLoader = delegateMethod.getDeclaringClass().getClassLoader(); if (methodLoader != null && ClassLoaders.containsClass(methodLoader, unwrappedValueType)) { valueDelegateLoader = methodLoader; } ClassLoader valueCallingLoader = getCallingLoader(); if (!ClassLoaders.containsClass(getCallingLoader(), unwrappedValueType)) { valueCallingLoader = unwrappedValueType.getClassLoader(); } // If it is a class, use the delegateLoader loaded version if (delegateParameterType.isPrimitive()) { return parameterValue; } else if (delegateParameterType.isEnum()) { return enhanceEnum(methodLoader, parameterValue); } else if (delegateParameterType.isArray()) { Object[] array = (Object[]) unwrappedValue; Object[] delegateArray = (Object[]) Array.newInstance(delegateParameterType.getComponentType(), array.length); for (int j = 0; j < array.length; j++) { delegateArray[j] = enhanceSingleParameterValue(delegateMethod, delegateParameterType.getComponentType(), stripClassLoaderAdapters(array[j])); } return delegateArray; } else { final Class<?> parameterType = parameterValue.getClass(); if ((!Proxies.isPassthroughType(delegateParameterType) && Proxies.isLanguageType(delegateParameterType)) || !delegateParameterType.isAssignableFrom(parameterType) || isEquals(delegateMethod)) { Class<?>[] compatibleClassHierarchy = ProxyTypeInspector.getCompatibleClassHierarchy( valueDelegateLoader, unwrappedValueType); if (compatibleClassHierarchy.length == 0) { compatibleClassHierarchy = new Class[] { delegateParameterType }; } Object delegateObject = parameterValue; if (parameterValue instanceof ForgeProxy) { if ((((ForgeProxy) parameterValue).getHandler() instanceof ClassLoaderAdapterCallback)) { ClassLoaderAdapterCallback handler = (ClassLoaderAdapterCallback) (((ForgeProxy) parameterValue) .getHandler()); if (handler.getCallingLoader().equals(getCallingLoader()) && handler.getDelegateLoader().equals(getDelegateLoader()) && delegateParameterType.isAssignableFrom(unwrappedValue.getClass())) { delegateObject = unwrappedValue; } } } Object delegateParameterValue = enhance(whitelist, valueDelegateLoader, valueCallingLoader, delegateObject, compatibleClassHierarchy); return delegateParameterValue; } else { return unwrappedValue; } } } } } return null; } private static boolean isEquals(Method method) { if (boolean.class.equals(method.getReturnType()) && "equals".equals(method.getName()) && method.getParameterTypes().length == 1 && Object.class.equals(method.getParameterTypes()[0])) return true; return false; } private static boolean isHashCode(Method method) { if (int.class.equals(method.getReturnType()) && "hashCode".equals(method.getName()) && method.getParameterTypes().length == 0) return true; return false; } private static boolean isAutoCloseableClose(Method method) { if (void.class.equals(method.getReturnType()) && "close".equals(method.getName()) && method.getParameterTypes().length == 0) return true; return false; } private List<Class<?>> translateParameterTypes(final Method method) throws ClassNotFoundException { List<Class<?>> parameterTypes = new ArrayList<>(); for (int i = 0; i < method.getParameterTypes().length; i++) { Class<?> parameterType = method.getParameterTypes()[i]; if (parameterType.isPrimitive()) { parameterTypes.add(parameterType); } else { Class<?> delegateParameterType = delegateLoader.loadClass(parameterType.getName()); parameterTypes.add(delegateParameterType); } } return parameterTypes; } static <T> T enhance(Callable<Set<ClassLoader>> whitelist, final ClassLoader callingLoader, final ClassLoader delegateLoader, final Object delegate, final Class<?>... types) { return enhance(whitelist, callingLoader, delegateLoader, null, delegate, types); } @SuppressWarnings("unchecked") private static <T> T enhance( final Callable<Set<ClassLoader>> whitelist, final ClassLoader callingLoader, final ClassLoader delegateLoader, final Method sourceMethod, final Object delegate, final Class<?>... types) { if (whitelistContainsAll(whitelist, callingLoader, delegateLoader)) return (T) delegate; // TODO consider removing option to set type hierarchy here. Instead it might just be // best to use type inspection of the given initialCallingLoader ClassLoader to figure out the proper type. final Class<?> delegateType = delegate.getClass(); try { return ClassLoaders.executeIn(JAVASSIST_LOADER, new Callable<T>() { @Override public T call() throws Exception { try { Class<?>[] hierarchy = null; if (types == null || types.length == 0) { hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(callingLoader, Proxies.unwrapProxyTypes(delegateType, callingLoader, delegateLoader)); if (hierarchy == null || hierarchy.length == 0) { Logger.getLogger(getClass().getName()).fine( "Must specify at least one non-final type to enhance for Object: " + delegate + " of type " + delegate.getClass()); return (T) delegate; } } else hierarchy = Arrays.copy(types, new Class<?>[types.length]); MethodFilter filter = new MethodFilter() { @Override public boolean isHandled(Method method) { if (!method.getDeclaringClass().getName().contains("java.lang") || !Proxies.isPassthroughType(method.getDeclaringClass()) || ("toString".equals(method.getName()) && method.getParameterTypes().length == 0) || isEquals(method) || isHashCode(method) || isAutoCloseableClose(method)) return true; return false; } }; Object enhancedResult = null; ProxyFactory f = new ProxyFactory() { @Override protected ClassLoader getClassLoader0() { ClassLoader result = callingLoader; if (!ClassLoaders.containsClass(result, ProxyObject.class)) result = super.getClassLoader0(); return result; }; }; f.setUseCache(true); Class<?> first = hierarchy[0]; if (!first.isInterface()) { f.setSuperclass(Proxies.unwrapProxyTypes(first, callingLoader, delegateLoader)); hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]); } int index = Arrays.indexOf(hierarchy, ProxyObject.class); if (index >= 0) { hierarchy = Arrays.removeElementAtIndex(hierarchy, index); } if (!Proxies.isProxyType(first) && !Arrays.contains(hierarchy, ForgeProxy.class)) hierarchy = Arrays.append(hierarchy, ForgeProxy.class); if (hierarchy.length > 0) f.setInterfaces(hierarchy); f.setFilter(filter); Class<?> c = f.createClass(); enhancedResult = c.newInstance(); try { ((ProxyObject) enhancedResult) .setHandler(new ClassLoaderAdapterCallback(whitelist, callingLoader, delegateLoader, delegate)); } catch (ClassCastException e) { Class<?>[] interfaces = enhancedResult.getClass().getInterfaces(); for (Class<?> javassistType : interfaces) { if (ProxyObject.class.getName().equals(javassistType.getName()) || Proxy.class.getName().equals(javassistType.getName())) { String callbackClassName = ClassLoaderAdapterCallback.class.getName(); ClassLoader javassistLoader = javassistType.getClassLoader(); Constructor<?> callbackConstructor = javassistLoader.loadClass(callbackClassName) .getConstructors()[0]; Class<?> typeArgument = javassistLoader.loadClass(MethodHandler.class.getName()); Method setHandlerMethod = javassistType.getMethod("setHandler", typeArgument); setHandlerMethod.invoke(enhancedResult, callbackConstructor.newInstance(whitelist, callingLoader, delegateLoader, delegate)); } } } return (T) enhancedResult; } catch (Exception e) { // Added try/catch for debug breakpoint purposes only. throw e; } } }); } catch (Exception e) { throw new ContainerException("Failed to create proxy for type [" + delegateType + "]", e); } } @Override public Object getDelegate() throws Exception { return delegate; } @Override public Object getHandler() throws Exception { return this; } public ClassLoader getDelegateLoader() { return delegateLoader; } public ClassLoader getInitialCallingLoader() { return initialCallingLoader; } }
epl-1.0
francoispfister/diagraph
org.isoe.fwk.utils.eclipse/src/org/isoe/fwk/utils/eclipse/PluginResourceCopy.java
7495
/** * Copyright (c) 2014 Laboratoire de Genie Informatique et Ingenierie de Production - Ecole des Mines d'Ales * * 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: * Francois Pfister (ISOE-LGI2P) - initial API and implementation */ package org.isoe.fwk.utils.eclipse; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.common.CommonPlugin; import org.eclipse.emf.common.util.URI; import org.isoe.fwk.core.DParams; import org.isoe.fwk.core.Separator; import org.osgi.framework.Bundle; //import org.isoe.diagraph.DParams; /** * * @author pfister * copy resources from the platform:/plugin space to the current * workbench * */ public class PluginResourceCopy { //FP120523z // TODO unify with BundleFileCopier private static final boolean LOG = DParams.PluginResourceCopy_LOG; private String sourceFolder; private String targetFolder; private static String SVN_FOLDER = ".svn/"; private static String CVS_FOLDER_ = "CVS/"; private List<String> log = new ArrayList<String>(); private static PluginResourceCopy instance; private List<String> copied; private PluginResourceCopy() { super(); // TODO Auto-generated constructor stub } public static PluginResourceCopy getInstance() { if (instance==null) instance= new PluginResourceCopy(); return instance; } public String getLogs() { String result=""; for (String lg : log) result+=lg +" "; return "files copied: "+result; } public List<String> getCopied() { return copied; } /* private static String REPLACE_SEPARATOR; static { REPLACE_SEPARATOR = File.separator; if (REPLACE_SEPARATOR.equals("\\")) REPLACE_SEPARATOR = "\\\\"; }*/ private String append(String location, String file) { if (!location.endsWith(File.separator)) location += File.separator; location += file; location = location.replaceAll("/", Separator.SEPARATOR); return location; } private void copy(URL source, String targetPath) { if (LOG){ clog("copying (1) file from "+source.getPath()+" to "+targetPath); } try { InputStream in = new FileInputStream(new File(FileLocator.resolve( FileLocator.toFileURL(source)).getFile())); OutputStream out = new FileOutputStream(new File(targetPath)); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("(5) error while copying " + source.toString() + " to " + targetPath); } } private boolean filtered(URL url){ boolean result = url.toString().endsWith(SVN_FOLDER) || url.toString().endsWith(CVS_FOLDER_); return result; } private boolean filtered(URL url, String [] filters){ String urs=url.toString(); if (filters!=null) for (String filter : filters) if (urs.endsWith(filter)) return true; return urs.endsWith(SVN_FOLDER) || urs.endsWith(CVS_FOLDER_); } private List<URL> getSubElements(Bundle bundle, String path, String extension, boolean absoluteURL, boolean nested, String[] filters) { List<URL> result = new ArrayList<URL>(); Enumeration entryPaths = bundle.getEntryPaths(path); if (entryPaths == null) return result; for (Enumeration entry = entryPaths; entry.hasMoreElements();) { String fileName = (String) entry.nextElement(); if (extension == null || (extension != null && fileName.endsWith(extension))) { URL url = bundle.getEntry(fileName); //if (!url.toString().endsWith(SVN_FOLDER) && !url.toString().endsWith(CVS_FOLDER_) ) if (!filtered(url,filters)) if (absoluteURL) { try { URL furl= FileLocator.toFileURL(url); //if (LOG) // clog(" abs "+furl.toString()); //file:/D:/pfister/workspaces/ws-dev-pref-4/org.isoe.diagraph.gmf.templates/DiagraphTemplates/aspects/ result.add(furl); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Exception " + e.getMessage()+" !!!!"); } } else{ if (LOG) clog("nabs "+url.toString()); result.add(url); } } else if (nested) { List<URL> urls = getSubElements(bundle, fileName, extension, absoluteURL, nested,filters); result.addAll(urls); } } return result; } private List<String> getItemsFromBundle(Bundle bundle, String path, String[] filters) { List<String> result = new ArrayList<String>(); for (URL url : getSubElements(bundle, path, null, true, false,filters)) { String urstring = url.toString(); urstring = urstring.substring(urstring.indexOf(path)); result.add(urstring); } return result; } private void copy(Bundle srcbundle, String sourceDir, File targetDir, boolean replace, String[] filters, String filext) { if (!targetDir.exists()) targetDir.mkdir(); if (LOG) clog("copying from bundle "+srcbundle.getSymbolicName()+"/"+sourceDir+" to "+targetDir.getAbsolutePath()); List<String> srcitems = getItemsFromBundle(srcbundle, sourceDir,filters); if (srcitems.size() == 0) return; for (String srcitem : srcitems) { //if (LOG) // clog("/"+srcitem); String targetPath = targetDir.getAbsolutePath(); targetPath = targetPath.substring( 0, targetPath.lastIndexOf(targetFolder) + targetFolder.length()); String filename = append(targetPath, srcitem.substring(sourceFolder.length() + 1)); if (srcitem.endsWith("/")) copy( srcbundle, srcitem, new File(filename), true,filters,filext); else{ String extension = null; try { extension = srcitem.substring(srcitem.lastIndexOf(".")+1); } catch (Exception e) { } if (filext == null || filext.isEmpty() || (extension!=null && extension.startsWith(filext))){ File target = new File(filename); if (!target.exists() || (target.exists() && replace)){ copy(srcbundle.getEntry(srcitem),filename); copied.add(filename); if (LOG) clog("copied: "+filename); } else if (LOG) clog(" *** not overwritten: "+filename); } //else // if (LOG) //clog("not to be copied: "+filename); } } } private void clog(String mesg) { if (LOG) System.out.println(mesg); } public void copy(String srcplugin, String sourcefolder, String targetplugin, String targetfolder, boolean replace, String[] filters, String prefix) { if (sourcefolder.startsWith("/")) sourcefolder = sourcefolder.substring(1); if (targetfolder.startsWith("/")) targetfolder = targetfolder.substring(1); this.sourceFolder = sourcefolder; this.targetFolder = targetfolder; File targetDir = new File(CommonPlugin.resolve(URI.createPlatformResourceURI(targetplugin + "/" + targetfolder, true)).toFileString()); copied = new ArrayList<String>(); copy(Platform.getBundle(srcplugin),sourcefolder,targetDir,replace,filters, prefix); //return getLogs(); } }
epl-1.0
krakdustten/JAVA-GAME
JAVA-GAME/src/drawers/NormalRenderer.java
2169
package drawers; //TODO comments import entity.Entity; import gameState.PlayState; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; public class NormalRenderer { private GameContainer gc; private PlayState playState; private Render render; private Entity entity; private float zoom = 1.0f; public float screendrawstartx; public float screendrawstarty; public int blockdrawstartx; public int blockdrawstarty; public NormalRenderer(GameContainer gc, PlayState playState, Entity entity) { this.gc = gc; this.playState = playState; render = new Render(gc.getGraphics()); this.entity = entity; } public void draw(Graphics g) { float x = entity.getX(); float y = entity.getY(); int width = gc.getWidth(); int height = gc.getHeight(); g.translate(width/2, height/2); g.scale(zoom, zoom); g.translate(-width/2, -height/2); width = (int) (width / zoom); height = (int) (height / zoom); float xrest = x- (float)(int)x; float yrest = y- (float)(int)y; screendrawstartx = (-32 * xrest - 32) -(((1 / zoom)-1)*gc.getWidth())/2; screendrawstarty = (-32 * yrest - 32) -(((1 / zoom)-1)*gc.getHeight())/2; int blockx = (int)x; int blocky = (int)y; blockdrawstartx = blockx - width/64 - 1; blockdrawstarty = blocky - height/64 - 1; int blockwidth = width/32 + 3; int blockheight = height/32 + 3; //render blocks for(int i = 0; i < blockwidth; i++) { for(int j = 0; j < blockheight; j++) { int drawblockx = blockdrawstartx + i; int drawblocky = blockdrawstarty + j; if(drawblocky < 0 || drawblocky >= playState.getDrawWorld().height*64) { } else { playState.getDrawWorld().getBlock(drawblockx, drawblocky) .draw(screendrawstartx + i*32, screendrawstarty + j*32, render , playState.getDrawWorld().getTextureId(drawblockx, drawblocky)); } } } entity.draw((entity.getX() - (float)blockdrawstartx)*32 + screendrawstartx, (entity.getY() - (float)blockdrawstarty)*32 + screendrawstarty,render,g); } }
epl-1.0
sunix/che-plugins
plugin-runner/che-plugin-runner-ext-runner/src/main/java/org/eclipse/che/ide/ext/runner/client/tabs/history/HistoryPanel.java
1607
/******************************************************************************* * Copyright (c) 2012-2015 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.ext.runner.client.tabs.history; import org.eclipse.che.ide.ext.runner.client.models.Runner; import org.eclipse.che.ide.ext.runner.client.tabs.common.TabPresenter; import com.google.inject.ImplementedBy; import javax.annotation.Nonnull; /** * Provides methods which allow work with history panel. * * @author Dmitry Shnurenko */ @ImplementedBy(HistoryPresenter.class) public interface HistoryPanel extends TabPresenter { /** * The method creates special widget for current runner and adds it on history panel. * * @param runner * runner which need add */ void addRunner(@Nonnull Runner runner); /** * The method update state of current runner. * * @param runner * runner which need update */ void update(@Nonnull Runner runner); /** * Selects runner widget using current runner. * * @param runner * runner which was selected */ void selectRunner(@Nonnull Runner runner); /** Clears runner widgets. */ void clear(); }
epl-1.0
Milstein/controllerODP
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/core/ISwitch.java
5919
/* * Copyright (c) 2013 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.controller.protocol_plugin.openflow.core; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPhysicalPort; import org.openflow.protocol.OFStatisticsRequest; /** * This interface defines an abstraction of an Open Flow Switch. * */ public interface ISwitch { /** * Gets a unique XID. * @return XID */ public int getNextXid(); /** * Returns the Switch's ID. * @return the Switch's ID */ public Long getId(); /** * Returns the Switch's table numbers supported by datapath * @return the tables */ public Byte getTables(); /** * Returns the Switch's bitmap of supported ofp_action_type * @return the actions */ public Integer getActions(); /** * Returns the Switch's bitmap of supported ofp_capabilities * @return the capabilities */ public Integer getCapabilities(); /** * Returns the Switch's buffering capacity in Number of Pkts * @return the buffers */ public Integer getBuffers(); /** * Returns the Date when the switch was connected. * @return Date The date when the switch was connected */ public Date getConnectedDate(); /** * This method puts the message in an outgoing priority queue with normal * priority. It will be served after high priority messages. The method * should be used for non-critical messages such as statistics request, * discovery packets, etc. An unique XID is generated automatically and * inserted into the message. * * @param msg The OF message to be sent * @return The XID used */ public Integer asyncSend(OFMessage msg); /** * This method puts the message in an outgoing priority queue with normal * priority. It will be served after high priority messages. The method * should be used for non-critical messages such as statistics request, * discovery packets, etc. The specified XID is inserted into the message. * * @param msg The OF message to be Sent * @param xid The XID to be used in the message * @return The XID used */ public Integer asyncSend(OFMessage msg, int xid); /** * This method puts the message in an outgoing priority queue with high * priority. It will be served first before normal priority messages. The * method should be used for critical messages such as hello, echo reply * etc. An unique XID is generated automatically and inserted into the * message. * * @param msg The OF message to be sent * @return The XID used */ public Integer asyncFastSend(OFMessage msg); /** * This method puts the message in an outgoing priority queue with high * priority. It will be served first before normal priority messages. The * method should be used for critical messages such as hello, echo reply * etc. The specified XID is inserted into the message. * * @param msg The OF message to be sent * @return The XID used */ public Integer asyncFastSend(OFMessage msg, int xid); /** * Sends the OF message followed by a Barrier Request with a unique XID which is automatically generated, * and waits for a result from the switch. * @param msg The message to be sent * @return An Object which has one of the followings instances/values: * Boolean with value true to indicate the message has been successfully processed and acknowledged by the switch; * Boolean with value false to indicate the message has failed to be processed by the switch within a period of time or * OFError to indicate that the message has been denied by the switch which responded with OFError. */ public Object syncSend(OFMessage msg); /** * Returns a map containing all OFPhysicalPorts of this switch. * @return The Map of OFPhysicalPort */ public Map<Short, OFPhysicalPort> getPhysicalPorts(); /** * Returns a Set containing all port IDs of this switch. * @return The Set of port ID */ public Set<Short> getPorts(); /** * Returns OFPhysicalPort of the specified portNumber of this switch. * @param portNumber The port ID * @return OFPhysicalPort for the specified PortNumber */ public OFPhysicalPort getPhysicalPort(Short portNumber); /** * Returns the bandwidth of the specified portNumber of this switch. * @param portNumber the port ID * @return bandwidth */ public Integer getPortBandwidth(Short portNumber); /** * Returns True if the port is enabled, * @param portNumber * @return True if the port is enabled */ public boolean isPortEnabled(short portNumber); /** * Returns True if the port is enabled. * @param port * @return True if the port is enabled */ public boolean isPortEnabled(OFPhysicalPort port); /** * Returns a list containing all enabled ports of this switch. * @return: List containing all enabled ports of this switch */ public List<OFPhysicalPort> getEnabledPorts(); /** * Sends OFStatisticsRequest with a unique XID generated automatically and waits for a result from the switch. * @param req the OF Statistic Request to be sent * @return Object has one of the following instances/values:: * List<OFStatistics>, a list of statistics records received from the switch as response from the request; * OFError if the switch failed handle the request or * NULL if timeout has occurred while waiting for the response. */ public Object getStatistics(OFStatisticsRequest req); /** * Returns true if the switch has reached the operational state (has sent FEATURE_REPLY to the controller). * @return true if the switch is operational */ public boolean isOperational(); }
epl-1.0
aikidojohn/casino
src/main/java/com/johnhite/casino/blackjack/strategy/AceFiveStrategy.java
1045
package com.johnhite.casino.blackjack.strategy; import com.johnhite.casino.Card; import com.johnhite.casino.Card.Ordinal; import com.johnhite.casino.blackjack.Action; import com.johnhite.casino.blackjack.DeckListener; import com.johnhite.casino.blackjack.Hand; public class AceFiveStrategy implements BlackjackStrategy, DeckListener { private final BlackjackStrategy basic = new BasicStrategy(); private int count = 0; private int maxBet; private int lastBet; public AceFiveStrategy(int maxBet) { this.maxBet = maxBet; } @Override public void cardDealt(Card c) { if (c.getOrdinal() == Ordinal.FIVE) { count++; } else if (c.getOrdinal() == Ordinal.ACE) { count--; } } @Override public void shuffle() { count = 0; lastBet = 0; } @Override public Action play(Card dealer, Hand hand) { return basic.play(dealer, hand); } @Override public int getBet(int min, int max) { if (count >= 2) { if (lastBet * 2 <= maxBet) { lastBet *= 2; } } else { lastBet = min; } return lastBet; } }
epl-1.0
sschafer/atomic
org.allmyinfo.nodes/src/org/allmyinfo/nodes/NodeIdSyntaxException.java
750
package org.allmyinfo.nodes; import org.allmyinfo.exception.Argument; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; public class NodeIdSyntaxException extends NodeIdParseException { private static final long serialVersionUID = 1L; @Nullable final String name; public NodeIdSyntaxException(final @NonNull Throwable e) { super(e); name = null; } public NodeIdSyntaxException(final @NonNull String name, final @NonNull Throwable e) { super(new Argument @NonNull [] { new Argument("name", name) }, e); this.name = name; } @Override public @NonNull String getTranslationKey() { return name == null ? "exception.invalid_node_id_syntax" : "exception.invalid_node_id_syntax_for_type"; } }
epl-1.0
sschafer/atomic
org.allmyinfo.security/src/org/allmyinfo/security/PublicSecurityRole.java
641
package org.allmyinfo.security; import org.allmyinfo.util.osgi.reactor.BaseReactor; import org.eclipse.jdt.annotation.NonNull; import org.osgi.framework.BundleContext; public interface PublicSecurityRole extends SecurityRole { public static class Reactor extends BaseReactor { @SuppressWarnings("null") public Reactor(final @NonNull BundleContext bundleContext, final @NonNull PublicSecurityRole defaultInstance) { super(bundleContext, PublicSecurityRole.class.getName(), null, defaultInstance); } @Override public @NonNull PublicSecurityRole getInstance() { return (PublicSecurityRole) super.getInstance(); } } }
epl-1.0
avojak/hydrogen
com.avojak.plugin.hydrogen.core/src/main/java/com/avojak/plugin/hydrogen/core/contributions/preferencepage/FileValidator.java
1191
package com.avojak.plugin.hydrogen.core.contributions.preferencepage; import java.nio.file.Files; import java.nio.file.Path; /** * Class to wrap {@link Files} methods to allow for facilitated testing. * * @author Andrew Vojak */ public class FileValidator { /** * Returns whether or not the given {@link Path} refers to a directory. * * @param path * The {@link Path}. Cannot be null. * @return {@code true} if the {@link Path} refers to a directory, otherwise * {@code false}. */ public boolean isDirectory(final Path path) { if (path == null) { throw new IllegalArgumentException("path cannot be null"); //$NON-NLS-1$ } return Files.isDirectory(path); } /** * Returns whether or not the given {@link Path} refers to a file which is * executable. * * @param path * The {@link Path}. Cannot be null. * @return {@code true} if the {@link Path} refers to a file which is * executable, otherwise {@code false}. */ public boolean isExecutable(final Path path) { if (path == null) { throw new IllegalArgumentException("path cannot be null"); //$NON-NLS-1$ } return Files.isExecutable(path); } }
epl-1.0
SK-HOLDINGS-CC/NEXCORE-UML-Modeler
nexcore.alm.common/src/nexcore/alm/common/word/meta/ClassElt.java
3831
/** * 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) */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) // Reference Implementation, vJAXB 2.1.3 in JDK 1.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: 2008.04.16 at 03:26:38 ���� KST // package nexcore.alm.common.word.meta; 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.XmlType; /** * <p> * Java class for ClassElt complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name=&quot;ClassElt&quot;&gt; * &lt;complexContent&gt; * &lt;restriction base=&quot;{http://www.w3.org/2001/XMLSchema}anyType&quot;&gt; * &lt;sequence&gt; * &lt;element ref=&quot;{http://skcc.com/2003/wordmeta}Key&quot; maxOccurs=&quot;unbounded&quot; minOccurs=&quot;0&quot;/&gt; * &lt;/sequence&gt; * &lt;attribute name=&quot;name&quot; type=&quot;{http://skcc.com/2003/wordmeta}type&quot; /&gt; * &lt;attribute name=&quot;field&quot; type=&quot;{http://skcc.com/2003/wordmeta}type&quot; /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ClassElt", propOrder = { "key" }) public class ClassElt { @XmlElement(name = "Key") protected List<KeyElt> key; @XmlAttribute(namespace = "http://skcc.com/2003/wordmeta") protected String name; @XmlAttribute(namespace = "http://skcc.com/2003/wordmeta") protected String field; /** * Gets the value of the key 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 key property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getKey().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link KeyElt } * * */ public List<KeyElt> getKey() { if (key == null) { key = new ArrayList<KeyElt>(); } return this.key; } /** * Gets the value of the name property. * * @return possible object is {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the field property. * * @return possible object is {@link String } * */ public String getField() { return field; } /** * Sets the value of the field property. * * @param value * allowed object is {@link String } * */ public void setField(String value) { this.field = value; } }
epl-1.0
lunifera/lunifera-dsl
org.lunifera.dsl.semantic.common.edit/src/org/lunifera/dsl/semantic/common/types/provider/LOperationItemProvider.java
11406
/** * Copyright (c) 2011 - 2014, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg) * 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 * * Based on ideas from Xtext, Xtend, Xcore * * Contributors: * Florian Pirchner - Initial implementation * */ package org.lunifera.dsl.semantic.common.types.provider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import org.eclipse.emf.edit.provider.ViewerNotification; import org.eclipse.xtext.common.types.TypesFactory; import org.eclipse.xtext.xbase.XbaseFactory; import org.eclipse.xtext.xbase.annotations.xAnnotations.XAnnotationsFactory; import org.lunifera.dsl.semantic.common.types.LOperation; import org.lunifera.dsl.semantic.common.types.LunTypesFactory; import org.lunifera.dsl.semantic.common.types.LunTypesPackage; /** * This is the item provider adapter for a {@link org.lunifera.dsl.semantic.common.types.LOperation} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class LOperationItemProvider extends LAnnotationTargetItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public LOperationItemProvider(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); } return itemPropertyDescriptors; } /** * This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an * {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or * {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) { if (childrenFeatures == null) { super.getChildrenFeatures(object); childrenFeatures.add(LunTypesPackage.Literals.LOPERATION__MODIFIER); childrenFeatures.add(LunTypesPackage.Literals.LOPERATION__TYPE); childrenFeatures.add(LunTypesPackage.Literals.LOPERATION__PARAMS); childrenFeatures.add(LunTypesPackage.Literals.LOPERATION__BODY); } return childrenFeatures; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EStructuralFeature getChildFeature(Object object, Object child) { // Check the type of the specified child object and return the proper feature to use for // adding (see {@link AddCommand}) it as a child. return super.getChildFeature(object, child); } /** * This returns LOperation.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/LOperation")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { return getString("_UI_LOperation_type"); } /** * 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(LOperation.class)) { case LunTypesPackage.LOPERATION__MODIFIER: case LunTypesPackage.LOPERATION__TYPE: case LunTypesPackage.LOPERATION__PARAMS: case LunTypesPackage.LOPERATION__BODY: fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false)); 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); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__MODIFIER, LunTypesFactory.eINSTANCE.createLModifier())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmParameterizedTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmGenericArrayTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmWildcardTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmAnyTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmMultiTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmDelegateTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmSynonymTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmUnknownTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__TYPE, TypesFactory.eINSTANCE.createJvmInnerTypeReference())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__PARAMS, TypesFactory.eINSTANCE.createJvmFormalParameter())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXIfExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXSwitchExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXBlockExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXVariableDeclaration())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXMemberFeatureCall())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXFeatureCall())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXConstructorCall())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXBooleanLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXNullLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXNumberLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXStringLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXListLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXSetLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXClosure())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXCastedExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXBinaryOperation())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXUnaryOperation())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXPostfixOperation())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXForLoopExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXBasicForLoopExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXDoWhileExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXWhileExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXTypeLiteral())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXInstanceOfExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXThrowExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXTryCatchFinallyExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXAssignment())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXReturnExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XbaseFactory.eINSTANCE.createXSynchronizedExpression())); newChildDescriptors.add (createChildParameter (LunTypesPackage.Literals.LOPERATION__BODY, XAnnotationsFactory.eINSTANCE.createXAnnotation())); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
utils/eclipselink.utils.workbench/scplugin/source/org/eclipse/persistence/tools/workbench/scplugin/ui/pool/EisReadPoolTabbedPropertiesPage.java
1363
/******************************************************************************* * 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.scplugin.ui.pool; import java.awt.Component; import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext; import org.eclipse.persistence.tools.workbench.scplugin.ui.pool.basic.EisReadPoolLoginPropertiesPage; public class EisReadPoolTabbedPropertiesPage extends PoolTabbedPropertiesPage { public EisReadPoolTabbedPropertiesPage(WorkbenchContext context) { super(context); } protected Component buildLoginPropertiesPage() { return new EisReadPoolLoginPropertiesPage( this.getNodeHolder(), getWorkbenchContextHolder()); } }
epl-1.0
nickmain/xmind
bundles/org.xmind.ui.mindmap/src/org/xmind/ui/internal/wizards/ITextExportPart.java
875
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See http://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.internal.wizards; import java.io.PrintStream; import org.xmind.ui.wizards.IExportPart; public interface ITextExportPart extends IExportPart { void write(PrintStream ps); }
epl-1.0
opendaylight/yangtools
codec/yang-data-codec-binfmt/src/main/java/org/opendaylight/yangtools/yang/data/codec/binfmt/NeonSR2NormalizedNodeOutputStreamWriter.java
3737
/* * Copyright (c) 2019 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.data.codec.binfmt; import java.io.DataOutput; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier; /** * NormalizedNodeOutputStreamWriter will be used by distributed datastore to send normalized node in * a stream. * A stream writer wrapper around this class will write node objects to stream in recursive manner. * for example - If you have a ContainerNode which has a two LeafNode as children, then * you will first call * {@link #startContainerNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, int)}, * then will call * {@link #leafNode(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier, Object)} twice * and then, {@link #endNode()} to end container node. * * <p>Based on the each node, the node type is also written to the stream, that helps in reconstructing the object, * while reading. */ final class NeonSR2NormalizedNodeOutputStreamWriter extends AbstractLithiumDataOutput { private final Map<AugmentationIdentifier, Integer> aidCodeMap = new HashMap<>(); private final Map<QNameModule, Integer> moduleCodeMap = new HashMap<>(); private final Map<QName, Integer> qnameCodeMap = new HashMap<>(); NeonSR2NormalizedNodeOutputStreamWriter(final DataOutput output) { super(output); } @Override short streamVersion() { return TokenTypes.NEON_SR2_VERSION; } @Override void writeQNameInternal(final QName qname) throws IOException { final Integer value = qnameCodeMap.get(qname); if (value == null) { // Fresh QName, remember it and emit as three strings qnameCodeMap.put(qname, qnameCodeMap.size()); writeByte(NeonSR2Tokens.IS_QNAME_VALUE); defaultWriteQName(qname); } else { // We have already seen this QName: write its code writeByte(NeonSR2Tokens.IS_QNAME_CODE); writeInt(value); } } @Override void writeAugmentationIdentifier(final AugmentationIdentifier aid) throws IOException { final Integer value = aidCodeMap.get(aid); if (value == null) { // Fresh AugmentationIdentifier, remember it and emit as three strings aidCodeMap.put(aid, aidCodeMap.size()); writeByte(NeonSR2Tokens.IS_AUGMENT_VALUE); defaultWriteAugmentationIdentifier(aid); } else { // We have already seen this AugmentationIdentifier: write its code writeByte(NeonSR2Tokens.IS_AUGMENT_CODE); writeInt(value); } } @Override void writeModule(final QNameModule module) throws IOException { final Integer value = moduleCodeMap.get(module); if (value == null) { // Fresh QNameModule, remember it and emit as three strings moduleCodeMap.put(module, moduleCodeMap.size()); writeByte(NeonSR2Tokens.IS_MODULE_VALUE); defaultWriteModule(module); } else { // We have already seen this QNameModule: write its code writeByte(NeonSR2Tokens.IS_MODULE_CODE); writeInt(value); } } }
epl-1.0
smadelenat/CapellaModeAutomata
Semantic/Scenario/org.gemoc.scenario.xdsml/src-gen/org/gemoc/scenario/xdsml/FunctionScenario.java
1187
package org.gemoc.scenario.xdsml; import fr.inria.diverse.melange.lib.IMetamodel; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.gemoc.scenario.xdsml.FunctionScenarioMT; @SuppressWarnings("all") public class FunctionScenario implements IMetamodel { private Resource resource; public Resource getResource() { return this.resource; } public void setResource(final Resource resource) { this.resource = resource; } public static FunctionScenario load(final String uri) { ResourceSet rs = new ResourceSetImpl(); Resource res = rs.getResource(URI.createURI(uri), true); FunctionScenario mm = new FunctionScenario(); mm.setResource(res); return mm ; } public FunctionScenarioMT toFunctionScenarioMT() { org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioAdapter adaptee = new org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioAdapter() ; adaptee.setAdaptee(resource); return adaptee; } }
epl-1.0
jankod/DigestedProteinDB
test/hr/pbf/digestdb/test/experiments/ProbeStep4CompressManyFiles.java
2209
package hr.pbf.digestdb.test.experiments; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.TreeSet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import hr.pbf.digestdb.nr.App_3_CreateMenyFilesFromCSV; import hr.pbf.digestdb.nr.App_4_CompressManyFilesSmall; import hr.pbf.digestdb.nr.App_4_CompressManyFilesSmall.PeptideMassIdRow; import hr.pbf.digestdb.uniprot.MyDataOutputStream; public class ProbeStep4CompressManyFiles { public static void main222(String[] args) throws FileNotFoundException, IOException { // NE RADI String file = "C:\\Eclipse\\OxygenWorkspace\\DigestedProteinDB\\misc\\4904.3.db"; file = "C:\\Eclipse\\OxygenWorkspace\\DigestedProteinDB\\misc\\500.3.db"; TreeSet<PeptideMassIdRow> result = App_4_CompressManyFilesSmall.readSmallDataFile(new File(file)); for (PeptideMassIdRow p : result) { System.out.println(p.mass + " " + p.id + " " + p.peptide); } } public static void main(String[] args) { // App_3_CreateMenyFilesFromCSV c = new App_3_CreateMenyFilesFromCSV(); // c.start(null); App_4_CompressManyFilesSmall read = new App_4_CompressManyFilesSmall(); read.start(null); } public static void main2(String[] args) throws IOException { // RADI App_3_CreateMenyFilesFromCSV c = new App_3_CreateMenyFilesFromCSV(); ByteArrayOutputStream out = new ByteArrayOutputStream(); MyDataOutputStream dout = new MyDataOutputStream(out); c.writeRow(1230D, "PEPTIDE", "WP_000184067.1", dout); c.writeRow(1230D, "PEPTIDESFDSDFSDFREWRWEFCSEFWS", "XP_642131.1", dout); dout.flush(); File tempFile = new File(FileUtils.getTempDirectory(), "proba.txt"); { FileOutputStream ooo = new FileOutputStream(tempFile); IOUtils.write(out.toByteArray(), ooo); ooo.close(); } { TreeSet<PeptideMassIdRow> res = App_4_CompressManyFilesSmall.readSmallDataFile(tempFile); for (PeptideMassIdRow p : res) { System.out.println(p.mass + " " + p.id + " " + p.peptide); } } } }
epl-1.0
noncom/lemur
java/com/simsilica/lemur/Slider.java
15133
/* * $Id: Slider.java 1587 2015-04-19 07:24:23Z PSpeed42@gmail.com $ * * Copyright (c) 2012-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simsilica.lemur; import com.simsilica.lemur.style.StyleDefaults; import com.simsilica.lemur.style.Attributes; import com.simsilica.lemur.style.ElementId; import com.simsilica.lemur.style.Styles; import com.simsilica.lemur.core.VersionedReference; import com.simsilica.lemur.core.GuiControl; import com.jme3.input.MouseInput; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Spatial; import com.simsilica.lemur.component.BorderLayout; import com.simsilica.lemur.core.AbstractGuiControlListener; import com.simsilica.lemur.event.CursorButtonEvent; import com.simsilica.lemur.event.CursorEventControl; import com.simsilica.lemur.event.CursorMotionEvent; import com.simsilica.lemur.event.DefaultCursorListener; /** * A composite GUI element consisting of a draggable slider * with increment and decrement buttons at each end. The slider * value is managed by a RangedValueModel. * * @author Paul Speed */ public class Slider extends Panel { public static final String ELEMENT_ID = "slider"; /*public static final String UP_ID = "slider.up.button"; public static final String DOWN_ID = "slider.down.button"; public static final String LEFT_ID = "slider.left.button"; public static final String RIGHT_ID = "slider.right.button"; public static final String THUMB_ID = "slider.thumb.button"; public static final String RANGE_ID = "slider.range";*/ public static final String UP_ID = "up.button"; public static final String DOWN_ID = "down.button"; public static final String LEFT_ID = "left.button"; public static final String RIGHT_ID = "right.button"; public static final String THUMB_ID = "thumb.button"; public static final String RANGE_ID = "range"; private BorderLayout layout; private Axis axis; private Button increment; private Button decrement; private Panel range; private Button thumb; private RangedValueModel model; private double delta = 1.0f; private VersionedReference<Double> state; public Slider() { this(new DefaultRangedValueModel(), Axis.X, true, new ElementId(ELEMENT_ID), null); } public Slider(Axis axis) { this(new DefaultRangedValueModel(), axis, true, new ElementId(ELEMENT_ID), null); } public Slider(RangedValueModel model) { this(model, Axis.X, true, new ElementId(ELEMENT_ID), null); } public Slider(RangedValueModel model, Axis axis) { this(model, axis, true, new ElementId(ELEMENT_ID), null); } public Slider(String style) { this(new DefaultRangedValueModel(), Axis.X, true, new ElementId(ELEMENT_ID), style); } public Slider(ElementId elementId, String style) { this(new DefaultRangedValueModel(), Axis.X, true, elementId, style); } public Slider(Axis axis, ElementId elementId, String style) { this(new DefaultRangedValueModel(), axis, true, elementId, style); } public Slider(Axis axis, String style) { this(new DefaultRangedValueModel(), axis, true, new ElementId(ELEMENT_ID), style); } public Slider( RangedValueModel model, String style ) { this(model, Axis.X, true, new ElementId(ELEMENT_ID), style); } public Slider( RangedValueModel model, Axis axis, String style ) { this(model, axis, true, new ElementId(ELEMENT_ID), style); } public Slider( RangedValueModel model, Axis axis, ElementId elementId, String style ) { this(model, axis, true, elementId, style); } protected Slider( RangedValueModel model, Axis axis, boolean applyStyles, ElementId elementId, String style ) { super(false, elementId, style); // Because the slider accesses styles (for its children) before // it has applied its own, it is possible that its default styles // will not have been applied. So we'll make sure. Styles styles = GuiGlobals.getInstance().getStyles(); styles.initializeStyles(getClass()); this.axis = axis; this.layout = new BorderLayout(); getControl(GuiControl.class).setLayout(layout); getControl(GuiControl.class).addListener(new ReshapeListener()); this.model = model; switch( axis ) { case X: increment = layout.addChild(BorderLayout.Position.East, new Button(null, true, elementId.child(RIGHT_ID), style)); increment.addClickCommands( new ChangeValueCommand(1) ); decrement = layout.addChild(BorderLayout.Position.West, new Button(null, true, elementId.child(LEFT_ID), style)); decrement.addClickCommands( new ChangeValueCommand(-1) ); range = layout.addChild(new Panel(true, 50, 2, elementId.child(RANGE_ID), style)); break; case Y: increment = layout.addChild(BorderLayout.Position.North, new Button(null, true, elementId.child(UP_ID), style)); increment.addClickCommands( new ChangeValueCommand(1) ); decrement = layout.addChild(BorderLayout.Position.South, new Button(null, true, elementId.child(DOWN_ID), style)); decrement.addClickCommands( new ChangeValueCommand(-1) ); range = layout.addChild(new Panel(true, 2, 50, elementId.child(RANGE_ID), style)); break; case Z: throw new IllegalArgumentException("Z axis not yet supported."); } thumb = new Button(null, true, elementId.child(THUMB_ID), style); ButtonDragger dragger = new ButtonDragger(); CursorEventControl.addListenersToSpatial(thumb, dragger); attachChild(thumb); // A child that is not managed by the layout will not otherwise lay itself // out... so we will force it to be its own preferred size. thumb.getControl(GuiControl.class).setSize(thumb.getControl(GuiControl.class).getPreferredSize()); if( applyStyles ) { styles.applyStyles(this, elementId.getId(), style); } } @StyleDefaults(ELEMENT_ID) public static void initializeDefaultStyles( Styles styles, Attributes attrs ) { ElementId parent = new ElementId(ELEMENT_ID); styles.getSelector(parent.child(UP_ID), null).set("text", "^", false); styles.getSelector(parent.child(DOWN_ID), null).set("text", "v", false); styles.getSelector(parent.child(LEFT_ID), null).set("text", "<", false); styles.getSelector(parent.child(RIGHT_ID), null).set("text", ">", false); styles.getSelector(parent.child(THUMB_ID), null).set("text", "#", false); } public void setModel( RangedValueModel model ) { if( this.model == model ) return; this.model = model; this.state = null; } public RangedValueModel getModel() { return model; } public void setDelta( double delta ) { this.delta = delta; } public double getDelta() { return delta; } public Button getIncrementButton() { return increment; } public Button getDecrementButton() { return decrement; } public Panel getRangePanel() { return range; } public Button getThumbButton() { return thumb; } /** * Returns the slider range value for the specified location * in the slider's local coordinate system. (For example, * for world space location use slider.worldToLocal() first.) */ public double getValueForLocation( Vector3f loc ) { Vector3f relative = loc.subtract(range.getLocalTranslation()); // Components always grow down from their location // so we'll invert y relative.y *= -1; Vector3f axisDir = axis.getDirection(); double projection = relative.dot(axisDir); if( projection < 0 ) { if( axis == Axis.Y ) { return model.getMaximum(); } else { return model.getMinimum(); } } Vector3f rangeSize = range.getSize().clone(); double rangeLength = rangeSize.dot(axisDir); projection = Math.min(projection, rangeLength); double part = projection / rangeLength; double rangeDelta = model.getMaximum() - model.getMinimum(); // For the y-axis, the slider is inverted from the direction // that the component's grow... so our part is backwards if( axis == Axis.Y ) { part = 1 - part; } return model.getMinimum() + rangeDelta * part; } @Override public void updateLogicalState(float tpf) { super.updateLogicalState(tpf); if( state == null || state.update() ) { resetStateView(); } } protected void resetStateView() { if( state == null ) { state = model.createReference(); } Vector3f pos = range.getLocalTranslation(); Vector3f rangeSize = range.getSize(); Vector3f thumbSize = thumb.getSize(); Vector3f size = getSize(); double visibleRange; double x; double y; switch( axis ) { case X: visibleRange = rangeSize.x - thumbSize.x; // Calculate where the thumb center should be x = pos.x + visibleRange * model.getPercent(); y = pos.y - rangeSize.y * 0.5; // We cheated and included the half-thumb spacing in x already which // is why this is axis-specific. thumb.setLocalTranslation((float)x, (float)(y + thumbSize.y * 0.5), pos.z + size.z); break; case Y: visibleRange = rangeSize.y - thumbSize.y; // Calculate where the thumb center should be x = pos.x + rangeSize.x * 0.5; y = pos.y - rangeSize.y + (visibleRange * model.getPercent()); thumb.setLocalTranslation((float)(x - thumbSize.x * 0.5), (float)(y + thumbSize.y), pos.z + size.z ); break; } } private class ChangeValueCommand implements Command<Button> { private double scale; public ChangeValueCommand( double scale ) { this.scale = scale; } public void execute( Button source ) { model.setValue(model.getValue() + delta * scale); } } private class ReshapeListener extends AbstractGuiControlListener { @Override public void reshape( GuiControl source, Vector3f pos, Vector3f size ) { // Make sure the thumb is positioned appropriately // for the new size resetStateView(); } } private class ButtonDragger extends DefaultCursorListener { private Vector2f drag = null; private double startPercent; @Override public void cursorButtonEvent( CursorButtonEvent event, Spatial target, Spatial capture ) { if( event.getButtonIndex() != MouseInput.BUTTON_LEFT ) return; //if( capture != null && capture != target ) // return; event.setConsumed(); if( event.isPressed() ) { drag = new Vector2f(event.getX(), event.getY()); startPercent = model.getPercent(); } else { // Dragging is done. drag = null; } } @Override public void cursorMoved( CursorMotionEvent event, Spatial target, Spatial capture ) { if( drag == null ) return; // Need to figure out how our mouse motion projects // onto the slider axis. Easiest way is to project // the end points onto the screen to create a vector // against which we can do dot products. Vector3f v1 = null; Vector3f v2 = null; switch( axis ) { case X: v1 = new Vector3f(thumb.getSize().x*0.5f,0,0); v2 = v1.add(range.getSize().x - thumb.getSize().x*0.5f, 0, 0); break; case Y: v1 = new Vector3f(0,thumb.getSize().y*0.5f,0); v2 = v1.add(0, (range.getSize().y - thumb.getSize().y*0.5f), 0); break; } v1 = event.getRelativeViewCoordinates(range, v1); v2 = event.getRelativeViewCoordinates(range, v2); Vector3f dir = v2.subtract(v1); float length = dir.length(); dir.multLocal(1/length); Vector3f cursorDir = new Vector3f(event.getX() - drag.x, event.getY() - drag.y, 0); float dot = cursorDir.dot(dir); // Now, the actual amount is then dot/length float percent = dot / length; model.setPercent(startPercent + percent); event.setConsumed(); } } }
epl-1.0
rohitmohan96/ceylon-ide-eclipse
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/code/open/OpenDeclarationInHierarchyHandler.java
551
package com.redhat.ceylon.eclipse.code.open; import static com.redhat.ceylon.eclipse.util.EditorUtil.getCurrentEditor; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; public class OpenDeclarationInHierarchyHandler extends AbstractHandler { @Override public Object execute(ExecutionEvent event) throws ExecutionException { new OpenDeclarationInHierarchyAction(getCurrentEditor()).run(); return null; } }
epl-1.0
sleshchenko/che
ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/actions/UndoAction.java
2408
/* * 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.ide.actions; import static org.eclipse.che.ide.part.perspectives.project.ProjectPerspective.PROJECT_PERSPECTIVE_ID; import com.google.inject.Inject; import java.util.Arrays; import javax.validation.constraints.NotNull; import org.eclipse.che.ide.CoreLocalizationConstant; import org.eclipse.che.ide.Resources; import org.eclipse.che.ide.api.action.AbstractPerspectiveAction; import org.eclipse.che.ide.api.action.ActionEvent; import org.eclipse.che.ide.api.editor.EditorAgent; import org.eclipse.che.ide.api.editor.EditorPartPresenter; import org.eclipse.che.ide.api.editor.texteditor.HandlesUndoRedo; import org.eclipse.che.ide.api.editor.texteditor.UndoableEditor; /** * Undo Action * * @author Roman Nikitenko * @author Dmitry Shnurenko */ public class UndoAction extends AbstractPerspectiveAction { private EditorAgent editorAgent; @Inject public UndoAction( EditorAgent editorAgent, CoreLocalizationConstant localization, Resources resources) { super( Arrays.asList(PROJECT_PERSPECTIVE_ID), localization.undoName(), localization.undoDescription(), resources.undo()); this.editorAgent = editorAgent; } @Override public void actionPerformed(ActionEvent e) { EditorPartPresenter activeEditor = editorAgent.getActiveEditor(); if (activeEditor != null && activeEditor instanceof UndoableEditor) { final HandlesUndoRedo undoRedo = ((UndoableEditor) activeEditor).getUndoRedo(); if (undoRedo != null) { undoRedo.undo(); } } } @Override public void updateInPerspective(@NotNull ActionEvent event) { EditorPartPresenter activeEditor = editorAgent.getActiveEditor(); boolean mustEnable = false; if (activeEditor != null && activeEditor instanceof UndoableEditor) { final HandlesUndoRedo undoRedo = ((UndoableEditor) activeEditor).getUndoRedo(); if (undoRedo != null) { mustEnable = undoRedo.undoable(); } } event.getPresentation().setEnabled(mustEnable); } }
epl-1.0
worldwidewoogie/demomod
src/main/java/net/woogie/demomod/entity/hostile/DemoRenderHostile.java
704
package net.woogie.demomod.entity.hostile; import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.woogie.demomod.Config; public class DemoRenderHostile extends RenderLiving { public DemoRenderHostile(RenderManager renderManager, ModelBase modelBase, float someFloat) { super(renderManager, modelBase, someFloat); } @Override protected ResourceLocation getEntityTexture(Entity entity) { return new ResourceLocation(Config.MODID + ":textures/entity/" + Config.entityHostileName + ".png"); } }
epl-1.0
zsmartsystems/com.zsmartsystems.zwave
com.zsmartsystems.zwave/src/test/java/com/zsmartsystems/zwave/commandclass/impl/loopback/CommandClassThermostatSetpointV2LoopbackTest.java
4478
/** * Copyright (c) 2016-2017 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.zwave.commandclass.impl.loopback; import static org.junit.Assert.assertEquals; import java.util.Map; import java.util.List; import com.zsmartsystems.zwave.commandclass.impl.CommandClassThermostatSetpointV2; /** * Class to implement loopback tests for command class <b>COMMAND_CLASS_THERMOSTAT_SETPOINT</b> version <b>2</b>. * <p> * Note that this code is autogenerated. Manual changes may be overwritten. * * @author Chris Jackson - Initial contribution of Java code generator */ public class CommandClassThermostatSetpointV2LoopbackTest { /** * Performs an in/out test of the THERMOSTAT_SETPOINT_SET command. * <p> * Test is designed to ensure that the command generates the same data * as the handler processes and is mainly a check of the code generator. * * @param setpointType {@link String} * @param scale {@link Integer} * @param precision {@link Integer} * @param value {@link byte[]} */ public static void testThermostatSetpointSetLoopback(String setpointType, Integer scale, Integer precision, byte[] value) { byte[] testPayload = CommandClassThermostatSetpointV2.getThermostatSetpointSet(setpointType, scale, precision, value); Map<String, Object> response = CommandClassThermostatSetpointV2.handleThermostatSetpointSet(testPayload); assertEquals(setpointType, (String) response.get("SETPOINT_TYPE")); assertEquals(scale, (Integer) response.get("SCALE")); assertEquals(precision, (Integer) response.get("PRECISION")); assertEquals(value, (byte[]) response.get("VALUE")); } /** * Performs an in/out test of the THERMOSTAT_SETPOINT_GET command. * <p> * Test is designed to ensure that the command generates the same data * as the handler processes and is mainly a check of the code generator. * * @param setpointType {@link String} */ public static void testThermostatSetpointGetLoopback(String setpointType) { byte[] testPayload = CommandClassThermostatSetpointV2.getThermostatSetpointGet(setpointType); Map<String, Object> response = CommandClassThermostatSetpointV2.handleThermostatSetpointGet(testPayload); assertEquals(setpointType, (String) response.get("SETPOINT_TYPE")); } /** * Performs an in/out test of the THERMOSTAT_SETPOINT_REPORT command. * <p> * Test is designed to ensure that the command generates the same data * as the handler processes and is mainly a check of the code generator. * * @param setpointType {@link String} * @param scale {@link Integer} * @param precision {@link Integer} * @param value {@link byte[]} */ public static void testThermostatSetpointReportLoopback(String setpointType, Integer scale, Integer precision, byte[] value) { byte[] testPayload = CommandClassThermostatSetpointV2.getThermostatSetpointReport(setpointType, scale, precision, value); Map<String, Object> response = CommandClassThermostatSetpointV2.handleThermostatSetpointReport(testPayload); assertEquals(setpointType, (String) response.get("SETPOINT_TYPE")); assertEquals(scale, (Integer) response.get("SCALE")); assertEquals(precision, (Integer) response.get("PRECISION")); assertEquals(value, (byte[]) response.get("VALUE")); } /** * Performs an in/out test of the THERMOSTAT_SETPOINT_SUPPORTED_REPORT command. * <p> * Test is designed to ensure that the command generates the same data * as the handler processes and is mainly a check of the code generator. * * @param bitMask {@link List<String>} */ public static void testThermostatSetpointSupportedReportLoopback(List<String> bitMask) { byte[] testPayload = CommandClassThermostatSetpointV2.getThermostatSetpointSupportedReport(bitMask); Map<String, Object> response = CommandClassThermostatSetpointV2.handleThermostatSetpointSupportedReport(testPayload); assertEquals(bitMask, (List<String>) response.get("BIT_MASK")); } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/tests/collections/map/TestUpdateEntityDirectMapMapping.java
5007
/******************************************************************************* * 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: * tware - initial implementation ******************************************************************************/ package org.eclipse.persistence.testing.tests.collections.map; import org.eclipse.persistence.expressions.Expression; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.internal.queries.MappedKeyMapContainerPolicy; import org.eclipse.persistence.mappings.DirectMapMapping; import org.eclipse.persistence.mappings.ForeignReferenceMapping; import org.eclipse.persistence.queries.ReadObjectQuery; import org.eclipse.persistence.sessions.UnitOfWork; import org.eclipse.persistence.testing.framework.TestErrorException; import org.eclipse.persistence.testing.models.collections.map.EntityDirectMapHolder; import org.eclipse.persistence.testing.models.collections.map.EntityMapKey; public class TestUpdateEntityDirectMapMapping extends TestReadEntityDirectMapMapping { private boolean usePrivateOwned = false; protected ForeignReferenceMapping keyMapping = null; private boolean oldKeyPrivateOwnedValue = false; protected EntityDirectMapHolder changedHolder = null; public TestUpdateEntityDirectMapMapping(){ super(); } public TestUpdateEntityDirectMapMapping(boolean usePrivateOwned){ this(); this.usePrivateOwned = usePrivateOwned; setName("TestUpdateEntityDirectMapMapping privateOwned=" + usePrivateOwned); } public void setup(){ DirectMapMapping mapping = (DirectMapMapping)getSession().getProject().getDescriptor(EntityDirectMapHolder.class).getMappingForAttributeName("entityToDirectMap"); keyMapping = (ForeignReferenceMapping)((MappedKeyMapContainerPolicy)mapping.getContainerPolicy()).getKeyMapping(); oldKeyPrivateOwnedValue = keyMapping.isPrivateOwned(); keyMapping.setIsPrivateOwned(usePrivateOwned); super.setup(); } public void test(){ UnitOfWork uow = getSession().acquireUnitOfWork(); holders = uow.readAllObjects(EntityDirectMapHolder.class, holderExp); changedHolder = (EntityDirectMapHolder)holders.get(0); EntityMapKey mapKey = new EntityMapKey(); mapKey.setId(1); changedHolder.removeEntityToDirectMapItem(mapKey); mapKey = new EntityMapKey(); mapKey.setId(3); mapKey.setData("testData"); mapKey = (EntityMapKey)uow.registerObject(mapKey); changedHolder.addEntityDirectMapItem(mapKey, new Integer(3)); uow.commit(); Object holderForComparison = uow.readObject(changedHolder); if (!compareObjects(changedHolder, holderForComparison)){ throw new TestErrorException("Objects do not match after write"); } } public void verify(){ getSession().getIdentityMapAccessor().initializeIdentityMaps(); holders = getSession().readAllObjects(EntityDirectMapHolder.class, holderExp); EntityDirectMapHolder holder = (EntityDirectMapHolder)holders.get(0); if (!compareObjects(holder, changedHolder)){ throw new TestErrorException("Objects do not match reinitialize"); } EntityMapKey mapKey = new EntityMapKey(); mapKey.setId(1); if (holder.getEntityToDirectMap().containsKey(mapKey)){ throw new TestErrorException("Item that was removed is still present in map."); } mapKey = new EntityMapKey(); mapKey.setId(3); Integer value = (Integer)holder.getEntityToDirectMap().get(mapKey); if (value.intValue() != 3){ throw new TestErrorException("Item was not correctly added to map"); } if (keyMapping.isPrivateOwned()){ ReadObjectQuery query = new ReadObjectQuery(EntityMapKey.class); ExpressionBuilder keys = new ExpressionBuilder(); Expression keycriteria = keys.get("id").equal(1); query.setSelectionCriteria(keycriteria); mapKey = (EntityMapKey)getSession().executeQuery(query); if (mapKey != null){ throw new TestErrorException("PrivateOwned EntityMapKey was not deleted."); } } } public void reset(){ super.reset(); keyMapping.setIsPrivateOwned(oldKeyPrivateOwnedValue); } }
epl-1.0
alovassy/titan.EclipsePlug-ins
org.eclipse.titan.designer/src/org/eclipse/titan/designer/AST/TTCN3/statements/Getcall_Statement.java
11497
/****************************************************************************** * Copyright (c) 2000-2015 Ericsson Telecom AB * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.eclipse.titan.designer.AST.TTCN3.statements; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.titan.designer.AST.ASTVisitor; import org.eclipse.titan.designer.AST.INamedNode; import org.eclipse.titan.designer.AST.IType; import org.eclipse.titan.designer.AST.Reference; import org.eclipse.titan.designer.AST.ReferenceFinder; import org.eclipse.titan.designer.AST.ReferenceFinder.Hit; import org.eclipse.titan.designer.AST.Scope; import org.eclipse.titan.designer.AST.TTCN3.templates.TemplateInstance; import org.eclipse.titan.designer.AST.TTCN3.types.PortTypeBody; import org.eclipse.titan.designer.AST.TTCN3.types.PortTypeBody.OperationModes; import org.eclipse.titan.designer.AST.TTCN3.types.Port_Type; import org.eclipse.titan.designer.AST.TTCN3.types.Signature_Type; import org.eclipse.titan.designer.AST.TTCN3.types.TypeSet; import org.eclipse.titan.designer.parsers.CompilationTimeStamp; import org.eclipse.titan.designer.parsers.ttcn3parser.ReParseException; import org.eclipse.titan.designer.parsers.ttcn3parser.Ttcn3Lexer; import org.eclipse.titan.designer.parsers.ttcn3parser.TTCN3ReparseUpdater; /** * @author Kristof Szabados * */ public final class Getcall_Statement extends Statement { private static final String SIGNATUREPARAMETEREXPECTED = "The type of parameter is `{0}'', which is not a signature"; private static final String ANYWITHREDIRECT = "Operation `any port.{0}'' cannot have parameter redirect"; private static final String ANYWITHPARAMETER = "operation `any port.{0}'' cannot have parameter"; private static final String SIGNATURENOTPRESENT = "Signature `{0}'' is not present on the incoming list of port type `{1}''"; private static final String UNKNOWNSIGNATURETYPE = "Cannot determine the type of the signature"; private static final String MESSAGEBASEDPORT = "Procedure-based operation `{0}'' is not applicable to a massage-based port of type `{1}''"; private static final String NOINSIGNATURES = "Port type `{0}'' does not have any incoming signatures"; private static final String REDIRECTWITHOUTSIGNATURE = "Parameter redirect cannot be used without signature template"; private static final String FULLNAMEPART1 = ".portreference"; private static final String FULLNAMEPART2 = ".parameter"; private static final String FULLNAMEPART3 = ".from"; private static final String FULLNAMEPART4 = ".parameters"; private static final String FULLNAMEPART5 = ".redirectSender"; private static final String STATEMENT_NAME = "getcall"; private final Reference portReference; private final TemplateInstance parameter; private final TemplateInstance fromClause; private final Parameter_Redirect redirectParameter; private final Reference redirectSender; public Getcall_Statement(final Reference portReference, final TemplateInstance parameter, final TemplateInstance fromClause, final Parameter_Redirect redirectParameter, final Reference redirectSender) { this.portReference = portReference; this.parameter = parameter; this.fromClause = fromClause; this.redirectParameter = redirectParameter; this.redirectSender = redirectSender; if (portReference != null) { portReference.setFullNameParent(this); } if (parameter != null) { parameter.setFullNameParent(this); } if (fromClause != null) { fromClause.setFullNameParent(this); } if (redirectParameter != null) { redirectParameter.setFullNameParent(this); } if (redirectSender != null) { redirectSender.setFullNameParent(this); } } @Override public Statement_type getType() { return Statement_type.S_GETCALL; } @Override public String getStatementName() { return STATEMENT_NAME; } @Override public StringBuilder getFullName(final INamedNode child) { final StringBuilder builder = super.getFullName(child); if (portReference == child) { return builder.append(FULLNAMEPART1); } else if (parameter == child) { return builder.append(FULLNAMEPART2); } else if (fromClause == child) { return builder.append(FULLNAMEPART3); } else if (redirectParameter == child) { return builder.append(FULLNAMEPART4); } else if (redirectSender == child) { return builder.append(FULLNAMEPART5); } return builder; } @Override public void setMyScope(final Scope scope) { super.setMyScope(scope); if (portReference != null) { portReference.setMyScope(scope); } if (parameter != null) { parameter.setMyScope(scope); } if (fromClause != null) { fromClause.setMyScope(scope); } if (redirectParameter != null) { redirectParameter.setMyScope(scope); } if (redirectSender != null) { redirectSender.setMyScope(scope); } } @Override public void check(final CompilationTimeStamp timestamp) { if (lastTimeChecked != null && !lastTimeChecked.isLess(timestamp)) { return; } checkGetcallStatement(timestamp, this, "getcall", portReference, parameter, fromClause, redirectParameter, redirectSender); if (redirectSender != null) { redirectSender.setUsedOnLeftHandSide(); } lastTimeChecked = timestamp; } public static void checkGetcallStatement(final CompilationTimeStamp timestamp, final Statement statement, final String statementName, final Reference portReference, final TemplateInstance parameter, final TemplateInstance fromClause, final Parameter_Redirect redirect, final Reference redirectSender) { final Port_Type portType = Port_Utility.checkPortReference(timestamp, statement, portReference); if (parameter == null) { if (portType != null) { final PortTypeBody body = portType.getPortBody(); if (OperationModes.OP_Message.equals(body.getOperationMode())) { portReference.getLocation().reportSemanticError( MessageFormat.format(MESSAGEBASEDPORT, statementName, portType.getTypename())); } else if (body.getInSignatures() == null) { portReference.getLocation().reportSemanticError(MessageFormat.format(NOINSIGNATURES, portType.getTypename())); } } if (redirect != null) { redirect.getLocation().reportSemanticError(REDIRECTWITHOUTSIGNATURE); redirect.checkErroneous(timestamp); } } else { IType signature = null; boolean signatureDetermined = false; if (portType != null) { final PortTypeBody body = portType.getPortBody(); final TypeSet inSignatures = body.getInSignatures(); if (OperationModes.OP_Message.equals(body.getOperationMode())) { portReference.getLocation().reportSemanticError( MessageFormat.format(MESSAGEBASEDPORT, statementName, portType.getTypename())); } else if (inSignatures != null) { if (inSignatures.getNofTypes() == 1) { signature = inSignatures.getTypeByIndex(0); } else { signature = Port_Utility.getOutgoingType(timestamp, parameter); if (signature == null) { parameter.getLocation().reportSemanticError(UNKNOWNSIGNATURETYPE); } else { if (!inSignatures.hasType(timestamp, signature)) { parameter.getLocation().reportSemanticError( MessageFormat.format(SIGNATURENOTPRESENT, signature.getTypename(), portType.getTypename())); } } } signatureDetermined = true; } else { portReference.getLocation().reportSemanticError(MessageFormat.format(NOINSIGNATURES, portType.getTypename())); } } else if (portReference == null) { // any port is referenced, or there was a syntax // error parameter.getLocation().reportSemanticError(MessageFormat.format(ANYWITHPARAMETER, statementName)); if (redirect != null) { redirect.getLocation().reportSemanticError(MessageFormat.format(ANYWITHREDIRECT, statementName)); } } if (!signatureDetermined) { signature = Port_Utility.getOutgoingType(timestamp, parameter); } if (signature != null) { parameter.check(timestamp, signature); signature = signature.getTypeRefdLast(timestamp); switch (signature.getTypetype()) { case TYPE_SIGNATURE: ((Signature_Type) signature).checkThisTemplate(timestamp, parameter.getTemplateBody(), false, false); if (redirect != null) { redirect.check(timestamp, (Signature_Type) signature, false); } break; default: parameter.getLocation().reportSemanticError( MessageFormat.format(SIGNATUREPARAMETEREXPECTED, signature.getTypename())); if (redirect != null) { redirect.checkErroneous(timestamp); } break; } } } Port_Utility.checkFromClause(timestamp, statement, portType, fromClause, redirectSender); } @Override public List<Integer> getPossibleExtensionStarterTokens() { if (redirectSender != null) { return null; } final List<Integer> result = new ArrayList<Integer>(); result.add(Ttcn3Lexer.SENDER); if (redirectParameter != null) { return result; } result.add(Ttcn3Lexer.PORTREDIRECTSYMBOL); if (fromClause != null) { return result; } result.add(Ttcn3Lexer.FROM); if (parameter != null) { return result; } result.add(Ttcn3Lexer.LPAREN); return result; } @Override public void updateSyntax(final TTCN3ReparseUpdater reparser, final boolean isDamaged) throws ReParseException { if (isDamaged) { throw new ReParseException(); } if (portReference != null) { portReference.updateSyntax(reparser, false); reparser.updateLocation(portReference.getLocation()); } if (parameter != null) { parameter.updateSyntax(reparser, false); reparser.updateLocation(parameter.getLocation()); } if (fromClause != null) { fromClause.updateSyntax(reparser, false); reparser.updateLocation(fromClause.getLocation()); } if (redirectParameter != null) { redirectParameter.updateSyntax(reparser, false); reparser.updateLocation(redirectParameter.getLocation()); } if (redirectSender != null) { redirectSender.updateSyntax(reparser, false); reparser.updateLocation(redirectSender.getLocation()); } } @Override public void findReferences(final ReferenceFinder referenceFinder, final List<Hit> foundIdentifiers) { if (portReference != null) { portReference.findReferences(referenceFinder, foundIdentifiers); } if (parameter != null) { parameter.findReferences(referenceFinder, foundIdentifiers); } if (fromClause != null) { fromClause.findReferences(referenceFinder, foundIdentifiers); } if (redirectParameter != null) { redirectParameter.findReferences(referenceFinder, foundIdentifiers); } if (redirectSender != null) { redirectSender.findReferences(referenceFinder, foundIdentifiers); } } @Override protected boolean memberAccept(final ASTVisitor v) { if (portReference != null && !portReference.accept(v)) { return false; } if (parameter != null && !parameter.accept(v)) { return false; } if (fromClause != null && !fromClause.accept(v)) { return false; } if (redirectParameter != null && !redirectParameter.accept(v)) { return false; } if (redirectSender != null && !redirectSender.accept(v)) { return false; } return true; } }
epl-1.0
asupdev/asup
org.asup.os.type.module/src/org/asup/os/type/module/QModule.java
2982
/** * Copyright (c) 2012, 2014 Sme.UP 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.asup.os.type.module; import java.net.URI; import org.asup.os.type.QTypedObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Module</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.asup.os.type.module.QModule#getAddress <em>Address</em>}</li> * <li>{@link org.asup.os.type.module.QModule#getSource <em>Source</em>}</li> * </ul> * </p> * * @see org.asup.os.type.module.QOperatingSystemModulePackage#getModule() * @model * @generated */ public interface QModule extends QTypedObject { /** * Returns the value of the '<em><b>Address</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Address</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Address</em>' attribute. * @see #setAddress(String) * @see org.asup.os.type.module.QOperatingSystemModulePackage#getModule_Address() * @model annotation="il-data length='128'" * @generated */ String getAddress(); /** * Sets the value of the '{@link org.asup.os.type.module.QModule#getAddress <em>Address</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Address</em>' attribute. * @see #getAddress() * @generated */ void setAddress(String value); /** * Returns the value of the '<em><b>Source</b></em>' containment reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Source</em>' containment reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Source</em>' containment reference. * @see #setSource(QModuleSource) * @see org.asup.os.type.module.QOperatingSystemModulePackage#getModule_Source() * @model containment="true" * @generated */ QModuleSource getSource(); /** * Sets the value of the '{@link org.asup.os.type.module.QModule#getSource <em>Source</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Source</em>' containment reference. * @see #getSource() * @generated */ void setSource(QModuleSource value); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model kind="operation" dataType="org.asup.fw.java.JavaURI" * @generated */ URI getClassURI(); /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @model kind="operation" dataType="org.asup.fw.java.JavaURI" * @generated */ URI getPackageInfoURI(); } // QModule
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/parser/antlr/Bug289524TestLanguageStandaloneSetupGenerated.java
1596
/* * generated by Xtext */ package org.eclipse.xtext.parser.antlr; import com.google.inject.Guice; import com.google.inject.Injector; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.xtext.ISetup; import org.eclipse.xtext.common.TerminalsStandaloneSetup; import org.eclipse.xtext.parser.antlr.bug289524Test.Bug289524TestPackage; import org.eclipse.xtext.resource.IResourceFactory; import org.eclipse.xtext.resource.IResourceServiceProvider; @SuppressWarnings("all") public class Bug289524TestLanguageStandaloneSetupGenerated implements ISetup { @Override public Injector createInjectorAndDoEMFRegistration() { TerminalsStandaloneSetup.doSetup(); Injector injector = createInjector(); register(injector); return injector; } public Injector createInjector() { return Guice.createInjector(new Bug289524TestLanguageRuntimeModule()); } public void register(Injector injector) { IResourceFactory resourceFactory = injector.getInstance(IResourceFactory.class); IResourceServiceProvider serviceProvider = injector.getInstance(IResourceServiceProvider.class); Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("bug289524testlanguage", resourceFactory); IResourceServiceProvider.Registry.INSTANCE.getExtensionToFactoryMap().put("bug289524testlanguage", serviceProvider); if (!EPackage.Registry.INSTANCE.containsKey("http://eclipse.org/xtext/Bug289524TestLanguage")) { EPackage.Registry.INSTANCE.put("http://eclipse.org/xtext/Bug289524TestLanguage", Bug289524TestPackage.eINSTANCE); } } }
epl-1.0
viatra/VIATRA-Generator
Tests/hu.bme.mit.inf.dslreasoner.application.FAMTest/src/functionalarchitecture/util/FunctionalarchitectureSwitch.java
10687
/** */ package functionalarchitecture.util; import functionalarchitecture.FAMTerminator; import functionalarchitecture.Function; import functionalarchitecture.FunctionalArchitectureModel; import functionalarchitecture.FunctionalData; import functionalarchitecture.FunctionalElement; import functionalarchitecture.FunctionalInput; import functionalarchitecture.FunctionalOutput; import functionalarchitecture.FunctionalarchitecturePackage; import functionalarchitecture.InformationLink; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see functionalarchitecture.FunctionalarchitecturePackage * @generated */ public class FunctionalarchitectureSwitch<T> extends Switch<T> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static FunctionalarchitecturePackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public FunctionalarchitectureSwitch() { if (modelPackage == null) { modelPackage = FunctionalarchitecturePackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case FunctionalarchitecturePackage.FUNCTIONAL_ELEMENT: { FunctionalElement functionalElement = (FunctionalElement)theEObject; T result = caseFunctionalElement(functionalElement); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FUNCTIONAL_ARCHITECTURE_MODEL: { FunctionalArchitectureModel functionalArchitectureModel = (FunctionalArchitectureModel)theEObject; T result = caseFunctionalArchitectureModel(functionalArchitectureModel); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FUNCTION: { Function function = (Function)theEObject; T result = caseFunction(function); if (result == null) result = caseFunctionalElement(function); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FAM_TERMINATOR: { FAMTerminator famTerminator = (FAMTerminator)theEObject; T result = caseFAMTerminator(famTerminator); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.INFORMATION_LINK: { InformationLink informationLink = (InformationLink)theEObject; T result = caseInformationLink(informationLink); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FUNCTIONAL_INTERFACE: { functionalarchitecture.FunctionalInterface functionalInterface = (functionalarchitecture.FunctionalInterface)theEObject; T result = caseFunctionalInterface(functionalInterface); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FUNCTIONAL_INPUT: { FunctionalInput functionalInput = (FunctionalInput)theEObject; T result = caseFunctionalInput(functionalInput); if (result == null) result = caseFunctionalData(functionalInput); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FUNCTIONAL_OUTPUT: { FunctionalOutput functionalOutput = (FunctionalOutput)theEObject; T result = caseFunctionalOutput(functionalOutput); if (result == null) result = caseFunctionalData(functionalOutput); if (result == null) result = defaultCase(theEObject); return result; } case FunctionalarchitecturePackage.FUNCTIONAL_DATA: { FunctionalData functionalData = (FunctionalData)theEObject; T result = caseFunctionalData(functionalData); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Functional Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Functional Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionalElement(FunctionalElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Functional Architecture Model</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Functional Architecture Model</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionalArchitectureModel(FunctionalArchitectureModel object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Function</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Function</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunction(Function object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>FAM Terminator</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>FAM Terminator</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFAMTerminator(FAMTerminator object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Information Link</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Information Link</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseInformationLink(InformationLink object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Functional Interface</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Functional Interface</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionalInterface(functionalarchitecture.FunctionalInterface object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Functional Input</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Functional Input</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionalInput(FunctionalInput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Functional Output</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Functional Output</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionalOutput(FunctionalOutput object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Functional Data</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Functional Data</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T caseFunctionalData(FunctionalData object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T defaultCase(EObject object) { return null; } } //FunctionalarchitectureSwitch
epl-1.0
kgibm/open-liberty
dev/com.ibm.ws.javaee.ddmodel/test/com/ibm/ws/javaee/ddmodel/web/WebFragmentTest.java
3404
/******************************************************************************* * Copyright (c) 2013, 2018 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.javaee.ddmodel.web; import org.junit.Test; import com.ibm.ws.javaee.dd.web.WebApp; import com.ibm.ws.javaee.ddmodel.DDParser; /** * Web fragment descriptor parsing unit tests. */ public class WebFragmentTest extends WebFragmentTestBase { // Servlet 3.0 cases ... // Parse 3.0. Do not parse 3.1 or 4.0. @Test public void testEE6WebFragment30() throws Exception { parse(webFragment30() + webFragmentTail()); } @Test public void testEE6WebFragment30OrderingElement() throws Exception { parse(webFragment30() + "<ordering>" + "</ordering>" + webFragmentTail()); } // The prohibition against having more than one ordering element // was added in JavaEE7. @Test public void testEE6WebFragment30OrderingDuplicates() throws Exception { parse(webFragment30() + "<ordering>" + "</ordering>" + "<ordering>" + "</ordering>" + webFragmentTail()); } @Test(expected = DDParser.ParseException.class) public void testEE6WebFragment31() throws Exception { parse(webFragment31() + webFragmentTail()); } @Test(expected = DDParser.ParseException.class) public void testEE6WebFragment40() throws Exception { parse(webFragment40() + webFragmentTail()); } // Servlet 3.1 cases ... // Parse 3.0 and 3.1. Do not parse 4.0. @Test() public void testEE7WebFragment30() throws Exception { parse(webFragment30() + webFragmentTail(), WebApp.VERSION_3_1); } @Test() public void testEE7WebFragment31() throws Exception { parse(webFragment31() + webFragmentTail(), WebApp.VERSION_3_1); } @Test(expected = DDParser.ParseException.class) public void testEE7WebFragment31OrderingDuplicates() throws Exception { parse(webFragment31() + "<ordering>" + "</ordering>" + "<ordering>" + "</ordering>" + webFragmentTail(), WebApp.VERSION_3_1); } @Test(expected = DDParser.ParseException.class) public void testEE7WebFragment40() throws Exception { parse(webFragment40() + webFragmentTail(), WebApp.VERSION_3_1); } // Servlet 4.0 cases ... // Parse everything. @Test() public void testEE8WebFragment30() throws Exception { parse(webFragment30() + webFragmentTail(), WebApp.VERSION_4_0); } @Test() public void testEE8WebFragment31() throws Exception { parse(webFragment31() + webFragmentTail(), WebApp.VERSION_4_0); } @Test() public void testEE8WebFragment40() throws Exception { parse(webFragment40() + webFragmentTail(), WebApp.VERSION_4_0); } // TODO: Other specific servlet 4.0 web fragment cases ... }
epl-1.0
ttimbul/eclipse.wst
bundles/org.eclipse.wst.xsd.ui/src-adt/org/eclipse/wst/xsd/ui/internal/adt/outline/ITreeElement.java
848
/******************************************************************************* * 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 *******************************************************************************/ package org.eclipse.wst.xsd.ui.internal.adt.outline; import org.eclipse.swt.graphics.Image; public interface ITreeElement { public final static ITreeElement[] EMPTY_LIST = {}; ITreeElement[] getChildren(); ITreeElement getParent(); boolean hasChildren(); String getText(); Image getImage(); }
epl-1.0
Kondi60PL/Pluginy-Minecraft-Bukkit
Wszystkie pluginy [1]/Tirex/TToolsEX source/com/gmail/tirexgta/ttoolsex/packet/WrapperPlayClientSettings.java
2296
package com.gmail.tirexgta.ttoolsex.packet; import com.comphenix.protocol.*; import com.comphenix.protocol.events.*; import com.comphenix.protocol.wrappers.*; public class WrapperPlayClientSettings extends AbstractPacket { public static final PacketType TYPE; static { TYPE = PacketType.Play.Client.SETTINGS; } public WrapperPlayClientSettings() { super(new PacketContainer(WrapperPlayClientSettings.TYPE), WrapperPlayClientSettings.TYPE); this.handle.getModifier().writeDefaults(); } public WrapperPlayClientSettings(final PacketContainer packet) { super(packet, WrapperPlayClientSettings.TYPE); } public String getLocale() { return (String)this.handle.getStrings().read(0); } public void setLocale(final String value) { this.handle.getStrings().write(0, (Object)value); } public byte getViewDistance() { return (byte)this.handle.getIntegers().read(0); } public void setViewDistance(final byte value) { this.handle.getIntegers().write(0, (Object)(int)value); } public EnumWrappers.ChatVisibility getChatVisibility() { return (EnumWrappers.ChatVisibility)this.handle.getChatVisibilities().read(0); } public void setChatFlags(final EnumWrappers.ChatVisibility value) { this.handle.getChatVisibilities().write(0, (Object)value); } public boolean getChatColours() { return (boolean)this.handle.getSpecificModifier((Class)Boolean.TYPE).read(0); } public void setChatColours(final boolean value) { this.handle.getSpecificModifier((Class)Boolean.TYPE).write(0, (Object)value); } public EnumWrappers.Difficulty getDifficulty() { return (EnumWrappers.Difficulty)this.handle.getDifficulties().read(0); } public void setDifficulty(final EnumWrappers.Difficulty difficulty) { this.handle.getDifficulties().write(0, (Object)difficulty); } public boolean getShowCape() { return (boolean)this.handle.getSpecificModifier((Class)Boolean.TYPE).read(1); } public void setShowCape(final boolean value) { this.handle.getSpecificModifier((Class)Boolean.TYPE).write(1, (Object)value); } }
epl-1.0
dhuebner/che
core/ide/che-core-ide-app/src/main/java/org/eclipse/che/ide/projectimport/wizard/ProjectNotificationSubscriberImpl.java
7549
/******************************************************************************* * 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.projectimport.wizard; import com.google.gwt.json.client.JSONObject; import com.google.gwt.json.client.JSONParser; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.che.api.machine.gwt.client.WsAgentStateController; import org.eclipse.che.api.promises.client.Operation; import org.eclipse.che.api.promises.client.OperationException; import org.eclipse.che.api.promises.client.Promise; import org.eclipse.che.api.promises.client.PromiseError; import org.eclipse.che.ide.CoreLocalizationConstant; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.notification.NotificationManager; import org.eclipse.che.ide.api.notification.StatusNotification; import org.eclipse.che.ide.api.project.wizard.ProjectNotificationSubscriber; import org.eclipse.che.ide.commons.exception.UnmarshallerException; import org.eclipse.che.ide.util.loging.Log; import org.eclipse.che.ide.websocket.Message; import org.eclipse.che.ide.websocket.MessageBus; import org.eclipse.che.ide.websocket.WebSocketException; import org.eclipse.che.ide.websocket.rest.SubscriptionHandler; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.FAIL; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.PROGRESS; import static org.eclipse.che.ide.api.notification.StatusNotification.Status.SUCCESS; /** * Subscribes on import project notifications. * It can be produced by {@code ImportProjectNotificationSubscriberFactory} * * @author Anton Korneta */ @Singleton public class ProjectNotificationSubscriberImpl implements ProjectNotificationSubscriber { private final Operation<PromiseError> logErrorHandler; private final CoreLocalizationConstant locale; private final NotificationManager notificationManager; private final String workspaceId; private final Promise<MessageBus> messageBusPromise; private String wsChannel; private String projectName; private StatusNotification notification; private SubscriptionHandler<String> subscriptionHandler; @Inject public ProjectNotificationSubscriberImpl(CoreLocalizationConstant locale, AppContext appContext, NotificationManager notificationManager, WsAgentStateController wsAgentStateController) { this.locale = locale; this.notificationManager = notificationManager; this.workspaceId = appContext.getWorkspace().getId(); this.messageBusPromise = wsAgentStateController.getMessageBus(); this.logErrorHandler = new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { Log.error(ProjectNotificationSubscriberImpl.class, error); } }; } @Override public void subscribe(final String projectName) { notification = notificationManager.notify(locale.importingProject(), PROGRESS, true); subscribe(projectName, notification); } @Override public void subscribe(final String projectName, final StatusNotification existingNotification) { this.projectName = projectName; this.wsChannel = "importProject:output:" + workspaceId + ":" + projectName; this.notification = existingNotification; this.subscriptionHandler = new SubscriptionHandler<String>(new LineUnmarshaller()) { @Override protected void onMessageReceived(String result) { notification.setContent(result); } @Override protected void onErrorReceived(final Throwable throwable) { messageBusPromise.then(new Operation<MessageBus>() { @Override public void apply(MessageBus messageBus) throws OperationException { try { messageBus.unsubscribe(wsChannel, subscriptionHandler); } catch (WebSocketException e) { Log.error(getClass(), e); } notification.setTitle(locale.importProjectMessageFailure(projectName)); notification.setContent(""); notification.setStatus(FAIL); Log.error(getClass(), throwable); } }).catchError(logErrorHandler); } }; messageBusPromise.then(new Operation<MessageBus>() { @Override public void apply(final MessageBus messageBus) throws OperationException { try { messageBus.subscribe(wsChannel, subscriptionHandler); } catch (WebSocketException wsEx) { Log.error(ProjectNotificationSubscriberImpl.class, wsEx); } } }).catchError(logErrorHandler); } @Override public void onSuccess() { messageBusPromise.then(new Operation<MessageBus>() { @Override public void apply(MessageBus messageBus) throws OperationException { try { messageBus.unsubscribe(wsChannel, subscriptionHandler); } catch (WebSocketException e) { Log.error(getClass(), e); } notification.setStatus(SUCCESS); notification.setTitle(locale.importProjectMessageSuccess(projectName)); notification.setContent(""); } }).catchError(logErrorHandler); } @Override public void onFailure(final String errorMessage) { messageBusPromise.then(new Operation<MessageBus>() { @Override public void apply(MessageBus messageBus) throws OperationException { try { messageBus.unsubscribe(wsChannel, subscriptionHandler); } catch (WebSocketException e) { Log.error(getClass(), e); } notification.setStatus(FAIL); notification.setContent(errorMessage); } }).catchError(logErrorHandler); } static class LineUnmarshaller implements org.eclipse.che.ide.websocket.rest.Unmarshallable<String> { private String line; @Override public void unmarshal(Message response) throws UnmarshallerException { JSONObject jsonObject = JSONParser.parseStrict(response.getBody()).isObject(); if (jsonObject == null) { return; } if (jsonObject.containsKey("line")) { line = jsonObject.get("line").isString().stringValue(); } } @Override public String getPayload() { return line; } } }
epl-1.0
sebastiangoetz/slr-toolkit
plugins/de.tudresden.slr.ui.chart/src/de/tudresden/slr/ui/chart/logic/BubbleChartGenerator3.java
16375
package de.tudresden.slr.ui.chart.logic; import java.util.List; import java.util.OptionalInt; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import org.eclipse.birt.chart.model.Chart; import org.eclipse.birt.chart.model.ChartWithAxes; import org.eclipse.birt.chart.model.attribute.AxisType; import org.eclipse.birt.chart.model.attribute.IntersectionType; import org.eclipse.birt.chart.model.attribute.LegendItemType; import org.eclipse.birt.chart.model.attribute.MarkerType; import org.eclipse.birt.chart.model.attribute.Position; import org.eclipse.birt.chart.model.attribute.TickStyle; import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl; import org.eclipse.birt.chart.model.component.Axis; import org.eclipse.birt.chart.model.component.Scale; import org.eclipse.birt.chart.model.component.Series; import org.eclipse.birt.chart.model.component.impl.SeriesImpl; import org.eclipse.birt.chart.model.data.BaseSampleData; import org.eclipse.birt.chart.model.data.DataFactory; import org.eclipse.birt.chart.model.data.OrthogonalSampleData; import org.eclipse.birt.chart.model.data.SampleData; import org.eclipse.birt.chart.model.data.SeriesDefinition; import org.eclipse.birt.chart.model.data.TextDataSet; import org.eclipse.birt.chart.model.data.impl.NumberDataElementImpl; import org.eclipse.birt.chart.model.data.impl.NumberDataSetImpl; import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl; import org.eclipse.birt.chart.model.data.impl.TextDataSetImpl; import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl; import org.eclipse.birt.chart.model.layout.Legend; import org.eclipse.birt.chart.model.layout.Plot; import org.eclipse.birt.chart.model.type.BubbleSeries; import org.eclipse.birt.chart.model.type.impl.BubbleSeriesImpl; import de.tudresden.slr.model.taxonomy.Term; /** * */ public class BubbleChartGenerator3 { public final Chart createBubble(List<BubbleDataContainer> input, Term first, Term second ) { StringBuilder jsScript = new StringBuilder(); ChartWithAxes cwaBubble = ChartWithAxesImpl.create( ); cwaBubble.setType( "Bubble Chart" ); //$NON-NLS-1$ cwaBubble.setSubType( "Standard Bubble Chart" ); //$NON-NLS-1$ // Plot cwaBubble.getBlock( ).setBackground( ColorDefinitionImpl.WHITE( ) ); cwaBubble.getBlock( ).getOutline( ).setVisible( true ); Plot p = cwaBubble.getPlot( ); p.getClientArea( ).setBackground( ColorDefinitionImpl.create( 255, 255, 225 ) ); // Title cwaBubble.getTitle( ) .getLabel( ) .getCaption( ) .setValue( "Bubble Chart" ); //$NON-NLS-1$ // Legend Legend lg = cwaBubble.getLegend( ); lg.setItemType( LegendItemType.SERIES_LITERAL ); // X-Axis Axis xAxisPrimary = cwaBubble.getPrimaryBaseAxes( )[0]; xAxisPrimary.setType( AxisType.TEXT_LITERAL ); xAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.BELOW_LITERAL ); xAxisPrimary.getMajorGrid().getLineAttributes().setVisible(true); xAxisPrimary.getOrigin( ).setType( IntersectionType.MIN_LITERAL ); Scale xScale = xAxisPrimary.getScale(); long numberOfXTerms = input.stream().map(x -> x.getxTerm().getName()).distinct().count(); xScale.setStep(1); xScale.setMin(NumberDataElementImpl.create(0)); xScale.setMax(NumberDataElementImpl.create(numberOfXTerms)); xScale.setMinorGridsPerUnit(2); xAxisPrimary.getLabel().getCaption().getFont().setRotation(45); if(numberOfXTerms > 15){ xAxisPrimary.getLabel().getCaption().getFont().setRotation(90); } //TODO: Find a more intelligent way to set the rotation... //Rotate labels even further if we have many bars xAxisPrimary.getLabel().getCaption().getFont().setName("Arial"); // Y-Axis Axis yAxisPrimary = cwaBubble.getPrimaryOrthogonalAxis( xAxisPrimary ); yAxisPrimary.getMajorGrid( ).setTickStyle( TickStyle.LEFT_LITERAL ); yAxisPrimary.getOrigin().setType(IntersectionType.MIN_LITERAL); yAxisPrimary.getMajorGrid().getLineAttributes().setVisible(true); yAxisPrimary.setType( AxisType.LINEAR_LITERAL); yAxisPrimary.setLabelPosition(Position.LEFT_LITERAL); yAxisPrimary.getLabel().getCaption().getFont().setWordWrap(true); yAxisPrimary.getLabel( ).getCaption( ).getFont( ).setRotation( 90 ); long numberOfYTerms = input.stream().map(x -> x.getyTerm().getName()).distinct().count(); Scale yScale = yAxisPrimary.getScale(); yScale.setStep(1); yScale.setMin(NumberDataElementImpl.create(0)); yScale.setMax(NumberDataElementImpl.create(numberOfYTerms + 1.0)); if(numberOfYTerms <= 10){ yAxisPrimary.getLabel().getCaption().getFont().setRotation(45); yAxisPrimary.getLabel().getCaption().getFont().setName("Arial"); } //Label span defines the margin between axis and page border. //Setting a fixed value is far from ideal because it should depend //on the size of the labels. Automatic label span doesn't work, since labels are change with scripts. //The following is a bad approximation to ensure that labels aren't cut-off OptionalInt maxStringLength = input.stream().map(x -> x.getyTerm().getName().length()).mapToInt(Integer::intValue).max(); if(maxStringLength.isPresent()){ double factor = yAxisPrimary.getLabel().getCaption().getFont().getRotation() != 0 ? 1 : 1.4; double margin = maxStringLength.getAsInt() * 4.2 * factor; yAxisPrimary.setLabelSpan(margin >= 20 ? margin : 20); } else { yAxisPrimary.setLabelSpan(75); } // Data Set /*NumberDataSet categoryValues = NumberDataSetImpl.create( new double[] { 20,45,70,100,120,130 }); Set<String> xValues = new HashSet<String>(); for (BubbleDataContainer data : input) { xValues.add(data.getxTerm().getName()); } String[] xEntries = new String[xValues.size()]; xEntries = xValues.toArray(xEntries); TextDataSet xAxisValues = TextDataSetImpl.create(xEntries); for(String inp : xValues) { System.out.println(inp.toString()); } Set<String> yValues = new HashSet<String>(); for (BubbleDataContainer data : input) { yValues.add(data.getyTerm().getName()); } String[] yEntries = new String[yValues.size()]; yEntries = yValues.toArray(yEntries); String[] test= {"alle","test","ja","nein","jo"}; NumberDataSet yAxisValues = NumberDataSetImpl.create(test); */ //System.out.println(xAxisValues.toString()); /*System.out.println(input.toString()); for(BubbleDataContainer data: input) { System.out.println(data.getxTerm().toString()); System.out.println(data.getyTerm().toString()); System.out.println(data.getBubbleSize()); }*/ /*List<BubbleDataSet> bubbleEntries = new ArrayList<BubbleDataSet>(); for(BubbleDataContainer data : input) { bubbleEntries.add(BubbleDataSetImpl.create(new BubbleEntry(data.getxTerm(), data.getBubbleSize()))); }*/ /*for(BubbleDataSet series : bubbleEntries) { System.out.println(series.getValues().toString()); }*/ /*BubbleDataSet values1 = BubbleDataSetImpl.create( new BubbleEntry[]{ new BubbleEntry( "nein", 5,1 ), new BubbleEntry( "jo", Integer.valueOf( 3 ),2 ) } ); */ List<String> xTerms = createXTerms(input, jsScript); TextDataSet dsNumericValues1 = TextDataSetImpl.create(xTerms); OptionalInt maxValue = input.stream().mapToInt(x -> x.getBubbleSize()).max(); jsScript.append("var maxValue = " + maxValue.getAsInt() + ";\n"); SampleData sd = DataFactory.eINSTANCE.createSampleData( ); BaseSampleData sdBase = DataFactory.eINSTANCE.createBaseSampleData( ); sdBase.setDataSetRepresentation( "" );//$NON-NLS-1$lman sd.getBaseSampleData( ).add( sdBase ); OrthogonalSampleData sdOrthogonal1 = DataFactory.eINSTANCE.createOrthogonalSampleData( ); sdOrthogonal1.setDataSetRepresentation( "" );//$NON-NLS-1$ sdOrthogonal1.setSeriesDefinitionIndex( 0 ); sd.getOrthogonalSampleData( ).add( sdOrthogonal1 ); //cwaBubble.setSampleData( sd ); // X-Series Series seCategory = SeriesImpl.create( ); seCategory.setDataSet( dsNumericValues1); SeriesDefinition sdX = SeriesDefinitionImpl.create( ); sdX.getSeriesPalette( ).shift( 0 ); xAxisPrimary.getSeriesDefinitions( ).add( sdX ); sdX.getSeries( ).add( seCategory ); SeriesDefinition sdY = SeriesDefinitionImpl.create(); yAxisPrimary.getSeriesDefinitions().add(sdY); createYSeries(input, xTerms, sdY, jsScript); // Y-Series /*Series yCategory = SeriesImpl.create(); yCategory.setDataSet(yAxisValues);*/ /* BubbleSeries bs1 = (BubbleSeries) BubbleSeriesImpl.create( ); bs1.setDataSet( values1 ); bs1.getLabel( ).setVisible( true ); SeriesDefinition sdY = SeriesDefinitionImpl.create( ); sdY.getSeriesPalette( ).shift( -1 ); yAxisPrimary.getSeriesDefinitions( ).add( sdY ); sdY.getSeries( ).add( bs1 ); sdY.getSeriesPalette().getEntries().clear(); sdY.getSeriesPalette().getEntries().add(ColorDefinitionImpl.BLACK()); */ //Add JS appendJsScript(jsScript); cwaBubble.setScript(jsScript.toString()); System.out.println(xTerms); System.out.println(jsScript.toString()); return cwaBubble; } private List<String> createXTerms(List<BubbleDataContainer> input, StringBuilder jsScript) { List<String> xTerms = input.stream().map(x -> x.getxTerm().getName()).distinct().sorted().collect(Collectors.toList()); jsScript.append("\n"); jsScript.append("var seriesLength = " + xTerms.size() + ";\n"); jsScript.append("var columns = " + xTerms.size() + ";\n"); return xTerms; } private void createYSeries(List<BubbleDataContainer> input, List<String> xTerms, SeriesDefinition sd, StringBuilder jsScript) { int xTermsLength = xTerms.size(); List<String> yTerms = input.stream().map(x -> x.getyTerm().getName()).distinct().sorted().collect(Collectors.toList()); StringBuilder jsLabels = new StringBuilder(); jsLabels.append("var labels = {\"0\" : \"\", "); jsScript.append("var rows = " + (yTerms.size() + 1) + ";\n"); jsScript.append("var seriesPosition = {"); int count = 1; for(String yTerm : yTerms){ BubbleSeries ss = (BubbleSeries) BubbleSeriesImpl.create( ); ss.getMarkers().stream().forEach(m -> m.setType(MarkerType.CIRCLE_LITERAL)); ss.getMarkers().stream().forEach(m -> m.getOutline().setColor(ColorDefinitionImpl.RED())); ss.getMarkers().stream().forEach(m -> m.getOutline().setThickness(20)); ss.getLabel().setVisible(true); //ss.setLabelPosition(Position.INSIDE_LITERAL); //System.out.println(ss.getLabel()); ss.setDataSet(NumberDataSetImpl.create(DoubleStream.iterate(count, i -> i).limit(xTermsLength).toArray())); String jsonKey = sanitizeJsonKey(yTerm); //System.out.println(jsonKey); //System.out.println(ss.getDataSet().toString()); ss.setSeriesIdentifier(jsonKey); sd.getSeries().add(ss); //System.out.println(sd.getSeries().toString()); sd.getSeriesPalette().getEntries().clear(); sd.getSeriesPalette().getEntries().add(ColorDefinitionImpl.WHITE()); sd.getSeriesPalette().getEntries().add(ColorDefinitionImpl.WHITE()); sd.getSeriesPalette().getEntries().add(ColorDefinitionImpl.WHITE()); sd.getSeriesPalette().getEntries().add(ColorDefinitionImpl.WHITE()); jsScript.append("\"" + jsonKey +"\": ["); input.stream().filter(x -> x.getyTerm().getName().equals(yTerm)) .sorted((a, b) -> a.getxTerm().getName().compareTo(b.getxTerm().getName())) .mapToInt(y -> y.getBubbleSize()).forEach(z -> {jsScript.append(z); jsScript.append(",");}); jsScript.append("],"); jsLabels.append("\"" + count + "\": \""); jsLabels.append(yTerms.get(count - 1)); jsLabels.append("\", "); count++; } jsLabels.append("\"" + (yTerms.size() + 1) + "\": \"\"};\n"); jsScript.append("};\n"); jsScript.append(jsLabels); } /** * Sanitize term names (or any other string) for use as JSON key. * @param Any string * @return Sanitized string */ private String sanitizeJsonKey(String str) { return str.replaceAll("[^\\w]", "_"); } /** * Add JS code. * @param jsValues */ private void appendJsScript(StringBuilder jsValues) { jsValues.append("var count = 0;\n"); jsValues.append("var labelCount = 0;\n"); jsValues.append("var resizeFactor;\n"); jsValues.append("/**\n"); jsValues.append(" * Called before drawing each marker.\n"); jsValues.append(" * \n"); jsValues.append(" * @param marker\n"); jsValues.append(" * Marker\n"); jsValues.append(" * @param dph\n"); jsValues.append(" * DataPointHints\n"); jsValues.append(" * @param icsc\n"); jsValues.append(" * IChartScriptContext\n"); jsValues.append(" */\n"); jsValues.append("function beforeDrawMarker( marker, dph, icsc ) {\n"); jsValues.append("\tvar seriesValue = dph.getSeriesValue();\n"); jsValues.append("\tvar size = 1;\n"); jsValues.append("\tif(seriesPosition[seriesValue] != void 0 && seriesPosition[seriesValue][count%seriesLength] != void 0){\n"); jsValues.append("\t\tsize = seriesPosition[seriesValue][count%seriesLength];\n"); jsValues.append("\t}\n"); jsValues.append("\tif(resizeFactor == void 0){\n"); jsValues.append("\t\tvar chart = icsc.getChartInstance()\n"); jsValues.append("\t\tvar bounds = chart.getBlock().getBounds();\n"); jsValues.append("\t\tvar width = bounds.getWidth();\n"); jsValues.append("\t\tvar height = bounds.getHeight();\n"); jsValues.append("\t\tvar maxSize = width/columns;\n"); jsValues.append("\t\tif(height/rows < maxSize){\n"); jsValues.append("\t\t\tmaxSize = height/columns;\n"); jsValues.append("\t\t}\n"); jsValues.append("\t\n"); jsValues.append("\t\tresizeFactor = ((maxSize/2)/maxValue) * 0.9;\n"); jsValues.append("\t}\n"); jsValues.append("\tmarker.setSize(size * resizeFactor);\n"); jsValues.append("\tcount++;\n"); jsValues.append("\tmarker.getOutline().setThickness(20);\n"); jsValues.append("}\n"); jsValues.append("/**\n"); jsValues.append(" * Called before rendering each label on a given Axis.\n"); jsValues.append(" * \n"); jsValues.append(" * @param axis\n"); jsValues.append(" * Axis\n"); jsValues.append(" * @param label\n"); jsValues.append(" * Label\n"); jsValues.append(" * @param icsc\n"); jsValues.append(" * IChartScriptContext\n"); jsValues.append(" */\n"); jsValues.append("function beforeDrawAxisLabel( axis, label, icsc )\n"); jsValues.append("{\n"); jsValues.append("\tif(labels[label.getCaption().getValue()] != void 0){\n"); jsValues.append("\t\tlabel.getCaption().setValue(labels[label.getCaption().getValue()]);\n"); jsValues.append("\t}\n"); jsValues.append("}\n"); jsValues.append("/**\n"); jsValues.append(" * Called before rendering the label for each datapoint.\n"); jsValues.append(" * \n"); jsValues.append(" * @param dph\n"); jsValues.append(" * DataPointHints\n"); jsValues.append(" * @param label\n"); jsValues.append(" * Label\n"); jsValues.append(" * @param icsc\n"); jsValues.append(" * IChartScriptContext\n"); jsValues.append(" */\n"); jsValues.append("function beforeDrawDataPointLabel( dph, label, icsc )\n"); jsValues.append("{\n"); jsValues.append("\tvar seriesValue = dph.getSeriesValue();\n"); jsValues.append("\tvar size = void 0;\n"); jsValues.append("\tif(seriesPosition[seriesValue] != void 0 && seriesPosition[seriesValue][count%seriesLength] != void 0){\n"); jsValues.append("\t\tsize = seriesPosition[seriesValue][labelCount%seriesLength];\n"); jsValues.append("\t}\n"); jsValues.append("\tlabel.getCaption().setValue(size);\n"); jsValues.append("\t(size <= 10) && label.setVisible(false);\n"); jsValues.append("\t(size > 10) && label.setVisible(true);\n"); jsValues.append("\tlabelCount++;\n"); jsValues.append("\ticsc.getChartInstance().getSeries().setLabelPosition(Position.INSIDE_LITERAL);\n"); jsValues.append("}\n"); } }
epl-1.0
ControlSystemStudio/cs-studio
thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/dialect/resolver/BasicDialectResolver.java
2723
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA * */ package org.hibernate.dialect.resolver; import java.sql.DatabaseMetaData; import java.sql.SQLException; import org.hibernate.dialect.Dialect; import org.hibernate.HibernateException; /** * Intended as support for custom resolvers. * * @author Steve Ebersole */ public class BasicDialectResolver extends AbstractDialectResolver { public static final int VERSION_INSENSITIVE_VERSION = -9999; private final String matchingName; private final int matchingVersion; private final Class dialectClass; public BasicDialectResolver(String matchingName, Class dialectClass) { this( matchingName, VERSION_INSENSITIVE_VERSION, dialectClass ); } public BasicDialectResolver(String matchingName, int matchingVersion, Class dialectClass) { this.matchingName = matchingName; this.matchingVersion = matchingVersion; this.dialectClass = dialectClass; } protected final Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { final String databaseName = metaData.getDatabaseProductName(); final int databaseMajorVersion = metaData.getDatabaseMajorVersion(); if ( matchingName.equalsIgnoreCase( databaseName ) && ( matchingVersion == VERSION_INSENSITIVE_VERSION || matchingVersion == databaseMajorVersion ) ) { try { return ( Dialect ) dialectClass.newInstance(); } catch ( HibernateException e ) { // conceivable that the dialect ctor could throw HibernateExceptions, so don't re-wrap throw e; } catch ( Throwable t ) { throw new HibernateException( "Could not instantiate specified Dialect class [" + dialectClass.getName() + "]", t ); } } return null; } }
epl-1.0
lbchen/ODL
opendaylight/northbound/networkconfiguration/bridgedomain/src/main/java/org/opendaylight/controller/networkconfig/bridgedomain/northbound/BridgeDomainNorthboundApplication.java
969
/* * Copyright (c) 2013 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.controller.networkconfig.bridgedomain.northbound; import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; /** * Instance of javax.ws.rs.core.Application used to return the classes * that will be instantiated for JAXRS processing, this is necessary * because the package scanning in jersey doesn't yet work in OSGi * environment. * */ public class BridgeDomainNorthboundApplication extends Application { @Override public Set<Class<?>> getClasses() { Set<Class<?>> classes = new HashSet<Class<?>>(); classes.add(BridgeDomainNorthbound.class); return classes; } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.core/src/org/eclipse/jdt/internal/compiler/lookup/TypeVariableBinding.java
47394
/******************************************************************************* * Copyright (c) 2000, 2018 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 * Stephan Herrmann <stephan@cs.tu-berlin.de> - Contributions for * bug 282152 - [1.5][compiler] Generics code rejected by Eclipse but accepted by javac * bug 349326 - [1.7] new warning for missing try-with-resources * bug 359362 - FUP of bug 349326: Resource leak on non-Closeable resource * bug 358903 - Filter practically unimportant resource leak warnings * bug 395002 - Self bound generic class doesn't resolve bounds properly for wildcards for certain parametrisation. * bug 392384 - [1.8][compiler][null] Restore nullness info from type annotations in class files * Bug 415043 - [1.8][null] Follow-up re null type annotations after bug 392099 * Bug 417295 - [1.8[[null] Massage type annotated null analysis to gel well with deep encoded type bindings. * Bug 400874 - [1.8][compiler] Inference infrastructure should evolve to meet JLS8 18.x (Part G of JSR335 spec) * Bug 426792 - [1.8][inference][impl] generify new type inference engine * Bug 428019 - [1.8][compiler] Type inference failure with nested generic invocation. * Bug 429384 - [1.8][null] implement conformance rules for null-annotated lower / upper type bounds * Bug 431269 - [1.8][compiler][null] StackOverflow in nullAnnotatedReadableName * Bug 431408 - Java 8 (1.8) generics bug * Bug 435962 - [RC2] StackOverFlowError when building * Bug 438458 - [1.8][null] clean up handling of null type annotations wrt type variables * Bug 438250 - [1.8][null] NPE trying to report bogus null annotation conflict * Bug 438179 - [1.8][null] 'Contradictory null annotations' error on type variable with explicit null-annotation. * Bug 440143 - [1.8][null] one more case of contradictory null annotations regarding type variables * Bug 440759 - [1.8][null] @NonNullByDefault should never affect wildcards and uses of a type variable * Bug 441693 - [1.8][null] Bogus warning for type argument annotated with @NonNull * Bug 456497 - [1.8][null] during inference nullness from target type is lost against weaker hint from applicability analysis * Bug 456459 - Discrepancy between Eclipse compiler and javac - Enums, interfaces, and generics * Bug 456487 - [1.8][null] @Nullable type variant of @NonNull-constrained type parameter causes grief * Bug 462790 - [null] NPE in Expression.computeConversion() * Bug 456532 - [1.8][null] ReferenceBinding.appendNullAnnotation() includes phantom annotations in error messages * Jesper S Møller <jesper@selskabet.org> - Contributions for bug 381345 : [1.8] Take care of the Java 8 major version * Bug 527554 - [18.3] Compiler support for JEP 286 Local-Variable Type *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; import java.util.Set; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.NullAnnotationMatching; import org.eclipse.jdt.internal.compiler.ast.NullAnnotationMatching.CheckMode; import org.eclipse.jdt.internal.compiler.ast.TypeParameter; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.eclipse.jdt.internal.compiler.ast.Wildcard; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.lookup.TypeConstants.BoundCheckStatus; /** * Binding for a type parameter, held by source/binary type or method. */ public class TypeVariableBinding extends ReferenceBinding { public Binding declaringElement; // binding of declaring type or method public int rank; // declaration rank, can be used to match variable in parameterized type /** * Denote the first explicit (binding) bound amongst the supertypes (from declaration in source) * If no superclass was specified, then it denotes the first superinterface, or null if none was specified. */ public TypeBinding firstBound; // MUST NOT be modified directly, use setter ! // actual resolved variable supertypes (if no superclass bound, then associated to Object) public ReferenceBinding superclass; // MUST NOT be modified directly, use setter ! public ReferenceBinding[] superInterfaces; // MUST NOT be modified directly, use setter ! public char[] genericTypeSignature; LookupEnvironment environment; public TypeVariableBinding(char[] sourceName, Binding declaringElement, int rank, LookupEnvironment environment) { this.sourceName = sourceName; this.declaringElement = declaringElement; this.rank = rank; this.modifiers = ClassFileConstants.AccPublic | ExtraCompilerModifiers.AccGenericSignature; // treat type var as public this.tagBits |= TagBits.HasTypeVariable; this.environment = environment; this.typeBits = TypeIds.BitUninitialized; computeId(environment); } // for subclass CaptureBinding protected TypeVariableBinding(char[] sourceName, LookupEnvironment environment) { this.sourceName = sourceName; this.modifiers = ClassFileConstants.AccPublic | ExtraCompilerModifiers.AccGenericSignature; // treat type var as public this.tagBits |= TagBits.HasTypeVariable; this.environment = environment; this.typeBits = TypeIds.BitUninitialized; // don't yet compute the ID! } public TypeVariableBinding(TypeVariableBinding prototype) { super(prototype); this.declaringElement = prototype.declaringElement; this.rank = prototype.rank; this.firstBound = prototype.firstBound; this.superclass = prototype.superclass; if (prototype.superInterfaces != null) { int len = prototype.superInterfaces.length; if (len > 0) System.arraycopy(prototype.superInterfaces, 0, this.superInterfaces = new ReferenceBinding[len], 0, len); else this.superInterfaces = Binding.NO_SUPERINTERFACES; } this.genericTypeSignature = prototype.genericTypeSignature; this.environment = prototype.environment; prototype.tagBits |= TagBits.HasAnnotatedVariants; this.tagBits &= ~TagBits.HasAnnotatedVariants; } /** * Returns true if the argument type satisfies all bounds of the type parameter * @param location if non-null this may be used for reporting errors relating to null type annotations (if enabled) */ public TypeConstants.BoundCheckStatus boundCheck(Substitution substitution, TypeBinding argumentType, Scope scope, ASTNode location) { TypeConstants.BoundCheckStatus code = internalBoundCheck(substitution, argumentType, scope, location); if (code == BoundCheckStatus.MISMATCH) { if (argumentType instanceof TypeVariableBinding && scope != null) { TypeBinding bound = ((TypeVariableBinding)argumentType).firstBound; if (bound instanceof ParameterizedTypeBinding) { BoundCheckStatus code2 = boundCheck(substitution, bound.capture(scope, -1, -1), scope, location); // no capture position needed as this capture will never escape this context return code.betterOf(code2); } } } return code; } private TypeConstants.BoundCheckStatus internalBoundCheck(Substitution substitution, TypeBinding argumentType, Scope scope, ASTNode location) { if (argumentType == TypeBinding.NULL || TypeBinding.equalsEquals(argumentType, this)) { return BoundCheckStatus.OK; } boolean hasSubstitution = substitution != null; if (!(argumentType instanceof ReferenceBinding || argumentType.isArrayType())) return BoundCheckStatus.MISMATCH; // special case for re-entrant source types (selection, code assist, etc)... // can request additional types during hierarchy walk that are found as source types that also 'need' to connect their hierarchy if (this.superclass == null) return BoundCheckStatus.OK; BoundCheckStatus nullStatus = BoundCheckStatus.OK; boolean checkNullAnnotations = scope.environment().usesNullTypeAnnotations() && (location == null || (location.bits & ASTNode.InsideJavadoc) == 0); if (argumentType.kind() == Binding.WILDCARD_TYPE) { WildcardBinding wildcard = (WildcardBinding) argumentType; switch(wildcard.boundKind) { case Wildcard.EXTENDS : boolean checkedAsOK = false; TypeBinding wildcardBound = wildcard.bound; if (TypeBinding.equalsEquals(wildcardBound, this)) checkedAsOK = true; // OK per JLS, but may require null checking below boolean isArrayBound = wildcardBound.isArrayType(); if (!wildcardBound.isInterface()) { TypeBinding substitutedSuperType = hasSubstitution ? Scope.substitute(substitution, this.superclass) : this.superclass; if (!checkedAsOK) { if (substitutedSuperType.id != TypeIds.T_JavaLangObject) { if (isArrayBound) { if (!wildcardBound.isCompatibleWith(substitutedSuperType, scope)) return BoundCheckStatus.MISMATCH; } else { TypeBinding match = wildcardBound.findSuperTypeOriginatingFrom(substitutedSuperType); if (match != null) { if (substitutedSuperType.isProvablyDistinct(match)) { return BoundCheckStatus.MISMATCH; } } else { match = substitutedSuperType.findSuperTypeOriginatingFrom(wildcardBound); if (match != null) { if (match.isProvablyDistinct(wildcardBound)) { return BoundCheckStatus.MISMATCH; } } else { if (denotesRelevantSuperClass(wildcardBound) && denotesRelevantSuperClass(substitutedSuperType)) { // non-object real superclass should have produced a valid 'match' above return BoundCheckStatus.MISMATCH; } // not fully spec-ed in JLS, but based on email communication (2017-09-13): // (a) bound check should apply capture // (b) capture applies glb // (c) and then the glb should be checked for well-formedness (see Scope.isMalformedPair() - this part missing in JLS). // Since we don't do (a), nor (b) for this case, we just directly proceed to (b) here. // For (a) see ParameterizedTypeBinding.boundCheck() - comment added as of this commit // for (b) see CaptureBinding.initializeBounds() - comment added as of this commit if (Scope.greaterLowerBound(new TypeBinding[] {substitutedSuperType, wildcardBound}, scope, this.environment) == null) { return BoundCheckStatus.MISMATCH; } } } } } } if (checkNullAnnotations && argumentType.hasNullTypeAnnotations()) { nullStatus = nullBoundCheck(scope, argumentType, substitutedSuperType, substitution, location, nullStatus); } } boolean mustImplement = isArrayBound || ((ReferenceBinding)wildcardBound).isFinal(); for (int i = 0, length = this.superInterfaces.length; i < length; i++) { TypeBinding substitutedSuperType = hasSubstitution ? Scope.substitute(substitution, this.superInterfaces[i]) : this.superInterfaces[i]; if (!checkedAsOK) { if (isArrayBound) { if (!wildcardBound.isCompatibleWith(substitutedSuperType, scope)) return BoundCheckStatus.MISMATCH; } else { TypeBinding match = wildcardBound.findSuperTypeOriginatingFrom(substitutedSuperType); if (match != null) { if (substitutedSuperType.isProvablyDistinct(match)) { return BoundCheckStatus.MISMATCH; } } else if (mustImplement) { return BoundCheckStatus.MISMATCH; // cannot be extended further to satisfy missing bounds } } } if (checkNullAnnotations && argumentType.hasNullTypeAnnotations()) { nullStatus = nullBoundCheck(scope, argumentType, substitutedSuperType, substitution, location, nullStatus); } } if (nullStatus != null) return nullStatus; break; case Wildcard.SUPER : // if the wildcard is lower-bounded by a type variable that has no relevant upper bound there's nothing to check here (bug 282152): if (wildcard.bound.isTypeVariable() && ((TypeVariableBinding)wildcard.bound).superclass.id == TypeIds.T_JavaLangObject) { return nullBoundCheck(scope, argumentType, null, substitution, location, nullStatus); } else { TypeBinding bound = wildcard.bound; if (checkNullAnnotations && this.environment.containsNullTypeAnnotation(wildcard.typeAnnotations)) bound = this.environment.createAnnotatedType(bound.withoutToplevelNullAnnotation(), wildcard.getTypeAnnotations()); BoundCheckStatus status = boundCheck(substitution, bound, scope, null); // do not report null-errors against the tweaked bound ... if (status == BoundCheckStatus.NULL_PROBLEM && location != null) scope.problemReporter().nullityMismatchTypeArgument(this, wildcard, location); // ... but against the wildcard return status; } case Wildcard.UNBOUND : if (checkNullAnnotations && argumentType.hasNullTypeAnnotations()) { return nullBoundCheck(scope, argumentType, null, substitution, location, nullStatus); } break; } return BoundCheckStatus.OK; } boolean unchecked = false; if (this.superclass.id != TypeIds.T_JavaLangObject) { TypeBinding substitutedSuperType = hasSubstitution ? Scope.substitute(substitution, this.superclass) : this.superclass; if (TypeBinding.notEquals(substitutedSuperType, argumentType)) { if (!argumentType.isCompatibleWith(substitutedSuperType, scope)) { return BoundCheckStatus.MISMATCH; } TypeBinding match = argumentType.findSuperTypeOriginatingFrom(substitutedSuperType); if (match != null){ // Enum#RAW is not a substitute for <E extends Enum<E>> (86838) if (match.isRawType() && substitutedSuperType.isBoundParameterizedType()) unchecked = true; } } if (checkNullAnnotations) { nullStatus = nullBoundCheck(scope, argumentType, substitutedSuperType, substitution, location, nullStatus); } } for (int i = 0, length = this.superInterfaces.length; i < length; i++) { TypeBinding substitutedSuperType = hasSubstitution ? Scope.substitute(substitution, this.superInterfaces[i]) : this.superInterfaces[i]; if (TypeBinding.notEquals(substitutedSuperType, argumentType)) { if (!argumentType.isCompatibleWith(substitutedSuperType, scope)) { return BoundCheckStatus.MISMATCH; } TypeBinding match = argumentType.findSuperTypeOriginatingFrom(substitutedSuperType); if (match != null){ // Enum#RAW is not a substitute for <E extends Enum<E>> (86838) if (match.isRawType() && substitutedSuperType.isBoundParameterizedType()) unchecked = true; } } if (checkNullAnnotations) { nullStatus = nullBoundCheck(scope, argumentType, substitutedSuperType, substitution, location, nullStatus); } } if (checkNullAnnotations && nullStatus != BoundCheckStatus.NULL_PROBLEM) { long nullBits = this.tagBits & TagBits.AnnotationNullMASK; if (nullBits != 0 && nullBits != (argumentType.tagBits & TagBits.AnnotationNullMASK)) { if (location != null) scope.problemReporter().nullityMismatchTypeArgument(this, argumentType, location); nullStatus = BoundCheckStatus.NULL_PROBLEM; } } return unchecked ? BoundCheckStatus.UNCHECKED : nullStatus != null ? nullStatus : BoundCheckStatus.OK; } private BoundCheckStatus nullBoundCheck(Scope scope, TypeBinding argumentType, TypeBinding substitutedSuperType, Substitution substitution, ASTNode location, BoundCheckStatus previousStatus) { if (NullAnnotationMatching.analyse(this, argumentType, substitutedSuperType, substitution, -1, null, CheckMode.BOUND_CHECK).isAnyMismatch()) { if (location != null) scope.problemReporter().nullityMismatchTypeArgument(this, argumentType, location); return BoundCheckStatus.NULL_PROBLEM; } return previousStatus; } boolean denotesRelevantSuperClass(TypeBinding type) { if (!type.isTypeVariable() && !type.isInterface() && type.id != TypeIds.T_JavaLangObject) return true; ReferenceBinding aSuperClass = type.superclass(); return aSuperClass != null && aSuperClass.id != TypeIds.T_JavaLangObject && !aSuperClass.isTypeVariable(); } public int boundsCount() { if (this.firstBound == null) return 0; if (this.firstBound.isInterface()) return this.superInterfaces.length; // only interface bounds return this.superInterfaces.length + 1; // class or array type isn't contained in superInterfaces } /** * @see org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding#canBeInstantiated() */ public boolean canBeInstantiated() { return false; } /** * Collect the substitutes into a map for certain type variables inside the receiver type * e.g. Collection<T>.collectSubstitutes(Collection<List<X>>, Map), will populate Map with: T --> List<X> * Constraints: * A << F corresponds to: F.collectSubstitutes(..., A, ..., CONSTRAINT_EXTENDS (1)) * A = F corresponds to: F.collectSubstitutes(..., A, ..., CONSTRAINT_EQUAL (0)) * A >> F corresponds to: F.collectSubstitutes(..., A, ..., CONSTRAINT_SUPER (2)) */ public void collectSubstitutes(Scope scope, TypeBinding actualType, InferenceContext inferenceContext, int constraint) { // only infer for type params of the generic method if (this.declaringElement != inferenceContext.genericMethod) return; // cannot infer anything from a null type switch (actualType.kind()) { case Binding.BASE_TYPE : if (actualType == TypeBinding.NULL) return; TypeBinding boxedType = scope.environment().computeBoxingType(actualType); if (boxedType == actualType) return; //$IDENTITY-COMPARISON$ actualType = boxedType; break; case Binding.POLY_TYPE: // cannot steer inference, only learn from it. case Binding.WILDCARD_TYPE : return; // wildcards are not true type expressions (JLS 15.12.2.7, p.453 2nd discussion) } // reverse constraint, to reflect variable on rhs: A << T --> T >: A int variableConstraint; switch(constraint) { case TypeConstants.CONSTRAINT_EQUAL : variableConstraint = TypeConstants.CONSTRAINT_EQUAL; break; case TypeConstants.CONSTRAINT_EXTENDS : variableConstraint = TypeConstants.CONSTRAINT_SUPER; break; default: //case CONSTRAINT_SUPER : variableConstraint =TypeConstants.CONSTRAINT_EXTENDS; break; } inferenceContext.recordSubstitute(this, actualType, variableConstraint); } /* * declaringUniqueKey : genericTypeSignature * p.X<T> { ... } --> Lp/X;:TT; * p.X { <T> void foo() {...} } --> Lp/X;.foo()V:TT; */ public char[] computeUniqueKey(boolean isLeaf) { StringBuffer buffer = new StringBuffer(); Binding declaring = this.declaringElement; if (!isLeaf && declaring.kind() == Binding.METHOD) { // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=97902 MethodBinding methodBinding = (MethodBinding) declaring; ReferenceBinding declaringClass = methodBinding.declaringClass; buffer.append(declaringClass.computeUniqueKey(false/*not a leaf*/)); buffer.append(':'); MethodBinding[] methods = declaringClass.methods(); if (methods != null) for (int i = 0, length = methods.length; i < length; i++) { MethodBinding binding = methods[i]; if (binding == methodBinding) { buffer.append(i); break; } } } else { buffer.append(declaring.computeUniqueKey(false/*not a leaf*/)); buffer.append(':'); } buffer.append(genericTypeSignature()); int length = buffer.length(); char[] uniqueKey = new char[length]; buffer.getChars(0, length, uniqueKey, 0); return uniqueKey; } public char[] constantPoolName() { /* java/lang/Object */ if (this.firstBound != null) { return this.firstBound.constantPoolName(); } return this.superclass.constantPoolName(); // java/lang/Object } public TypeBinding clone(TypeBinding enclosingType) { return new TypeVariableBinding(this); } public String annotatedDebugName() { StringBuffer buffer = new StringBuffer(10); buffer.append(super.annotatedDebugName()); if (!this.inRecursiveFunction) { this.inRecursiveFunction = true; try { if (this.superclass != null && TypeBinding.equalsEquals(this.firstBound, this.superclass)) { buffer.append(" extends ").append(this.superclass.annotatedDebugName()); //$NON-NLS-1$ } if (this.superInterfaces != null && this.superInterfaces != Binding.NO_SUPERINTERFACES) { if (TypeBinding.notEquals(this.firstBound, this.superclass)) { buffer.append(" extends "); //$NON-NLS-1$ } for (int i = 0, length = this.superInterfaces.length; i < length; i++) { if (i > 0 || TypeBinding.equalsEquals(this.firstBound, this.superclass)) { buffer.append(" & "); //$NON-NLS-1$ } buffer.append(this.superInterfaces[i].annotatedDebugName()); } } } finally { this.inRecursiveFunction = false; } } return buffer.toString(); } /** * @see org.eclipse.jdt.internal.compiler.lookup.TypeBinding#debugName() */ public String debugName() { if (this.hasTypeAnnotations()) return super.annotatedDebugName(); return new String(this.sourceName); } public TypeBinding erasure() { if (this.firstBound != null) { return this.firstBound.erasure(); } return this.superclass; // java/lang/Object } /** * T::Ljava/util/Map;:Ljava/io/Serializable; * T:LY<TT;> */ public char[] genericSignature() { StringBuffer sig = new StringBuffer(10); sig.append(this.sourceName).append(':'); int interfaceLength = this.superInterfaces == null ? 0 : this.superInterfaces.length; if (interfaceLength == 0 || TypeBinding.equalsEquals(this.firstBound, this.superclass)) { if (this.superclass != null) sig.append(this.superclass.genericTypeSignature()); } for (int i = 0; i < interfaceLength; i++) { sig.append(':').append(this.superInterfaces[i].genericTypeSignature()); } int sigLength = sig.length(); char[] genericSignature = new char[sigLength]; sig.getChars(0, sigLength, genericSignature, 0); return genericSignature; } /** * T::Ljava/util/Map;:Ljava/io/Serializable; * T:LY<TT;> */ public char[] genericTypeSignature() { if (this.genericTypeSignature != null) return this.genericTypeSignature; return this.genericTypeSignature = CharOperation.concat('T', this.sourceName, ';'); } /** * Compute the initial type bounds for one inference variable as per JLS8 sect 18.1.3. */ TypeBound[] getTypeBounds(InferenceVariable variable, InferenceSubstitution theta) { int n = boundsCount(); if (n == 0) return NO_TYPE_BOUNDS; TypeBound[] bounds = new TypeBound[n]; int idx = 0; if (!this.firstBound.isInterface()) bounds[idx++] = TypeBound.createBoundOrDependency(theta, this.firstBound, variable); for (int i = 0; i < this.superInterfaces.length; i++) bounds[idx++] = TypeBound.createBoundOrDependency(theta, this.superInterfaces[i], variable); return bounds; } boolean hasOnlyRawBounds() { if (this.superclass != null && TypeBinding.equalsEquals(this.firstBound, this.superclass)) if (!this.superclass.isRawType()) return false; if (this.superInterfaces != null) for (int i = 0, l = this.superInterfaces.length; i < l; i++) if (!this.superInterfaces[i].isRawType()) return false; return true; } public boolean hasTypeBit(int bit) { if (this.typeBits == TypeIds.BitUninitialized) { // initialize from bounds this.typeBits = 0; if (this.superclass != null && this.superclass.hasTypeBit(~TypeIds.BitUninitialized)) this.typeBits |= (this.superclass.typeBits & TypeIds.InheritableBits); if (this.superInterfaces != null) for (int i = 0, l = this.superInterfaces.length; i < l; i++) if (this.superInterfaces[i].hasTypeBit(~TypeIds.BitUninitialized)) this.typeBits |= (this.superInterfaces[i].typeBits & TypeIds.InheritableBits); } return (this.typeBits & bit) != 0; } /** * Returns true if the type variable is directly bound to a given type */ public boolean isErasureBoundTo(TypeBinding type) { if (TypeBinding.equalsEquals(this.superclass.erasure(), type)) return true; for (int i = 0, length = this.superInterfaces.length; i < length; i++) { if (TypeBinding.equalsEquals(this.superInterfaces[i].erasure(), type)) return true; } return false; } public boolean isHierarchyConnected() { return (this.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0; } /** * Returns true if the 2 variables are playing exact same role: they have * the same bounds, providing one is substituted with the other: <T1 extends * List<T1>> is interchangeable with <T2 extends List<T2>>. */ public boolean isInterchangeableWith(TypeVariableBinding otherVariable, Substitution substitute) { if (TypeBinding.equalsEquals(this, otherVariable)) return true; int length = this.superInterfaces.length; if (length != otherVariable.superInterfaces.length) return false; if (TypeBinding.notEquals(this.superclass, Scope.substitute(substitute, otherVariable.superclass))) return false; next : for (int i = 0; i < length; i++) { TypeBinding superType = Scope.substitute(substitute, otherVariable.superInterfaces[i]); for (int j = 0; j < length; j++) if (TypeBinding.equalsEquals(superType, this.superInterfaces[j])) continue next; return false; // not a match } return true; } @Override public boolean isSubtypeOf(TypeBinding other) { if (isSubTypeOfRTL(other)) return true; if (this.firstBound != null && this.firstBound.isSubtypeOf(other)) return true; if (this.superclass != null && this.superclass.isSubtypeOf(other)) return true; if (this.superInterfaces != null) for (int i = 0, l = this.superInterfaces.length; i < l; i++) if (this.superInterfaces[i].isSubtypeOf(other)) return true; return other.id == TypeIds.T_JavaLangObject; } // to prevent infinite recursion when inspecting recursive generics: boolean inRecursiveFunction = false; @Override public boolean enterRecursiveFunction() { if (this.inRecursiveFunction) return false; this.inRecursiveFunction = true; return true; } @Override public void exitRecursiveFunction() { this.inRecursiveFunction = false; } // to prevent infinite recursion when inspecting recursive generics: boolean inRecursiveProjectionFunction = false; public boolean enterRecursiveProjectionFunction() { if (this.inRecursiveProjectionFunction) return false; this.inRecursiveProjectionFunction = true; return true; } public void exitRecursiveProjectionFunction() { this.inRecursiveProjectionFunction = false; } public boolean isProperType(boolean admitCapture18) { // handle recursive calls: if (this.inRecursiveFunction) // be optimistic, since this node is not an inference variable return true; this.inRecursiveFunction = true; try { if (this.superclass != null && !this.superclass.isProperType(admitCapture18)) { return false; } if (this.superInterfaces != null) for (int i = 0, l = this.superInterfaces.length; i < l; i++) if (!this.superInterfaces[i].isProperType(admitCapture18)) { return false; } return true; } finally { this.inRecursiveFunction = false; } } TypeBinding substituteInferenceVariable(InferenceVariable var, TypeBinding substituteType) { if (this.inRecursiveFunction) return this; this.inRecursiveFunction = true; try { boolean haveSubstitution = false; ReferenceBinding currentSuperclass = this.superclass; if (currentSuperclass != null) { currentSuperclass = (ReferenceBinding) currentSuperclass.substituteInferenceVariable(var, substituteType); haveSubstitution |= TypeBinding.notEquals(currentSuperclass, this.superclass); } ReferenceBinding[] currentSuperInterfaces = null; if (this.superInterfaces != null) { int length = this.superInterfaces.length; if (haveSubstitution) System.arraycopy(this.superInterfaces, 0, currentSuperInterfaces=new ReferenceBinding[length], 0, length); for (int i = 0; i < length; i++) { ReferenceBinding currentSuperInterface = this.superInterfaces[i]; if (currentSuperInterface != null) { currentSuperInterface = (ReferenceBinding) currentSuperInterface.substituteInferenceVariable(var, substituteType); if (TypeBinding.notEquals(currentSuperInterface, this.superInterfaces[i])) { if (currentSuperInterfaces == null) System.arraycopy(this.superInterfaces, 0, currentSuperInterfaces=new ReferenceBinding[length], 0, length); currentSuperInterfaces[i] = currentSuperInterface; haveSubstitution = true; } } } } if (haveSubstitution) { TypeVariableBinding newVar = new TypeVariableBinding(this.sourceName, this.declaringElement, this.rank, this.environment); newVar.superclass = currentSuperclass; newVar.superInterfaces = currentSuperInterfaces; newVar.tagBits = this.tagBits; return newVar; } return this; } finally { this.inRecursiveFunction = false; } } /** * Returns true if the type was declared as a type variable */ public boolean isTypeVariable() { return true; } // /** // * Returns the original type variable for a given variable. // * Only different from receiver for type variables of generic methods of parameterized types // * e.g. X<U> { <V1 extends U> U foo(V1) } --> X<String> { <V2 extends String> String foo(V2) } // * and V2.original() --> V1 // */ // public TypeVariableBinding original() { // if (this.declaringElement.kind() == Binding.METHOD) { // MethodBinding originalMethod = ((MethodBinding)this.declaringElement).original(); // if (originalMethod != this.declaringElement) { // return originalMethod.typeVariables[this.rank]; // } // } else { // ReferenceBinding originalType = (ReferenceBinding)((ReferenceBinding)this.declaringElement).erasure(); // if (originalType != this.declaringElement) { // return originalType.typeVariables()[this.rank]; // } // } // return this; // } public int kind() { return Binding.TYPE_PARAMETER; } public boolean mentionsAny(TypeBinding[] parameters, int idx) { if (this.inRecursiveFunction) return false; // nothing seen this.inRecursiveFunction = true; try { if (super.mentionsAny(parameters, idx)) return true; if (this.superclass != null && this.superclass.mentionsAny(parameters, idx)) return true; if (this.superInterfaces != null) for (int j = 0; j < this.superInterfaces.length; j++) { if (this.superInterfaces[j].mentionsAny(parameters, idx)) return true; } return false; } finally { this.inRecursiveFunction = false; } } void collectInferenceVariables(Set<InferenceVariable> variables) { if (this.inRecursiveFunction) return; // nothing seen this.inRecursiveFunction = true; try { if (this.superclass != null) this.superclass.collectInferenceVariables(variables); if (this.superInterfaces != null) for (int j = 0; j < this.superInterfaces.length; j++) { this.superInterfaces[j].collectInferenceVariables(variables); } } finally { this.inRecursiveFunction = false; } } public TypeBinding[] otherUpperBounds() { if (this.firstBound == null) return Binding.NO_TYPES; if (TypeBinding.equalsEquals(this.firstBound, this.superclass)) return this.superInterfaces; int otherLength = this.superInterfaces.length - 1; if (otherLength > 0) { TypeBinding[] otherBounds; System.arraycopy(this.superInterfaces, 1, otherBounds = new TypeBinding[otherLength], 0, otherLength); return otherBounds; } return Binding.NO_TYPES; } /** * @see org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding#readableName() */ public char[] readableName() { return this.sourceName; } ReferenceBinding resolve() { if ((this.modifiers & ExtraCompilerModifiers.AccUnresolved) == 0) return this; long nullTagBits = this.tagBits & TagBits.AnnotationNullMASK; TypeBinding oldSuperclass = this.superclass, oldFirstInterface = null; if (this.superclass != null) { ReferenceBinding resolveType = (ReferenceBinding) BinaryTypeBinding.resolveType(this.superclass, this.environment, true /* raw conversion */); this.tagBits |= resolveType.tagBits & TagBits.ContainsNestedTypeReferences; long superNullTagBits = resolveType.tagBits & TagBits.AnnotationNullMASK; if (superNullTagBits != 0L) { if (nullTagBits == 0L) { if ((superNullTagBits & TagBits.AnnotationNonNull) != 0) { nullTagBits = superNullTagBits; } } else { // System.err.println("TODO(stephan): report proper error: conflict binary TypeVariable vs. first bound"); } } this.setSuperClass(resolveType); } ReferenceBinding[] interfaces = this.superInterfaces; int length; if ((length = interfaces.length) != 0) { oldFirstInterface = interfaces[0]; for (int i = length; --i >= 0;) { ReferenceBinding resolveType = (ReferenceBinding) BinaryTypeBinding.resolveType(interfaces[i], this.environment, true /* raw conversion */); this.tagBits |= resolveType.tagBits & TagBits.ContainsNestedTypeReferences; long superNullTagBits = resolveType.tagBits & TagBits.AnnotationNullMASK; if (superNullTagBits != 0L) { if (nullTagBits == 0L) { if ((superNullTagBits & TagBits.AnnotationNonNull) != 0) { nullTagBits = superNullTagBits; } } else { // System.err.println("TODO(stephan): report proper error: conflict binary TypeVariable vs. bound "+i); } } interfaces[i] = resolveType; } } if (nullTagBits != 0) this.tagBits |= nullTagBits | TagBits.HasNullTypeAnnotation; // refresh the firstBound in case it changed if (this.firstBound != null) { if (TypeBinding.equalsEquals(this.firstBound, oldSuperclass)) { this.setFirstBound(this.superclass); } else if (TypeBinding.equalsEquals(this.firstBound, oldFirstInterface)) { this.setFirstBound(interfaces[0]); } } this.modifiers &= ~ExtraCompilerModifiers.AccUnresolved; return this; } public void setTypeAnnotations(AnnotationBinding[] annotations, boolean evalNullAnnotations) { if (getClass() == TypeVariableBinding.class) { // TVB only: if the declaration itself carries type annotations, // make sure TypeSystem will still have an unannotated variant at position 0, to answer getUnannotated() // (in this case the unannotated type is never explicit in source code, that's why we need this charade). this.environment.typeSystem.forceRegisterAsDerived(this); } else { this.environment.getUnannotatedType(this); // exposes original TVB/capture to type system for id stamping purposes. } super.setTypeAnnotations(annotations, evalNullAnnotations); } /** * @see org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding#shortReadableName() */ public char[] shortReadableName() { return readableName(); } public ReferenceBinding superclass() { return this.superclass; } public ReferenceBinding[] superInterfaces() { return this.superInterfaces; } /** * @see java.lang.Object#toString() */ public String toString() { if (this.hasTypeAnnotations()) return annotatedDebugName(); StringBuffer buffer = new StringBuffer(10); buffer.append('<').append(this.sourceName);//.append('[').append(this.rank).append(']'); if (this.superclass != null && TypeBinding.equalsEquals(this.firstBound, this.superclass)) { buffer.append(" extends ").append(this.superclass.debugName()); //$NON-NLS-1$ } if (this.superInterfaces != null && this.superInterfaces != Binding.NO_SUPERINTERFACES) { if (TypeBinding.notEquals(this.firstBound, this.superclass)) { buffer.append(" extends "); //$NON-NLS-1$ } for (int i = 0, length = this.superInterfaces.length; i < length; i++) { if (i > 0 || TypeBinding.equalsEquals(this.firstBound, this.superclass)) { buffer.append(" & "); //$NON-NLS-1$ } buffer.append(this.superInterfaces[i].debugName()); } } buffer.append('>'); return buffer.toString(); } @Override public char[] nullAnnotatedReadableName(CompilerOptions options, boolean shortNames) { StringBuffer nameBuffer = new StringBuffer(10); appendNullAnnotation(nameBuffer, options); nameBuffer.append(this.sourceName()); if (!this.inRecursiveFunction) { this.inRecursiveFunction = true; try { if (this.superclass != null && TypeBinding.equalsEquals(this.firstBound, this.superclass)) { nameBuffer.append(" extends ").append(this.superclass.nullAnnotatedReadableName(options, shortNames)); //$NON-NLS-1$ } if (this.superInterfaces != null && this.superInterfaces != Binding.NO_SUPERINTERFACES) { if (TypeBinding.notEquals(this.firstBound, this.superclass)) { nameBuffer.append(" extends "); //$NON-NLS-1$ } for (int i = 0, length = this.superInterfaces.length; i < length; i++) { if (i > 0 || TypeBinding.equalsEquals(this.firstBound, this.superclass)) { nameBuffer.append(" & "); //$NON-NLS-1$ } nameBuffer.append(this.superInterfaces[i].nullAnnotatedReadableName(options, shortNames)); } } } finally { this.inRecursiveFunction = false; } } int nameLength = nameBuffer.length(); char[] readableName = new char[nameLength]; nameBuffer.getChars(0, nameLength, readableName, 0); return readableName; } protected void appendNullAnnotation(StringBuffer nameBuffer, CompilerOptions options) { int oldSize = nameBuffer.length(); super.appendNullAnnotation(nameBuffer, options); if (oldSize == nameBuffer.length()) { // nothing appended in super.appendNullAnnotation()? if (hasNullTypeAnnotations()) { // see if the prototype has null type annotations: TypeVariableBinding[] typeVariables = null; if (this.declaringElement instanceof ReferenceBinding) { typeVariables = ((ReferenceBinding) this.declaringElement).typeVariables(); } else if (this.declaringElement instanceof MethodBinding) { typeVariables = ((MethodBinding) this.declaringElement).typeVariables(); } if (typeVariables != null && typeVariables.length > this.rank) { TypeVariableBinding prototype = typeVariables[this.rank]; if (prototype != this)//$IDENTITY-COMPARISON$ prototype.appendNullAnnotation(nameBuffer, options); } } } } public TypeBinding unannotated() { return this.hasTypeAnnotations() ? this.environment.getUnannotatedType(this) : this; } @Override public TypeBinding withoutToplevelNullAnnotation() { if (!hasNullTypeAnnotations()) return this; TypeBinding unannotated = this.environment.getUnannotatedType(this); AnnotationBinding[] newAnnotations = this.environment.filterNullTypeAnnotations(this.typeAnnotations); if (newAnnotations.length > 0) return this.environment.createAnnotatedType(unannotated, newAnnotations); return unannotated; } /** * Upper bound doesn't perform erasure */ public TypeBinding upperBound() { if (this.firstBound != null) { return this.firstBound; } return this.superclass; // java/lang/Object } public void evaluateNullAnnotations(Scope scope, TypeParameter parameter) { long nullTagBits = NullAnnotationMatching.validNullTagBits(this.tagBits); if (this.firstBound != null && this.firstBound.isValidBinding()) { long superNullTagBits = NullAnnotationMatching.validNullTagBits(this.firstBound.tagBits); if (superNullTagBits != 0L) { if (nullTagBits == 0L) { if ((superNullTagBits & TagBits.AnnotationNonNull) != 0) { nullTagBits = superNullTagBits; } } else if (superNullTagBits != nullTagBits) { if(parameter != null) this.firstBound = nullMismatchOnBound(parameter, this.firstBound, superNullTagBits, nullTagBits, scope); } } } ReferenceBinding[] interfaces = this.superInterfaces; int length; if (interfaces != null && (length = interfaces.length) != 0) { for (int i = length; --i >= 0;) { ReferenceBinding resolveType = interfaces[i]; long superNullTagBits = NullAnnotationMatching.validNullTagBits(resolveType.tagBits); if (superNullTagBits != 0L) { if (nullTagBits == 0L) { if ((superNullTagBits & TagBits.AnnotationNonNull) != 0) { nullTagBits = superNullTagBits; } } else if (superNullTagBits != nullTagBits) { if(parameter != null) interfaces[i] = (ReferenceBinding) nullMismatchOnBound(parameter, resolveType, superNullTagBits, nullTagBits, scope); } } } } if (nullTagBits != 0) this.tagBits |= nullTagBits | TagBits.HasNullTypeAnnotation; } private TypeBinding nullMismatchOnBound(TypeParameter parameter, TypeBinding boundType, long superNullTagBits, long nullTagBits, Scope scope) { // not finding bound should be considered a compiler bug TypeReference bound = findBound(boundType, parameter); Annotation ann = bound.findAnnotation(superNullTagBits); if (ann != null) { // explicit annotation: error scope.problemReporter().contradictoryNullAnnotationsOnBounds(ann, nullTagBits); this.tagBits &= ~TagBits.AnnotationNullMASK; } else { // implicit annotation: let the new one override return boundType.withoutToplevelNullAnnotation(); } return boundType; } private TypeReference findBound(TypeBinding bound, TypeParameter parameter) { if (parameter.type != null && TypeBinding.equalsEquals(parameter.type.resolvedType, bound)) return parameter.type; TypeReference[] bounds = parameter.bounds; if (bounds != null) { for (int i = 0; i < bounds.length; i++) { if (TypeBinding.equalsEquals(bounds[i].resolvedType, bound)) return bounds[i]; } } return null; } /* An annotated type variable use differs from its declaration exactly in its annotations and in nothing else. Propagate writes to all annotated variants so the clones evolve along. */ public TypeBinding setFirstBound(TypeBinding firstBound) { this.firstBound = firstBound; if ((this.tagBits & TagBits.HasAnnotatedVariants) != 0) { TypeBinding [] annotatedTypes = getDerivedTypesForDeferredInitialization(); for (int i = 0, length = annotatedTypes == null ? 0 : annotatedTypes.length; i < length; i++) { TypeVariableBinding annotatedType = (TypeVariableBinding) annotatedTypes[i]; annotatedType.firstBound = firstBound; } } if (firstBound != null && firstBound.hasNullTypeAnnotations()) this.tagBits |= TagBits.HasNullTypeAnnotation; return firstBound; } /* An annotated type variable use differs from its declaration exactly in its annotations and in nothing else. Propagate writes to all annotated variants so the clones evolve along. */ public ReferenceBinding setSuperClass(ReferenceBinding superclass) { this.superclass = superclass; if ((this.tagBits & TagBits.HasAnnotatedVariants) != 0) { TypeBinding [] annotatedTypes = getDerivedTypesForDeferredInitialization(); for (int i = 0, length = annotatedTypes == null ? 0 : annotatedTypes.length; i < length; i++) { TypeVariableBinding annotatedType = (TypeVariableBinding) annotatedTypes[i]; annotatedType.superclass = superclass; } } return superclass; } /* An annotated type variable use differs from its declaration exactly in its annotations and in nothing else. Propagate writes to all annotated variants so the clones evolve along. */ public ReferenceBinding [] setSuperInterfaces(ReferenceBinding[] superInterfaces) { this.superInterfaces = superInterfaces; if ((this.tagBits & TagBits.HasAnnotatedVariants) != 0) { TypeBinding [] annotatedTypes = getDerivedTypesForDeferredInitialization(); for (int i = 0, length = annotatedTypes == null ? 0 : annotatedTypes.length; i < length; i++) { TypeVariableBinding annotatedType = (TypeVariableBinding) annotatedTypes[i]; annotatedType.superInterfaces = superInterfaces; } } return superInterfaces; } protected TypeBinding[] getDerivedTypesForDeferredInitialization() { return this.environment.getAnnotatedTypes(this); } public TypeBinding combineTypeAnnotations(TypeBinding substitute) { if (hasTypeAnnotations()) { // may need to merge annotations from the original variable and from substitution: if (hasRelevantTypeUseNullAnnotations()) { // explicit type use null annotation overrides any annots on type parameter and concrete type arguments substitute = substitute.withoutToplevelNullAnnotation(); } if (this.typeAnnotations != Binding.NO_ANNOTATIONS) return this.environment.createAnnotatedType(substitute, this.typeAnnotations); // annots on originalVariable not relevant, and substitute has annots, keep substitute unmodified: } return substitute; } private boolean hasRelevantTypeUseNullAnnotations() { TypeVariableBinding[] parameters; if (this.declaringElement instanceof ReferenceBinding) { parameters = ((ReferenceBinding)this.declaringElement).original().typeVariables(); } else if (this.declaringElement instanceof MethodBinding) { parameters = ((MethodBinding)this.declaringElement).original().typeVariables; } else { throw new IllegalStateException("Unexpected declaring element:"+String.valueOf(this.declaringElement.readableName())); //$NON-NLS-1$ } TypeVariableBinding parameter = parameters[this.rank]; // recognize explicit annots by their effect on null tag bits, if there's no effect, then the annot is not considered relevant long currentNullBits = this.tagBits & TagBits.AnnotationNullMASK; long declarationNullBits = parameter.tagBits & TagBits.AnnotationNullMASK; return (currentNullBits & ~declarationNullBits) != 0; } public boolean acceptsNonNullDefault() { return false; } @Override public long updateTagBits() { if (!this.inRecursiveFunction) { this.inRecursiveFunction = true; try { if (this.superclass != null) this.tagBits |= this.superclass.updateTagBits(); if (this.superInterfaces != null) for (TypeBinding superIfc : this.superInterfaces) this.tagBits |= superIfc.updateTagBits(); } finally { this.inRecursiveFunction = false; } } return super.updateTagBits(); } @Override public boolean isFreeTypeVariable() { return this.environment.usesNullTypeAnnotations() && this.environment.globalOptions.pessimisticNullAnalysisForFreeTypeVariablesEnabled && (this.tagBits & TagBits.AnnotationNullMASK) == 0; } public ReferenceBinding upwardsProjection(Scope scope, TypeBinding[] mentionedTypeVariables) { return this; } public ReferenceBinding downwardsProjection(Scope scope, TypeBinding[] mentionedTypeVariables) { return this; } }
epl-1.0
MichaelOchel/smarthome
extensions/binding/org.eclipse.smarthome.binding.digitalstrom/src/main/java/org/eclipse/smarthome/binding/digitalstrom/internal/digitalSTROMLibary/digitalSTROMStructure/digitalSTROMScene/constants/SceneEnum.java
6037
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.binding.digitalstrom.internal.digitalSTROMLibary.digitalSTROMStructure.digitalSTROMScene.constants; import java.util.HashMap; /** * The {@link SceneEnum} lists all available scenes in digitalSTROM. * * @author Alexander Betker * @since 1.3.0 * @version digitalSTROM-API 1.14.5 * * @author Michael Ochel - add EVENT_NAME and missing java-doc * @author Mathias Siegele - add EVENT_NAME and missing java-doc * * @see http://developer.digitalstrom.org/Architecture/ds-basics.pdf appendix B, page 44 */ public enum SceneEnum implements Scene { /* Area scene commands */ AREA_1_OFF(1), // Set output value to Preset Area 1 Off (Default: Off) AREA_1_ON(6), // Set output value to Preset Area 1 On (Default: On) AREA_1_INCREMENT(43), // Initial command to increment output value AREA_1_DECREMENT(42), // Initial command to decrement output value AREA_1_STOP(52), // Stop output value change at current position AREA_STEPPING_CONTINUE(10), // Next step to increment or decrement AREA_2_OFF(2), // Set output value to Area 2 Off (Default: Off) AREA_2_ON(7), // Set output value to Area 2 On (Default: On) AREA_2_INCREMENT(45), // Initial command to increment output value AREA_2_DECREMENT(44), // Initial command to decrement output value AREA_2_STOP(53), // Stop output value change at current position AREA_3_OFF(3), // Set output value to Area 3 Off (Default: Off) AREA_3_ON(8), // Set output value to Area 3 On (Default: On) AREA_3_INCREMENT(47), // Initial command to increment output value AREA_3_DECREMENT(46), // Initial command to decrement output value AREA_3_STOP(54), // Stop output value change at current position AREA_4_OFF(4), // Set output value to Area 4 Off (Default: Off) AREA_4_ON(9), // Set output value to Area 4 On (Default: On) AREA_4_INCREMENT(49), // Initial command to increment output value AREA_4_DECREMENT(48), // Initial command to decrement output value AREA_4_STOP(55), // Stop output value change at current position /* local pushbutton scene commands */ DEVICE_ON(51), // Local on DEVICE_OFF(50), // Local off DEVICE_STOP(15), // Stop output value change at current position /* special scene commands */ MINIMUM(13), // Minimum output value MAXIMUM(14), // Maximum output value STOP(15), // Stop output value change at current position AUTO_OFF(40), // slowly fade down to off /* stepping scene commands */ INCREMENT(11), // Increment output value DECREMENT(12), // Decrement output value /* presets */ PRESET_0(0), // Set output value to Preset 0 (Default: Off) PRESET_1(5), // Set output value to Preset 1 (Default: On) PRESET_2(17), // Set output value to Preset 2 PRESET_3(18), // Set output value to Preset 3 PRESET_4(19), // Set output value to Preset 4 PRESET_10(32), // Set output value to Preset 10 (Default: Off) PRESET_11(33), // Set output value to Preset 11 (Default: On) PRESET_12(20), // Set output value to Preset 12 PRESET_13(21), // Set output value to Preset 13 PRESET_14(22), // Set output value to Preset 14 PRESET_20(34), // Set output value to Preset 20 (Default: Off) PRESET_21(35), // Set output value to Preset 21 (Default: On) PRESET_22(23), // Set output value to Preset 22 PRESET_23(24), // Set output value to Preset 23 PRESET_24(25), // Set output value to Preset 24 PRESET_30(36), // Set output value to Preset 30 (Default: Off) PRESET_31(37), // Set output value to Preset 31 (Default: On) PRESET_32(26), // Set output value to Preset 32 PRESET_33(27), // Set output value to Preset 33 PRESET_34(28), // Set output value to Preset 34 PRESET_40(38), // Set output value to Preset 40 (Default: Off) PRESET_41(39), // Set output value to Preset 41 (Default: On) PRESET_42(29), // Set output value to Preset 42 PRESET_43(30), // Set output value to Preset 43 PRESET_44(31), // Set output value to Preset 44 /* Temperature control scenes */ /* * OFF (0), * CONFORT (1), * ECONEMY (2), * NOT_USED (3), * NIGHT (4), * HOLLYDAY (5), */ /* group independent scene commands */ DEEP_OFF(68), ENERGY_OVERLOAD(66), STANDBY(67), ZONE_ACTIVE(75), ALARM_SIGNAL(74), AUTO_STANDBY(64), ABSENT(72), PRESENT(71), SLEEPING(69), WAKEUP(70), DOOR_BELL(73), PANIC(65), FIRE(76), ALARM_1(74), ALARM_2(83), ALARM_3(84), ALARM_4(85), WIND(86), NO_WIND(87), RAIN(88), NO_RAIN(89), HAIL(90), NO_HAIL(91); private final int sceneNumber; static final HashMap<Integer, SceneEnum> digitalstromScenes = new HashMap<Integer, SceneEnum>(); static { for (SceneEnum zs : SceneEnum.values()) { digitalstromScenes.put(zs.getSceneNumber(), zs); } } private SceneEnum(int sceneNumber) { this.sceneNumber = sceneNumber; } /** * Returns the {@link SceneEnum} for the given scene number. * * @param sceneNumber * @return SceneEnum */ public static SceneEnum getScene(int sceneNumber) { return digitalstromScenes.get(sceneNumber); } /** * Returns true if the given scene number contains in digitalSTROM scenes otherwise false. * * @param sceneNumber * @return true if contains otherwise false */ public static boolean containsScene(Integer sceneNumber) { return digitalstromScenes.keySet().contains(sceneNumber); } @Override public int getSceneNumber() { return this.sceneNumber; } }
epl-1.0
lintaian/edc
src/com/lps/edc/dao/interfaces/SysTeacherDaoIF.java
174
package com.lps.edc.dao.interfaces; import com.lps.edc.entity.SysTeacher; public interface SysTeacherDaoIF { public SysTeacher get(String name) throws Exception; }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/composite/advanced/member_2/EmployeeCustomizer.java
2284
/******************************************************************************* * 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.models.jpa.composite.advanced.member_2; import org.eclipse.persistence.config.DescriptorCustomizer; import org.eclipse.persistence.descriptors.ClassDescriptor; import org.eclipse.persistence.expressions.ExpressionBuilder; import org.eclipse.persistence.mappings.querykeys.OneToManyQueryKey; import org.eclipse.persistence.mappings.querykeys.OneToOneQueryKey; import org.eclipse.persistence.testing.models.jpa.composite.advanced.member_3.PhoneNumber; public class EmployeeCustomizer implements DescriptorCustomizer { public EmployeeCustomizer() {} public void customize(ClassDescriptor descriptor) { descriptor.setShouldDisableCacheHits(false); descriptor.addDirectQueryKey("startTime", "START_TIME"); OneToOneQueryKey queryKey = new OneToOneQueryKey(); queryKey.setName("boss"); queryKey.setReferenceClass(Employee.class); ExpressionBuilder builder = new ExpressionBuilder(); queryKey.setJoinCriteria(builder.getField("MANAGER_EMP_ID").equal(builder.getParameter("EMP_ID"))); descriptor.addQueryKey(queryKey); OneToManyQueryKey otmQueryKey = new OneToManyQueryKey(); otmQueryKey.setName("phoneQK"); otmQueryKey.setReferenceClass(PhoneNumber.class); builder = new ExpressionBuilder(); otmQueryKey.setJoinCriteria(builder.getField("OWNER_ID").equal(builder.getParameter("EMP_ID"))); descriptor.addQueryKey(otmQueryKey); } }
epl-1.0
YsuSERESL/OnionUmlVisualization
src/edu/ysu/onionuml/ui/graphics/IEventRegistrar.java
386
package edu.ysu.onionuml.ui.graphics; /** * Defines a class that can register and unregister event listeners. */ public interface IEventRegistrar { /** * Begins listening for model events using the specified listener. */ public void registerEventListener(IEventListener listener); /** * Stops using the specified listener. */ public void unregisterEventListener(); }
epl-1.0
sonatype/nexus-public
components/nexus-base/src/test/java/org/sonatype/nexus/internal/security/model/CUserRoleMappingDAOTest.java
5785
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.internal.security.model; import java.util.stream.Stream; import org.sonatype.goodies.testsupport.TestSupport; import org.sonatype.nexus.content.testsuite.groups.SQLTestGroup; import org.sonatype.nexus.datastore.api.DataSession; import org.sonatype.nexus.datastore.api.DataStoreManager; import org.sonatype.nexus.testdb.DataSessionRule; import com.google.common.collect.Iterables; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.stream.Collectors.toSet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; @Category(SQLTestGroup.class) public class CUserRoleMappingDAOTest extends TestSupport { @Rule public DataSessionRule sessionRule = new DataSessionRule().access(CUserRoleMappingDAO.class); private DataSession session; private CUserRoleMappingDAO dao; @Before public void setup() { session = sessionRule.openSession(DataStoreManager.DEFAULT_DATASTORE_NAME); dao = (CUserRoleMappingDAO) session.access(CUserRoleMappingDAO.class); } @After public void cleanup() { session.close(); } @Test public void testCreateReadUpdateDelete_caseInsensitive() { CUserRoleMappingData roleMapping = new CUserRoleMappingData(); roleMapping.setUserId("admin"); roleMapping.setSource("default"); roleMapping.setRoles(Stream.of("role1", "role2").collect(toSet())); dao.create(roleMapping); CUserRoleMappingData read = dao.read("ADMIN", "default").get(); assertThat(read, not(nullValue())); assertThat(read.getUserId(), is("admin")); assertThat(read.getSource(), is("default")); assertThat(read.getRoles(), is(Stream.of("role1", "role2").collect(toSet()))); roleMapping.setUserId("Admin"); roleMapping.setRoles(singleton("role3")); dao.update(roleMapping); read = dao.read("admin", "default").get(); assertThat(read, not(nullValue())); assertThat(read.getRoles(), is(singleton("role3"))); assertThat(dao.delete("ADMIN", "default"), is(true)); assertThat(dao.read("admin", "default").isPresent(), is(false)); } @Test public void testCreateReadUpdateDelete_caseSensitive() { CUserRoleMappingData roleMapping = new CUserRoleMappingData(); roleMapping.setUserId("admin"); roleMapping.setSource("other"); roleMapping.setRoles(Stream.of("role1", "role2").collect(toSet())); dao.create(roleMapping); assertThat(dao.read("ADMIN", "other").isPresent(), is(false)); CUserRoleMappingData read = dao.read("admin", "other").get(); assertThat(read, not(nullValue())); assertThat(read.getUserId(), is("admin")); assertThat(read.getSource(), is("other")); assertThat(read.getRoles(), is(Stream.of("role1", "role2").collect(toSet()))); roleMapping.setUserId("ADMIN"); roleMapping.setRoles(singleton("role3")); dao.update(roleMapping); read = dao.read("admin", "other").get(); assertThat(read, not(nullValue())); assertThat(read.getUserId(), is("admin")); assertThat(read.getSource(), is("other")); assertThat(read.getRoles(), is(Stream.of("role1", "role2").collect(toSet()))); roleMapping.setUserId("admin"); dao.update(roleMapping); read = dao.read("admin", "other").get(); assertThat(read.getRoles(), is(singleton("role3"))); assertThat(dao.delete("Admin", "other"), is(false)); assertThat(dao.read("admin", "other").isPresent(), is(true)); assertThat(dao.delete("admin", "other"), is(true)); assertThat(dao.read("admin", "other").isPresent(), is(false)); } @Test public void testBrowse() { CUserRoleMappingData roleMapping1 = new CUserRoleMappingData(); roleMapping1.setUserId("user1"); roleMapping1.setSource("default"); roleMapping1.setRoles(emptySet()); CUserRoleMappingData roleMapping2 = new CUserRoleMappingData(); roleMapping2.setUserId("user2"); roleMapping2.setSource("default"); roleMapping2.setRoles(emptySet()); CUserRoleMappingData roleMapping3 = new CUserRoleMappingData(); roleMapping3.setUserId("user3"); roleMapping3.setSource("default"); roleMapping3.setRoles(emptySet()); dao.create(roleMapping1); dao.create(roleMapping2); dao.create(roleMapping3); assertThat(Iterables.size(dao.browse()), is(3)); } @Test public void testUpdate_returnsStatus() { CUserRoleMappingData roleMapping = new CUserRoleMappingData(); roleMapping.setUserId("user1"); roleMapping.setSource("default"); roleMapping.setRoles(emptySet()); assertThat(dao.update(roleMapping), is(false)); dao.create(roleMapping); roleMapping.setRoles(singleton("role1")); assertThat(dao.update(roleMapping), is(true)); } }
epl-1.0
pgaufillet/topcased-req
plugins/org.topcased.requirement.import.document/src/org/topcased/requirement/document/utils/DocumentTypeParser.java
8193
/***************************************************************************** * Copyright (c) 2011 Atos. * * * 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: * Anass RADOUANI (Atos) anass.radouani@atos.net - Initial API and implementation * *****************************************************************************/ package org.topcased.requirement.document.utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.core.runtime.Status; import org.topcased.requirement.document.Activator; import org.topcased.requirement.document.elements.AttributeRequirement; import org.topcased.requirement.document.elements.Column; import org.topcased.requirement.document.elements.Mapping; import org.topcased.requirement.document.elements.RecognizedElement; import org.topcased.requirement.document.elements.RecognizedTree; import org.topcased.requirement.document.elements.Regex; import org.topcased.requirement.document.elements.Style; import org.topcased.typesmodel.handler.IniManager; import org.topcased.typesmodel.model.inittypes.DocumentType; import org.topcased.typesmodel.model.inittypes.Type; /** * Parse type Document to extract useful information for import requirement * */ public class DocumentTypeParser { private DocumentType type; /** * Constructor * * @param type the document type to parse */ public DocumentTypeParser(DocumentType type) { this.type = type; } /** * Gets the end Text description * * @return */ public String getDescription() { if (type != null) { return type.getTextType(); } return null; } /** * Gets the id * * @param idType The id to get (use the Constants Class) * @return */ public RecognizedElement getIdentification(String idType) { if (type == null || type.getId() == null) { return null; } RecognizedElement result = null; Type id = type.getId(); if (Constants.REGEX_STYLE_TYPE.equals(idType)) { if (id instanceof org.topcased.typesmodel.model.inittypes.Style) { if (((org.topcased.typesmodel.model.inittypes.Style) id).getExpression() != null) { result = new Style(((org.topcased.typesmodel.model.inittypes.Style) id).getLabel(), ((org.topcased.typesmodel.model.inittypes.Style) id).getExpression()); } else { result = new Style(((org.topcased.typesmodel.model.inittypes.Style) id).getLabel(),""); } } else if (id instanceof org.topcased.typesmodel.model.inittypes.Regex) { result = new Regex(((org.topcased.typesmodel.model.inittypes.Regex) id).getExpression()); } } else if (Constants.COLUMN_TYPE.equals(idType)) { if (id instanceof org.topcased.typesmodel.model.inittypes.Column) { result = new Column(((org.topcased.typesmodel.model.inittypes.Column) id).getNumber(), ((org.topcased.typesmodel.model.inittypes.Column) id).getExpression()); } } return result; } /** * Gets if its hierarchical or not * * @return */ public boolean getIsHiearachical() { if (type != null) { return type.isHierarchical(); } return false; } /** * Gets the mapping * * @param idType The id type (use the Constants Class) * @return */ public Collection<Mapping> getMapping(String idType) { RecognizedTree tree = new RecognizedTree(); if (type == null) { return null; } Collection<Mapping> mapping = new ArrayList<Mapping>(); if (Constants.REGEX_STYLE_TYPE.equals(idType)) { List<org.topcased.typesmodel.model.inittypes.Style> styles = IniManager.getInstance().getStyles(type); List<org.topcased.typesmodel.model.inittypes.Regex> regex = IniManager.getInstance().getRegex(type); for (org.topcased.typesmodel.model.inittypes.Regex oneRegex : regex) { if (oneRegex.getExpression() != null && oneRegex.getName() != null) { Regex newRegex = new Regex(oneRegex.getExpression()); tree.add(newRegex); AttributeRequirement regexAttribute = new AttributeRequirement(oneRegex.getName(), false,oneRegex.isIsText(), "Requirement"); mapping.add(new Mapping(newRegex, regexAttribute)); } else { Activator.getDefault().getLog().log( new Status(Status.WARNING, Activator.PLUGIN_ID, "The regex " + oneRegex.getName() + " has been ignored because it doesn't contains a name or an expression")); } } for (org.topcased.typesmodel.model.inittypes.Style style : styles) { if (style.getName() != null && style.getLabel() != null) { Style newStyle; if (style.getExpression() != null) { newStyle = new Style(style.getLabel(), style.getExpression()); } else { newStyle = new Style(style.getLabel(), ""); } tree.add(newStyle); AttributeRequirement newAttribute = new AttributeRequirement(style.getName(), false, style.isIsText(), "Requirement"); mapping.add(new Mapping(newStyle, newAttribute)); } else { Activator.getDefault().getLog().log( new Status(Status.WARNING, Activator.PLUGIN_ID, "The style " + style.getName() + " " + style.getName() + " has been ignored because it doesn't contains a name or an expression")); } } } else if (Constants.COLUMN_TYPE.equals(idType)) { List<org.topcased.typesmodel.model.inittypes.Column> columns = IniManager.getInstance().getColumns(type); for (org.topcased.typesmodel.model.inittypes.Column column : columns) { if (column.getExpression() != null && column.getName() != null) { Column newColumn = new Column(column.getNumber(), column.getExpression()); AttributeRequirement newAttribute = new AttributeRequirement(column.getName(), false,column.isIsText(), "Requirement"); mapping.add(new Mapping(newColumn, newAttribute)); tree.add(newColumn); } else if (column.getName() != null) { Column newColumn = new Column(column.getNumber(), ""); AttributeRequirement newAttribute = new AttributeRequirement(column.getName(), false,column.isIsText(), "Requirement"); mapping.add(new Mapping(newColumn, newAttribute)); tree.add(newColumn); } else { Activator.getDefault().getLog().log( new Status(Status.WARNING, Activator.PLUGIN_ID, "Column with number " + column.getNumber() + " has been ignored because it doesn't contains a name or an expression")); } } } return mapping; } /** * Returns the description Regex */ public String getDescriptionReg(){ return type.getTextRegex(); } }
epl-1.0
hammacher/ccs
core/tests/de/unisb/cs/depend/ccs_sem/junit/integrationtests/invalid/Unguarded2.java
387
package de.unisb.cs.depend.ccs_sem.junit.integrationtests.invalid; import de.unisb.cs.depend.ccs_sem.junit.FailingIntegrationTest; public class Unguarded2 extends FailingIntegrationTest { @Override protected String getExpressionString() { return "X[a] := X[a+1]; X[0]"; } @Override protected boolean expectGuardedness() { return false; } }
epl-1.0
forge/javaee-descriptors
api/src/main/java/org/jboss/shrinkwrap/descriptor/api/application5/WebType.java
3234
package org.jboss.shrinkwrap.descriptor.api.application5; import org.jboss.shrinkwrap.descriptor.api.Child; /** * This interface defines the contract for the <code> webType </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 interface WebType<T> extends Child<T> { // --------------------------------------------------------------------------------------------------------|| // ClassName: WebType ElementName: xsd:token ElementType : web-uri // MaxOccurs: - isGeneric: true isAttribute: false isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>web-uri</code> element * @param webUri the value for the element <code>web-uri</code> * @return the current instance of <code>WebType<T></code> */ public WebType<T> webUri(String webUri); /** * Returns the <code>web-uri</code> element * @return the node defined for the element <code>web-uri</code> */ public String getWebUri(); /** * Removes the <code>web-uri</code> element * @return the current instance of <code>WebType<T></code> */ public WebType<T> removeWebUri(); // --------------------------------------------------------------------------------------------------------|| // ClassName: WebType ElementName: xsd:token ElementType : context-root // MaxOccurs: - isGeneric: true isAttribute: false isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>context-root</code> element * @param contextRoot the value for the element <code>context-root</code> * @return the current instance of <code>WebType<T></code> */ public WebType<T> contextRoot(String contextRoot); /** * Returns the <code>context-root</code> element * @return the node defined for the element <code>context-root</code> */ public String getContextRoot(); /** * Removes the <code>context-root</code> element * @return the current instance of <code>WebType<T></code> */ public WebType<T> removeContextRoot(); // --------------------------------------------------------------------------------------------------------|| // ClassName: WebType ElementName: xsd:ID ElementType : id // MaxOccurs: - isGeneric: true isAttribute: true isEnum: false isDataType: true // --------------------------------------------------------------------------------------------------------|| /** * Sets the <code>id</code> attribute * @param id the value for the attribute <code>id</code> * @return the current instance of <code>WebType<T></code> */ public WebType<T> id(String id); /** * Returns the <code>id</code> attribute * @return the value defined for the attribute <code>id</code> */ public String getId(); /** * Removes the <code>id</code> attribute * @return the current instance of <code>WebType<T></code> */ public WebType<T> removeId(); }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src/org/eclipse/xtext/mwe/PathTraverserTest.java
2112
/******************************************************************************* * Copyright (c) 2010 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.mwe; import java.util.Set; import org.eclipse.emf.common.util.URI; import org.junit.Assert; import org.junit.Test; import com.google.common.base.Predicate; /** * @author Sven Efftinge - Initial contribution and API */ public class PathTraverserTest extends Assert { public static Predicate<URI> everythingButDummy = new Predicate<URI>() { @Override public boolean apply(URI input) { return !input.fileExtension().equals("dummy"); } }; /** * PathTraverser should not throw an exception but log a warning if a path doesn't exist. * <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=376944">Bug 376944</a> */ @Test public void testNoneExistingFile() throws Exception { String path = "fileNotExists"; Set<URI> uris = new PathTraverser().findAllResourceUris(path, everythingButDummy); assertTrue(uris.isEmpty()); } @Test public void testEmptyFolder() throws Exception { String path = pathTo("emptyFolder"); Set<URI> uris = new PathTraverser().findAllResourceUris(path, everythingButDummy); assertTrue(uris.isEmpty()); } @Test public void testNonEmptyFolder() throws Exception { String path = pathTo("nonemptyFolder"); Set<URI> uris = new PathTraverser().findAllResourceUris(path, everythingButDummy); assertEquals(2, uris.size()); } @Test public void testArchive() throws Exception { String path = pathTo("nonemptyJar.jar"); Set<URI> uris = new PathTraverser().findAllResourceUris(path, everythingButDummy); assertEquals(3, uris.size()); } private String pathTo(String string) throws Exception { return new ReaderTest().pathTo(string); } }
epl-1.0
blackberry/Eclipse-JDE
net.rim.ejde/src/net/rim/ejde/internal/util/StatusFactory.java
2962
/* * Copyright (c) 2010-2012 Research In Motion Limited. All rights reserved. * * This program and the accompanying materials are made available * under the terms of the Eclipse Public License, Version 1.0, * which accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html * */ package net.rim.ejde.internal.util; import net.rim.ejde.internal.core.ContextManager; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Status; /** * Utility class to auto-create Status objects for this plugin * * @author bchabot, cmalinescu */ public class StatusFactory { private StatusFactory() { } /** * Create error status * * @param message * @param exception * @return */ public static IStatus createErrorStatus( String message, Throwable exception ) { return new Status( IStatus.ERROR, ContextManager.PLUGIN_ID, IStatus.ERROR, message, exception ); } /** * Create error status * * @param message * @return */ public static IStatus createErrorStatus( String message ) { return createErrorStatus( message, null ); } /** * Create status of given type * * @param severity * @param message * @return */ public static IStatus createStatus( int severity, String message ) { return new Status( severity, ContextManager.PLUGIN_ID, severity, message, null ); } /** * Create warning status * * @param message * @param exception * @return */ public static IStatus createWarningStatus( String message ) { return new Status( IStatus.WARNING, ContextManager.PLUGIN_ID, IStatus.WARNING, message, null ); } /** * Create info status * * @param message * @param exception * @return */ public static IStatus createinfoStatus( String message ) { return new Status( IStatus.INFO, ContextManager.PLUGIN_ID, IStatus.INFO, message, null ); } /** * Merge's two status objects together * * @param currentStatus * @param newStatus * @return merged status */ public static IStatus mergeStatus( IStatus currentStatus, IStatus newStatus ) { MultiStatus multiStatus = null; if( currentStatus instanceof MultiStatus ) { multiStatus = (MultiStatus) currentStatus; } else { multiStatus = new MultiStatus( ContextManager.PLUGIN_ID, IStatus.OK, "", null ); multiStatus.add( currentStatus ); } multiStatus.merge( newStatus ); return multiStatus; } /** * Creates a blank MultiStatus with given message * * @param msg * @return */ public static MultiStatus createMultiStatus( String msg ) { return new MultiStatus( ContextManager.PLUGIN_ID, IStatus.OK, msg, null ); } }
epl-1.0
abreslav/alvor
com.googlecode.alvor.checkers.generic/src/com/googlecode/alvor/checkers/generic/GenericSyntacticalSQLSyntaxChecker.java
680
package com.googlecode.alvor.checkers.generic; import com.googlecode.alvor.checkers.sqlstatic.SyntacticalSQLChecker; import com.googlecode.alvor.lexer.automata.LexerData; import com.googlecode.alvor.sqllexer.GenericSQLLexerData; import com.googlecode.alvor.sqlparser.GLRStack; import com.googlecode.alvor.sqlparser.ILRParser; import com.googlecode.alvor.sqlparser.Parsers; public class GenericSyntacticalSQLSyntaxChecker extends SyntacticalSQLChecker { @Override protected LexerData provideLexerData() { return GenericSQLLexerData.DATA; } @Override protected ILRParser<GLRStack> provideParser() { return Parsers.getGenericGLRParserForSQL(); } }
epl-1.0
FTSRG/mondo-collab-framework
archive/mondo-access-control/CollaborationIncQuery/WTSpec/src/WTSpec/validation/CtrlUnit83Validator.java
1014
/** * * $Id$ */ package WTSpec.validation; import WTSpec.WTCInput; import WTSpec.WTCOutput; /** * A sample validator interface for {@link WTSpec.CtrlUnit83}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface CtrlUnit83Validator { boolean validate(); boolean validateInput__iPinSafetyCmd(WTCInput value); boolean validateInput__iPinAutoCmd(WTCInput value); boolean validateInput__iPinManualCmd(WTCInput value); boolean validateInput__iLockingSet(WTCInput value); boolean validateInput__iManualMode(WTCInput value); boolean validateInput__iSafetyBlock(WTCInput value); boolean validateOutput__oPinEnable(WTCOutput value); boolean validateOutput__oPinExtend(WTCOutput value); boolean validateOutput__oPinRetract(WTCOutput value); }
epl-1.0
ghillairet/gmf-tooling-gwt-runtime
org.eclipse.gmf.runtime.lite.gwt/src/org/eclipse/gmf/runtime/gwt/edit/parts/update/canonical/AbstractNotationModelRefresher.java
4309
/** * Copyright (c) 2006, 2007 Borland Software Corporation * * 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: * bblajer - initial API and implementation */ package org.eclipse.gmf.runtime.gwt.edit.parts.update.canonical; import static org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain.getEditingDomainFor; import org.eclipse.emf.common.command.Command; import org.eclipse.emf.common.notify.Notification; import org.eclipse.gef.EditPart; import org.eclipse.gmf.runtime.gwt.commands.AbstractWrappingCommand; import org.eclipse.gmf.runtime.gwt.commands.CreateNotationalElementCommand; import org.eclipse.gmf.runtime.gwt.commands.WrappingCommand; import org.eclipse.gmf.runtime.gwt.edit.parts.update.IUpdatableEditPart.Refresher; import org.eclipse.gmf.runtime.notation.View; /** * Listens to the given transactional editing domain in order to update the notational model to reflect changes in the domain model. */ public abstract class AbstractNotationModelRefresher implements Refresher { // private EditingDomain myEditingDomain; private final EditPart editPart; public AbstractNotationModelRefresher(EditPart part) { this.editPart = part; } public final View getView() { return getHost(); } @Override public void refresh() { final View host = getHost(); if (host == null) { return; } final Command command = buildCommand(); if (command == null) { return; } final AbstractWrappingCommand gefCommand = new WrappingCommand(getEditingDomainFor(host), command); editPart.getViewer().getEditDomain().getCommandStack().execute(gefCommand); } /** * @deprecated Use {@link TransactionalUpdateManager}. */ // public void install(EditingDomain editingDomain) { // if (this.myEditingDomain != null && !this.myEditingDomain.equals(editingDomain)) { // throw new IllegalStateException("Already listening to another editing domain"); // } // this.myEditingDomain = editingDomain; // } // /** // * @deprecated Use {@link TransactionalUpdateManager}. // */ // public boolean isInstalled() { // return myEditingDomain != null; // } // /** // * @deprecated Use {@link TransactionalUpdateManager}. // */ // public void uninstall() { // if (isInstalled()) { // myEditingDomain = null; // } // } // public boolean isPrecommitOnly() { // return true; // } // public Command transactionAboutToCommit(ResourceSetChangeEvent event) { // if (shouldHandleNotification(event)) { // return buildRefreshNotationModelCommand(); // } // return null; // } // public NotificationFilter getFilter() { // return myFilter; // } /** * Creates and returns the command that will update the notational model to reflect changes in the domain model. */ public abstract Command buildCommand(); // private boolean shouldHandleNotification(ResourceSetChangeEvent event) { // if (getHost() == null || getHost().getElement() == null) { // return false; // } // for(Iterator<?> it = event.getNotifications().iterator(); it.hasNext(); ) { // Notification next = (Notification) it.next(); // if (shouldHandleNotification(next)) { // return true; // } // } // return false; // } /** * This method may be overridden in subclasses to filter unneeded notifications that passed the NotificationFilter. * By default, it is assumed that all notifications that passed through the NotificationFilter could trigger the update. */ protected boolean shouldHandleNotification(Notification nofitication) { return true; } protected int getVisualID(View view) { try { return Integer.parseInt(view.getType()); } catch (NumberFormatException e) { return -1; } } /** * Returns a command that will create a notational element to represent the domain model element described by the given <code>ElementDescriptor</code>. */ protected abstract CreateNotationalElementCommand getCreateNotationalElementCommand(ElementDescriptor descriptor); // protected abstract NotificationFilter createFilter(); protected abstract boolean shouldCreateView(ElementDescriptor descriptor); protected abstract View getHost(); }
epl-1.0
ttimbul/eclipse.wst
bundles/org.eclipse.wst.xml.core/src-contentmodel/org/eclipse/wst/xml/core/internal/contentmodel/CMAttributeDeclaration.java
1597
/******************************************************************************* * Copyright (c) 2002, 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.xml.core.internal.contentmodel; import java.util.Enumeration; /** * AttributeDeclaration interface */ public interface CMAttributeDeclaration extends CMNode { public static final int OPTIONAL = 1; public static final int REQUIRED = 2; public static final int FIXED = 3; public static final int PROHIBITED = 4; /** * getAttrName method * @return java.lang.String */ String getAttrName(); /** * getAttrType method * @return CMDataType */ CMDataType getAttrType(); /** * getDefaultValue method * @return java.lang.String * @deprecated -- to be replaced in future with additional CMDataType methods (currently found on CMDataTypeHelper) */ String getDefaultValue(); /** * getEnumAttr method * @return java.util.Enumeration * @deprecated -- to be replaced in future with additional CMDataType methods (currently found on CMDataTypeHelper) */ Enumeration getEnumAttr(); /** * getUsage method * @return int */ int getUsage(); }
epl-1.0
oxmcvusd/eclipse-integration-gradle
org.springsource.ide.eclipse.gradle.ui/src/org/springsource/ide/eclipse/gradle/ui/launch/GradleLaunchTasksTab.java
10087
/******************************************************************************* * Copyright (c) 2012, 2015 Pivotal Software, 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: * Pivotal Software, Inc. - initial API and implementation *******************************************************************************/ package org.springsource.ide.eclipse.gradle.ui.launch; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.ui.AbstractLaunchConfigurationTab; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; 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.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.springsource.ide.eclipse.gradle.core.GradleCore; import org.springsource.ide.eclipse.gradle.core.GradleNature; import org.springsource.ide.eclipse.gradle.core.GradleProject; import org.springsource.ide.eclipse.gradle.core.classpathcontainer.FastOperationFailedException; import org.springsource.ide.eclipse.gradle.core.launch.GradleLaunchConfigurationDelegate; import org.springsource.ide.eclipse.gradle.core.util.GradleProjectIndex; import org.springsource.ide.eclipse.gradle.ui.cli.editor.TasksViewer; /** * @author Kris De Volder * @author Alex Boyko */ public class GradleLaunchTasksTab extends AbstractLaunchConfigurationTab { private static final boolean DEBUG = false; private static final String CTRL_SPACE_LABEL = "<Ctrl> + <Space>"; private static final String EDITOR_INFO_LABEL = "Type tasks in the editor below. Use " + CTRL_SPACE_LABEL + " to activate content assistant."; private Combo projectCombo; private GradleProject project; private GradleProjectIndex tasksIndex= new GradleProjectIndex(); private TasksViewer tasksViewer; private Button refreshButton; public void createControl(Composite parent) { Composite page = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); page.setLayout(layout); createProjectCombo(page); createTaskEditor(page); setControl(page); } private void createProjectCombo(Composite _parent) { GridDataFactory grabHor = GridDataFactory.fillDefaults().grab(true, false); Composite parent = new Composite(_parent, SWT.NONE); parent.setLayout(new GridLayout(3,false)); grabHor.applyTo(parent); Label label = new Label(parent, SWT.NONE); label.setText("Project"); projectCombo = new Combo(parent, SWT.DROP_DOWN|SWT.READ_ONLY); List<GradleProject> projects = getGradleProjects(); String[] items = new String[projects.size()]; int i = 0; for (GradleProject p : projects) { items[i++] = p.getName(); } projectCombo.setItems(items); if (project!=null) { projectCombo.setText(project.getName()); } projectCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String newProjectName = projectCombo.getText(); if ("".equals(newProjectName)) { setProject(null); setTasksDocument(""); } else { IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(newProjectName); setProject(GradleCore.create(newProject)); setTasksDocument(tasksViewer.getSourceViewer().getDocument().get()); } } }); refreshButton = new Button(parent, SWT.PUSH); refreshButton.setText("Refresh"); refreshButton.setToolTipText("Rebuild the gradle model and refresh the task list"); refreshButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent evt) { GradleProject currentProject = project; if (currentProject != null) { try { project.requestGradleModelRefresh(); } catch (CoreException e) { // ignore } tasksIndex.setProject(project); } } }); grabHor.align(SWT.RIGHT, SWT.CENTER).applyTo(refreshButton); } private List<GradleProject> getGradleProjects() { IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); ArrayList<GradleProject> result = new ArrayList<GradleProject>(); for (IProject p : projects) { try { if (p.isAccessible() && p.hasNature(GradleNature.NATURE_ID)) { result.add(GradleCore.create(p)); } } catch (CoreException e) { GradleCore.log(e); } } return result; } private void createTaskEditor(final Composite parent) { StyledText styledText = new StyledText(parent, SWT.READ_ONLY | SWT.WRAP); styledText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); styledText.setBackground(parent.getBackground()); styledText.setText(EDITOR_INFO_LABEL); styledText.setStyleRange(new StyleRange(EDITOR_INFO_LABEL .indexOf(CTRL_SPACE_LABEL), CTRL_SPACE_LABEL.length(), styledText.getForeground(), styledText.getBackground(), SWT.BOLD | SWT.ITALIC)); tasksViewer = new TasksViewer(parent, tasksIndex, false); tasksViewer.setActivateContentAssistOnEmptyDocument(true); tasksViewer.getSourceViewer().getControl().setLayoutData(new GridData(GridData.FILL_BOTH)); setTasksDocument(""); } public void setDefaults(ILaunchConfigurationWorkingCopy configuration) { setProject(getContext()); if (tasksViewer != null) { setTasksDocument(""); } } private void setProject(GradleProject project) { //TODO: when restoring from persistent conf, can get non-existent projects... // how to handle that case? if (this.project==project) //Don't do anything if project is unchanged return; this.project = project; tasksIndex.setProject(project); if (projectCombo!=null) { if (project!=null) { projectCombo.setText(project.getName()); } else { projectCombo.deselectAll(); } } updateLaunchConfigurationDialog(); } private GradleProject getContext() { IWorkbench wb = PlatformUI.getWorkbench(); IWorkbenchWindow win = wb.getActiveWorkbenchWindow(); IWorkbenchPage page = win==null ? null : win.getActivePage(); if (page != null) { ISelection selection = page.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection ss = (IStructuredSelection)selection; if (!ss.isEmpty()) { Object obj = ss.getFirstElement(); if (obj instanceof IResource) { IResource rsrc = (IResource) obj; IProject prj = rsrc.getProject(); if (prj!=null) { return GradleCore.create(prj); } } } } IEditorPart part = page.getActiveEditor(); if (part != null) { IEditorInput input = part.getEditorInput(); IResource rsrc = (IResource) input.getAdapter(IResource.class); if (rsrc!=null) { IProject prj = rsrc.getProject(); if (prj!=null) { return GradleCore.create(prj); } } } } return null; } public void initializeFrom(ILaunchConfiguration conf) { debug(">>> initializing Gradle launch tab"); try { for (Object attName : conf.getAttributes().keySet()) { debug(""+attName); } } catch (CoreException e) { GradleCore.log(e); } debug("<<< initializing Gradle launch tab"); setProject(GradleLaunchConfigurationDelegate.getProject(conf)); setTasksDocument(GradleLaunchConfigurationDelegate.getTasks(conf)); } private void setTasksDocument(String tasks) { Document document = new Document(tasks); document.addDocumentListener(new IDocumentListener() { @Override public void documentChanged(DocumentEvent event) { GradleLaunchTasksTab.this.updateLaunchConfigurationDialog(); } @Override public void documentAboutToBeChanged(DocumentEvent event) { // empty } }); tasksViewer.setDocument(document); } @Override public void updateLaunchConfigurationDialog() { super.updateLaunchConfigurationDialog(); } private static void debug(String string) { if (DEBUG) { System.out.println(string); } } @Override public boolean canSave() { //Don't allow saving until the model is properly initialized. If it isn't, the checkboxes in the tree //don't have well defined state. return haveGradleModel(); } public boolean isValid() { return canSave(); } public void performApply(ILaunchConfigurationWorkingCopy conf) { GradleLaunchConfigurationDelegate.setProject(conf, project); GradleLaunchConfigurationDelegate.setTasks(conf, tasksViewer.getSourceViewer().getDocument().get()); } private boolean haveGradleModel() { try { return project != null && project.getGradleModel()!=null; } catch (FastOperationFailedException e) { } catch (CoreException e) { GradleCore.log(e); } return false; } public String getName() { return "Gradle Tasks"; } @Override public void dispose() { if (tasksViewer != null) { tasksViewer.dispose(); } super.dispose(); } }
epl-1.0
Snickermicker/openhab2
bundles/org.openhab.binding.nibeheatpump/src/test/java/org/openhab/binding/nibeheatpump/internal/models/PumpModelTest.java
1687
/** * Copyright (c) 2010-2019 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.nibeheatpump.internal.models; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; /** * @author Pauli Anttila - Initial contribution */ public class PumpModelTest { @Before public void Before() { } @Test public void TestF1X45() { final String pumpModelString = "F1X45"; final PumpModel pumpModel = PumpModel.getPumpModel(pumpModelString); assertEquals(PumpModel.F1X45, pumpModel); } @Test public void TestF1X55() { final String pumpModelString = "F1X55"; final PumpModel pumpModel = PumpModel.getPumpModel(pumpModelString); assertEquals(PumpModel.F1X55, pumpModel); } @Test public void TestF750() { final String pumpModelString = "F750"; final PumpModel pumpModel = PumpModel.getPumpModel(pumpModelString); assertEquals(PumpModel.F750, pumpModel); } @Test public void TestF470() { final String pumpModelString = "F470"; final PumpModel pumpModel = PumpModel.getPumpModel(pumpModelString); assertEquals(PumpModel.F470, pumpModel); } @Test(expected = IllegalArgumentException.class) public void badPumpModelTest() { PumpModel.getPumpModel("XXXX"); } }
epl-1.0
eclipse/ice
org.eclipse.ice.tests.datastructures/src/org/eclipse/ice/tests/datastructures/MaterialTester.java
7902
/******************************************************************************* * Copyright (c) 2012, 2014 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.ice.tests.datastructures; 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 java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.xml.bind.JAXBException; import org.eclipse.ice.datastructures.ICEObject.ICEJAXBHandler; import org.eclipse.ice.datastructures.form.Material; import org.eclipse.ice.datastructures.form.MaterialStack; import org.junit.Test; /** * This class is responsible for testing the Material class. * * @author Jay Jay Billings * */ public class MaterialTester { /** * This operation checks the Material class to make sure that simple * attributes such as names and properties can be changed. */ @Test public void checkSimpleAttributes() { // Local Declarations Material testMaterial = TestMaterialFactory.createCO2(); // Check the name testMaterial.setName("CO2"); assertEquals("CO2", testMaterial.getName()); // Check properties - just test handling a few testMaterial.setProperty("molar mass (g/mol)", 44.01); double mass = testMaterial.getProperty("molar mass (g/mol)"); assertEquals(44.01, mass, 1.0e-16); testMaterial.setProperty("vapor pressure (MPa)", 5.73); double pressure = testMaterial.getProperty("vapor pressure (MPa)"); assertEquals(5.73, pressure, 1.0e-16); // Get all the properties and make sure they have molar mass and vapor // pressure. Map<String, Double> properties = testMaterial.getProperties(); assertTrue(properties.containsKey("molar mass (g/mol)")); assertTrue(properties.containsKey("vapor pressure (MPa)")); // Make sure that requesting a property that isn't in the map returns // 0.0. assertEquals(0.0, testMaterial.getProperty("penguin"), 1.0e-8); // Make some more test materials Material carbon = new Material(); carbon.setName("C"); Material c1 = new Material(); c1.setName("12C"); // Test the get isotopic number and get elemental name assertEquals(12, c1.getIsotopicNumber()); assertEquals(carbon.getName(), carbon.getElementalName()); assertEquals(0, carbon.getIsotopicNumber()); assertEquals(carbon.getName(), c1.getElementalName()); return; } /** * This operation checks that the Material class can properly manage a set * of component Materials that define its detailed composition. */ @Test public void checkComponents() { // Local Declarations Material testMaterial = TestMaterialFactory.createCO2(); // Check its components assertNotNull(testMaterial.getComponents()); List<MaterialStack> components = testMaterial.getComponents(); assertEquals(2, components.size()); // Get the Materials Material firstMaterial = components.get(0).getMaterial(); Material secondMaterial = components.get(1).getMaterial(); // Check them in an order independent way. It is enough to check that // the components are there. There is no need to check their sizes. assertTrue(("C".equals(firstMaterial.getName()) && "O".equals(secondMaterial.getName())) || ("O".equals(firstMaterial.getName()) && "C".equals(secondMaterial.getName()))); } /** * This operation checks that a set of materials can properly sort itself * using the compare to method on the material's names. For example, sorting * a list such as b, c, 1c, d, f, 5c should give the resulting order of a, * b, c, 1c, 5c, d, f. */ @Test public void checkSorting() { // Make some test materials Material A = new Material(); A.setName("A"); Material B = new Material(); B.setName("B"); Material co2 = TestMaterialFactory.createCO2(); Material B1 = new Material(); B1.setName("3B"); // Make sure that alphabetical order is followed assertTrue(A.compareTo(B) < 0); // Make sure that isotopes go in numeric order assertTrue(B.compareTo(B1) < 0); // Make sure that a blank material would be at the front of a list assertTrue(A.compareTo(new Material()) > 0); // Make sure that if materials have the same name they are the same when // compared. Material A1 = new Material(); A1.setName(A.getName()); assertTrue(A.compareTo(A1) == 0); // Make sure that the compound is in proper alphabetic order (no numeric // sorting). assertTrue(co2.compareTo(B1) > 0); Material C = new Material(); C.setName("C"); assertTrue(C.compareTo(co2) < 0); } /** * This operation checks that Materials.equals() and Materials.hashCode() * work. */ @Test public void checkEquality() { // Create two test materials to compare against each other Material testMat1 = TestMaterialFactory.createCO2(); Material testMat2 = TestMaterialFactory.createCO2(); // They should be equal assertTrue(testMat1.equals(testMat2)); // Make sure that a self comparison works assertTrue(testMat1.equals(testMat1)); // Make sure that passing something else in fails assertFalse(testMat1.equals(1)); // Check that the hash code doesn't change with no changes in state assertEquals(testMat1.hashCode(), testMat1.hashCode()); // Check that they have the same hash codes assertEquals(testMat1.hashCode(), testMat2.hashCode()); } /** * This operation checks that Material.copy() and Material.clone() work. */ @Test public void checkCopying() { // Create a material to copy and check Material material = TestMaterialFactory.createCO2(); Material materialCopy = new Material(), materialClone = null; // Copy it and check it materialCopy.copy(material); // Make sure they are equal assertTrue(material.equals(materialCopy)); // Checking cloning materialClone = (Material) material.clone(); assertEquals(material, materialClone); } /** * This operation checks that the Material class can be loaded and written * with JAXB. */ @Test public void checkPersistence() { // Local Declarations ICEJAXBHandler xmlHandler = new ICEJAXBHandler(); ArrayList<Class> classList = new ArrayList<Class>(); classList.add(Material.class); // Use the ICE JAXB Manipulator instead of raw JAXB. Waste not want not. ICEJAXBHandler jaxbHandler = new ICEJAXBHandler(); // Create a Material that will be written to XML Material material = TestMaterialFactory.createCO2(); try { // Write the material to a byte stream so that it can be converted // easily and read back in. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jaxbHandler.write(material, classList, outputStream); // Read it back from the stream into a second Material by converting // the output stream into a byte array and then an input stream. ByteArrayInputStream inputStream = new ByteArrayInputStream( outputStream.toByteArray()); Material readMaterial = (Material) jaxbHandler.read(classList, inputStream); // They should be equal. assertTrue(readMaterial.equals(material)); } catch (NullPointerException | JAXBException | IOException e) { // Just learned about Multicatch! Is this not the coolest #!@%? e.printStackTrace(); } return; } }
epl-1.0
codenvy/che-core
platform-api-client-gwt/che-core-client-gwt-project/src/main/java/org/eclipse/che/api/project/gwt/client/QueryExpression.java
3646
/******************************************************************************* * 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.project.gwt.client; /** @author Artem Zatsarynnyy */ public class QueryExpression { private String name; private String path; private String mediaType; private String text; private int maxItems; private int skipCount; /** * Get path to start search. * * @return path to start search */ public String getPath() { return path; } /** * Set path to start search. * * @param path * path to start search * @return this {@code QueryExpression} */ public QueryExpression setPath(String path) { this.path = path; return this; } /** * Get name of file to search. * * @return file name to search */ public String getName() { return name; } /** * Set name of file to search. * <p/> * Supported wildcards are: * <ul> * <li><code>*</code>, which matches any character sequence (including the empty one); * <li><code>?</code>, which matches any single character. * </ul> * * @param name * file name to search * @return this {@code QueryExpression} */ public QueryExpression setName(String name) { this.name = name; return this; } /** * Get media type of file to search. * * @return media type of file to search */ public String getMediaType() { return mediaType; } /** * Set media type of file to search. * * @param mediaType * media type of file to search * @return this {@code QueryExpression} */ public QueryExpression setMediaType(String mediaType) { this.mediaType = mediaType; return this; } /** * Get text to search. * * @return text to search */ public String getText() { return text; } /** * Set text to search. * * @param text * text to search * @return this {@code QueryExpression} */ public QueryExpression setText(String text) { this.text = text; return this; } /** * Get maximum number of items in response. * * @return maximum number of items in response */ public int getMaxItems() { return maxItems; } /** * Set maximum number of items in response. * * @param maxItems * maximum number of items in response * @return this {@code QueryExpression} */ public QueryExpression setMaxItems(int maxItems) { this.maxItems = maxItems; return this; } /** * Get amount of items to skip. * * @return amount of items to skip */ public int getSkipCount() { return skipCount; } /** * Set amount of items to skip. * * @param skipCount * amount of items to skip * @return this {@code QueryExpression} */ public QueryExpression setSkipCount(int skipCount) { this.skipCount = skipCount; return this; } }
epl-1.0
tetrabox/minijava
plugins/org.tetrabox.minijava.model/src/org/tetrabox/minijava/model/miniJava/VariableDeclaration.java
401
/** */ package org.tetrabox.minijava.model.miniJava; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Variable Declaration</b></em>'. * <!-- end-user-doc --> * * * @see org.tetrabox.minijava.model.miniJava.MiniJavaPackage#getVariableDeclaration() * @model * @generated */ public interface VariableDeclaration extends Symbol, Assignee { } // VariableDeclaration
epl-1.0
mischwarz/Weasis
weasis-base/weasis-base-ui/src/main/java/org/weasis/base/ui/Messages.java
1097
/******************************************************************************* * Copyright (c) 2016 Weasis Team 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: * Nicolas Roduit - initial API and implementation *******************************************************************************/ package org.weasis.base.ui; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = "org.weasis.base.ui.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
epl-1.0
CodeOffloading/JikesRVM-CCO
jikesrvm-3.1.3/rvm/src/org/jikesrvm/scheduler/SoftLatch.java
2290
/* * This file is part of the Jikes RVM project (http://jikesrvm.org). * * This file is licensed to You under the Eclipse Public License (EPL); * 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 * * See the COPYRIGHT.txt file distributed with this work for information * regarding copyright ownership. */ package org.jikesrvm.scheduler; /** * An implementation of a latch using monitors. * This essentially gives you park/unpark functionality. It can also * be used like the Win32-style AutoResetEvent or ManualResetEvent. * <p> * Park/unpark example: use open() to unpark and waitAndClose() to park. * <p> * AutoResetEvent example: use open() to set, close() to reset, and * waitAndClose() to wait. * <p> * ManualResetEvent example: use open() to set, close() to reset, and * wait() to wait. * <p> * Note: <b><i>never</i></b> synchronize on instances of this class. */ public class SoftLatch { private boolean open; /** Create a new latch, with the given open/closed state. */ public SoftLatch(boolean open) { this.open = open; } /** * Open the latch and let all of the thread(s) waiting on it through. * But - if any of the threads is using waitAndClose(), then as soon * as that thread awakes further threads will be blocked. */ public synchronized void open() { open=true; notifyAll(); } /** * Close the latch, causing future calls to wait() or waitAndClose() * to block. */ public synchronized void close() { open=false; } /** * Wait for the latch to become open. If it is already open, don't * wait at all. */ public synchronized void await() { while (!open) { try { wait(); } catch (InterruptedException e) { throw new Error(e); } } } /** * Wait for the latch to become open, and then close it and return. * If the latch is already open, don't wait at all, just close it * immediately and return. */ public synchronized void waitAndClose() { while (!open) { try { wait(); } catch (InterruptedException e) { throw new Error(e); } } open=false; } }
epl-1.0
uncomplicate/neanderthal
src/java/uncomplicate/neanderthal/internal/api/RealBufferAccessor.java
722
// Copyright (c) Dragan Djuric. All rights reserved. // The use and distribution terms for this software are covered by the // Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) or later // which can be found in the file LICENSE at the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by // the terms of this license. // You must not remove this notice, or any other, from this software. package uncomplicate.neanderthal.internal.api; import java.nio.ByteBuffer; public interface RealBufferAccessor extends BufferAccessor { double get (ByteBuffer buf, long index); void set (ByteBuffer buf, long index, double value); }
epl-1.0
opendaylight/yangtools
data/yang-data-tree-spi/src/main/java/org/opendaylight/yangtools/yang/data/tree/spi/AbstractAvailableLeafCandidateNode.java
766
/* * Copyright (c) 2015 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.data.tree.spi; import java.util.Optional; import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; abstract class AbstractAvailableLeafCandidateNode extends AbstractLeafCandidateNode { AbstractAvailableLeafCandidateNode(final NormalizedNode dataAfter) { super(dataAfter); } @Override public final Optional<NormalizedNode> getDataAfter() { return dataOptional(); } }
epl-1.0
ttimbul/eclipse.wst
bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/util/SelectionAdapter.java
2831
/******************************************************************************* * 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 *******************************************************************************/ package org.eclipse.wst.xsd.ui.internal.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; public abstract class SelectionAdapter implements ISelectionProvider { protected List listenerList = new ArrayList(); protected ISelection selection = new StructuredSelection(); protected ISelectionProvider eventSource; public void setEventSource(ISelectionProvider eventSource) { this.eventSource = eventSource; } public void addSelectionChangedListener(ISelectionChangedListener listener) { listenerList.add(listener); } public void removeSelectionChangedListener(ISelectionChangedListener listener) { listenerList.remove(listener); } public ISelection getSelection() { return selection; } /** * This method should be specialized to return the correct object that corresponds to the 'other' model */ abstract protected Object getObjectForOtherModel(Object object); public void setSelection(ISelection modelSelection) { List otherModelObjectList = new ArrayList(); if (modelSelection instanceof IStructuredSelection) { for (Iterator i = ((IStructuredSelection)modelSelection).iterator(); i.hasNext(); ) { Object modelObject = i.next(); Object otherModelObject = getObjectForOtherModel(modelObject); if (otherModelObject != null) { otherModelObjectList.add(otherModelObject); } } } StructuredSelection nodeSelection = new StructuredSelection(otherModelObjectList); selection = nodeSelection; SelectionChangedEvent event = new SelectionChangedEvent(eventSource != null ? eventSource : this, nodeSelection); for (Iterator i = listenerList.iterator(); i.hasNext(); ) { ISelectionChangedListener listener = (ISelectionChangedListener)i.next(); listener.selectionChanged(event); } } }
epl-1.0
debabratahazra/DS
designstudio/components/workbench/ui/com.odcgroup.workbench.compare/src/main/java/com/odcgroup/workbench/compare/team/action/SvnEditConflictsAction.java
605
package com.odcgroup.workbench.compare.team.action; import org.eclipse.team.internal.ui.actions.TeamAction; import org.eclipse.team.svn.ui.action.local.EditConflictsAction; /** * * @author pkk * */ @SuppressWarnings("restriction") public class SvnEditConflictsAction extends AbstractTeamAction { /** * @param text */ public SvnEditConflictsAction() { super("Edit Conflicts"); } /* (non-Javadoc) * @see com.odcgroup.workbench.compare.team.action.AbstractTeamAction#fetchTeamActionDelegate() */ public TeamAction fetchTeamActionDelegate() { return new EditConflictsAction(); } }
epl-1.0
aschmois/ForgeEssentialsMain
src/main/java/com/forgeessentials/commands/world/CommandFindblock.java
3510
package com.forgeessentials.commands.world; import java.util.ArrayList; import java.util.List; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.permissions.PermissionsManager.RegisteredPermValue; import com.forgeessentials.commands.util.FEcmdModuleCommands; import com.forgeessentials.commands.util.TickTaskBlockFinder; import com.forgeessentials.core.misc.TranslatedCommandException; import com.forgeessentials.core.misc.FECommandManager.ConfigurableCommand; import cpw.mods.fml.common.registry.GameData; public class CommandFindblock extends FEcmdModuleCommands implements ConfigurableCommand { public static final int defaultCount = 1; public static int defaultRange = 20 * 16; public static int defaultSpeed = 16 * 16; @Override public void loadConfig(Configuration config, String category) { defaultRange = config.get(category, "defaultRange", defaultRange, "Default max distance used.").getInt(); defaultSpeed = config.get(category, "defaultSpeed", defaultSpeed, "Default speed used.").getInt(); } @Override public String[] getDefaultAliases() { return new String[] { "fb" }; } @Override public String getCommandName() { return "findblock"; } /* * syntax: /fb <block> [max distance, def = 20 * 16] [amount of blocks, def = 1] [speed, def = 10] */ @Override public void processCommandPlayer(EntityPlayerMP sender, String[] args) { if (args.length < 2) { throw new TranslatedCommandException(getCommandUsage(sender)); } String id = args[0]; int meta = parseInt(sender, args[1]); int range = (args.length < 2) ? defaultRange : parseIntWithMin(sender, args[2], 1); int amount = (args.length < 3) ? defaultCount : parseIntWithMin(sender, args[3], 1); int speed = (args.length < 4) ? defaultSpeed : parseIntWithMin(sender, args[4], 1); new TickTaskBlockFinder(sender, id, meta, range, amount, speed); } @Override public boolean canConsoleUseCommand() { return false; } @Override public List<String> addTabCompletionOptions(ICommandSender sender, String[] args) { if (args.length == 1) { List<String> names = new ArrayList<String>(); for (Item i : GameData.getItemRegistry().typeSafeIterable()) { names.add(i.getUnlocalizedName()); } return getListOfStringsMatchingLastWord(args, names); } else if (args.length == 2) { return getListOfStringsMatchingLastWord(args, defaultRange + ""); } else if (args.length == 3) { return getListOfStringsMatchingLastWord(args, defaultCount + ""); } else if (args.length == 4) { return getListOfStringsMatchingLastWord(args, defaultSpeed + ""); } else { throw new TranslatedCommandException(getCommandUsage(sender)); } } @Override public RegisteredPermValue getDefaultPermission() { return RegisteredPermValue.OP; } @Override public String getCommandUsage(ICommandSender sender) { return "/fb <block> [max distance] [amount of blocks] [speed] Finds a block."; } }
epl-1.0
caxcaxcoatl/org.loezto.e
org.loezto.e/src/org/loezto/e/part/Workplate.java
4688
package org.loezto.e.part; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.inject.Inject; import org.eclipse.core.databinding.beans.BeanProperties; import org.eclipse.core.databinding.observable.list.WritableList; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.core.services.events.IEventBroker; import org.eclipse.e4.ui.di.Focus; import org.eclipse.e4.ui.di.UIEventTopic; import org.eclipse.e4.ui.services.EMenuService; import org.eclipse.e4.ui.workbench.modeling.ESelectionService; import org.eclipse.jface.databinding.viewers.ViewerSupport; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.loezto.e.events.EEvents; import org.loezto.e.model.EService; import org.loezto.e.model.Entry; import org.loezto.e.model.Task; public class Workplate { private Table table; private TableColumn tblclmnDeadline; private TableColumn tblclmnTask; private TableColumn tblclmnTopic; private TableColumn tblclmnFullname; private WritableList<Task> wl; private TableViewer tableViewer; @Inject EService eService; @Inject IEventBroker eBroker; @Inject EMenuService menuService; @Inject ESelectionService selService; public Workplate() { } @PostConstruct void buildUI(Composite parent) { tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION); table = tableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); TableViewerColumn tableViewerColumn = new TableViewerColumn(tableViewer, SWT.NONE); tblclmnDeadline = tableViewerColumn.getColumn(); tblclmnDeadline.setWidth(100); tblclmnDeadline.setText("Deadline"); TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(tableViewer, SWT.NONE); tblclmnTask = tableViewerColumn_1.getColumn(); tblclmnTask.setWidth(100); tblclmnTask.setText("Task"); TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(tableViewer, SWT.NONE); tblclmnTopic = tableViewerColumn_2.getColumn(); tblclmnTopic.setWidth(100); tblclmnTopic.setText("Topic"); TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(tableViewer, SWT.NONE); tblclmnFullname = tableViewerColumn_3.getColumn(); tblclmnFullname.setWidth(100); tblclmnFullname.setText("Fullname"); setupViewer(); if (eService.isActive()) wl.addAll(eService.incomingDeadlines()); tableViewer.addDoubleClickListener(new IDoubleClickListener() { @Override public void doubleClick(DoubleClickEvent event) { Task task; IStructuredSelection sel = (IStructuredSelection) tableViewer.getSelection(); if (sel.size() != 1) return; task = (Task) sel.getFirstElement(); eBroker.send("E_SELECT_TOPIC", task.getTopic()); eBroker.post("E_SELECT_TASK", task); } }); } private void setupViewer() { // This would need tasklist to be reworked to accept a parameter menuService.registerContextMenu(table, "org.loezto.e.popupmenu.workplate"); wl = new WritableList<>(new ArrayList<Task>(), Entry.class); ViewerSupport.bind(tableViewer, wl, BeanProperties.values(new String[] { "dueDate", "name", "topic.fullName", "fullName" })); tableViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection sel = (IStructuredSelection) event.getSelection(); if (sel != null) selService.setSelection(sel.getFirstElement()); } }); table.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { tableViewer.setSelection(null); } @Override public void focusGained(FocusEvent e) { } }); } @Inject @Optional void updateList(@UIEventTopic(EEvents.TASK_ALL) Task task) { wl.clear(); wl.addAll(eService.incomingDeadlines()); } @Inject @Optional private void openListener(@UIEventTopic("E_OPEN") String s) { wl.clear(); wl.addAll(eService.incomingDeadlines()); } @Inject @Optional private void closeListener(@UIEventTopic("E_CLOSE") String s) { wl.clear(); } @Focus void focus() { table.setFocus(); } }
epl-1.0
scmod/nexus-public
testsuite/legacy-testsuite/src/test/java/org/sonatype/nexus/testsuite/repo/nexus4594/NEXUS4594Blocked2NFCIT.java
1629
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.testsuite.repo.nexus4594; import org.junit.Test; public class NEXUS4594Blocked2NFCIT extends Blocked2NFCITSupport { @Test public void whileNexusIsAutoBlockedItDoesNotAddPathsToNFC() throws Exception { // auto block Nexus autoBlockNexus(); // make a request to an arbitrary artifact and verify that Nexus did not went remote (repository is blocked) // Nexus should not add it to NFC, but that will see later while re-requesting the artifact with Nexus unblocked downloadArtifact("foo", "bar", "5.0"); verifyNexusDidNotWentRemote(); // unblock Nexus so we can request again the arbitrary artifact autoUnblockNexus(); // make a request and check that Nexus went remote (so is not in NFC) downloadArtifact("foo", "bar", "5.0"); verifyNexusWentRemote(); } }
epl-1.0
scmod/nexus-public
plugins/rubygem/nexus-ruby-client/src/main/java/org/sonatype/nexus/ruby/client/internal/JerseyRubyProxyRepositoryFactory.java
2361
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ package org.sonatype.nexus.ruby.client.internal; import javax.inject.Named; import javax.inject.Singleton; import org.sonatype.nexus.client.core.subsystem.repository.Repository; import org.sonatype.nexus.client.internal.rest.jersey.subsystem.repository.JerseyProxyRepositoryFactory; import org.sonatype.nexus.client.rest.jersey.JerseyNexusClient; import org.sonatype.nexus.rest.model.RepositoryBaseResource; import org.sonatype.nexus.rest.model.RepositoryProxyResource; import org.sonatype.nexus.ruby.client.RubyProxyRepository; @Named @Singleton public class JerseyRubyProxyRepositoryFactory extends JerseyProxyRepositoryFactory { @Override public int canAdapt(final RepositoryBaseResource resource) { int score = super.canAdapt(resource); if (score > 0) { if (JerseyRubyProxyRepository.PROVIDER_ROLE.equals(resource.getProviderRole()) && JerseyRubyProxyRepository.PROVIDER.equals(resource.getProvider())) { score++; } } return score; } @Override public JerseyRubyProxyRepository adapt(final JerseyNexusClient nexusClient, final RepositoryBaseResource resource) { return new JerseyRubyProxyRepository(nexusClient, (RepositoryProxyResource) resource); } @Override public boolean canCreate(final Class<? extends Repository> type) { return RubyProxyRepository.class.equals(type); } @Override public JerseyRubyProxyRepository create(final JerseyNexusClient nexusClient, final String id) { return new JerseyRubyProxyRepository(nexusClient, id); } }
epl-1.0
TatyPerson/Xtext2Sonar
evaluation-scenarios/sonar-PogoDsl/PogoDsl-squid/src/main/java/org/sonar/PogoDsl/api/PogoDslParseErrorLoggerVisitor.java
1117
package org.sonar.PogoDsl.api; import org.sonar.PogoDsl.api.PogoDslImpl; import org.sonar.squidbridge.SquidAstVisitor; import org.sonar.squidbridge.SquidAstVisitorContext; import com.sonar.sslr.api.AstAndTokenVisitor; import com.sonar.sslr.api.AstNode; import com.sonar.sslr.api.GenericTokenType; import com.sonar.sslr.api.Grammar; import com.sonar.sslr.api.Token; public class PogoDslParseErrorLoggerVisitor <GRAMMAR extends Grammar> extends SquidAstVisitor<GRAMMAR> implements AstAndTokenVisitor { private SquidAstVisitorContext context = null; public PogoDslParseErrorLoggerVisitor(SquidAstVisitorContext context){ this.context = context; } @Override public void init() { subscribeTo(PogoDslImpl.POGOSYSTEM); } @Override public void visitNode(AstNode node) { AstNode identifierAst = node.getFirstChild(GenericTokenType.IDENTIFIER); if( identifierAst != null ) { PogoDslImpl.LOG.warn("[{}:{}]: syntax error, skip '{}'", new Object[] {context.getFile(), node.getToken().getLine(), identifierAst.getTokenValue()}); } } public void visitToken(Token token) { } }
epl-1.0
opendaylight/vtn
manager/implementation/src/main/java/org/opendaylight/vtn/manager/internal/util/pathmap/PathMapUtils.java
19208
/* * Copyright (c) 2015, 2016 NEC Corporation. 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.vtn.manager.internal.util.pathmap; import static org.opendaylight.vtn.manager.internal.util.MiscUtils.LOG_SEPARATOR; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import javax.annotation.Nonnull; import com.google.common.base.Optional; import org.slf4j.Logger; import org.opendaylight.vtn.manager.VTNException; import org.opendaylight.vtn.manager.internal.util.ChangedData; import org.opendaylight.vtn.manager.internal.util.DataStoreUtils; import org.opendaylight.vtn.manager.internal.util.IdentifiedData; import org.opendaylight.vtn.manager.internal.util.MiscUtils; import org.opendaylight.vtn.manager.internal.util.VtnIndexComparator; import org.opendaylight.vtn.manager.internal.util.flow.FlowUtils; import org.opendaylight.vtn.manager.internal.util.flow.cond.FlowCondUtils; import org.opendaylight.vtn.manager.internal.util.pathpolicy.PathPolicyUtils; import org.opendaylight.vtn.manager.internal.util.rpc.RpcException; import org.opendaylight.vtn.manager.internal.util.vnode.VTenantIdentifier; import org.opendaylight.controller.md.sal.binding.api.ReadTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.pathmap.rev150328.GlobalPathMaps; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.pathmap.rev150328.VtnPathMapConfig; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.pathmap.rev150328.VtnPathMapList; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.pathmap.rev150328.vtn.path.map.list.VtnPathMap; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.pathmap.rev150328.vtn.path.map.list.VtnPathMapBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.pathmap.rev150328.vtn.path.map.list.VtnPathMapKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.rev150328.vtn.info.VtnPathMaps; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.rev150328.vtns.Vtn; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.rev150328.vtns.VtnKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.types.rev150209.VnodeName; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.types.rev150209.VtnFlowTimeoutConfig; import org.opendaylight.yang.gen.v1.urn.opendaylight.vtn.types.rev150209.VtnUpdateType; /** * {@code PathMapUtils} class is a collection of utility class methods * for path map. */ public final class PathMapUtils { /** * Private constructor that protects this class from instantiating. */ private PathMapUtils() {} /** * Return a new {@link RpcException} that indicates the path map ID is * missing. * * @return An {@link RpcException}. */ public static RpcException getNullMapIndexException() { return RpcException.getNullArgumentException("Path map index"); } /** * Return a new {@link RpcException} that indicates the given path map * index is invalid. * * @param index The path map index. * @param cause A throwable that indicates the cause of error. * @return An {@link RpcException}. */ public static RpcException getInvalidMapIndexException( Integer index, Throwable cause) { String msg = MiscUtils.joinColon("Invalid path map index", index); return RpcException.getBadArgumentException(msg, cause); } /** * Convert the given {@link VtnPathMapConfig} instance into a * {@link VtnPathMapBuilder} instance. * * <p> * If the given instance does not contain the path policy ID, this * method set zero as the path policy ID. * </p> * * @param vpmc A {@link VtnPathMapConfig} instance. * @return A {@link VtnPathMapBuilder} instance that contains values * in the given {@link VtnPathMapConfig} instance. * @throws RpcException * The given {@link VtnPathMapConfig} instance contains invalid data. */ public static VtnPathMapBuilder toVtnPathMapBuilder(VtnPathMapConfig vpmc) throws RpcException { if (vpmc == null) { throw RpcException.getNullArgumentException( "Path map configuration"); } VtnPathMapBuilder builder = new VtnPathMapBuilder((VtnFlowTimeoutConfig)vpmc); setIndex(builder, vpmc.getIndex()); setCondition(builder, vpmc.getCondition()); Integer policy = vpmc.getPolicy(); if (policy == null) { // Use the system default routing policy. policy = Integer.valueOf(PathPolicyUtils.DEFAULT_POLICY); } setPolicy(builder, policy); FlowUtils.verifyFlowTimeout(vpmc); return builder; } /** * Ensure that there is not duplicate map index in the path map list. * * @param set A set of map indices. * @param index An index to be tested. * @throws RpcException An error occurred. */ public static void verifyMapIndex(Set<Integer> set, Integer index) throws RpcException { if (!set.add(index)) { String msg = "Duplicate map index: " + index; throw RpcException.getBadArgumentException(msg); } } /** * Ensure that the given map index is valid. * * @param index An index to be tested. * @throws RpcException * The given map index is invalid. */ public static void verifyMapIndex(Integer index) throws RpcException { setIndex(new VtnPathMapBuilder(), index); } /** * Return the path map index in the given instance identifier. * * @param path An {@link InstanceIdentifier} instance. * @return The index of the path map if found. * {@code null} if not found. */ public static Integer getIndex(InstanceIdentifier<?> path) { VtnPathMapKey key = path.firstKeyOf(VtnPathMap.class); return (key == null) ? null : key.getIndex(); } /** * Create the instance identifier for the global path map specified by the * given map index. * * @param index The index assigned to the global path map. * @return An {@link InstanceIdentifier} instance. * @throws RpcException * The given map index is invalid. */ public static InstanceIdentifier<VtnPathMap> getIdentifier(Integer index) throws RpcException { if (index == null) { throw getNullMapIndexException(); } return InstanceIdentifier.builder(GlobalPathMaps.class). child(VtnPathMap.class, new VtnPathMapKey(index)).build(); } /** * Create the instance identifier for the VTN path map specified by the * given VTN name and map index. * * <p> * This method is used to retrieve path map in existing VTN. * </p> * * @param name The name of the VTN. * @param index The index assigned to the path map in the specified VTN. * @return An {@link InstanceIdentifier} instance. * @throws RpcException * The given VTN name or map index is invalid. */ public static InstanceIdentifier<VtnPathMap> getIdentifier( String name, Integer index) throws RpcException { return getIdentifier(VTenantIdentifier.create(name, true), index); } /** * Create the instance identifier for the VTN path map specified by the * given VTN identifier and map index. * * @param ident The identifier for the target VTN. * @param index The index assigned to the path map in the specified VTN. * @return An {@link InstanceIdentifier} instance. * @throws RpcException * The given map index is invalid. */ public static InstanceIdentifier<VtnPathMap> getIdentifier( VTenantIdentifier ident, Integer index) throws RpcException { if (index == null) { throw getNullMapIndexException(); } return ident.getIdentifierBuilder(). child(VtnPathMaps.class). child(VtnPathMap.class, new VtnPathMapKey(index)).build(); } /** * Determine whether the given path map container is empty or not. * * @param vplist A {@link VtnPathMapList} instance. * @return {@code true} only if the given path map container is empty. */ public static boolean isEmpty(VtnPathMapList vplist) { if (vplist == null) { return true; } List<VtnPathMap> list = vplist.getVtnPathMap(); return (list == null || list.isEmpty()); } /** * Read the path maps in the global path map list. * * @param rtx A {@link ReadTransaction} instance associated with the * read transaction for the MD-SAL datastore. * @return A list of all global path maps. * Each element in the list is sorted by index in ascending order. * An empty list is returned if no global path map is configured. * @throws VTNException An error occurred. */ public static List<VtnPathMap> readPathMaps(ReadTransaction rtx) throws VTNException { InstanceIdentifier<GlobalPathMaps> path = InstanceIdentifier.create(GlobalPathMaps.class); LogicalDatastoreType oper = LogicalDatastoreType.OPERATIONAL; Optional<GlobalPathMaps> opt = DataStoreUtils.read(rtx, oper, path); if (opt.isPresent()) { GlobalPathMaps maps = opt.get(); List<VtnPathMap> list = maps.getVtnPathMap(); if (list != null && !list.isEmpty()) { return MiscUtils.sortedCopy(list, new VtnIndexComparator()); } } return Collections.<VtnPathMap>emptyList(); } /** * Read the path map associated with the given index in the global path * map list. * * @param rtx A {@link ReadTransaction} instance associated with the * read transaction for the MD-SAL datastore. * @param index The index that specifies the path map. * @return A {@link VtnPathMap} instance if found. * {@code null} if not found. * @throws VTNException An error occurred. */ public static VtnPathMap readPathMap(ReadTransaction rtx, Integer index) throws VTNException { InstanceIdentifier<VtnPathMap> path = getIdentifier(index); LogicalDatastoreType oper = LogicalDatastoreType.OPERATIONAL; return DataStoreUtils.read(rtx, oper, path).orNull(); } /** * Read the VTN path maps in the given VTN. * * @param rtx A {@link ReadTransaction} instance associated with the * read transaction for the MD-SAL datastore. * @param ident The identifier for the target VTN. * @return A list of all VTN path maps in the given VTN. * Each element in the list is sorted by index in ascending order. * An empty list is returned if no VTN path map is configured. * @throws VTNException An error occurred. */ public static List<VtnPathMap> readPathMaps( ReadTransaction rtx, VTenantIdentifier ident) throws VTNException { InstanceIdentifier<VtnPathMaps> path = ident.getIdentifierBuilder(). child(VtnPathMaps.class).build(); LogicalDatastoreType oper = LogicalDatastoreType.OPERATIONAL; Optional<VtnPathMaps> opt = DataStoreUtils.read(rtx, oper, path); if (opt.isPresent()) { VtnPathMaps maps = opt.get(); List<VtnPathMap> list = maps.getVtnPathMap(); if (list != null && !list.isEmpty()) { return MiscUtils.sortedCopy(list, new VtnIndexComparator()); } } else { // Check to see if the target VTN is present. ident.fetch(rtx); } return Collections.<VtnPathMap>emptyList(); } /** * Read the path map associated with the given index in the given VTN. * * @param rtx A {@link ReadTransaction} instance associated with the * read transaction for the MD-SAL datastore. * @param ident The identifier for the target VTN. * @param index The index that specifies the path map. * @return A {@link VtnPathMap} instance if found. * {@code null} if not found. * @throws VTNException An error occurred. */ public static VtnPathMap readPathMap( ReadTransaction rtx, VTenantIdentifier ident, Integer index) throws VTNException { InstanceIdentifier<VtnPathMap> path = getIdentifier(ident, index); LogicalDatastoreType oper = LogicalDatastoreType.OPERATIONAL; Optional<VtnPathMap> opt = DataStoreUtils.read(rtx, oper, path); VtnPathMap vpm; if (opt.isPresent()) { vpm = opt.get(); } else { // Check to see if the target VTN is present. ident.fetch(rtx); vpm = null; } return vpm; } /** * Determine whether the specified path map was actually updated or not. * * <p> * Note that this method expects that both {@code before} and * {@code after} have the same index. * </p> * * @param old The path map before modification. * @param vpm The path map after modification. * @return {@code true} if the specified path map was actually updated. * {@code false} otherwise. */ public static boolean isUpdated(@Nonnull VtnPathMap old, @Nonnull VtnPathMap vpm) { // Compare flow condition name and policy ID. boolean changed = !(Objects.equals(old.getCondition(), vpm.getCondition()) && Objects.equals(old.getPolicy(), vpm.getPolicy())); if (!changed) { // Compare timeouts. changed = !FlowUtils.equalsFlowTimeoutConfig(old, vpm); } return changed; } /** * Return a string that describes the specified path map. * * @param vpm The path map. * Note that this method expects that the specified path map * is valid. * @return A string that describes the specified path map. */ public static String toString(VtnPathMap vpm) { StringBuilder builder = new StringBuilder("index="). append(vpm.getIndex()).append(LOG_SEPARATOR). append("cond=").append(vpm.getCondition().getValue()). append(LOG_SEPARATOR). append("policy=").append(vpm.getPolicy()); FlowUtils.setDescription(builder, vpm, LOG_SEPARATOR); return builder.toString(); } /** * Record an informational log message that indicates a path map has been * created or removed. * * @param logger A logger instance. * @param data An {@link IdentifiedData} instance that contains a * path map. * @param type {@link VtnUpdateType#CREATED} on added, * {@link VtnUpdateType#REMOVED} on removed. */ public static void log(Logger logger, IdentifiedData<?> data, VtnUpdateType type) { if (logger.isInfoEnabled()) { IdentifiedData<VtnPathMap> cdata = data.checkType(VtnPathMap.class); logger.info("{} path map has been {}: value={{}}", getDescription(cdata.getIdentifier()), MiscUtils.toLowerCase(type), toString(cdata.getValue())); } } /** * Record an informational log message that indicates a path map has been * changed. * * @param logger A logger instance. * @param data An {@link ChangedData} instance that contains a path map. */ public static void log(Logger logger, ChangedData<?> data) { if (logger.isInfoEnabled()) { ChangedData<VtnPathMap> cdata = data.checkType(VtnPathMap.class); logger.info("{} path map has been changed: old={{}}, new={{}}", getDescription(cdata.getIdentifier()), toString(cdata.getOldValue()), toString(cdata.getValue())); } } /** * Set the map index into the given {@link VtnPathMapBuilder} instance. * * @param builder A {@link VtnPathMapBuilder} instance. * @param index A map index to be set. * @throws RpcException The given map index is invalid. */ private static void setIndex(VtnPathMapBuilder builder, Integer index) throws RpcException { if (index == null) { throw getNullMapIndexException(); } try { builder.setIndex(index); } catch (RuntimeException e) { throw getInvalidMapIndexException(index, e); } } /** * Set the flow condition name into the given {@link VtnPathMapBuilder} * instance. * * @param builder A {@link VtnPathMapBuilder} instance. * @param vname A {@link VnodeName} instance that contains the name of * the flow condition. * @throws RpcException The given flow condition name is invalid. */ private static void setCondition(VtnPathMapBuilder builder, VnodeName vname) throws RpcException { FlowCondUtils.checkName(vname); builder.setCondition(vname); } /** * Set the path policy ID into the given {@link VtnPathMapBuilder} * instance. * * @param builder A {@link VtnPathMapBuilder} instance. * @param policy An {@link Integer} instance which represents the path * policy ID. * @throws RpcException The given path policy ID is invalid. */ private static void setPolicy(VtnPathMapBuilder builder, Integer policy) throws RpcException { try { builder.setPolicy(policy); } catch (RuntimeException e) { throw PathPolicyUtils.getInvalidPolicyIdException(policy, e); } } /** * Create a brief description about the path map specified by the given * instance identifier. * * @param path The path to the path map. * @return A brief description about the specified path map. */ private static String getDescription(InstanceIdentifier<VtnPathMap> path) { VtnKey key = path.firstKeyOf(Vtn.class); String desc; if (key == null) { desc = "Global"; } else { VTenantIdentifier vtnId = new VTenantIdentifier(key.getName()); desc = vtnId.toString() + ": VTN"; } return desc; } }
epl-1.0
paulianttila/openhab2
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/factory/VeluxHandlerFactory.java
10016
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.velux.internal.factory; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.velux.internal.VeluxBindingConstants; import org.openhab.binding.velux.internal.discovery.VeluxDiscoveryService; import org.openhab.binding.velux.internal.handler.VeluxBindingHandler; import org.openhab.binding.velux.internal.handler.VeluxBridgeHandler; import org.openhab.binding.velux.internal.handler.VeluxHandler; import org.openhab.binding.velux.internal.utils.Localization; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.i18n.LocaleProvider; import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.binding.BaseThingHandlerFactory; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerFactory; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.ComponentContext; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link VeluxHandlerFactory} is responsible for creating things and thing * handlers. * * @author Guenther Schreiner - Initial contribution */ @NonNullByDefault @Component(service = ThingHandlerFactory.class, name = "binding.velux") public class VeluxHandlerFactory extends BaseThingHandlerFactory { private final Logger logger = LoggerFactory.getLogger(VeluxHandlerFactory.class); // Class internal private @Nullable ServiceRegistration<?> discoveryServiceRegistration = null; private @Nullable VeluxDiscoveryService discoveryService = null; private Set<VeluxBindingHandler> veluxBindingHandlers = new HashSet<>(); private Set<VeluxBridgeHandler> veluxBridgeHandlers = new HashSet<>(); private Set<VeluxHandler> veluxHandlers = new HashSet<>(); private @NonNullByDefault({}) LocaleProvider localeProvider; private @NonNullByDefault({}) TranslationProvider i18nProvider; private Localization localization = Localization.UNKNOWN; private @Nullable static VeluxHandlerFactory activeInstance = null; // Private private void registerDeviceDiscoveryService(VeluxBridgeHandler bridgeHandler) { logger.trace("registerDeviceDiscoveryService({}) called.", bridgeHandler); VeluxDiscoveryService discoveryService = this.discoveryService; if (discoveryService == null) { discoveryService = this.discoveryService = new VeluxDiscoveryService(localization); } discoveryService.addBridge(bridgeHandler); if (discoveryServiceRegistration == null) { discoveryServiceRegistration = bundleContext.registerService(DiscoveryService.class.getName(), discoveryService, new Hashtable<>()); } } private synchronized void unregisterDeviceDiscoveryService(VeluxBridgeHandler bridgeHandler) { logger.trace("unregisterDeviceDiscoveryService({}) called.", bridgeHandler); VeluxDiscoveryService discoveryService = this.discoveryService; if (discoveryService != null) { discoveryService.removeBridge(bridgeHandler); if (discoveryService.isEmpty()) { ServiceRegistration<?> discoveryServiceRegistration = this.discoveryServiceRegistration; if (discoveryServiceRegistration != null) { discoveryServiceRegistration.unregister(); this.discoveryServiceRegistration = null; } } } } private @Nullable ThingHandler createBindingHandler(Thing thing) { logger.trace("createBindingHandler({}) called for thing named '{}'.", thing.getUID(), thing.getLabel()); VeluxBindingHandler veluxBindingHandler = new VeluxBindingHandler(thing, localization); veluxBindingHandlers.add(veluxBindingHandler); return veluxBindingHandler; } private @Nullable ThingHandler createBridgeHandler(Thing thing) { logger.trace("createBridgeHandler({}) called for thing named '{}'.", thing.getUID(), thing.getLabel()); VeluxBridgeHandler veluxBridgeHandler = new VeluxBridgeHandler((Bridge) thing, localization); veluxBridgeHandlers.add(veluxBridgeHandler); registerDeviceDiscoveryService(veluxBridgeHandler); return veluxBridgeHandler; } private @Nullable ThingHandler createThingHandler(Thing thing) { logger.trace("createThingHandler({}) called for thing named '{}'.", thing.getUID(), thing.getLabel()); VeluxHandler veluxHandler = new VeluxHandler(thing, localization); veluxHandlers.add(veluxHandler); return veluxHandler; } private void updateBindingState() { veluxBindingHandlers.forEach((VeluxBindingHandler veluxBindingHandler) -> { veluxBindingHandler.updateBindingState(veluxBridgeHandlers.size(), veluxHandlers.size()); }); } private void updateLocalization() { if (localization == Localization.UNKNOWN && localeProvider != null && i18nProvider != null) { logger.trace("updateLocalization(): creating Localization based on locale={},translation={}).", localeProvider, i18nProvider); localization = new Localization(localeProvider, i18nProvider); } } // Constructor @Activate public VeluxHandlerFactory(final @Reference LocaleProvider givenLocaleProvider, final @Reference TranslationProvider givenI18nProvider) { logger.trace("VeluxHandlerFactory(locale={},translation={}) called.", givenLocaleProvider, givenI18nProvider); localeProvider = givenLocaleProvider; i18nProvider = givenI18nProvider; } @Reference protected void setLocaleProvider(final LocaleProvider givenLocaleProvider) { logger.trace("setLocaleProvider(): provided locale={}.", givenLocaleProvider); localeProvider = givenLocaleProvider; updateLocalization(); } @Reference protected void setTranslationProvider(TranslationProvider givenI18nProvider) { logger.trace("setTranslationProvider(): provided translation={}.", givenI18nProvider); i18nProvider = givenI18nProvider; updateLocalization(); } // Utility methods @Override public boolean supportsThingType(ThingTypeUID thingTypeUID) { boolean result = VeluxBindingConstants.SUPPORTED_THINGS_BINDING.contains(thingTypeUID) || VeluxBindingConstants.SUPPORTED_THINGS_BRIDGE.contains(thingTypeUID) || VeluxBindingConstants.SUPPORTED_THINGS_ITEMS.contains(thingTypeUID); logger.trace("supportsThingType({}) called and returns {}.", thingTypeUID, result); return result; } @Override protected @Nullable ThingHandler createHandler(Thing thing) { ThingHandler resultHandler = null; ThingTypeUID thingTypeUID = thing.getThingTypeUID(); // Handle Binding creation if (VeluxBindingConstants.SUPPORTED_THINGS_BINDING.contains(thingTypeUID)) { resultHandler = createBindingHandler(thing); } else // Handle Bridge creation if (VeluxBindingConstants.SUPPORTED_THINGS_BRIDGE.contains(thingTypeUID)) { resultHandler = createBridgeHandler(thing); } else // Handle creation of Things behind the Bridge if (VeluxBindingConstants.SUPPORTED_THINGS_ITEMS.contains(thingTypeUID)) { resultHandler = createThingHandler(thing); } else { logger.warn("createHandler({}) failed: ThingHandler not found for {}.", thingTypeUID, thing.getLabel()); } updateBindingState(); return resultHandler; } @Override protected void removeHandler(ThingHandler thingHandler) { // Handle Binding removal if (thingHandler instanceof VeluxBindingHandler) { logger.trace("removeHandler() removing information element '{}'.", thingHandler.toString()); veluxBindingHandlers.remove(thingHandler); } else // Handle Bridge removal if (thingHandler instanceof VeluxBridgeHandler) { logger.trace("removeHandler() removing bridge '{}'.", thingHandler.toString()); veluxBridgeHandlers.remove(thingHandler); unregisterDeviceDiscoveryService((VeluxBridgeHandler) thingHandler); } else // Handle removal of Things behind the Bridge if (thingHandler instanceof VeluxHandler) { logger.trace("removeHandler() removing thing '{}'.", thingHandler.toString()); veluxHandlers.remove(thingHandler); } updateBindingState(); super.removeHandler(thingHandler); } @Override protected void activate(ComponentContext componentContext) { activeInstance = this; super.activate(componentContext); } @Override protected void deactivate(ComponentContext componentContext) { activeInstance = null; super.deactivate(componentContext); } public static void refreshBindingInfo() { VeluxHandlerFactory instance = VeluxHandlerFactory.activeInstance; if (instance != null) { instance.updateBindingState(); } } }
epl-1.0
GazeboHub/Democrapedia
module/brontes/module/brontes-runner/src/test/java/ws/gazebo/brontes/runner/test/TestApp.java
1214
package ws.gazebo.brontes.runner.test; import java.io.File; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.jboss.shrinkwrap.resolver.api.maven.MavenResolverSystem; public class TestApp { public static void main(String[] args) { System.out.println("Hello World"); System.err.println("Args were: "); for (String a : args) { System.out.println('\t' + a); } // FIXME: provide POM as an arg MavenResolverSystem rs = Maven.resolver(); rs.loadPomFromFile("application-test.xml"); // This fails consistenly when used in the same classpath with // maven-embedder, // without sufficient dep. exclusions onto maven-embedder. // With sufficient dep. exclsions, TestApp runs successfully in itself, // but maven-embedder cannot successfully create and run a MavenCli // then. It seems to be a matter of weirdness in the dependency // injection framework. // // So: Consider OSGI, alternately, as a runtime container, rather than // Jena. Continue using Shrinkwrap for dependency resolution File it = rs.resolve("junit:junit:4.10").withoutTransitivity() .asSingle(File.class); // for (File f : libs) { System.out.println("Resolved: " + it); // } } }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface/test52/out/A.java
159
package p; class A implements I { A fA; /* (non-Javadoc) * @see p.I#m() */ public void m() {} public void m1() {} void f(){ A a= fA; a.m1(); } }
epl-1.0
ikus060/fontawesome
src/test/java/com/patrikdufresne/fontawesome/FontAwesomeTest.java
1869
/** * Copyright (c) 2015 Patrik Dufresne Service Logiciel <info@patrikdufresne.com> * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Patrik Dufresne - initial API and implementation */ package com.patrikdufresne.fontawesome; import java.lang.reflect.Field; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; public class FontAwesomeTest { public static void main(final String[] args) throws IllegalArgumentException, IllegalAccessException { final Display display = new Display(); final Shell shell = new Shell(display); shell.setText("FontAwesome Snippet"); shell.setSize(600, 600); shell.setLayout(new GridLayout(24, false)); // Loop on each COLOR constants. Field[] fields = FontAwesome.class.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (!field.getType().equals(String.class)) { continue; } String value = (String) field.get(null); if (value.length() != 1) { continue; } Label text = new Label(shell, SWT.NONE); text.setFont(FontAwesome.getFont(22)); text.setText(value); text.setToolTipText(field.getName()); } shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } }
epl-1.0
firegold4/RCP_Training
com.sii.rental.core/src/com/sii/rental/core/RentalCoreActivator.java
1031
package com.sii.rental.core; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import com.opcoach.training.rental.RentalAgency; import com.opcoach.training.rental.core.helpers.RentalAgencyGenerator; public class RentalCoreActivator implements BundleActivator { private static BundleContext context; private static RentalAgency agency = RentalAgencyGenerator.createSampleAgency(); public static RentalAgency getAgency() { return agency; } static BundleContext getContext() { return context; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext) */ public void start(BundleContext bundleContext) throws Exception { RentalCoreActivator.context = bundleContext; } /* * (non-Javadoc) * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext bundleContext) throws Exception { RentalCoreActivator.context = null; } }
epl-1.0
MentorEmbedded/p2-installer
plugins/com.codesourcery.installer/src/com/codesourcery/installer/IInstallConsoleProvider.java
1921
/******************************************************************************* * Copyright (c) 2014 Mentor Graphics 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: * Mentor Graphics - initial API and implementation *******************************************************************************/ package com.codesourcery.installer; /** * Install pages that support console mode should implement this interface. */ public interface IInstallConsoleProvider { /** * Provides page text for console installation. * This method should process the input and return the text to display * in the console. * This method will be called initially with <code>null</code> for the input. * This method should return the initial information for display along with * a prompt. * Subsequent calls will provide the text entered by the user. * This method should return <code>null</code> when the page is complete and * no further input is required. * If the page returns more text than can be displayed, it will be * paginated. * Helper classes in the <code>com.codesourcery.installer.console</code> can * be used to build console responses. * * @param input <code>null</code> on first call. Text entered by user * on subsequent calls. * @return Text to display in console. * @throws IllegalArgumentException when the provided input is not valid. * The installer will print the exception message and terminate * . * @see {@link com.codesourcery.installer.console.ConsoleListPrompter} * @see {@link com.codesourcery.installer.console.ConsoleYesNoPrompter} */ public String getConsoleResponse(String input) throws IllegalArgumentException; }
epl-1.0
aciancone/klapersuite
klapersuite.metamodel.klaper/src/klaper/expr/impl/BinaryImpl.java
8127
/** * <copyright> * </copyright> * * $Id$ */ package klaper.expr.impl; import klaper.expr.Binary; import klaper.expr.ExprPackage; import klaper.expr.Expression; import klaper.expr.Operator; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Binary</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link klaper.expr.impl.BinaryImpl#getOperator <em>Operator</em>}</li> * <li>{@link klaper.expr.impl.BinaryImpl#getLeft <em>Left</em>}</li> * <li>{@link klaper.expr.impl.BinaryImpl#getRight <em>Right</em>}</li> * </ul> * </p> * * @generated */ public class BinaryImpl extends ExpressionImpl implements Binary { /** * The cached value of the '{@link #getOperator() <em>Operator</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOperator() * @generated * @ordered */ protected Operator operator; /** * The cached value of the '{@link #getLeft() <em>Left</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getLeft() * @generated * @ordered */ protected Expression left; /** * The cached value of the '{@link #getRight() <em>Right</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getRight() * @generated * @ordered */ protected Expression right; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BinaryImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ExprPackage.Literals.BINARY; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Operator getOperator() { return operator; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetOperator(Operator newOperator, NotificationChain msgs) { Operator oldOperator = operator; operator = newOperator; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ExprPackage.BINARY__OPERATOR, oldOperator, newOperator); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOperator(Operator newOperator) { if (newOperator != operator) { NotificationChain msgs = null; if (operator != null) msgs = ((InternalEObject)operator).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ExprPackage.BINARY__OPERATOR, null, msgs); if (newOperator != null) msgs = ((InternalEObject)newOperator).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ExprPackage.BINARY__OPERATOR, null, msgs); msgs = basicSetOperator(newOperator, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExprPackage.BINARY__OPERATOR, newOperator, newOperator)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expression getLeft() { return left; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetLeft(Expression newLeft, NotificationChain msgs) { Expression oldLeft = left; left = newLeft; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ExprPackage.BINARY__LEFT, oldLeft, newLeft); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setLeft(Expression newLeft) { if (newLeft != left) { NotificationChain msgs = null; if (left != null) msgs = ((InternalEObject)left).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ExprPackage.BINARY__LEFT, null, msgs); if (newLeft != null) msgs = ((InternalEObject)newLeft).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ExprPackage.BINARY__LEFT, null, msgs); msgs = basicSetLeft(newLeft, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExprPackage.BINARY__LEFT, newLeft, newLeft)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Expression getRight() { return right; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetRight(Expression newRight, NotificationChain msgs) { Expression oldRight = right; right = newRight; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, ExprPackage.BINARY__RIGHT, oldRight, newRight); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setRight(Expression newRight) { if (newRight != right) { NotificationChain msgs = null; if (right != null) msgs = ((InternalEObject)right).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - ExprPackage.BINARY__RIGHT, null, msgs); if (newRight != null) msgs = ((InternalEObject)newRight).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - ExprPackage.BINARY__RIGHT, null, msgs); msgs = basicSetRight(newRight, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ExprPackage.BINARY__RIGHT, newRight, newRight)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case ExprPackage.BINARY__OPERATOR: return basicSetOperator(null, msgs); case ExprPackage.BINARY__LEFT: return basicSetLeft(null, msgs); case ExprPackage.BINARY__RIGHT: return basicSetRight(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ExprPackage.BINARY__OPERATOR: return getOperator(); case ExprPackage.BINARY__LEFT: return getLeft(); case ExprPackage.BINARY__RIGHT: return getRight(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ExprPackage.BINARY__OPERATOR: setOperator((Operator)newValue); return; case ExprPackage.BINARY__LEFT: setLeft((Expression)newValue); return; case ExprPackage.BINARY__RIGHT: setRight((Expression)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ExprPackage.BINARY__OPERATOR: setOperator((Operator)null); return; case ExprPackage.BINARY__LEFT: setLeft((Expression)null); return; case ExprPackage.BINARY__RIGHT: setRight((Expression)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ExprPackage.BINARY__OPERATOR: return operator != null; case ExprPackage.BINARY__LEFT: return left != null; case ExprPackage.BINARY__RIGHT: return right != null; } return super.eIsSet(featureID); } } //BinaryImpl
epl-1.0
bradsdavis/cxml-api
src/main/java/org/cxml/invoicedetail/DsSPKIData.java
1343
// // 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 10:57:51 AM CEST // package org.cxml.invoicedetail; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "dsSPKISexp" }) @XmlRootElement(name = "ds:SPKIData") public class DsSPKIData { @XmlElement(name = "ds:SPKISexp", required = true) protected String dsSPKISexp; /** * Gets the value of the dsSPKISexp property. * * @return * possible object is * {@link String } * */ public String getDsSPKISexp() { return dsSPKISexp; } /** * Sets the value of the dsSPKISexp property. * * @param value * allowed object is * {@link String } * */ public void setDsSPKISexp(String value) { this.dsSPKISexp = value; } }
epl-1.0
z1986s8x11/androidLib
help/src/main/java/org/zsx/android/api/widget/GridView_Activity.java
1177
package org.zsx.android.api.widget; import org.zsx.android.api.R; import org.zsx.android.base._BaseActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; public class GridView_Activity extends _BaseActivity implements GridView.OnItemClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.widget_gridview); GridView mGridView = (GridView) findViewById(R.id.act_widget_current_view); String[] sts = new String[] { "java", "php", "sql", "plsql", "html", "javascript", "css", "android", "c++", "xml" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, sts); mGridView.setAdapter(adapter); mGridView.setOnItemClickListener(this); } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { TextView t = (TextView) arg1; Toast.makeText(this, t.getText().toString(), Toast.LENGTH_SHORT).show(); } }
epl-1.0
kopl/SPLevo
UI/org.splevo.ui.wizard.consolidation/src/org/splevo/ui/wizard/consolidation/util/PackageUtil.java
6192
/******************************************************************************* * Copyright (c) 2015 * * 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: * Thomas Czogalik *******************************************************************************/ package org.splevo.ui.wizard.consolidation.util; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; import java.util.TreeSet; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jface.viewers.IContentProvider; import org.splevo.project.SPLevoProject; import org.splevo.ui.wizard.consolidation.provider.PackagesTreeContentProvider; /** * Utility class of the consolidation wizard. */ public class PackageUtil { /** * Get all projects the user has chosen on the previous page. * @param projectConfiguration The SPLevo project model * @return List with all chosen projects. */ public static List<IProject> getAllChosenProjects(SPLevoProject projectConfiguration) { IWorkspace workspace = ResourcesPlugin.getWorkspace(); IWorkspaceRoot root = workspace.getRoot(); List<IProject> allChosenProjects = new ArrayList<IProject>(); for (String chosenProjectName : projectConfiguration.getLeadingProjects()) { allChosenProjects.add(root.getProject(chosenProjectName)); } for (String chosenProjectName : projectConfiguration.getIntegrationProjects()) { allChosenProjects.add(root.getProject(chosenProjectName)); } return allChosenProjects; } /** * Returns a list for each project in the projectConfiguration that contains all java packages which are not * members in the other projects. * @param projectConfiguration The SPLevo project model * @return a list for each project in the projectConfiguration that contains all java packages which are not * members in the other projects */ public static List<SortedSet<IPackageFragment>> getNonDuplicatesJavaPackages(SPLevoProject projectConfiguration) { List<SortedSet<IPackageFragment>> javaPackages = new ArrayList<SortedSet<IPackageFragment>>(); for (IProject project : getAllChosenProjects(projectConfiguration)) { javaPackages.add(getJavaPackages(project)); } removeDuplicates(javaPackages); return javaPackages; } private static void removeDuplicates(List<SortedSet<IPackageFragment>> javaPackages) { for (int i = 0; i < javaPackages.size(); i++) { SortedSet<IPackageFragment> temp = new TreeSet<IPackageFragment>(javaPackages.get(i)); for (int j = 0; j < javaPackages.size(); j++) { if (i == j) { continue; } javaPackages.get(i).removeAll(javaPackages.get(j)); javaPackages.get(j).removeAll(temp); } } } /** * Get all root packages which have to be shown in the tree. * @param contentProvider content provider for packages * @param javaPackages the java packages to find their root packages * @return Array with all root packages. */ public static List<IPackageFragment> getRootpackages(IContentProvider contentProvider, SortedSet<IPackageFragment> javaPackages) { List<IPackageFragment> rootPackages = new ArrayList<IPackageFragment>(); if (!(contentProvider instanceof PackagesTreeContentProvider)) { return rootPackages; } PackagesTreeContentProvider packagesTreeContentProvider = (PackagesTreeContentProvider) contentProvider; for (IPackageFragment javaPackage : javaPackages) { if (packagesTreeContentProvider.getParentPackage(javaPackage) == null) { rootPackages.add(javaPackage); } } return rootPackages; } /** * Get all java packages which are in the class path of the chosen projects without duplicates * and ordered by name (ascending). * @param projectConfiguration The SPLevo project model * * @return A sorted set with all java packages. */ public static SortedSet<IPackageFragment> getJavaPackages(SPLevoProject projectConfiguration) { SortedSet<IPackageFragment> javaPackagesSet = new TreeSet<IPackageFragment>(new PackagesComparator()); for (IProject project : getAllChosenProjects(projectConfiguration)) { addPackage(project, javaPackagesSet); } return javaPackagesSet; } private static SortedSet<IPackageFragment> getJavaPackages(IProject project) { SortedSet<IPackageFragment> javaPackagesSet = new TreeSet<IPackageFragment>(new PackagesComparator()); addPackage(project, javaPackagesSet); return javaPackagesSet; } private static void addPackage(IProject project, SortedSet<IPackageFragment> javaPackagesSet) { try { if (project.isNatureEnabled("org.eclipse.jdt.core.javanature")) { for (IPackageFragment packageFragment : JavaCore.create(project).getPackageFragments()) { if (!packageFragment.getElementName().equals("")) { javaPackagesSet.add(packageFragment); } } } } catch (Exception e) { } } /** * Returns the name of the given package. * @param packageFragment the given package * @return the name of the given package */ public static String getName(IPackageFragment packageFragment) { return packageFragment != null ? packageFragment.getElementName() : ""; } }
epl-1.0
AGES-Initiatives/alwb-utils-gui
alwb.utils/src/main/java/net/ages/alwb/utils/db/couchDb/models/user/NewUser.java
1353
package net.ages.alwb.utils.db.couchDb.models.user; import java.util.Arrays; import java.util.List; import com.google.gson.annotations.Expose; import net.ages.alwb.utils.db.couchDb.models.AbstractModel; /** * Model for creating a new user in a CouchDb server * @author mac002 * */ public class NewUser extends AbstractModel { private @Expose String _id; // org.couchdb.user:$ID private @Expose String name; // $ID private @Expose String [] roles = {""}; // ["*_r","*_m"] private @Expose String type = "user"; private @Expose String password; private static final String prefix = "org.couchdb.user:"; public NewUser() { super(); } public String get_id() { return _id; } public void set_id(String _id) { if (_id.startsWith(prefix)) { this._id = _id; } else { this._id = prefix+_id; } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String[] getRoles() { return roles; } public void setRoles(String[] roles) { this.roles = roles; } public List<String> getRolesAsList() { return Arrays.asList(roles); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
epl-1.0
sleshchenko/che
infrastructures/docker/docker-client/src/test/java/org/eclipse/che/infrastructure/docker/client/DockerfileParserTest.java
22583
/* * 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.infrastructure.docker.client; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.io.File; import java.io.FileWriter; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import org.eclipse.che.commons.lang.Pair; import org.testng.annotations.Test; /** @author andrew00x */ public class DockerfileParserTest { @Test public void testParse() throws Exception { String dockerfileContent = "FROM base_image\n" + "# Comment 1\n" + "MAINTAINER Codenvy Corp\n" + "# Comment 2\n" + "RUN echo 1 > /dev/null\n" + "RUN echo 2 > /dev/null\n" + "RUN echo 3 > /dev/null\n" + "ADD file1 /tmp/file1\n" + "ADD http://example.com/folder/some_file.txt /tmp/file.txt \n" + "EXPOSE 6000 7000\n" + "EXPOSE 8000 9000\n" + "# Comment 3\n" + "ENV ENV_VAR1 hello world\n" + "ENV ENV_VAR2\t to be or not to be\n" + "VOLUME [\"/data1\", \t\"/data2\"]\n" + "USER andrew\n" + "WORKDIR /tmp\n" + "ENTRYPOINT echo hello > /dev/null\n" + "CMD echo hello > /tmp/test"; File targetDir = new File(Thread.currentThread().getContextClassLoader().getResource(".").toURI()) .getParentFile(); File file = new File(targetDir, "testParse"); FileWriter w = new FileWriter(file); w.write(dockerfileContent); w.flush(); w.close(); List<DockerImage> dockerImages = DockerfileParser.parse(file).getImages(); assertEquals(dockerImages.size(), 1); DockerImage dockerImage = dockerImages.get(0); assertEquals(dockerImage.getFrom(), "base_image"); assertEquals(dockerImage.getMaintainer(), Arrays.asList("Codenvy Corp")); assertEquals( dockerImage.getRun(), Arrays.asList("echo 1 > /dev/null", "echo 2 > /dev/null", "echo 3 > /dev/null")); assertEquals(dockerImage.getCmd(), "echo hello > /tmp/test"); assertEquals(dockerImage.getExpose(), Arrays.asList("6000", "7000", "8000", "9000")); Map<String, String> env = new LinkedHashMap<>(); env.put("ENV_VAR1", "hello world"); env.put("ENV_VAR2", "to be or not to be"); assertEquals(env, dockerImage.getEnv()); assertEquals( dockerImage.getAdd(), Arrays.asList( Pair.of("file1", "/tmp/file1"), Pair.of("http://example.com/folder/some_file.txt", "/tmp/file.txt"))); assertEquals(dockerImage.getEntrypoint(), "echo hello > /dev/null"); assertEquals(dockerImage.getVolume(), Arrays.asList("/data1", "/data2")); assertEquals(dockerImage.getUser(), "andrew"); assertEquals(dockerImage.getWorkdir(), "/tmp"); assertEquals(dockerImage.getComments(), Arrays.asList("Comment 1", "Comment 2", "Comment 3")); } @Test public void testParseMultipleImages() throws Exception { String dockerfileContent = "FROM base_image_1\n" + "# Image 1\n" + "MAINTAINER Codenvy Corp\n" + "RUN echo 1 > /dev/null\n" + "ADD http://example.com/folder/some_file.txt /tmp/file.txt \n" + "EXPOSE 6000 7000\n" + "ENV ENV_VAR\t to be or not to be\n" + "VOLUME [\"/data1\"]\n" + "USER andrew\n" + "WORKDIR /tmp\n" + "ENTRYPOINT echo hello > /dev/null\n" + "CMD echo hello > /tmp/test1" + "\n" + "\n" + "FROM base_image_2\n" + "# Image 2\n" + "MAINTAINER Codenvy Corp\n" + "RUN echo 2 > /dev/null\n" + "ADD file1 /tmp/file1\n" + "EXPOSE 8000 9000\n" + "ENV ENV_VAR\t to be or not to be\n" + "VOLUME [\"/data2\"]\n" + "USER andrew\n" + "WORKDIR /home/andrew\n" + "ENTRYPOINT echo test > /dev/null\n" + "CMD echo hello > /tmp/test2"; File targetDir = new File(Thread.currentThread().getContextClassLoader().getResource(".").toURI()) .getParentFile(); File file = new File(targetDir, "testParse"); FileWriter w = new FileWriter(file); w.write(dockerfileContent); w.flush(); w.close(); List<DockerImage> dockerImages = DockerfileParser.parse(file).getImages(); assertEquals(2, dockerImages.size()); DockerImage dockerImage1 = dockerImages.get(0); assertEquals(dockerImage1.getFrom(), "base_image_1"); assertEquals(dockerImage1.getMaintainer(), Arrays.asList("Codenvy Corp")); assertEquals(dockerImage1.getRun(), Arrays.asList("echo 1 > /dev/null")); assertEquals(dockerImage1.getCmd(), "echo hello > /tmp/test1"); assertEquals(dockerImage1.getExpose(), Arrays.asList("6000", "7000")); Map<String, String> env1 = new LinkedHashMap<>(); env1.put("ENV_VAR", "to be or not to be"); assertEquals(dockerImage1.getEnv(), env1); assertEquals( dockerImage1.getAdd(), Arrays.asList(Pair.of("http://example.com/folder/some_file.txt", "/tmp/file.txt"))); assertEquals(dockerImage1.getEntrypoint(), "echo hello > /dev/null"); assertEquals(dockerImage1.getVolume(), Arrays.asList("/data1")); assertEquals(dockerImage1.getUser(), "andrew"); assertEquals(dockerImage1.getWorkdir(), "/tmp"); assertEquals(dockerImage1.getComments(), Arrays.asList("Image 1")); DockerImage dockerImage2 = dockerImages.get(1); assertEquals(dockerImage2.getFrom(), "base_image_2"); assertEquals(dockerImage2.getMaintainer(), Arrays.asList("Codenvy Corp")); assertEquals(dockerImage2.getRun(), Arrays.asList("echo 2 > /dev/null")); assertEquals(dockerImage2.getCmd(), "echo hello > /tmp/test2"); assertEquals(dockerImage2.getExpose(), Arrays.asList("8000", "9000")); Map<String, String> env2 = new LinkedHashMap<>(); env2.put("ENV_VAR", "to be or not to be"); assertEquals(dockerImage2.getEnv(), env2); assertEquals(dockerImage2.getAdd(), Arrays.asList(Pair.of("file1", "/tmp/file1"))); assertEquals(dockerImage2.getEntrypoint(), "echo test > /dev/null"); assertEquals(dockerImage2.getVolume(), Arrays.asList("/data2")); assertEquals(dockerImage2.getUser(), "andrew"); assertEquals(dockerImage2.getWorkdir(), "/home/andrew"); assertEquals(dockerImage2.getComments(), Arrays.asList("Image 2")); } @Test public void testTemplate() throws Exception { String templateContent = "FROM $from$\n" + "MAINTAINER Codenvy Corp\n" + "ADD $app$ /tmp/$app$\n" + "CMD /bin/bash -cl \"java $jvm_args$ -classpath /tmp/$app$ $main_class$ $prg_args$\"\n"; String expectedContent = "FROM base\n" + "MAINTAINER Codenvy Corp\n" + "ADD hello.jar /tmp/hello.jar\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n -classpath /tmp/hello.jar test.Main name=andrew\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("from", "base"); parameters.put("app", "hello.jar"); parameters.put( "jvm_args", "-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n"); parameters.put("main_class", "test.Main"); parameters.put("prg_args", "name=andrew"); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } /** * Ensures that we're able to find and replace parameters with default values * * @throws Exception */ @Test public void testDefaultValueInTemplate() throws Exception { final String TASKNAME_KEY = "taskName"; final String TASKNAME_DEFAULT_VALUE = "server"; final String TASKNAME_VALUE = "test"; String templateContent = "FROM codenvy/mytemplatetest\n" + "grunt $" + TASKNAME_KEY + ":-" + TASKNAME_DEFAULT_VALUE + "$\n"; // first case, parameter is not given so we are expecting the default value String expectedWithoutParameter = "FROM codenvy/mytemplatetest\n" + "grunt server\n"; // second case, parameter is given so we are expecting the given value String expectedWithParameter = "FROM codenvy/mytemplatetest\n" + "grunt " + TASKNAME_VALUE + "\n"; writeDockerfileAndMatch(templateContent, null, expectedWithoutParameter); Map<String, Object> parameters = new HashMap<>(); parameters.put("taskName", TASKNAME_VALUE); writeDockerfileAndMatch(templateContent, parameters, expectedWithParameter); } /** * Try with invalid syntax for default Here there is the missing - after : like * $myKey:wrongDefaultValue$ */ @Test public void testErrorInDefaultValueInTemplate() throws Exception { final String TASKNAME_KEY = "taskName"; final String TASKNAME_DEFAULT_VALUE = "server"; final String TASKNAME_VALUE = "test"; String templateContent = "FROM codenvy/mytemplatetest\n" + "grunt $" + TASKNAME_KEY + ":" + TASKNAME_DEFAULT_VALUE + "$\n"; // We shouldn't have exceptions // first case, parameter is not given so we are expecting the default value String expectedContent = "FROM codenvy/mytemplatetest\n" + "grunt $taskName:server$\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("taskName", TASKNAME_VALUE); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testConditionPatternBooleanCondition() { String conditionTemplate = "aaa?bbb:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertNull(m.group(2)); assertEquals(m.group(3), ""); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPatternEmptyCondition() { String conditionTemplate = "aaa=?bbb:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), "="); assertEquals(m.group(3), ""); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPatternEmptyCondition2() { String conditionTemplate = "aaa>=?bbb:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), ">="); assertEquals(m.group(3), ""); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPattern() { String conditionTemplate = "aaa>=xxx?bbb:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), ">="); assertEquals(m.group(3), "xxx"); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPatternNoExpression1() { String conditionTemplate = "aaa>=xxx?:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), ">="); assertEquals(m.group(3), "xxx"); assertEquals(m.group(4), ""); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPatternNoExpression2() { String conditionTemplate = "aaa>=xxx?bbb:"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), ">="); assertEquals(m.group(3), "xxx"); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), ""); } @Test public void testConditionPatternEmptyConditionAndNoExpression1() { String conditionTemplate = "aaa>=?:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), ">="); assertEquals(m.group(4), ""); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPatternEmptyConditionAndNoExpression2() { String conditionTemplate = "aaa=?bbb:"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), "="); assertEquals(m.group(3), ""); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), ""); } @Test public void testConditionPatternBooleanConditionAndNoExpression1() { String conditionTemplate = "aaa?:ccc"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertNull(m.group(2)); assertEquals(m.group(4), ""); assertEquals(m.group(5), "ccc"); } @Test public void testConditionPatternBooleanConditionAndNoExpression2() { String conditionTemplate = "aaa?bbb:"; Matcher m = Dockerfile.TEMPLATE_CONDITIONAL_PATTERN.matcher(conditionTemplate); assertTrue(m.matches()); assertEquals(m.groupCount(), 5); assertEquals(m.group(1), "aaa"); assertEquals(m.group(2), null); assertEquals(m.group(3), ""); assertEquals(m.group(4), "bbb"); assertEquals(m.group(5), ""); } @Test public void testBooleanConditionTemplateMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", true); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testBooleanConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; writeDockerfileAndMatch(templateContent, null, expectedContent); } @Test public void testBooleanConditionTemplateEmptyOutput() throws Exception { String templateContent = "$debug?EXPOSE 8000:$\n" + "$debug?ENV CODENVY_APP_PORT_8000_DEBUG 8000:$\n" + "$debug?CMD ./catalina.sh jpda run 2>&1:$\n"; String expectedContent = ""; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", false); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testEqualsConditionTemplateMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug=y?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", "y"); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testEqualsConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug=y?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", "n"); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNotEqualsConditionTemplateMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug!=n?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", "yeeeeesssss"); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNotEqualsConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug!=n?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", "n"); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNumberMoreConditionTemplateMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug>123?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 127); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNumberMoreConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug>132?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 127); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testInvalidNumberMoreConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug>test?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 127); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNumberMoreEqualsConditionTemplateMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug>=123?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 123); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNumberMoreEqualsConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug>=123?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 111); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNumberLessConditionTemplateMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug<123?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 121); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } @Test public void testNumberLessConditionTemplateNotMatched() throws Exception { String templateContent = "FROM base\n" + "CMD /bin/bash -cl \"java $debug<123?-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n:$ test.Main\"\n"; String expectedContent = "FROM base\n" + "CMD /bin/bash -cl \"java test.Main\"\n"; Map<String, Object> parameters = new HashMap<>(); parameters.put("debug", 123); writeDockerfileAndMatch(templateContent, parameters, expectedContent); } private void writeDockerfileAndMatch( String templateContent, Map<String, Object> parameters, String expectedContent) throws Exception { Dockerfile template = DockerfileParser.parse(templateContent); StringBuilder buf = new StringBuilder(); if (parameters != null) { template.getParameters().putAll(parameters); } template.writeDockerfile(buf); assertEquals(buf.toString(), expectedContent); } }
epl-1.0
asupdev/asup
org.asup.db.syntax/src/org/asup/db/syntax/impl/BindingStatementImpl.java
1493
/** * Copyright (c) 2012, 2014 Sme.UP 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.asup.db.syntax.impl; import org.asup.db.syntax.QBindingStatement; import org.asup.db.syntax.QDatabaseSyntaxPackage; import org.asup.db.syntax.StatementType; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.EObjectImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Binding Statement</b></em>'. * <!-- end-user-doc --> * <p> * </p> * * @generated */ public abstract class BindingStatementImpl extends EObjectImpl implements QBindingStatement { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected BindingStatementImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return QDatabaseSyntaxPackage.Literals.BINDING_STATEMENT; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public StatementType getStatementType() { // TODO: implement this method // Ensure that you remove @generated or mark it @generated NOT throw new UnsupportedOperationException(); } } //BindingStatementImpl
epl-1.0
zsmartsystems/com.zsmartsystems.bluetooth.bluegiga
com.zsmartsystems.bluetooth.bluegiga/src/main/java/com/zsmartsystems/bluetooth/bluegiga/command/attributeclient/BlueGigaReadLongResponse.java
3032
/** * Copyright (c) 2014-2017 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.bluetooth.bluegiga.command.attributeclient; import com.zsmartsystems.bluetooth.bluegiga.BlueGigaResponse; import com.zsmartsystems.bluetooth.bluegiga.enumeration.BgApiResponse; /** * Class to implement the BlueGiga command <b>readLong</b>. * <p> * This command can be used to read long attribute values, which are longer than 22 bytes and * cannot be read with a simple Read by Handle command. The command starts a procedure, where the * client first sends a normal read command to the server and if the returned attribute value * length is equal to MTU, the client will send further read long read requests until rest of the * attribute is read. * <p> * This class provides methods for processing BlueGiga API commands. * <p> * Note that this code is autogenerated. Manual changes may be overwritten. * * @author Chris Jackson - Initial contribution of Java code generator */ public class BlueGigaReadLongResponse extends BlueGigaResponse { public static int COMMAND_CLASS = 0x04; public static int COMMAND_METHOD = 0x08; /** * Connection handle * <p> * BlueGiga API type is <i>uint8</i> - Java type is {@link int} */ private int connection; /** * 0 : the command was successful. Otherwise an error occurred * <p> * BlueGiga API type is <i>BgApiResponse</i> - Java type is {@link BgApiResponse} */ private BgApiResponse result; /** * Response constructor */ public BlueGigaReadLongResponse(int[] inputBuffer) { // Super creates deserializer and reads header fields super(inputBuffer); event = (inputBuffer[0] & 0x80) != 0; // Deserialize the fields connection = deserializeUInt8(); result = deserializeBgApiResponse(); } /** * Connection handle * <p> * BlueGiga API type is <i>uint8</i> - Java type is {@link int} * * @return the current connection as {@link int} */ public int getConnection() { return connection; } /** * 0 : the command was successful. Otherwise an error occurred * <p> * BlueGiga API type is <i>BgApiResponse</i> - Java type is {@link BgApiResponse} * * @return the current result as {@link BgApiResponse} */ public BgApiResponse getResult() { return result; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("BlueGigaReadLongResponse [connection="); builder.append(connection); builder.append(", result="); builder.append(result); builder.append(']'); return builder.toString(); } }
epl-1.0
proyecto-adalid/adalid
source/adalid-core/src/adalid/core/properties/IntegerProperty.java
1793
/* * Este programa es software libre; usted puede redistribuirlo y/o modificarlo bajo los terminos * de la licencia "GNU General Public License" publicada por la Fundacion "Free Software Foundation". * Este programa se distribuye con la esperanza de que pueda ser util, pero SIN NINGUNA GARANTIA; * vea la licencia "GNU General Public License" para obtener mas informacion. */ package adalid.core.properties; import adalid.core.annotations.BaseField; import adalid.core.annotations.BusinessKey; import adalid.core.annotations.CastingField; import adalid.core.annotations.ColumnField; import adalid.core.annotations.DiscriminatorColumn; import adalid.core.annotations.NumericDataGen; import adalid.core.annotations.NumericField; import adalid.core.annotations.NumericKey; import adalid.core.annotations.PrimaryKey; import adalid.core.annotations.PropertyField; import adalid.core.annotations.UniqueKey; import adalid.core.data.types.IntegerData; import adalid.core.interfaces.Property; import java.lang.annotation.Annotation; import java.util.List; /** * @author Jorge Campins */ public class IntegerProperty extends IntegerData implements Property { @Override protected List<Class<? extends Annotation>> getValidFieldAnnotations() { List<Class<? extends Annotation>> valid = super.getValidFieldAnnotations(); valid.add(BaseField.class); valid.add(BusinessKey.class); valid.add(CastingField.class); valid.add(ColumnField.class); valid.add(DiscriminatorColumn.class); valid.add(NumericDataGen.class); valid.add(NumericField.class); valid.add(NumericKey.class); valid.add(PrimaryKey.class); valid.add(PropertyField.class); valid.add(UniqueKey.class); return valid; } }
gpl-2.0
VyacheslavBobrov/fiction_biblioteca
src/com/github/bobrov/vyacheslav/fiction_biblioteca/book_db_sync/DearchiverIf.java
457
/** * */ package com.github.bobrov.vyacheslav.fiction_biblioteca.book_db_sync; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * @author Vyacheslav Bobrov */ public interface DearchiverIf { public String[] getSupportedTypes(); public void setArchive(File arch) throws FileNotFoundException; public boolean haveNextEntry() throws IOException; public InputStream getEntry(); }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/model/MWebProject.java
4306
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.CCache; /** * Web Project Model * * @author Jorg Janke * @version $Id: MWebProject.java,v 1.3 2006/07/30 00:51:03 jjanke Exp $ */ public class MWebProject extends X_CM_WebProject { /** * */ private static final long serialVersionUID = -7404800005095450170L; /** * Get MWebProject from Cache * @param ctx context * @param CM_WebProject_ID id * @return MWebProject */ public static MWebProject get (Properties ctx, int CM_WebProject_ID) { Integer key = new Integer (CM_WebProject_ID); MWebProject retValue = (MWebProject)s_cache.get (key); if (retValue != null) return retValue; retValue = new MWebProject (ctx, CM_WebProject_ID, null); if (retValue.get_ID () == CM_WebProject_ID) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MWebProject> s_cache = new CCache<Integer, MWebProject> ("CM_WebProject", 5); /************************************************************************** * Web Project * @param ctx context * @param CM_WebProject_ID id * @param trxName transaction */ public MWebProject (Properties ctx, int CM_WebProject_ID, String trxName) { super (ctx, CM_WebProject_ID, trxName); } // MWebProject /** * Web Project * @param ctx context * @param rs result set * @param trxName transaction */ public MWebProject (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MWebProject /** * Before Save * @param newRecord new * @return true */ protected boolean beforeSave (boolean newRecord) { // Create Trees if (newRecord) { MTree_Base tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMContainer, MTree_Base.TREETYPE_CMContainer, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMC_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMContainerStage, MTree_Base.TREETYPE_CMContainerStage, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMS_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMTemplate, MTree_Base.TREETYPE_CMTemplate, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMT_ID(tree.getAD_Tree_ID()); // tree = new MTree_Base (getCtx(), getName()+MTree_Base.TREETYPE_CMMedia, MTree_Base.TREETYPE_CMMedia, get_TrxName()); if (!tree.save()) return false; setAD_TreeCMM_ID(tree.getAD_Tree_ID()); } return true; } // beforeSave /** * After Save. * Insert * - create tree * @param newRecord insert * @param success save success * @return true if saved */ protected boolean afterSave (boolean newRecord, boolean success) { if (!success) return success; if (!newRecord) { // Clean Web Project Cache } return success; } // afterSave } // MWebProject
gpl-2.0
Esleelkartea/aon-employee
aonemployee_v2.3.0_src/paquetes descomprimidos/aon.ui.employee-2.3.0-sources/com/code/aon/ui/cvitae/controller/CurriculumController.java
3797
package com.code.aon.ui.cvitae.controller; import java.util.Date; import java.util.StringTokenizer; import javax.faces.event.ActionEvent; import org.apache.myfaces.custom.fileupload.UploadedFile; import com.code.aon.common.ManagerBeanException; import com.code.aon.cvitae.Curriculum; import com.code.aon.cvitae.enumeration.DriverLicense; import com.code.aon.geozone.GeoZone; import com.code.aon.registry.RegistryAttachment; import com.code.aon.ui.employee.util.Constants; import com.code.aon.ui.form.BasicController; import com.code.aon.ui.menu.jsf.MenuEvent; import com.code.aon.ui.util.AonUtil; public class CurriculumController extends BasicController { private static final long serialVersionUID = 3850759963483739573L; public static final String MANAGER_BEAN_NAME = "curriculum"; private DriverLicense[] driverLicenses; private UploadedFile file; private RegistryAttachment attach; public String getLicensesAsString() { String licenses = new String(); for(int i = 0;i < driverLicenses.length;i++){ licenses = licenses.concat((licenses.length() > 0?"+":Constants.EMPTY_STRING) + driverLicenses[i].toString()); } return licenses; } public DriverLicense[] getDriverLicenses(){ String licenses = ((Curriculum)this.getTo()).getDriverLicenses(); if(licenses == null){ return driverLicenses = new DriverLicense[0]; } StringTokenizer tokenizer = new StringTokenizer(licenses,"+"); driverLicenses = new DriverLicense[tokenizer.countTokens()]; int tokens = tokenizer.countTokens(); for(int i = 0;i < tokens;i++){ String license = tokenizer.nextToken(); driverLicenses[i] = DriverLicense.valueOf(license); } return driverLicenses; } public void setDriverLicenses(DriverLicense[] driverLicenses) { this.driverLicenses = driverLicenses; } public UploadedFile getFile() { return this.file; } public void setFile(UploadedFile file) { this.file = file; } public RegistryAttachment getAttach() { return attach; } public void setAttach(RegistryAttachment attach) { this.attach = attach; } @SuppressWarnings("unused") public void onReset(MenuEvent event){ super.onEditSearch(null); } /* (non-Javadoc) * @see com.code.aon.ui.form.BasicController#onReset(javax.faces.event.ActionEvent) */ @Override public void onReset(ActionEvent event) { super.onReset(event); Curriculum cv = (Curriculum) getTo(); cv.setEntryDate( new Date() ); cv.setGeoZone( new GeoZone() ); } /* (non-Javadoc) * @see com.code.aon.ui.form.BasicController#onSelect(javax.faces.event.ActionEvent) */ @Override public void onSelect(ActionEvent event) { super.onSelect(event); StudiesController sc = (StudiesController) AonUtil.getController( StudiesController.MANAGER_BEAN_NAME ); KnowledgeController kc = (KnowledgeController) AonUtil.getController( KnowledgeController.MANAGER_BEAN_NAME ); WorkExperienceController wec = (WorkExperienceController) AonUtil.getController( WorkExperienceController.MANAGER_BEAN_NAME ); LanguageController lc = (LanguageController) AonUtil.getController( LanguageController.MANAGER_BEAN_NAME ); EvaluateController oc = (EvaluateController) AonUtil.getController( EvaluateController.MANAGER_BEAN_NAME ); try { sc.onStudies(null); kc.onKnowledges(null); wec.onWorkExperience(null); lc.onLanguages(null); oc.onEvaluation(null); } catch (ManagerBeanException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public boolean isImageAttached(){ if(this.attach != null){ return true; } return false; } public String getUrl(){ return ((Curriculum)this.getTo()).getId() + ".photo"; } }
gpl-2.0
jcrcano/DrakkarKeel
Modules/DrakkarOar/src/drakkar/oar/util/KeyTransaction.java
8053
/* * DrakkarKeel - An Enterprise Collaborative Search Platform * * The contents of this file are subject under the terms described in the * DRAKKARKEEL_LICENSE file included in this distribution; you may not use this * file except in compliance with the License. * * 2013-2014 DrakkarKeel Platform. */ package drakkar.oar.util; /** * Esta clase contiene las diferentes constantes que pueden ser empleadas para * la construcción de los objetos Request/Response de las distintas operaciones */ public class KeyTransaction { /** * Nombre de la operación */ public static final int OPERATION = 1; /** * Usuario */ public static final int SEEKER = 2; /** * Usuario emisor */ public static final int SEEKER_EMITTER = 3; /** * Usuario receptor */ public static final int MEMBER_RECEPTOR = 4; /** * Estado del usuario */ public static final int SEEKER_STATE = 5; /** * Nombre de la sesión */ public static final int SESSION_NAME = 6; /** * Contenido del mensaje */ public static final int MESSAGE = 7; /** * Tipo de mensaje */ public static final int MESSAGE_TYPE = 8; /** * Tipo de actualización * @deprecated use DISTRIBUTED_EVENT * */ public static final int UPDATE_TYPE = 9; /** * Resusltados de la búsqueda */ public static final int SEARCH_RESULTS = 10; /** * Recomendación */ public static final int RECOMMENDATION = 11; /** * Comnetarios */ public static final int COMMENT = 12; /** * ¿Existen resultados? */ public static final int IS_EMPTY = 13; /** * Causa */ public static final int CAUSE = 14; /** * Usuarios de la sesión */ public static final int SEEKERS_SESSION = 15; /** * Jefe de la sesión */ public static final int SEEKER_CHAIRMAN = 16; /** * Objeto proxy */ public static final int PROXY = 17; /** * Número mínimo de miembros */ public static final int MEMBERS_MIN_NUMBER = 18; /** * Número maximo de miembros */ public static final int MEMBERS_MAX_NUMBER = 19; /** * Criterio de Integridad de la sesión */ public static final int INTEGRITY_CRITERIA = 20; /** * Política de membresía de sesión */ public static final int MEMBERSHIP_POLICY = 21; /** * Usuarios receptores */ public static final int SEEKERS_RECEPTORS = 22; /** * Búscador */ public static final int SEARCHER = 23; /** * Consulta */ public static final int QUERY = 24; /** * Tipo de documento */ public static final int DOC_TYPE = 25; /** * Campo */ public static final int FIELD = 26; /** * Campos */ public static final int FIELDS = 27; /** * Principio de Búsqueda */ public static final int SEARCH_PRINCIPLE = 28; /** * Indices de los documentos a recomnedar */ public static final int RECOMMENDATIONS_INDEX = 29; /** * Nombre de la otra sesión */ public static final int OTHER_SESSION_NAME = 30; /** * Usuario a notificar */ public static final int SEEKER_NOTIFY = 31; /** * Indice del documento */ public static final int DOC_INDEX = 32; /** * Relevancia del documento */ public static final int RELEVANCE = 33; /** * Nombre del contenedor de la sesión */ public static final int CONTAINER_NAME = 34; /** * */ public static final int CONTAINER_UUID = 50; /** * */ public static final int SESSION_ID = 51; /** * */ public static final int SESSION_DESCRIPTION = 52; /** * */ public static final int SESSIONS_IDS = 53; /** * */ public static final int PERSISTENT_SESSIONS = 54; /** * */ public static final int MANAGER_NAME = 55; /** * */ public static final int MANAGER_PASSWORD = 56; /** * */ public static final int CONTAINERS = 57; /** * Resultado */ public static final int RESULT = 58; /** * Estado del servidor */ public static final int SERVER_STATE = 61; /** * Buscadores */ public static final int SEARCHERS = 62; /** * Tener en cuenta mayúsculas y minúsculas */ public static final int CASE_SENTITIVE = 63; /** * Tipos de documentos */ public static final int DOC_TYPES = 64; /** * Nombre del usuario */ public static final int SEEKER_NAME = 65; /** * Apellidos del usuario */ public static final int SEEKER_LAST_NAME = 66; /** * Contraseña del usuario */ public static final int SEEKER_PASSWORD = 67; /** * Correo del usuario */ public static final int SEEKER_EMAIL = 68; /** * Sobrenombre del usuario */ public static final int SEEKER_NICKNAME = 69; /** * Foto del usuario */ public static final int SEEKER_AVATAR = 70; /** * Respuesta */ public static final int ANSWER = 71; /** * Antiguo contraseña */ public static final int OLD_PASSWORD = 72; /** * nueva contraseña */ public static final int NEW_PASSWORD = 73; /** * Valor */ public static final int VALUE = 74; /** * Rol de el usuario */ public static final int SEEKER_ROL = 75; /** * PARA LOS HISTORIALES */ public static final int TRACK_FILTER = 80; /** * */ public static final int DATE = 81; /** * */ public static final int DOCUMENT_GROUP = 82; /** * */ public static final int URI = 83; /** * */ public static final int EMITTER_NICKNAME = 84; /** * */ public static final int RECEPTOR_NICKNAME = 85; /** * */ public static final int RECOMMEND_DATA = 86; /** * */ public static final int SEARCH_DATA = 87; /** * */ public static final int SEARCH_RESULT_SOURCE = 88; /** * */ public static final int QUERY_SOURCE = 89; /** * */ public static final int DOCUMENTS = 90; /** * */ public static final int TIME = 91; /** * */ public static final int REPLY = 92; /** * */ public static final int SEARCH_PRINCIPLES = 93; /** * */ public static final int IS_CHAIRMAN = 94; /** * */ public static final int CHAIRMAN_NAME = 95; /** * */ public static final int OPEN_SESSIONS = 96; /** * */ public static final int SESSION = 97; /** * */ public static final int SESSION_DATA = 98; /** * */ public static final int SEEKER_DESCRIPTION = 99; /** * */ public static final int SEARCH_TYPE = 100; /** * */ public static final int DISTRIBUTED_EVENT = 101; /** * */ public static final int ACTION = 102; /** * */ public static final int SEEKER_ID = 103; /** * */ public static final int SVN_REPOSITORIES_NAMES = 104; /** * */ public static final int SVN_REPOSITORY = 105; /** * */ public static final int ONLY_FILE_BODY = 106; /** * */ public static final int FILE_TYPE = 107; /** * */ public static final int SORT_TYPE = 108; /** * */ public static final int LAST_MODIFIED = 109; /** * */ public static final int SCORE_PQT = 110; /** * */ public static final int QUERY_TYPED = 111; /** * */ public static final int QUERY_TERM = 112; /** * */ public static final int QUERY_TERMS_SUGGEST = 113; }
gpl-2.0
TaronLiu/adddressBook
addressBook/src/impl/Add.java
2221
/* * @(#)Add.java 1.0 15/07/06 * * Copyright 2013 http://taronliu.blogspot.com/. All rights reserved. * TARON PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /** * @projectName addressBook * @title <p>【用一句话描述该文件做什么】</p> * @fileName Add.java * @packageName impl * @date 2015-9-14 上午11:10:18 * @version %I%, %G% * @author <a href="http://taronliu.blogspot.com/">Administrator</a> * @copyright (c) http://taronliu.blogspot.com/ * @description TODO <p>【详细描述该文件做什么】</p> * @see */ package impl; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.IOException; import pojo.User; /** * @title <p> * 添加数据 * </p> * @className Add * @date 2015-9-14 上午11:10:18 * @author <a href="http://taronliu.blogspot.com/">Administrator</a> * @version %I%, %G% * @since JDK 1.6 * @description TODO * <p> * 添加数据 * </p> * @modifiedBy Date Author Version Description * ----------------------------------------------------------------- * 2015-9-14 Taron v1.0.0 create * @see */ class Add { static void addUser(User user,File dbFile) { String lineSeparator = (String) java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction("line.separator"));//系统换行符 StringBuffer sb=new StringBuffer(); String info=sb.toString(); FileOutputStream writerStream=null; BufferedWriter writer=null; sb=sb.append(user.getId().toString()).append(',').append(user.getName()).append(',').append(user.getTelephone()).append(',').append(user.getAddress()); info=sb.toString(); try {//UTF-8追加数据 writerStream=new FileOutputStream(dbFile,true); writer= new BufferedWriter(new OutputStreamWriter(writerStream,"UTF-8")); writer.write(info,0,info.length()); writer.newLine(); writer.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(writer!=null){ writer.close(); writer=null; } } catch (IOException e) { e.printStackTrace(); } } } }
gpl-2.0
sharenav/sharenav
Osm2ShareNav/src/net/sharenav/osmToShareNav/model/WayDescription.java
2130
/** * OSM2ShareNav * * * * Copyright (C) 2008 */ package net.sharenav.osmToShareNav.model; import net.sharenav.osmToShareNav.Configuration; import java.util.List; public class WayDescription extends EntityDescription{ public int minOnewayArrowScale; public int minDescriptionScale; public int lineColor; public int lineColorAtNight = -1; public int wayDescFlags; public int boardedColor; public int boardedColorAtNight = -1; public boolean isArea; public boolean ignoreOsmAreaTag; public boolean showNameAsForArea; public int wayWidth; /** Up to 4 travel Modes (motorcar, bicycle, etc.) supported by this WayDescription (1 bit per travel mode) * The upper 4 bits equal to Connection.CONNTYPE_* flags */ public byte wayDescTravelModes; /** typical speed of this WayDescription for up to MAXTRAVELMODES travel modes */ public float typicalSpeed[] = new float[TravelModes.MAXTRAVELMODES]; public int noWaysOfType; public byte forceToLayer; // line styles public final static int WDFLAG_LINESTYLE_SOLID = 0x00; // same as Graphics.SOLID public final static int WDFLAG_LINESTYLE_DOTTED = 0x01; // same as Graphics.DOTTED; public final static int WDFLAG_LINESTYLE_RAIL = 0x02; public final static int WDFLAG_LINESTYLE_STEPS = 0x04; public final static int WDFLAG_LINESTYLE_POWERLINE = 0x08; public final static int WDFLAG_BUILDING = 0x10; public final static int WDFLAG_HIGHWAY_LINK = 0x20; public final static int WDFLAG_MOTORWAY = 0x40; public final static int WDFLAG_MAINSTREET_NET = 0x80; public WayDescription() { wayDescFlags = WDFLAG_LINESTYLE_SOLID; boardedColor = 0; isArea = false; ignoreOsmAreaTag = false; showNameAsForArea = false; wayWidth = 2; wayDescTravelModes = 0; for (int i = 0; i < TravelModes.travelModeCount; i++) { typicalSpeed[i] = 5f; } rulePriority = 0; } public boolean isHighwayLink() { return (wayDescFlags & WDFLAG_HIGHWAY_LINK) > 0; } public boolean isMotorway() { return (wayDescFlags & WDFLAG_MOTORWAY) > 0; } public boolean isMainstreet() { return (wayDescFlags & WDFLAG_MAINSTREET_NET) > 0; } }
gpl-2.0
Earbuds/UntitledScape
UntitledScape/untitledscape/world/mapdata/MapList.java
235
package untitledscape.world.mapdata; public class MapList { /** * The region the mapdata is for. */ public int region = 0; /** * The four pieces of mapdata. */ public int[] data = new int[4]; }
gpl-2.0
christianchristensen/resin
modules/servlet16/src/javax/el/ArrayELResolver.java
4729
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.el; import java.beans.FeatureDescriptor; import java.lang.reflect.Array; import java.util.Iterator; /** * Resolves properties based on arrays. */ public class ArrayELResolver extends ELResolver { private final boolean _isReadOnly; public ArrayELResolver() { _isReadOnly = false; } public ArrayELResolver(boolean isReadOnly) { _isReadOnly = isReadOnly; } @Override public Class<?> getCommonPropertyType(ELContext context, Object base) { if (base == null) return null; else if (base.getClass().isArray()) return base.getClass().getComponentType(); else return null; } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { if (base == null) return null; else if (base.getClass().isArray()) { context.setPropertyResolved(true); return null; } else return null; } @Override public Class<?> getType(ELContext context, Object base, Object property) { if (base == null) return null; else if (base.getClass().isArray()) { context.setPropertyResolved(true); int index = getIndex(property); if (index < 0 || Array.getLength(base) <= index) throw new PropertyNotFoundException("array index '" + index + "' is invalid"); return base.getClass().getComponentType(); } else return null; } /** * * @param context * @param base * @param property * @return If the <code>propertyResolved</code> property of * <code>ELContext</code> was set to <code>true</code>, then * the value at the given index or <code>null</code> * if the index was out of bounds. Otherwise, undefined. */ @Override public Object getValue(ELContext context, Object base, Object property) { if (base == null) return null; else if (base.getClass().isArray()) { context.setPropertyResolved(true); int index = getIndex(property); if (0 <= index && index < Array.getLength(base)) return Array.get(base, index); else return null; } else { return null; } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { if (base == null) return false; else if (base.getClass().isArray()) { context.setPropertyResolved(true); int index = getIndex(property); if (index < 0 || index >= Array.getLength(base)) throw new PropertyNotFoundException("array index '" + index + "' is invalid"); return _isReadOnly; } else return false; } @Override public void setValue(ELContext context, Object base, Object property, Object value) { if (base == null) { } else if (base.getClass().isArray()) { context.setPropertyResolved(true); if (_isReadOnly) throw new PropertyNotWritableException("resolver is read-only"); int index = getIndex(property); if (0 <= index && index < Array.getLength(base)) Array.set(base, index, value); else throw new PropertyNotFoundException("array index '" + index + "' is invalid"); } } static int getIndex(Object property) { if (property instanceof Number) return ((Number) property).intValue(); else if (property instanceof String) { try { return Integer.parseInt((String) property); } catch (Exception e) { throw new IllegalArgumentException("can't convert '" + property + "' to long."); } } else throw new IllegalArgumentException("can't convert '" + property + "' to long."); } }
gpl-2.0
cblichmann/idajava
javasrc/src/de/blichmann/idajava/natives/screen_graph_selection_t.java
2080
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.0 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package de.blichmann.idajava.natives; public class screen_graph_selection_t { private long swigCPtr; protected boolean swigCMemOwn; public screen_graph_selection_t(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } public static long getCPtr(screen_graph_selection_t obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; IdaJavaJNI.delete_screen_graph_selection_t(swigCPtr); } swigCPtr = 0; } } public boolean has(selection_item_t item) { return IdaJavaJNI.screen_graph_selection_t_has(swigCPtr, this, selection_item_t.getCPtr(item), item); } public void add(screen_graph_selection_t s) { IdaJavaJNI.screen_graph_selection_t_add(swigCPtr, this, screen_graph_selection_t.getCPtr(s), s); } public void sub(screen_graph_selection_t s) { IdaJavaJNI.screen_graph_selection_t_sub(swigCPtr, this, screen_graph_selection_t.getCPtr(s), s); } public void add_node(int n) { IdaJavaJNI.screen_graph_selection_t_add_node(swigCPtr, this, n); } public void del_node(int n) { IdaJavaJNI.screen_graph_selection_t_del_node(swigCPtr, this, n); } public void add_point(edge_t e, int idx) { IdaJavaJNI.screen_graph_selection_t_add_point(swigCPtr, this, edge_t.getCPtr(e), e, idx); } public void del_point(edge_t e, int idx) { IdaJavaJNI.screen_graph_selection_t_del_point(swigCPtr, this, edge_t.getCPtr(e), e, idx); } public screen_graph_selection_t() { this(IdaJavaJNI.new_screen_graph_selection_t(), true); } }
gpl-2.0