repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Merve13/meinwebtechprojekt
webtech2013-master/webtech2013-master/play_basics/app/controllers/ShopListController.java
1281
package controllers; import java.util.List; import models.ShopList; import models.ShopListItem; import play.Logger; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; public class ShopListController extends Controller { /** * Posten der Liste hinzufügen * @return */ public static Result addItem(){ ShopList shopList = ShopList.get(); /** * formular auslesen */ Form<ShopListItem> form = Form.form(ShopListItem.class); form = form.bindFromRequest(); if(form.hasErrors() || form.hasGlobalErrors()){ return badRequest(views.html.shoplist.shoplist.render(shopList.items)); } ShopListItem item = form.get(); shopList.addItem(item); Logger.info("Zu Liste hinzugefügt: " +item +" Posten: " +shopList.items.size()); return redirect(routes.ShopListController.list()); } /** * Posten von Liste löschen */ public static Result deleteItem(String itemname){ ShopList shopList = ShopList.get(); shopList.remove(itemname); Logger.info("Von Liste gelöscht: " +itemname); return redirect("/shoplist/"); } /** * Einkausliste anzeigen * @return */ public static Result list(){ List<ShopListItem> items = ShopList.get().items; return ok(views.html.shoplist.shoplist.render(items)); } }
apache-2.0
wjbuys/blox
scheduling-manager/src/main/java/com/amazonaws/blox/scheduling/SchedulingApplication.java
3092
/* * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "LICENSE" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.blox.scheduling; import com.amazonaws.blox.dataservicemodel.v1.client.DataService; import com.amazonaws.blox.dataservicemodel.v1.serialization.DataServiceMapperFactory; import com.amazonaws.blox.jsonrpc.JsonRpcLambdaClient; import com.amazonaws.blox.lambda.JacksonRequestStreamHandler; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Profile; import software.amazon.awssdk.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.ecs.ECSAsyncClient; import software.amazon.awssdk.services.lambda.LambdaAsyncClient; /** Common beans required by all Scheduling lambda functions. */ public abstract class SchedulingApplication { static { // HACK: Disable IPv6 for the current JVM, since the Netty `epoll` driver fails in a Lambda // function if IPv6 is enabled. // Remove after https://github.com/aws/aws-sdk-java-v2/issues/193 is fixed. System.setProperty("java.net.preferIPv4Stack", "true"); } /** The X-Ray Trace ID provided by the Lambda runtime environment. */ @Value("${_X_AMZN_TRACE_ID}") public String traceId; @Value("${data_service_function_name}") public String dataServiceFunctionName; @Bean public <IN, OUT> RequestStreamHandler streamHandler(RequestHandler<IN, OUT> innerHandler) { return new JacksonRequestStreamHandler<>(mapper(), innerHandler); } @Bean @Profile("!test") public LambdaAsyncClient lambdaClient() { // add trace ID to downstream calls, for X-Ray integration ClientOverrideConfiguration configuration = ClientOverrideConfiguration.builder() .addAdditionalHttpHeader("X-Amzn-Trace-Id", traceId) .build(); return LambdaAsyncClient.builder().overrideConfiguration(configuration).build(); } @Bean @Profile("!test") public ECSAsyncClient ecs() { return ECSAsyncClient.builder().build(); } @Bean public ObjectMapper mapper() { return new ObjectMapper().findAndRegisterModules(); } @Bean @Profile("!test") public DataService dataService(LambdaAsyncClient lambda) { return new JsonRpcLambdaClient( DataServiceMapperFactory.newMapper(), lambda, dataServiceFunctionName) .newProxy(DataService.class); } }
apache-2.0
objmagic/heron
heron/statemgrs/src/java/com/twitter/heron/statemgr/FileSystemStateManager.java
10845
// Copyright 2016 Twitter. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.twitter.heron.statemgr; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import com.google.protobuf.Message; import com.twitter.heron.api.generated.TopologyAPI; import com.twitter.heron.proto.scheduler.Scheduler; import com.twitter.heron.proto.system.ExecutionEnvironment; import com.twitter.heron.proto.system.PackingPlans; import com.twitter.heron.proto.system.PhysicalPlans; import com.twitter.heron.proto.tmaster.TopologyMaster; import com.twitter.heron.spi.common.Config; import com.twitter.heron.spi.common.Context; import com.twitter.heron.spi.common.Key; import com.twitter.heron.spi.statemgr.IStateManager; import com.twitter.heron.spi.statemgr.Lock; import com.twitter.heron.spi.statemgr.WatchCallback; public abstract class FileSystemStateManager implements IStateManager { private static final Logger LOG = Logger.getLogger(FileSystemStateManager.class.getName()); // Store the root address of the hierarchical file system protected String rootAddress; protected enum StateLocation { TMASTER_LOCATION("tmasters", "TMaster location"), METRICSCACHE_LOCATION("metricscaches", "MetricsCache location"), TOPOLOGY("topologies", "Topologies"), PACKING_PLAN("packingplans", "Packing plan"), PHYSICAL_PLAN("pplans", "Physical plan"), EXECUTION_STATE("executionstate", "Execution state"), SCHEDULER_LOCATION("schedulers", "Scheduler location"), LOCKS("locks", "Distributed locks"); private final String dir; private final String name; StateLocation(String dir, String name) { this.dir = dir; this.name = name; } public String getName() { return name; } public String getDirectory(String root) { return concatPath(root, dir); } public String getNodePath(String root, String topology) { return concatPath(getDirectory(root), topology); } public String getNodePath(String root, String topology, String extraToken) { return getNodePath(root, String.format("%s__%s", topology, extraToken)); } private static String concatPath(String basePath, String appendPath) { return String.format("%s/%s", basePath, appendPath); } } protected abstract ListenableFuture<Boolean> nodeExists(String path); protected abstract ListenableFuture<Boolean> deleteNode(String path, boolean deleteChildrenIfNecessary); protected abstract <M extends Message> ListenableFuture<M> getNodeData(WatchCallback watcher, String path, Message.Builder builder); protected abstract Lock getLock(String path); protected String getStateDirectory(StateLocation location) { return location.getDirectory(rootAddress); } protected String getStatePath(StateLocation location, String topologyName) { return location.getNodePath(rootAddress, topologyName); } @Override public void initialize(Config config) { this.rootAddress = Context.stateManagerRootPath(config); LOG.log(Level.FINE, "File system state manager root address: {0}", rootAddress); } @Override public Lock getLock(String topologyName, LockName lockName) { return getLock( StateLocation.LOCKS.getNodePath(this.rootAddress, topologyName, lockName.getName())); } @Override public ListenableFuture<Boolean> deleteTMasterLocation(String topologyName) { return deleteNode(StateLocation.TMASTER_LOCATION, topologyName); } @Override public ListenableFuture<Boolean> deleteMetricsCacheLocation(String topologyName) { return deleteNode(StateLocation.METRICSCACHE_LOCATION, topologyName); } @Override public ListenableFuture<Boolean> deleteSchedulerLocation(String topologyName) { return deleteNode(StateLocation.SCHEDULER_LOCATION, topologyName); } @Override public ListenableFuture<Boolean> deleteExecutionState(String topologyName) { return deleteNode(StateLocation.EXECUTION_STATE, topologyName); } @Override public ListenableFuture<Boolean> deleteTopology(String topologyName) { return deleteNode(StateLocation.TOPOLOGY, topologyName); } @Override public ListenableFuture<Boolean> deletePackingPlan(String topologyName) { return deleteNode(StateLocation.PACKING_PLAN, topologyName); } @Override public ListenableFuture<Boolean> deletePhysicalPlan(String topologyName) { return deleteNode(StateLocation.PHYSICAL_PLAN, topologyName); } @Override public ListenableFuture<Scheduler.SchedulerLocation> getSchedulerLocation( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.SCHEDULER_LOCATION, topologyName, Scheduler.SchedulerLocation.newBuilder()); } @Override public ListenableFuture<TopologyAPI.Topology> getTopology( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.TOPOLOGY, topologyName, TopologyAPI.Topology.newBuilder()); } @Override public ListenableFuture<ExecutionEnvironment.ExecutionState> getExecutionState( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.EXECUTION_STATE, topologyName, ExecutionEnvironment.ExecutionState.newBuilder()); } @Override public ListenableFuture<PackingPlans.PackingPlan> getPackingPlan( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.PACKING_PLAN, topologyName, PackingPlans.PackingPlan.newBuilder()); } @Override public ListenableFuture<PhysicalPlans.PhysicalPlan> getPhysicalPlan( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.PHYSICAL_PLAN, topologyName, PhysicalPlans.PhysicalPlan.newBuilder()); } @Override public ListenableFuture<TopologyMaster.TMasterLocation> getTMasterLocation( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.TMASTER_LOCATION, topologyName, TopologyMaster.TMasterLocation.newBuilder()); } @Override public ListenableFuture<TopologyMaster.MetricsCacheLocation> getMetricsCacheLocation( WatchCallback watcher, String topologyName) { return getNodeData(watcher, StateLocation.METRICSCACHE_LOCATION, topologyName, TopologyMaster.MetricsCacheLocation.newBuilder()); } @Override public ListenableFuture<Boolean> isTopologyRunning(String topologyName) { return nodeExists(getStatePath(StateLocation.TOPOLOGY, topologyName)); } @Override public ListenableFuture<Boolean> deleteLocks(String topologyName) { boolean result = true; for (LockName lockName : LockName.values()) { String path = StateLocation.LOCKS.getNodePath(this.rootAddress, topologyName, lockName.getName()); ListenableFuture<Boolean> thisResult = deleteNode(path, true); try { if (!thisResult.get()) { result = false; } } catch (InterruptedException | ExecutionException e) { LOG.log(Level.WARNING, "Error while waiting on result of delete lock at " + thisResult, e); } } final SettableFuture<Boolean> future = SettableFuture.create(); future.set(result); return future; } private ListenableFuture<Boolean> deleteNode(StateLocation location, String topologyName) { return deleteNode(getStatePath(location, topologyName), false); } private <M extends Message> ListenableFuture<M> getNodeData(WatchCallback watcher, StateLocation location, String topologyName, Message.Builder builder) { return getNodeData(watcher, getStatePath(location, topologyName), builder); } /** * Returns all information stored in the StateManager. This is a utility method used for debugging * while developing. To invoke, run: * * bazel run heron/statemgrs/src/java:localfs-statemgr-unshaded -- \ * &lt;topology-name&gt; [new_instance_distribution] * * If a new_instance_distribution is provided, the instance distribution will be updated to * trigger a scaling event. For example: * * bazel run heron/statemgrs/src/java:localfs-statemgr-unshaded -- \ * ExclamationTopology 1:word:3:0:exclaim1:2:0:exclaim1:1:0 * */ protected void doMain(String[] args, Config config) throws ExecutionException, InterruptedException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (args.length < 1) { throw new RuntimeException(String.format( "Usage: java %s <topology_name> - view state manager details for a topology", this.getClass().getCanonicalName())); } String topologyName = args[0]; print("==> State Manager root path: %s", config.getStringValue(Key.STATEMGR_ROOT_PATH)); initialize(config); if (isTopologyRunning(topologyName).get()) { print("==> Topology %s found", topologyName); print("==> Topology %s:", getTopology(null, topologyName).get()); print("==> ExecutionState:\n%s", getExecutionState(null, topologyName).get()); print("==> SchedulerLocation:\n%s", getSchedulerLocation(null, topologyName).get()); print("==> TMasterLocation:\n%s", getTMasterLocation(null, topologyName).get()); print("==> MetricsCacheLocation:\n%s", getMetricsCacheLocation(null, topologyName).get()); print("==> PackingPlan:\n%s", getPackingPlan(null, topologyName).get()); print("==> PhysicalPlan:\n%s", getPhysicalPlan(null, topologyName).get()); } else { print("==> Topology %s not found under %s", topologyName, config.getStringValue(Key.STATEMGR_ROOT_PATH)); } } protected void print(String format, Object... values) { System.out.println(String.format(format, values)); } }
apache-2.0
dropbox/bazel
src/main/java/com/google/devtools/build/skyframe/ShareabilityOfValue.java
1299
// Copyright 2018 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.skyframe; /** * When the {@link NodeEntry#getValue} corresponding to a given {@link SkyFunctionName} is * shareable: always, sometimes (depending on the specific key argument and/or value), or never. * * <p>Values may be unshareable because they are just not serializable, or because they contain data * that cannot safely be re-used as-is by another invocation. * * <p>Unshareable data should not be serialized, since it will never be re-used. Attempts to fetch * serialized data will check this value and only perform the fetch if the value is not {@link * #NEVER}. */ public enum ShareabilityOfValue { ALWAYS, SOMETIMES, NEVER }
apache-2.0
MerritCR/merrit
gerrit-server/src/test/java/com/google/gerrit/testutil/TestChanges.java
5973
// Copyright (C) 2014 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.testutil; import static com.google.common.base.MoreObjects.firstNonNull; import static org.easymock.EasyMock.expect; import com.google.common.collect.Ordering; import com.google.gerrit.common.TimeUtil; import com.google.gerrit.extensions.config.FactoryModule; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Branch; import com.google.gerrit.reviewdb.client.Change; import com.google.gerrit.reviewdb.client.PatchSet; import com.google.gerrit.reviewdb.client.PatchSetInfo; import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.RevId; import com.google.gerrit.server.CurrentUser; import com.google.gerrit.server.git.GitRepositoryManager; import com.google.gerrit.server.notedb.AbstractChangeNotes; import com.google.gerrit.server.notedb.ChangeNotes; import com.google.gerrit.server.notedb.ChangeUpdate; import com.google.gerrit.server.notedb.NotesMigration; import com.google.gerrit.server.project.ChangeControl; import com.google.gwtorm.server.OrmException; import com.google.inject.Injector; import org.easymock.EasyMock; import org.eclipse.jgit.junit.TestRepository; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicInteger; /** * Utility functions to create and manipulate Change, ChangeUpdate, and * ChangeControl objects for testing. */ public class TestChanges { private static final AtomicInteger nextChangeId = new AtomicInteger(1); public static Change newChange(Project.NameKey project, Account.Id userId) { return newChange(project, userId, nextChangeId.getAndIncrement()); } public static Change newChange(Project.NameKey project, Account.Id userId, int id) { Change.Id changeId = new Change.Id(id); Change c = new Change( new Change.Key("Iabcd1234abcd1234abcd1234abcd1234abcd1234"), changeId, userId, new Branch.NameKey(project, "master"), TimeUtil.nowTs()); incrementPatchSet(c); return c; } public static PatchSet newPatchSet(PatchSet.Id id, ObjectId revision, Account.Id userId) { return newPatchSet(id, revision.name(), userId); } public static PatchSet newPatchSet(PatchSet.Id id, String revision, Account.Id userId) { PatchSet ps = new PatchSet(id); ps.setRevision(new RevId(revision)); ps.setUploader(userId); ps.setCreatedOn(TimeUtil.nowTs()); return ps; } public static ChangeUpdate newUpdate(Injector injector, Change c, final CurrentUser user) throws Exception { injector = injector.createChildInjector(new FactoryModule() { @Override public void configure() { bind(CurrentUser.class).toInstance(user); } }); ChangeUpdate update = injector.getInstance(ChangeUpdate.Factory.class) .create( stubChangeControl( injector.getInstance(AbstractChangeNotes.Args.class), c, user), TimeUtil.nowTs(), Ordering.<String> natural()); ChangeNotes notes = update.getNotes(); boolean hasPatchSets = notes.getPatchSets() != null && !notes.getPatchSets().isEmpty(); NotesMigration migration = injector.getInstance(NotesMigration.class); if (hasPatchSets || !migration.readChanges()) { return update; } // Change doesn't exist yet. NoteDb requires that there be a commit for the // first patch set, so create one. GitRepositoryManager repoManager = injector.getInstance(GitRepositoryManager.class); try (Repository repo = repoManager.openRepository(c.getProject())) { TestRepository<Repository> tr = new TestRepository<>(repo); PersonIdent ident = user.asIdentifiedUser() .newCommitterIdent(update.getWhen(), TimeZone.getDefault()); TestRepository<Repository>.CommitBuilder cb = tr.commit() .author(ident) .committer(ident) .message(firstNonNull(c.getSubject(), "Test change")); Ref parent = repo.exactRef(c.getDest().get()); if (parent != null) { cb.parent(tr.getRevWalk().parseCommit(parent.getObjectId())); } update.setBranch(c.getDest().get()); update.setChangeId(c.getKey().get()); update.setCommit(tr.getRevWalk(), cb.create()); return update; } } private static ChangeControl stubChangeControl( AbstractChangeNotes.Args args, Change c, CurrentUser user) throws OrmException { ChangeControl ctl = EasyMock.createMock(ChangeControl.class); expect(ctl.getChange()).andStubReturn(c); expect(ctl.getProject()).andStubReturn(new Project(c.getProject())); expect(ctl.getUser()).andStubReturn(user); ChangeNotes notes = new ChangeNotes(args, c.getProject(), c).load(); expect(ctl.getNotes()).andStubReturn(notes); expect(ctl.getId()).andStubReturn(c.getId()); EasyMock.replay(ctl); return ctl; } public static void incrementPatchSet(Change change) { PatchSet.Id curr = change.currentPatchSetId(); PatchSetInfo ps = new PatchSetInfo(new PatchSet.Id( change.getId(), curr != null ? curr.get() + 1 : 1)); ps.setSubject("Change subject"); change.setCurrentPatchSet(ps); } }
apache-2.0
backpaper0/doma2
src/main/java/org/seasar/doma/DomainConverters.java
1970
/* * Copyright 2004-2010 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.doma; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.seasar.doma.jdbc.domain.DomainConverter; /** * {@link DomainConverter} を複数登録します。 * <p> * このアノテーションの{@code value} 要素に指定される {@code DomainConverter} のクラスには * {@link ExternalDomain} が注釈されていないければいけません。 * * このアノテーションが注釈されたクラスの完全修飾名は、注釈処理のオプションに登録する必要があります。オプションのキーは * {@code doma.domain.converters} です。 * * <h3>例:</h3> * * <pre> * &#064;DomainConverters({ SalaryConverter.class, DayConverter.class, * LocationConverter.class }) * public class DomainConvertersProvider { * } * </pre> * * @author taedium * @since 1.25.0 * @see DomainConverter * @see ExternalDomain */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DomainConverters { /** * {@code DomainConverter} のクラスの配列を返します。 * * @return {@code DomainConverter} のクラスの配列 */ Class<? extends DomainConverter<?, ?>>[] value() default {}; }
apache-2.0
porcelli-forks/jbpm-form-modeler
jbpm-form-modeler-core/jbpm-form-modeler-api/src/main/java/org/jbpm/formModeler/api/events/FormSubmitFailEvent.java
1202
/** * Copyright (C) 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.formModeler.api.events; import org.jboss.errai.common.client.api.annotations.Portable; import org.jbpm.formModeler.api.client.FormRenderContextTO; import java.lang.String; @Portable public class FormSubmitFailEvent extends FormRenderEvent { private String cause; public FormSubmitFailEvent() { } public FormSubmitFailEvent(FormRenderContextTO context, String cause) { super(context); this.cause = cause; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } }
apache-2.0
openhab/jmdns
src/main/java/javax/jmdns/impl/tasks/resolver/DNSResolverTask.java
3416
// Licensed under Apache License version 2.0 package javax.jmdns.impl.tasks.resolver; import java.io.IOException; import java.util.Timer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jmdns.impl.DNSOutgoing; import javax.jmdns.impl.JmDNSImpl; import javax.jmdns.impl.constants.DNSConstants; import javax.jmdns.impl.tasks.DNSTask; /** * This is the root class for all resolver tasks. * * @author Pierre Frisch */ public abstract class DNSResolverTask extends DNSTask { private static Logger logger = LoggerFactory.getLogger(DNSResolverTask.class.getName()); /** * Counts the number of queries being sent. */ protected int _count = 0; /** * @param jmDNSImpl */ public DNSResolverTask(JmDNSImpl jmDNSImpl) { super(jmDNSImpl); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return super.toString() + " count: " + _count; } /* * (non-Javadoc) * @see javax.jmdns.impl.tasks.DNSTask#start(java.util.Timer) */ @Override public void start(Timer timer) { if (!this.getDns().isCanceling() && !this.getDns().isCanceled()) { timer.schedule(this, DNSConstants.QUERY_WAIT_INTERVAL, DNSConstants.QUERY_WAIT_INTERVAL); } } /* * (non-Javadoc) * @see java.util.TimerTask#run() */ @Override public void run() { try { if (this.getDns().isCanceling() || this.getDns().isCanceled()) { this.cancel(); } else { if (_count++ < 3) { logger.debug("{}.run() JmDNS {}",this.getName(), this.description()); DNSOutgoing out = new DNSOutgoing(DNSConstants.FLAGS_QR_QUERY); out = this.addQuestions(out); if (this.getDns().isAnnounced()) { out = this.addAnswers(out); } if (!out.isEmpty()) { this.getDns().send(out); } } else { // After three queries, we can quit. this.cancel(); } } } catch (Throwable e) { logger.warn(this.getName() + ".run() exception ", e); this.getDns().recover(); } } /** * Overridden by subclasses to add questions to the message.<br/> * <b>Note:</b> Because of message size limitation the returned message may be different than the message parameter. * * @param out * outgoing message * @return the outgoing message. * @exception IOException */ protected abstract DNSOutgoing addQuestions(DNSOutgoing out) throws IOException; /** * Overridden by subclasses to add questions to the message.<br/> * <b>Note:</b> Because of message size limitation the returned message may be different than the message parameter. * * @param out * outgoing message * @return the outgoing message. * @exception IOException */ protected abstract DNSOutgoing addAnswers(DNSOutgoing out) throws IOException; /** * Returns a description of the resolver for debugging * * @return resolver description */ protected abstract String description(); }
apache-2.0
DarwinSPL/DarwinSPL
plugins/eu.hyvar.mspl.manifest.resource.hymanifest/src-gen/eu/hyvar/mspl/manifest/resource/hymanifest/IHymanifestResourcePostProcessor.java
971
/** * <copyright> * </copyright> * * */ package eu.hyvar.mspl.manifest.resource.hymanifest; /** * Implementors of this interface can be used to post-process parsed text * resources. This can be useful to validate or modify the model that was * instantiated for the text. */ public interface IHymanifestResourcePostProcessor { /** * <p> * Processes the resource after it was parsed. This method is automatically called * for registered post processors. * </p> * * @param resource the resource to validate of modify */ public void process(eu.hyvar.mspl.manifest.resource.hymanifest.mopp.HymanifestResource resource); /** * This method is called to request the post processor to terminate. It is called * from a different thread than the one that called process(). Terminating post * processors is required when text resources are parsed in the background. * Implementing this method is optional. */ public void terminate(); }
apache-2.0
glahiru/airavata
modules/xbaya-gui/src/test/java/org/apache/airavata/xbaya/interpreter/SimpleForEachWorkflowTest.java
3805
///* // * // * Licensed to the Apache Software Foundation (ASF) under one // * or more contributor license agreements. See the NOTICE file // * distributed with this work for additional information // * regarding copyright ownership. The ASF licenses this file // * to you under the Apache License, Version 2.0 (the // * "License"); you may not use this file except in compliance // * with the License. You may obtain a copy of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, // * software distributed under the License is distributed on an // * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // * KIND, either express or implied. See the License for the // * specific language governing permissions and limitations // * under the License. // * //*/ //package org.apache.airavata.xbaya.interpreter; // //import java.io.IOException; //import java.net.URISyntaxException; //import java.net.URL; //import java.util.UUID; // ////import org.apache.airavata.registry.api.AiravataRegistry2; //import org.apache.airavata.workflow.model.exceptions.WorkflowException; //import org.apache.airavata.workflow.model.wf.Workflow; //import org.apache.airavata.xbaya.XBayaConfiguration; //import org.apache.airavata.xbaya.interpreter.utils.WorkflowTestUtils; //import org.apache.airavata.xbaya.interpretor.SSWorkflowInterpreterInteractorImpl; //import org.apache.airavata.xbaya.interpretor.StandaloneNotificationSender; //import org.apache.airavata.xbaya.interpretor.WorkflowInterpreter; //import org.apache.airavata.xbaya.interpretor.WorkflowInterpreterConfiguration; //import org.junit.Rule; //import org.junit.Test; //import org.junit.rules.MethodRule; //import org.junit.rules.TestWatchman; //import org.junit.runners.model.FrameworkMethod; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; // //public class SimpleForEachWorkflowTest { // final Logger logger = LoggerFactory.getLogger(ForEachWorkflowTest.class); // // @Rule // public MethodRule watchman = new TestWatchman() { // public void starting(FrameworkMethod method) { // logger.info("{} being run...", method.getName()); // } // }; // // @Test // public void testScheduleDynamically() throws IOException, URISyntaxException, WorkflowException { // logger.info("Running SimpleForEachWorkflowTest..."); // URL systemResource = this.getClass().getClassLoader().getSystemResource("SimpleForEach.xwf"); // Workflow workflow = new Workflow(WorkflowTestUtils.readWorkflow(systemResource)); // XBayaConfiguration conf = WorkflowTestUtils.getConfiguration(); //// AiravataRegistry2 registry = conf.getJcrComponentRegistry()==null? null:conf.getJcrComponentRegistry().getRegistry(); //// WorkflowInterpreterConfiguration workflowInterpreterConfiguration = new WorkflowInterpreterConfiguration(workflow, UUID.randomUUID().toString(),conf.getMessageBoxURL(), conf.getBrokerURL(), registry, conf, null,null,true); // WorkflowInterpreterConfiguration workflowInterpreterConfiguration = new WorkflowInterpreterConfiguration(workflow, // UUID.randomUUID().toString(),conf.getMessageBoxURL(), conf.getBrokerURL(), conf.getAiravataAPI(), conf, null,null,true); // workflowInterpreterConfiguration.setNotifier(new StandaloneNotificationSender(workflowInterpreterConfiguration.getTopic(),workflowInterpreterConfiguration.getWorkflow())); // // SSWorkflowInterpreterInteractorImpl ssWorkflowInterpreterInteractorImpl = new SSWorkflowInterpreterInteractorImpl(); // // WorkflowInterpreter interpretor = new WorkflowInterpreter(workflowInterpreterConfiguration,ssWorkflowInterpreterInteractorImpl); // interpretor.scheduleDynamically(); // } //}
apache-2.0
NBANDROIDTEAM/NBANDROID-V2
nbandroid.core/src/main/java/org/nbandroid/netbeans/gradle/v2/NbOptionalDependencySpiLoader.java
6180
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.nbandroid.netbeans.gradle.v2; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.ByteBuffer; import java.util.Collections; import java.util.Enumeration; import java.util.Vector; import org.netbeans.core.startup.MainLookup; import org.openide.util.Lookup; /** * A class loader that combines NetBeans SPI and Impl module into one.<br> * The Impl classes loaded by this class loader are associated with this class * loader, i.e. Class.getClassLoader() points to this class loader. * * @author ArSi */ public class NbOptionalDependencySpiLoader extends ClassLoader { private final ClassLoader spiModuleClassLoader; private final String implPackage; private final String spiPackage; /** * Add Impl of SPI to NB default lookup if the SPI module is available. To * use as optional (weak) dependency add <scope>provided</scope> to SPI * dependency in POM. Dont access Impl classes from Impl module. * * @param spiFullClassName SPI full Class name * @param implFullClassName Impl full Class name * @param classToExtractImplClassLoader Class from Impl module to get * Classloader * @return true if SPI is created */ public static final boolean installServiceProvider(String spiFullClassName,String spiPackageName, String implFullClassName, Class<?> classToExtractImplClassLoader) { ClassLoader classLoader = Lookup.getDefault().lookup(ClassLoader.class); try { Class<?> colorCodesProvider = classLoader.loadClass(spiFullClassName); if (colorCodesProvider != null) { ClassLoader previewClassLoader = colorCodesProvider.getClassLoader(); ClassLoader androidClassLoader = classToExtractImplClassLoader.getClassLoader(); NbOptionalDependencySpiLoader proxyClassLoader = new NbOptionalDependencySpiLoader(androidClassLoader, implFullClassName.substring(0, implFullClassName.lastIndexOf('.')), previewClassLoader, spiPackageName); Class<?> androidColorCodesProvider = proxyClassLoader.findClass(implFullClassName); Object newInstance = androidColorCodesProvider.newInstance(); MainLookup.register(colorCodesProvider.cast(newInstance)); } return true; } catch (Exception ex) { } return false; } public NbOptionalDependencySpiLoader(ClassLoader implModuleClassLoader, String implPackage, ClassLoader spiModuleClassLoader, String spiPackage) { super(implModuleClassLoader); this.spiModuleClassLoader = spiModuleClassLoader; this.implPackage = implPackage; this.spiPackage = spiPackage; } @Override public Class<?> loadClass(String name) throws ClassNotFoundException { if (name.startsWith(implPackage) || name.startsWith(spiPackage)) { return findClass(name); } return super.loadClass(name); } @Override public Class<?> findClass(String name) throws ClassNotFoundException { if (name.startsWith(spiPackage)) { return spiModuleClassLoader.loadClass(name); } String path = name.replace('.', '/') + ".class"; URL url = findResource(path); if (url == null) { throw new ClassNotFoundException(name); } ByteBuffer byteCode; try { byteCode = loadResource(url); } catch (IOException e) { throw new ClassNotFoundException(name, e); } return defineClass(name, byteCode, null); } private ByteBuffer loadResource(URL url) throws IOException { InputStream stream = null; try { stream = url.openStream(); int initialBufferCapacity = Math.min(0x40000, stream.available() + 1); if (initialBufferCapacity <= 2) { initialBufferCapacity = 0x10000; } else { initialBufferCapacity = Math.max(initialBufferCapacity, 0x200); } ByteBuffer buf = ByteBuffer.allocate(initialBufferCapacity); while (true) { if (!buf.hasRemaining()) { ByteBuffer newBuf = ByteBuffer.allocate(2 * buf.capacity()); buf.flip(); newBuf.put(buf); buf = newBuf; } int len = stream.read(buf.array(), buf.position(), buf.remaining()); if (len <= 0) { break; } buf.position(buf.position() + len); } buf.flip(); return buf; } finally { if (stream != null) { stream.close(); } } } @Override protected URL findResource(String name) { URL resource = spiModuleClassLoader.getResource(name); if (resource == null) { return super.getResource(name); } return resource; } @Override protected Enumeration<URL> findResources(String name) throws IOException { Vector<URL> vector = new Vector<>(); vector.addAll(Collections.list(spiModuleClassLoader.getResources(name))); vector.addAll(Collections.list(super.getResources(name))); return vector.elements(); } }
apache-2.0
apache/parquet-mr
parquet-hadoop/src/test/java/org/apache/parquet/filter2/compat/TestRowGroupFilter.java
5088
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.parquet.filter2.compat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.HashSet; import org.junit.Test; import org.apache.parquet.column.statistics.IntStatistics; import org.apache.parquet.filter2.predicate.Operators.IntColumn; import org.apache.parquet.hadoop.metadata.BlockMetaData; import org.apache.parquet.schema.MessageType; import org.apache.parquet.schema.MessageTypeParser; import static org.junit.Assert.assertEquals; import static org.apache.parquet.filter2.predicate.FilterApi.eq; import static org.apache.parquet.filter2.predicate.FilterApi.in; import static org.apache.parquet.filter2.predicate.FilterApi.intColumn; import static org.apache.parquet.filter2.predicate.FilterApi.notEq; import static org.apache.parquet.filter2.predicate.FilterApi.notIn; import static org.apache.parquet.hadoop.TestInputFormat.makeBlockFromStats; public class TestRowGroupFilter { @Test public void testApplyRowGroupFilters() { List<BlockMetaData> blocks = new ArrayList<BlockMetaData>(); IntStatistics stats1 = new IntStatistics(); stats1.setMinMax(10, 100); stats1.setNumNulls(4); BlockMetaData b1 = makeBlockFromStats(stats1, 301); blocks.add(b1); IntStatistics stats2 = new IntStatistics(); stats2.setMinMax(8, 102); stats2.setNumNulls(0); BlockMetaData b2 = makeBlockFromStats(stats2, 302); blocks.add(b2); IntStatistics stats3 = new IntStatistics(); stats3.setMinMax(100, 102); stats3.setNumNulls(12); BlockMetaData b3 = makeBlockFromStats(stats3, 303); blocks.add(b3); IntStatistics stats4 = new IntStatistics(); stats4.setMinMax(0, 0); stats4.setNumNulls(304); BlockMetaData b4 = makeBlockFromStats(stats4, 304); blocks.add(b4); IntStatistics stats5 = new IntStatistics(); stats5.setMinMax(50, 50); stats5.setNumNulls(7); BlockMetaData b5 = makeBlockFromStats(stats5, 305); blocks.add(b5); IntStatistics stats6 = new IntStatistics(); stats6.setMinMax(0, 0); stats6.setNumNulls(12); BlockMetaData b6 = makeBlockFromStats(stats6, 306); blocks.add(b6); MessageType schema = MessageTypeParser.parseMessageType("message Document { optional int32 foo; }"); IntColumn foo = intColumn("foo"); Set<Integer> set1 = new HashSet<>(); set1.add(9); set1.add(10); set1.add(50); List<BlockMetaData> filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(in(foo, set1)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b5), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(notIn(foo, set1)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b3, b4, b5, b6), filtered); Set<Integer> set2 = new HashSet<>(); set2.add(null); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(in(foo, set2)), blocks, schema); assertEquals(Arrays.asList(b1, b3, b4, b5, b6), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(notIn(foo, set2)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b3, b4, b5, b6), filtered); set2.add(8); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(in(foo, set2)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b3, b4, b5, b6), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(notIn(foo, set2)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b3, b4, b5, b6), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(eq(foo, 50)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b5), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(notEq(foo, 50)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b3, b4, b5, b6), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(eq(foo, null)), blocks, schema); assertEquals(Arrays.asList(b1, b3, b4, b5, b6), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(notEq(foo, null)), blocks, schema); assertEquals(Arrays.asList(b1, b2, b3, b5, b6), filtered); filtered = RowGroupFilter.filterRowGroups(FilterCompat.get(eq(foo, 0)), blocks, schema); assertEquals(Arrays.asList(b6), filtered); } }
apache-2.0
pencil-box/NetKnight
MPChartLib/src/com/github/mikephil/charting/charts/PieRadarChartBase.java
16549
package com.github.mikephil.charting.charts; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.animation.ValueAnimator.AnimatorUpdateListener; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.PointF; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.components.Legend; import com.github.mikephil.charting.components.Legend.LegendPosition; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.data.ChartData; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.interfaces.datasets.IDataSet; import com.github.mikephil.charting.listener.PieRadarChartTouchListener; import com.github.mikephil.charting.utils.SelectionDetail; import com.github.mikephil.charting.utils.Utils; import java.util.ArrayList; import java.util.List; /** * Baseclass of PieChart and RadarChart. * * @author Philipp Jahoda */ public abstract class PieRadarChartBase<T extends ChartData<? extends IDataSet<? extends Entry>>> extends Chart<T> { /** holds the normalized version of the current rotation angle of the chart */ private float mRotationAngle = 270f; /** holds the raw version of the current rotation angle of the chart */ private float mRawRotationAngle = 270f; /** flag that indicates if rotation is enabled or not */ protected boolean mRotateEnabled = true; /** Sets the minimum offset (padding) around the chart, defaults to 0.f */ protected float mMinOffset = 0.f; public PieRadarChartBase(Context context) { super(context); } public PieRadarChartBase(Context context, AttributeSet attrs) { super(context, attrs); } public PieRadarChartBase(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void init() { super.init(); mChartTouchListener = new PieRadarChartTouchListener(this); } @Override protected void calcMinMax() { mXAxis.mAxisRange = mData.getXVals().size() - 1; } @Override public boolean onTouchEvent(MotionEvent event) { // use the pie- and radarchart listener own listener if (mTouchEnabled && mChartTouchListener != null) return mChartTouchListener.onTouch(this, event); else return super.onTouchEvent(event); } @Override public void computeScroll() { if (mChartTouchListener instanceof PieRadarChartTouchListener) ((PieRadarChartTouchListener) mChartTouchListener).computeScroll(); } @Override public void notifyDataSetChanged() { if (mData == null) return; calcMinMax(); if (mLegend != null) mLegendRenderer.computeLegend(mData); calculateOffsets(); } @Override public void calculateOffsets() { float legendLeft = 0f, legendRight = 0f, legendBottom = 0f, legendTop = 0f; if (mLegend != null && mLegend.isEnabled() && !mLegend.isDrawInsideEnabled()) { float fullLegendWidth = Math.min(mLegend.mNeededWidth, mViewPortHandler.getChartWidth() * mLegend.getMaxSizePercent()) + mLegend.getFormSize() + mLegend.getFormToTextSpace(); switch (mLegend.getOrientation()) { case VERTICAL: { float xLegendOffset = 0.f; if (mLegend.getHorizontalAlignment() == Legend.LegendHorizontalAlignment.LEFT || mLegend.getHorizontalAlignment() == Legend.LegendHorizontalAlignment.RIGHT) { if (mLegend.getVerticalAlignment() == Legend.LegendVerticalAlignment.CENTER) { // this is the space between the legend and the chart final float spacing = Utils.convertDpToPixel(13f); xLegendOffset = fullLegendWidth + spacing; } else { // this is the space between the legend and the chart float spacing = Utils.convertDpToPixel(8f); float legendWidth = fullLegendWidth + spacing; float legendHeight = mLegend.mNeededHeight + mLegend.mTextHeightMax; PointF c = getCenter(); float bottomX = mLegend.getHorizontalAlignment() == Legend.LegendHorizontalAlignment.RIGHT ? getWidth() - legendWidth + 15.f : legendWidth - 15.f; float bottomY = legendHeight + 15.f; float distLegend = distanceToCenter(bottomX, bottomY); PointF reference = getPosition(c, getRadius(), getAngleForPoint(bottomX, bottomY)); float distReference = distanceToCenter(reference.x, reference.y); float minOffset = Utils.convertDpToPixel(5f); if (bottomY >= c.y && getHeight() - legendWidth > getWidth()) { xLegendOffset = legendWidth; } else if (distLegend < distReference) { float diff = distReference - distLegend; xLegendOffset = minOffset + diff; } } } switch (mLegend.getHorizontalAlignment()) { case LEFT: legendLeft = xLegendOffset; break; case RIGHT: legendRight = xLegendOffset; break; case CENTER: switch (mLegend.getVerticalAlignment()) { case TOP: legendTop = Math.min(mLegend.mNeededHeight, mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent()); break; case BOTTOM: legendBottom = Math.min(mLegend.mNeededHeight, mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent()); break; } break; } } break; case HORIZONTAL: float yLegendOffset = 0.f; if (mLegend.getVerticalAlignment() == Legend.LegendVerticalAlignment.TOP || mLegend.getVerticalAlignment() == Legend.LegendVerticalAlignment.BOTTOM) { // It's possible that we do not need this offset anymore as it // is available through the extraOffsets, but changing it can mean // changing default visibility for existing apps. float yOffset = getRequiredLegendOffset(); yLegendOffset = Math.min(mLegend.mNeededHeight + yOffset, mViewPortHandler.getChartHeight() * mLegend.getMaxSizePercent()); switch (mLegend.getVerticalAlignment()) { case TOP: legendTop = yLegendOffset; break; case BOTTOM: legendBottom = yLegendOffset; break; } } break; } legendLeft += getRequiredBaseOffset(); legendRight += getRequiredBaseOffset(); legendTop += getRequiredBaseOffset(); legendBottom += getRequiredBaseOffset(); } float minOffset = Utils.convertDpToPixel(mMinOffset); if (this instanceof RadarChart) { XAxis x = this.getXAxis(); if (x.isEnabled() && x.isDrawLabelsEnabled()) { minOffset = Math.max(minOffset, x.mLabelRotatedWidth); } } legendTop += getExtraTopOffset(); legendRight += getExtraRightOffset(); legendBottom += getExtraBottomOffset(); legendLeft += getExtraLeftOffset(); float offsetLeft = Math.max(minOffset, legendLeft); float offsetTop = Math.max(minOffset, legendTop); float offsetRight = Math.max(minOffset, legendRight); float offsetBottom = Math.max(minOffset, Math.max(getRequiredBaseOffset(), legendBottom)); mViewPortHandler.restrainViewPort(offsetLeft, offsetTop, offsetRight, offsetBottom); if (mLogEnabled) Log.i(LOG_TAG, "offsetLeft: " + offsetLeft + ", offsetTop: " + offsetTop + ", offsetRight: " + offsetRight + ", offsetBottom: " + offsetBottom); } /** * returns the angle relative to the chart center for the given point on the * chart in degrees. The angle is always between 0 and 360°, 0° is NORTH, * 90° is EAST, ... * * @param x * @param y * @return */ public float getAngleForPoint(float x, float y) { PointF c = getCenterOffsets(); double tx = x - c.x, ty = y - c.y; double length = Math.sqrt(tx * tx + ty * ty); double r = Math.acos(ty / length); float angle = (float) Math.toDegrees(r); if (x > c.x) angle = 360f - angle; // add 90° because chart starts EAST angle = angle + 90f; // neutralize overflow if (angle > 360f) angle = angle - 360f; return angle; } /** * Calculates the position around a center point, depending on the distance * from the center, and the angle of the position around the center. * * @param center * @param dist * @param angle in degrees, converted to radians internally * @return */ protected PointF getPosition(PointF center, float dist, float angle) { PointF p = new PointF((float) (center.x + dist * Math.cos(Math.toRadians(angle))), (float) (center.y + dist * Math.sin(Math.toRadians(angle)))); return p; } /** * Returns the distance of a certain point on the chart to the center of the * chart. * * @param x * @param y * @return */ public float distanceToCenter(float x, float y) { PointF c = getCenterOffsets(); float dist = 0f; float xDist = 0f; float yDist = 0f; if (x > c.x) { xDist = x - c.x; } else { xDist = c.x - x; } if (y > c.y) { yDist = y - c.y; } else { yDist = c.y - y; } // pythagoras dist = (float) Math.sqrt(Math.pow(xDist, 2.0) + Math.pow(yDist, 2.0)); return dist; } /** * Returns the xIndex for the given angle around the center of the chart. * Returns -1 if not found / outofbounds. * * @param angle * @return */ public abstract int getIndexForAngle(float angle); /** * Set an offset for the rotation of the RadarChart in degrees. Default 270f * --> top (NORTH) * * @param angle */ public void setRotationAngle(float angle) { mRawRotationAngle = angle; mRotationAngle = Utils.getNormalizedAngle(mRawRotationAngle); } /** * gets the raw version of the current rotation angle of the pie chart the * returned value could be any value, negative or positive, outside of the * 360 degrees. this is used when working with rotation direction, mainly by * gestures and animations. * * @return */ public float getRawRotationAngle() { return mRawRotationAngle; } /** * gets a normalized version of the current rotation angle of the pie chart, * which will always be between 0.0 < 360.0 * * @return */ public float getRotationAngle() { return mRotationAngle; } /** * Set this to true to enable the rotation / spinning of the chart by touch. * Set it to false to disable it. Default: true * * @param enabled */ public void setRotationEnabled(boolean enabled) { mRotateEnabled = enabled; } /** * Returns true if rotation of the chart by touch is enabled, false if not. * * @return */ public boolean isRotationEnabled() { return mRotateEnabled; } /** Gets the minimum offset (padding) around the chart, defaults to 0.f */ public float getMinOffset() { return mMinOffset; } /** Sets the minimum offset (padding) around the chart, defaults to 0.f */ public void setMinOffset(float minOffset) { mMinOffset = minOffset; } /** * returns the diameter of the pie- or radar-chart * * @return */ public float getDiameter() { RectF content = mViewPortHandler.getContentRect(); content.left += getExtraLeftOffset(); content.top += getExtraTopOffset(); content.right -= getExtraRightOffset(); content.bottom -= getExtraBottomOffset(); return Math.min(content.width(), content.height()); } /** * Returns the radius of the chart in pixels. * * @return */ public abstract float getRadius(); /** * Returns the required offset for the chart legend. * * @return */ protected abstract float getRequiredLegendOffset(); /** * Returns the base offset needed for the chart without calculating the * legend size. * * @return */ protected abstract float getRequiredBaseOffset(); @Override public float getYChartMax() { // TODO Auto-generated method stub return 0; } @Override public float getYChartMin() { // TODO Auto-generated method stub return 0; } /** * Returns an array of SelectionDetail objects for the given x-index. The SelectionDetail * objects give information about the value at the selected index and the * DataSet it belongs to. INFORMATION: This method does calculations at * runtime. Do not over-use in performance critical situations. * * @return */ public List<SelectionDetail> getSelectionDetailsAtIndex(int xIndex) { List<SelectionDetail> vals = new ArrayList<SelectionDetail>(); for (int i = 0; i < mData.getDataSetCount(); i++) { IDataSet<?> dataSet = mData.getDataSetByIndex(i); // extract all y-values from all DataSets at the given x-index final float yVal = dataSet.getYValForXIndex(xIndex); if (Float.isNaN(yVal)) continue; vals.add(new SelectionDetail(yVal, i, dataSet)); } return vals; } /** * ################ ################ ################ ################ */ /** CODE BELOW THIS RELATED TO ANIMATION */ /** * Applys a spin animation to the Chart. * * @param durationmillis * @param fromangle * @param toangle */ @SuppressLint("NewApi") public void spin(int durationmillis, float fromangle, float toangle, Easing.EasingOption easing) { if (android.os.Build.VERSION.SDK_INT < 11) return; setRotationAngle(fromangle); ObjectAnimator spinAnimator = ObjectAnimator.ofFloat(this, "rotationAngle", fromangle, toangle); spinAnimator.setDuration(durationmillis); spinAnimator.setInterpolator(Easing.getEasingFunctionFromOption(easing)); spinAnimator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { postInvalidate(); } }); spinAnimator.start(); } }
apache-2.0
wcm-io-devops/conga
tooling/conga-maven-plugin/src/main/java/io/wcm/devops/conga/tooling/maven/plugin/ValidateMojo.java
14677
/* * #%L * wcm.io * %% * Copyright (C) 2015 wcm.io * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package io.wcm.devops.conga.tooling.maven.plugin; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.SortedSet; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.resolver.ResolutionErrorHandler; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import org.sonatype.plexus.build.incremental.BuildContext; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import com.google.common.collect.ImmutableList; import io.wcm.devops.conga.generator.GeneratorException; import io.wcm.devops.conga.generator.GeneratorOptions; import io.wcm.devops.conga.generator.UrlFileManager; import io.wcm.devops.conga.generator.handlebars.HandlebarsManager; import io.wcm.devops.conga.generator.spi.context.PluginContextOptions; import io.wcm.devops.conga.generator.spi.context.UrlFilePluginContext; import io.wcm.devops.conga.generator.util.PluginManager; import io.wcm.devops.conga.generator.util.PluginManagerImpl; import io.wcm.devops.conga.model.environment.Environment; import io.wcm.devops.conga.model.reader.EnvironmentReader; import io.wcm.devops.conga.model.reader.RoleReader; import io.wcm.devops.conga.model.role.Role; import io.wcm.devops.conga.resource.Resource; import io.wcm.devops.conga.resource.ResourceCollection; import io.wcm.devops.conga.resource.ResourceInfo; import io.wcm.devops.conga.resource.ResourceLoader; import io.wcm.devops.conga.tooling.maven.plugin.util.ClassLoaderUtil; import io.wcm.devops.conga.tooling.maven.plugin.util.MavenContext; import io.wcm.devops.conga.tooling.maven.plugin.util.PathUtil; import io.wcm.devops.conga.tooling.maven.plugin.util.VersionInfoUtil; import io.wcm.devops.conga.tooling.maven.plugin.validation.DefinitionValidator; import io.wcm.devops.conga.tooling.maven.plugin.validation.ModelValidator; import io.wcm.devops.conga.tooling.maven.plugin.validation.NoValueProviderInRoleValidator; import io.wcm.devops.conga.tooling.maven.plugin.validation.RoleTemplateFileValidator; import io.wcm.devops.conga.tooling.maven.plugin.validation.TemplateValidator; /** * Validates definitions by trying to parse them with model reader or compile them via handlebars. * Validates that the CONGA maven plugin version and CONGA plugin versions match or are newer than those versions * used when generating the dependency artifacts. */ @Mojo(name = "validate", defaultPhase = LifecyclePhase.VALIDATE, requiresProject = true, threadSafe = true, requiresDependencyResolution = ResolutionScope.COMPILE) public class ValidateMojo extends AbstractCongaMojo { /** * Selected environments to validate. */ @Parameter(property = "conga.environments") private String[] environments; @Parameter(property = "project", required = true, readonly = true) private MavenProject project; @Component private org.apache.maven.repository.RepositorySystem repositorySystem; @Component private ResolutionErrorHandler resolutionErrorHandler; @Component private RepositorySystem repoSystem; @Component private BuildContext buildContext; @Parameter(property = "repositorySystemSession", readonly = true) private RepositorySystemSession repoSession; @Parameter(property = "project.remoteProjectRepositories", readonly = true) private List<RemoteRepository> remoteRepos; @Parameter(defaultValue = "${session}", readonly = true, required = false) private MavenSession session; @Override public void execute() throws MojoExecutionException, MojoFailureException { List<URL> mavenProjectClasspathUrls = ClassLoaderUtil.getMavenProjectClasspathUrls(project); ClassLoader mavenProjectClassLoader = ClassLoaderUtil.buildClassLoader(mavenProjectClasspathUrls); ResourceLoader mavenProjectResourceLoader = new ResourceLoader(mavenProjectClassLoader); ResourceCollection roleDir = mavenProjectResourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + getRoleDir()); ResourceCollection templateDir = mavenProjectResourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + getTemplateDir()); ResourceCollection environmentDir = mavenProjectResourceLoader.getResourceCollection(ResourceLoader.FILE_PREFIX + getEnvironmentDir()); // validate role definition syntax validateFiles(roleDir, roleDir, new ModelValidator<Role>("Role", new RoleReader())); PluginManager pluginManager = new PluginManagerImpl(); MavenContext mavenContext = new MavenContext() .project(project) .session(session) .setRepositorySystem(repositorySystem) .resolutionErrorHandler(resolutionErrorHandler) .buildContext(buildContext) .log(getLog()) .repoSystem(repoSystem) .repoSession(repoSession) .remoteRepos(remoteRepos) .artifactTypeMappings(getArtifactTypeMappings()); UrlFilePluginContext urlFilePluginContext = new UrlFilePluginContext() .baseDir(project.getBasedir()) .resourceClassLoader(mavenProjectClassLoader) .pluginContextOptions(new PluginContextOptions() .containerContext(mavenContext)); UrlFileManager urlFileManager = new UrlFileManager(pluginManager, urlFilePluginContext); PluginContextOptions pluginContextOptions = new PluginContextOptions() .pluginManager(pluginManager) .urlFileManager(urlFileManager) .valueProviderConfig(getValueProviderConfig()) .genericPluginConfig(getPluginConfig()) .containerContext(mavenContext) .logger(new MavenSlf4jLogFacade(getLog())); // validate that all templates can be compiled HandlebarsManager handlebarsManager = new HandlebarsManager(ImmutableList.of(templateDir), pluginContextOptions); validateFiles(templateDir, templateDir, new TemplateValidator(templateDir, handlebarsManager)); // validate that roles reference existing templates validateFiles(roleDir, roleDir, new RoleTemplateFileValidator(handlebarsManager)); // validate that no value providers are used in role files - they should be only used in environment validateFiles(roleDir, roleDir, new NoValueProviderInRoleValidator()); // validate environment definition syntax List<Environment> environmentList = validateFiles(environmentDir, environmentDir, new ModelValidator<Environment>("Environment", new EnvironmentReader()), // filter environments resourceInfo -> { if (this.environments == null || this.environments.length == 0) { return true; } for (String environment : this.environments) { if (StringUtils.equals(environment, FilenameUtils.getBaseName(resourceInfo.getName()))) { return true; } } return false; }); // validate version information - for each environment separately for (Environment environment : environmentList) { UrlFilePluginContext environmentUrlFilePluginContext = new UrlFilePluginContext() .baseDir(project.getBasedir()) .resourceClassLoader(mavenProjectClassLoader) .environment(environment) .pluginContextOptions(new PluginContextOptions() .containerContext(mavenContext)); UrlFileManager environmentUrlFileManager = new UrlFileManager(pluginManager, environmentUrlFilePluginContext); PluginContextOptions environmentPluginContextOptions = new PluginContextOptions() .pluginContextOptions(pluginContextOptions) .urlFileManager(environmentUrlFileManager); validateVersionInfo(environment, mavenProjectClasspathUrls, environmentPluginContextOptions); } } // ===== FILE VALIDATION ===== private <T> List<T> validateFiles(ResourceCollection sourceDir, ResourceCollection rootSourceDir, DefinitionValidator<T> validator) throws MojoFailureException { return validateFiles(sourceDir, rootSourceDir, validator, resourceInfo -> true); } private <T> List<T> validateFiles(ResourceCollection sourceDir, ResourceCollection rootSourceDir, DefinitionValidator<T> validator, Function<ResourceInfo, Boolean> resourceFilter) throws MojoFailureException { if (!sourceDir.exists()) { return ImmutableList.of(); } SortedSet<Resource> files = sourceDir.getResources(); SortedSet<ResourceCollection> dirs = sourceDir.getResourceCollections(); if (files.isEmpty() && dirs.isEmpty()) { return ImmutableList.of(); } List<T> result = new ArrayList<>(); for (Resource file : files) { if (resourceFilter.apply(file)) { result.add(validator.validate(file, getPathForLog(rootSourceDir, file))); } } for (ResourceCollection dir : dirs) { if (resourceFilter.apply(dir)) { result.addAll(validateFiles(dir, rootSourceDir, validator, resourceFilter)); } } return result; } private static String getPathForLog(ResourceCollection rootSourceDir, Resource file) { String path = PathUtil.unifySlashes(file.getCanonicalPath()); String rootPath = PathUtil.unifySlashes(rootSourceDir.getCanonicalPath()) + "/"; return StringUtils.substringAfter(path, rootPath); } // ===== PLUGIN VERSION INFO VALIDATION ===== /** * Validates that the CONGA maven plugin version and CONGA plugin versions match or are newer than those versions used * when generating the dependency artifacts. * @param environment Environment * @param mavenProjectClasspathUrls Classpath URLs of maven project * @param pluginContextOptions Plugin context options */ private void validateVersionInfo(Environment environment, List<URL> mavenProjectClasspathUrls, PluginContextOptions pluginContextOptions) throws MojoExecutionException { // build combined classpath for dependencies defined in environment and maven project List<URL> classpathUrls = new ArrayList<>(); classpathUrls.addAll(getEnvironmentClasspathUrls(environment.getDependencies(), pluginContextOptions)); classpathUrls.addAll(mavenProjectClasspathUrls); ClassLoader environmentDependenciesClassLoader = ClassLoaderUtil.buildClassLoader(classpathUrls); // get version info from this project Properties currentVersionInfo = VersionInfoUtil.getVersionInfoProperties(project); // validate current version info against dependency version infos for (Properties dependencyVersionInfo : getDependencyVersionInfos(environmentDependenciesClassLoader)) { validateVersionInfo(currentVersionInfo, dependencyVersionInfo); } } private List<URL> getEnvironmentClasspathUrls(List<String> dependencyUrls, PluginContextOptions pluginContextOptions) { return dependencyUrls.stream() .map(dependencyUrl -> { String resolvedDependencyUrl = ClassLoaderUtil.resolveDependencyUrl(dependencyUrl, pluginContextOptions); try { return pluginContextOptions.getUrlFileManager().getFileUrlsWithDependencies(resolvedDependencyUrl); } catch (IOException ex) { throw new GeneratorException("Unable to resolve: " + resolvedDependencyUrl, ex); } }) .flatMap(list -> list.stream()) .collect(Collectors.toList()); } private void validateVersionInfo(Properties currentVersionInfo, Properties dependencyVersionInfo) throws MojoExecutionException { for (Object keyObject : currentVersionInfo.keySet()) { String key = keyObject.toString(); String currentVersionString = currentVersionInfo.getProperty(key); String dependencyVersionString = dependencyVersionInfo.getProperty(key); if (StringUtils.isEmpty(currentVersionString) || StringUtils.isEmpty(dependencyVersionString)) { continue; } DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(currentVersionString); DefaultArtifactVersion dependencyVersion = new DefaultArtifactVersion(dependencyVersionString); if (currentVersion.compareTo(dependencyVersion) < 0) { throw new MojoExecutionException("Newer CONGA maven plugin or plugin version required: " + key + ":" + dependencyVersion.toString()); } } } private List<Properties> getDependencyVersionInfos(ClassLoader classLoader) throws MojoExecutionException { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(classLoader); try { org.springframework.core.io.Resource[] resources = resolver.getResources( "classpath*:" + GeneratorOptions.CLASSPATH_PREFIX + BuildConstants.FILE_VERSION_INFO); return Arrays.stream(resources) .map(resource -> toProperties(resource)) .collect(Collectors.toList()); } catch (IOException ex) { throw new MojoExecutionException("Unable to get classpath resources: " + ex.getMessage(), ex); } } private Properties toProperties(org.springframework.core.io.Resource resource) { try (InputStream is = resource.getInputStream()) { Properties props = new Properties(); props.load(is); return props; } catch (IOException ex) { throw new RuntimeException("Unable to read properties file: " + resource.toString(), ex); } } }
apache-2.0
microg/android_packages_apps_GmsCore
play-services-cast-api/src/main/java/com/google/android/gms/cast/CastDevice.java
5192
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gms.cast; import android.os.Bundle; import android.net.Uri; import android.text.TextUtils; import com.google.android.gms.common.images.WebImage; import org.microg.gms.common.PublicApi; import org.microg.safeparcel.AutoSafeParcelable; import org.microg.safeparcel.SafeParceled; import java.net.InetAddress; import java.net.Inet4Address; import java.util.ArrayList; import java.util.List; @PublicApi public class CastDevice extends AutoSafeParcelable { private static final String EXTRA_CAST_DEVICE = "com.google.android.gms.cast.EXTRA_CAST_DEVICE"; public CastDevice () { } public CastDevice ( String id, String name, InetAddress host, int port, String deviceVersion, String friendlyName, String modelName, String iconPath, int status, int capabilities) { this.deviceId = id; this.address = host.getHostAddress(); this.servicePort = port; this.deviceVersion = deviceVersion; this.friendlyName = friendlyName; this.icons = new ArrayList<WebImage>(); this.icons.add(new WebImage(Uri.parse(String.format("http://%s:8008%s", this.address, iconPath)))); this.modelName = modelName; this.capabilities = capabilities; } /** * Video-output device capability. */ public static final int CAPABILITY_VIDEO_OUT = 1; /** * Video-input device capability. */ public static final int CAPABILITY_VIDEO_IN = 2; /** * Audio-output device capability. */ public static final int CAPABILITY_AUDIO_OUT = 4; /** * Audio-input device capability. */ public static final int CAPABILITY_AUDIO_IN = 8; @SafeParceled(1) private int versionCode = 3; @SafeParceled(2) private String deviceId; @SafeParceled(3) private String address; @SafeParceled(4) private String friendlyName; @SafeParceled(5) private String modelName; @SafeParceled(6) private String deviceVersion; @SafeParceled(7) private int servicePort; @SafeParceled(value = 8, subClass = WebImage.class) private ArrayList<WebImage> icons; @SafeParceled(9) private int capabilities; @SafeParceled(10) private int status; @SafeParceled(11) private String unknown; // TODO: Need to figure this one out public String getDeviceId() { return deviceId; } public String getDeviceVersion() { return deviceVersion; } public String getFriendlyName() { return friendlyName; } public static CastDevice getFromBundle(Bundle extras) { if (extras == null) { return null; } extras.setClassLoader(CastDevice.class.getClassLoader()); return extras.getParcelable(EXTRA_CAST_DEVICE); } public WebImage getIcon(int preferredWidth, int preferredHeight) { return null; } public List<WebImage> getIcons() { return icons; } public String getAddress() { return address; } public String getModelName() { return modelName; } public int getServicePort() { return servicePort; } public boolean hasCapabilities(int[] capabilities) { for (int capability : capabilities) { if (!this.hasCapability(capability)) { return false; } } return true; } public boolean hasCapability(int capability) { return (capability & capabilities) == capability; } public boolean hasIcons() { return !icons.isEmpty(); } public boolean isOnLocalNetwork() { return false; } public boolean isSameDevice(CastDevice castDevice) { return TextUtils.equals(castDevice.deviceId, deviceId); } public void putInBundle(Bundle bundle) { bundle.putParcelable(EXTRA_CAST_DEVICE, this); } @Override public String toString() { return "CastDevice{" + "deviceId=" + this.deviceId + ", address=" + address + ", friendlyName=" + friendlyName + ", modelName=" + modelName + ", deviceVersion=" + deviceVersion + ", servicePort=" + servicePort + (icons == null ? "" : (", icons=" + icons.toString())) + ", capabilities=" + capabilities + ", status=" + status + "}"; } public static Creator<CastDevice> CREATOR = new AutoCreator<CastDevice>(CastDevice.class); }
apache-2.0
palantir/atlasdb
atlasdb-api/src/main/java/com/palantir/atlasdb/keyvalue/api/Prefix.java
1149
/* * (c) Copyright 2018 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.keyvalue.api; import com.palantir.common.annotation.Immutable; import com.palantir.logsafe.Preconditions; import javax.annotation.Nonnull; /** * Represents a partial row to be used for range requests. */ @Immutable public class Prefix { private final byte[] bytes; public Prefix(byte[] bytes) { this.bytes = Preconditions.checkNotNull(bytes, "bytes cannot be null").clone(); } @Nonnull public byte[] getBytes() { return bytes.clone(); } }
apache-2.0
bpupadhyaya/dashboard-demo-1
src/main/java/org/vaadin/viritin/grid/MGrid.java
7164
package org.vaadin.viritin.grid; import com.vaadin.data.Item; import com.vaadin.data.RpcDataProviderExtension; import com.vaadin.data.fieldgroup.FieldGroup; import com.vaadin.server.Extension; import com.vaadin.ui.Grid; import org.vaadin.viritin.LazyList; import org.vaadin.viritin.ListContainer; import org.vaadin.viritin.SortableLazyList; import org.vaadin.viritin.grid.utils.GridUtils; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.vaadin.viritin.LazyList.DEFAULT_PAGE_SIZE; /** * * @param <T> the entity type listed in the Grid */ public class MGrid<T> extends Grid { public MGrid() { } /** * Creates a new instance of MGrid that contains certain types of rows. * * @param typeOfRows the type of entities that are listed in the grid */ public MGrid(Class<T> typeOfRows) { setContainerDataSource(new ListContainer(typeOfRows)); } /** * Creates a new instance of MGrid with given list of rows. * * @param listOfEntities the list of entities to be displayed in the grid */ public MGrid(List<T> listOfEntities) { setRows(listOfEntities); } /** * A shorthand to create MGrid using LazyList. By default page size of * LazyList.DEFAULT_PAGE_SIZE (30) is used. * * @param pageProvider the interface via entities are fetched * @param countProvider the interface via the count of items is detected */ public MGrid(LazyList.PagingProvider<T> pageProvider, LazyList.CountProvider countProvider) { this(new LazyList(pageProvider, countProvider, DEFAULT_PAGE_SIZE)); } /** * A shorthand to create MGrid using a LazyList. * * @param pageProvider the interface via entities are fetched * @param countProvider the interface via the count of items is detected * @param pageSize the page size (aka maxResults) that is used in paging. */ public MGrid(LazyList.PagingProvider<T> pageProvider, LazyList.CountProvider countProvider, int pageSize) { this(new LazyList(pageProvider, countProvider, pageSize)); } /** * A shorthand to create an MGrid using SortableLazyList. By default page * size of LazyList.DEFAULT_PAGE_SIZE (30) is used. * * @param pageProvider the interface via entities are fetched * @param countProvider the interface via the count of items is detected */ public MGrid(SortableLazyList.SortablePagingProvider<T> pageProvider, LazyList.CountProvider countProvider) { this(new SortableLazyList(pageProvider, countProvider, DEFAULT_PAGE_SIZE)); } /** * A shorthand to create MTable using SortableLazyList. * * @param pageProvider the interface via entities are fetched * @param countProvider the interface via the count of items is detected * @param pageSize the page size (aka maxResults) that is used in paging. */ public MGrid(SortableLazyList.SortablePagingProvider<T> pageProvider, LazyList.CountProvider countProvider, int pageSize) { this(new SortableLazyList(pageProvider, countProvider, pageSize)); } /** * Enables saving/loading grid settings (visible columns, sort order, etc) * to cookies. * * @param settingsName cookie name where settings are saved should be * unique. */ public void attachSaveSettings(String settingsName) { GridUtils.attachToGrid(this, settingsName); } public MGrid<T> setRows(List<T> rows) { setContainerDataSource(new ListContainer(rows)); return this; } public MGrid<T> setRows(T... rows) { setContainerDataSource(new ListContainer(Arrays.asList(rows))); return this; } @Override public T getSelectedRow() throws IllegalStateException { return (T) super.getSelectedRow(); } /** * * @param entity the entity (row) to be selected. * @return <code>true</code> if the selection state changed, * <code>false</code> if the itemId already was selected */ public boolean selectRow(T entity) { return select(entity); } /** * @deprecated use the typed selectRow instead */ @Deprecated @Override public boolean select(Object itemId) throws IllegalArgumentException, IllegalStateException { return super.select(itemId); } public Collection<T> getSelectedRowsWithType() { // Maybe this is more complicated than it should be :-) return (Collection<T>) super.getSelectedRows(); } public MGrid<T> withProperties(String... propertyIds) { setColumns((Object[]) propertyIds); return this; } private FieldGroup.CommitHandler reloadDataEfficientlyAfterEditor; @Override public void setEditorEnabled(boolean isEnabled) throws IllegalStateException { super.setEditorEnabled(isEnabled); ensureRowRefreshListener(isEnabled); } protected void ensureRowRefreshListener(boolean isEnabled) { if (isEnabled && reloadDataEfficientlyAfterEditor == null) { reloadDataEfficientlyAfterEditor = new FieldGroup.CommitHandler() { @Override public void preCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException { } @Override public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException { Item itemDataSource = commitEvent.getFieldBinder(). getItemDataSource(); if (itemDataSource instanceof ListContainer.DynaBeanItem) { ListContainer.DynaBeanItem dynaBeanItem = (ListContainer.DynaBeanItem) itemDataSource; T bean = (T) dynaBeanItem.getBean(); refreshRow(bean); } } }; getEditorFieldGroup().addCommitHandler( reloadDataEfficientlyAfterEditor); } } /** * Manually forces refresh of the row that represents given entity. * ListContainer backing MGrid/MTable don't support property change * listeners (to save memory and CPU cycles). In some case with Grid, if you * know only certain row(s) are changed, you can make a smaller client side * change by refreshing rows with this method, instead of refreshing the * whole Grid (e.g. by re-assigning the bean list). * <p> * This method is automatically called if you use "editor row". * * @param bean the bean whose row should be refreshed. */ public void refreshRow(T bean) { Collection<Extension> extensions = getExtensions(); for (Extension extension : extensions) { if (extension instanceof RpcDataProviderExtension) { RpcDataProviderExtension rpcDataProviderExtension = (RpcDataProviderExtension) extension; rpcDataProviderExtension.updateRowData(bean); break; } } } }
apache-2.0
TommyLemon/Android-ZBLibrary
app/src/main/java/zblibrary/demo/DEMO/DemoBottomWindow.java
4436
/*Copyright ©2015 TommyLemon(https://github.com/TommyLemon) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ package zblibrary.demo.DEMO; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import zblibrary.demo.R; import zblibrary.demo.activity.UserActivity; import zuo.biao.library.base.BaseViewBottomWindow; import zuo.biao.library.model.Entry; /** 使用方法:复制>粘贴>改名>改代码 */ /**底部弹出窗口界面示例 * @author Lemon * <br> toActivity或startActivityForResult (DemoBottomWindow.createIntent(...), requestCode); * <br> 然后在onActivityResult方法内 * <br> data.getStringExtra(DemoBottomWindow.RESULT_DATA); 可得到返回值 */ public class DemoBottomWindow extends BaseViewBottomWindow<Entry<String, String>, DemoComplexView> implements OnClickListener { private static final String TAG = "DemoBottomWindow"; //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< public static Intent createIntent(Context context, String title) { return new Intent(context, DemoBottomWindow.class).putExtra(INTENT_TITLE, title); } //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //功能归类分区方法,必须调用<<<<<<<<<< initView(); initData(); initEvent(); //功能归类分区方法,必须调用>>>>>>>>>> } //UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initView() {//必须调用 super.initView(); } //UI显示区(操作UI,但不存在数据获取或处理代码,也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //Data数据区(存在数据获取或处理代码,但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initData() {//必须调用 super.initData(); data = new Entry<String, String>("Activity", TAG); data.setId(1); containerView.bindView(data); } @Override public String getTitleName() { return "Demo"; } @Override public String getReturnName() { return null; } @Override public String getForwardName() { return null; } @Override protected DemoComplexView createView() { return new DemoComplexView(context); } @Override protected void setResult() { //示例代码<<<<<<<<<<<<<<<<<<< setResult(RESULT_OK, new Intent().putExtra(RESULT_DATA, TAG + " saved")); //示例代码>>>>>>>>>>>>>>>>>>> } //Data数据区(存在数据获取或处理代码,但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @Override public void initEvent() {//必须调用 super.initEvent(); containerView.ivDemoComplexViewHead.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ivDemoViewHead: if (data != null) { toActivity(UserActivity.createIntent(context, data.getId())); } break; default: break; } } //生命周期、onActivityResult<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //生命周期、onActivityResult>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //内部类,尽量少用<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< //内部类,尽量少用>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> }
apache-2.0
lucky-code/Practice
kuaichuan2.0/app/src/main/java/com/lu/kuaichuan/wifidirect/fragment/ToolBarFragment.java
1045
package com.lu.kuaichuan.wifidirect.fragment; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.support.v7.widget.Toolbar; import com.lu.kuaichuan.wifidirect.activity.MainActivity; import com.lu.kuaichuan.wifidirect.R; /** * Created by ckt on 2/28/16. */ public class ToolBarFragment extends Fragment { private Toolbar toolbar; MainActivity activity; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.toolbar_layout, container, false); activity = (MainActivity) getActivity(); toolbar = (Toolbar) view.findViewById(R.id.id_toolbar_layout); toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); toolbar.setTitleTextColor(getResources().getColor(R.color.white)); activity.setSupportActionBar(toolbar); return view; } }
apache-2.0
apache/incubator-shardingsphere
shardingsphere-infra/shardingsphere-infra-merge/src/test/java/org/apache/shardingsphere/infra/merge/engine/decorator/impl/TransparentResultDecoratorTest.java
2205
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.infra.merge.engine.decorator.impl; import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext; import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResult; import org.apache.shardingsphere.infra.merge.result.MergedResult; import org.junit.Test; import java.sql.SQLException; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class TransparentResultDecoratorTest { @Test public void assertDecorateQueryResult() throws SQLException { QueryResult queryResult = mock(QueryResult.class); when(queryResult.next()).thenReturn(true); TransparentResultDecorator decorator = new TransparentResultDecorator(); MergedResult actual = decorator.decorate(queryResult, mock(SQLStatementContext.class), new TransparentRule()); assertTrue(actual.next()); } @Test public void assertDecorateMergedResult() throws SQLException { MergedResult mergedResult = mock(MergedResult.class); when(mergedResult.next()).thenReturn(true); TransparentResultDecorator decorator = new TransparentResultDecorator(); MergedResult actual = decorator.decorate(mergedResult, mock(SQLStatementContext.class), new TransparentRule()); assertTrue(actual.next()); } }
apache-2.0
kunickiaj/datacollector
container/src/main/java/com/streamsets/datacollector/config/KeytabSource.java
1148
/* * Copyright 2019 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.datacollector.config; import com.streamsets.pipeline.api.GenerateResourceBundle; import com.streamsets.pipeline.api.Label; @GenerateResourceBundle public enum KeytabSource implements Label { PROPERTIES_FILE("Transformer Configuration File"), PIPELINE("Pipeline Configuration - File"), PIPELINE_CREDENTIAL_STORE("Pipeline Configuration - Credential Store"), ; private final String label; KeytabSource(String label) { this.label = label; } @Override public String getLabel() { return label; } }
apache-2.0
objectiser/camel
core/camel-core-engine/src/main/java/org/apache/camel/model/PollEnrichDefinition.java
9612
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.model; import java.util.function.Supplier; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.AggregationStrategy; import org.apache.camel.model.language.ExpressionDefinition; import org.apache.camel.spi.Metadata; /** * Enriches messages with data polled from a secondary resource * * @see org.apache.camel.processor.Enricher */ @Metadata(label = "eip,transformation") @XmlRootElement(name = "pollEnrich") @XmlAccessorType(XmlAccessType.FIELD) public class PollEnrichDefinition extends ExpressionNode { @XmlAttribute @Metadata(defaultValue = "-1") private String timeout; @XmlAttribute(name = "strategyRef") private String aggregationStrategyRef; @XmlAttribute(name = "strategyMethodName") private String aggregationStrategyMethodName; @XmlAttribute(name = "strategyMethodAllowNull") private String aggregationStrategyMethodAllowNull; @XmlAttribute private String aggregateOnException; @XmlTransient private AggregationStrategy aggregationStrategy; @XmlAttribute private String cacheSize; @XmlAttribute private String ignoreInvalidEndpoint; public PollEnrichDefinition() { } public PollEnrichDefinition(AggregationStrategy aggregationStrategy, long timeout) { this.aggregationStrategy = aggregationStrategy; this.timeout = Long.toString(timeout); } @Override public String toString() { return "PollEnrich[" + getExpression() + "]"; } @Override public String getShortName() { return "pollEnrich"; } @Override public String getLabel() { return "pollEnrich[" + getExpression() + "]"; } // Fluent API // ------------------------------------------------------------------------- /** * Timeout in millis when polling from the external service. * <p/> * The timeout has influence about the poll enrich behavior. It basically * operations in three different modes: * <ul> * <li>negative value - Waits until a message is available and then returns * it. Warning that this method could block indefinitely if no messages are * available.</li> * <li>0 - Attempts to receive a message exchange immediately without * waiting and returning <tt>null</tt> if a message exchange is not * available yet.</li> * <li>positive value - Attempts to receive a message exchange, waiting up * to the given timeout to expire if a message is not yet available. Returns * <tt>null</tt> if timed out</li> * </ul> * The default value is -1 and therefore the method could block * indefinitely, and therefore its recommended to use a timeout value */ public PollEnrichDefinition timeout(long timeout) { setTimeout(Long.toString(timeout)); return this; } /** * Sets the AggregationStrategy to be used to merge the reply from the * external service, into a single outgoing message. By default Camel will * use the reply from the external service as outgoing message. */ public PollEnrichDefinition aggregationStrategy(AggregationStrategy aggregationStrategy) { setAggregationStrategy(aggregationStrategy); return this; } /** * Sets the AggregationStrategy to be used to merge the reply from the * external service, into a single outgoing message. By default Camel will * use the reply from the external service as outgoing message. */ public PollEnrichDefinition aggregationStrategy(Supplier<AggregationStrategy> aggregationStrategy) { setAggregationStrategy(aggregationStrategy.get()); return this; } /** * Refers to an AggregationStrategy to be used to merge the reply from the * external service, into a single outgoing message. By default Camel will * use the reply from the external service as outgoing message. */ public PollEnrichDefinition aggregationStrategyRef(String aggregationStrategyRef) { setAggregationStrategyRef(aggregationStrategyRef); return this; } /** * This option can be used to explicit declare the method name to use, when * using POJOs as the AggregationStrategy. */ public PollEnrichDefinition aggregationStrategyMethodName(String aggregationStrategyMethodName) { setAggregationStrategyMethodName(aggregationStrategyMethodName); return this; } /** * If this option is false then the aggregate method is not used if there * was no data to enrich. If this option is true then null values is used as * the oldExchange (when no data to enrich), when using POJOs as the * AggregationStrategy. */ public PollEnrichDefinition aggregationStrategyMethodAllowNull(boolean aggregationStrategyMethodAllowNull) { setAggregationStrategyMethodAllowNull(Boolean.toString(aggregationStrategyMethodAllowNull)); return this; } /** * If this option is false then the aggregate method is not used if there * was an exception thrown while trying to retrieve the data to enrich from * the resource. Setting this option to true allows end users to control * what to do if there was an exception in the aggregate method. For example * to suppress the exception or set a custom message body etc. */ public PollEnrichDefinition aggregateOnException(boolean aggregateOnException) { setAggregateOnException(Boolean.toString(aggregateOnException)); return this; } /** * Sets the maximum size used by the * {@link org.apache.camel.spi.ConsumerCache} which is used to cache and * reuse consumers when uris are reused. * * @param cacheSize the cache size, use <tt>0</tt> for default cache size, * or <tt>-1</tt> to turn cache off. * @return the builder */ public PollEnrichDefinition cacheSize(int cacheSize) { setCacheSize(Integer.toString(cacheSize)); return this; } /** * Ignore the invalidate endpoint exception when try to create a producer * with that endpoint * * @return the builder */ public PollEnrichDefinition ignoreInvalidEndpoint() { setIgnoreInvalidEndpoint(Boolean.toString(true)); return this; } // Properties // ------------------------------------------------------------------------- /** * Expression that computes the endpoint uri to use as the resource endpoint * to enrich from */ @Override public void setExpression(ExpressionDefinition expression) { // override to include javadoc what the expression is used for super.setExpression(expression); } public String getTimeout() { return timeout; } public void setTimeout(String timeout) { this.timeout = timeout; } public String getAggregationStrategyRef() { return aggregationStrategyRef; } public void setAggregationStrategyRef(String aggregationStrategyRef) { this.aggregationStrategyRef = aggregationStrategyRef; } public String getAggregationStrategyMethodName() { return aggregationStrategyMethodName; } public void setAggregationStrategyMethodName(String aggregationStrategyMethodName) { this.aggregationStrategyMethodName = aggregationStrategyMethodName; } public String getAggregationStrategyMethodAllowNull() { return aggregationStrategyMethodAllowNull; } public void setAggregationStrategyMethodAllowNull(String aggregationStrategyMethodAllowNull) { this.aggregationStrategyMethodAllowNull = aggregationStrategyMethodAllowNull; } public AggregationStrategy getAggregationStrategy() { return aggregationStrategy; } public void setAggregationStrategy(AggregationStrategy aggregationStrategy) { this.aggregationStrategy = aggregationStrategy; } public String getAggregateOnException() { return aggregateOnException; } public void setAggregateOnException(String aggregateOnException) { this.aggregateOnException = aggregateOnException; } public String getCacheSize() { return cacheSize; } public void setCacheSize(String cacheSize) { this.cacheSize = cacheSize; } public String getIgnoreInvalidEndpoint() { return ignoreInvalidEndpoint; } public void setIgnoreInvalidEndpoint(String ignoreInvalidEndpoint) { this.ignoreInvalidEndpoint = ignoreInvalidEndpoint; } }
apache-2.0
flaxsearch/BioSolr
ontology/ontology-annotator/core/src/main/java/uk/co/flax/biosolr/ontology/core/ols/OLSOntologyConfiguration.java
1865
/** * Copyright (c) 2016 Lemur Consulting Ltd. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.flax.biosolr.ontology.core.ols; import uk.co.flax.biosolr.ontology.core.OntologyHelperConfiguration; /** * OLS-specific configuration details. * * <p>Created by Matt Pearce on 23/02/16.</p> * @author Matt Pearce */ public class OLSOntologyConfiguration extends OntologyHelperConfiguration { private final String olsBaseUrl; private final String ontology; private final int pageSize; /** * Build the configuration for an OLS OntologyHelper instance. * @param olsBaseUrl the base URL for the OLS API endpoint. * @param ontology the ontology being referenced, if known. * @param pageSize the number of items to fetch from the API at a time. */ public OLSOntologyConfiguration(String olsBaseUrl, String ontology, int pageSize) { this.olsBaseUrl = olsBaseUrl; this.ontology = ontology; this.pageSize = pageSize; } /** * @return the base URL for the OLS API endpoint. */ public String getOlsBaseUrl() { return olsBaseUrl; } /** * @return the name of the ontology being referenced, as used in an * OLS URL. */ public String getOntology() { return ontology; } /** * @return the maximum number of items to retrieve in one call. */ public int getPageSize() { return pageSize; } }
apache-2.0
linkedin/indextank-engine
src/main/java/com/flaptor/indextank/suggest/NoSuggestor.java
1535
/* * Copyright (c) 2011 LinkedIn, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.flaptor.indextank.suggest; import java.util.Collections; import java.util.List; import java.util.Map; import com.flaptor.indextank.index.Document; import com.flaptor.indextank.query.Query; import com.google.common.collect.Lists; /** * A dummy suggestor implementation that does not suggest anything. */ public class NoSuggestor implements Suggestor { @Override public void noteQuery(Query query, int matches) { } @Override public void noteAdd(String documentId, Document doc) { } @Override public List<String> complete(String partialQuery, String field) { List<String> retVal = Lists.newArrayList(); retVal.add(partialQuery); return retVal; } @Override public void dump() { } @Override public Map<String, String> getStats() { return Collections.emptyMap(); } }
apache-2.0
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/components/MessageStoreParameterPropertiesEditionComponent.java
8062
/** * Generated with Acceleo */ package org.wso2.developerstudio.eclipse.gmf.esb.components; // Start of user code for imports import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EcorePackage; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.util.Diagnostician; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.emf.eef.runtime.api.notify.EStructuralFeatureNotificationFilter; import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent; import org.eclipse.emf.eef.runtime.api.notify.NotificationFilter; import org.eclipse.emf.eef.runtime.context.PropertiesEditingContext; import org.eclipse.emf.eef.runtime.impl.components.SinglePartPropertiesEditingComponent; import org.eclipse.emf.eef.runtime.impl.utils.EEFConverterUtil; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.MessageStoreParameter; import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository; import org.wso2.developerstudio.eclipse.gmf.esb.parts.MessageStoreParameterPropertiesEditionPart; // End of user code /** * * */ public class MessageStoreParameterPropertiesEditionComponent extends SinglePartPropertiesEditingComponent { public static String BASE_PART = "Base"; //$NON-NLS-1$ /** * Default constructor * */ public MessageStoreParameterPropertiesEditionComponent(PropertiesEditingContext editingContext, EObject messageStoreParameter, String editing_mode) { super(editingContext, messageStoreParameter, editing_mode); parts = new String[] { BASE_PART }; repositoryKey = EsbViewsRepository.class; partKey = EsbViewsRepository.MessageStoreParameter.class; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#initPart(java.lang.Object, int, org.eclipse.emf.ecore.EObject, * org.eclipse.emf.ecore.resource.ResourceSet) * */ public void initPart(Object key, int kind, EObject elt, ResourceSet allResource) { setInitializing(true); if (editingPart != null && key == partKey) { editingPart.setContext(elt, allResource); final MessageStoreParameter messageStoreParameter = (MessageStoreParameter)elt; final MessageStoreParameterPropertiesEditionPart basePart = (MessageStoreParameterPropertiesEditionPart)editingPart; // init values if (isAccessible(EsbViewsRepository.MessageStoreParameter.Properties.parameterName)) basePart.setParameterName(EEFConverterUtil.convertToString(EcorePackage.Literals.ESTRING, messageStoreParameter.getParameterName())); if (isAccessible(EsbViewsRepository.MessageStoreParameter.Properties.parameterValue)) basePart.setParameterValue(EEFConverterUtil.convertToString(EcorePackage.Literals.ESTRING, messageStoreParameter.getParameterValue())); // init filters // init values for referenced views // init filters for referenced views } setInitializing(false); } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#associatedFeature(java.lang.Object) */ public EStructuralFeature associatedFeature(Object editorKey) { if (editorKey == EsbViewsRepository.MessageStoreParameter.Properties.parameterName) { return EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterName(); } if (editorKey == EsbViewsRepository.MessageStoreParameter.Properties.parameterValue) { return EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterValue(); } return super.associatedFeature(editorKey); } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#updateSemanticModel(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent) * */ public void updateSemanticModel(final IPropertiesEditionEvent event) { MessageStoreParameter messageStoreParameter = (MessageStoreParameter)semanticObject; if (EsbViewsRepository.MessageStoreParameter.Properties.parameterName == event.getAffectedEditor()) { messageStoreParameter.setParameterName((java.lang.String)EEFConverterUtil.createFromString(EcorePackage.Literals.ESTRING, (String)event.getNewValue())); } if (EsbViewsRepository.MessageStoreParameter.Properties.parameterValue == event.getAffectedEditor()) { messageStoreParameter.setParameterValue((java.lang.String)EEFConverterUtil.createFromString(EcorePackage.Literals.ESTRING, (String)event.getNewValue())); } } /** * {@inheritDoc} * @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#updatePart(org.eclipse.emf.common.notify.Notification) */ public void updatePart(Notification msg) { super.updatePart(msg); if (editingPart.isVisible()) { MessageStoreParameterPropertiesEditionPart basePart = (MessageStoreParameterPropertiesEditionPart)editingPart; if (EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterName().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.MessageStoreParameter.Properties.parameterName)) { if (msg.getNewValue() != null) { basePart.setParameterName(EcoreUtil.convertToString(EcorePackage.Literals.ESTRING, msg.getNewValue())); } else { basePart.setParameterName(""); } } if (EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterValue().equals(msg.getFeature()) && msg.getNotifier().equals(semanticObject) && basePart != null && isAccessible(EsbViewsRepository.MessageStoreParameter.Properties.parameterValue)) { if (msg.getNewValue() != null) { basePart.setParameterValue(EcoreUtil.convertToString(EcorePackage.Literals.ESTRING, msg.getNewValue())); } else { basePart.setParameterValue(""); } } } } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.impl.components.StandardPropertiesEditionComponent#getNotificationFilters() */ @Override protected NotificationFilter[] getNotificationFilters() { NotificationFilter filter = new EStructuralFeatureNotificationFilter( EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterName(), EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterValue() ); return new NotificationFilter[] {filter,}; } /** * {@inheritDoc} * * @see org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent#validateValue(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent) * */ public Diagnostic validateValue(IPropertiesEditionEvent event) { Diagnostic ret = Diagnostic.OK_INSTANCE; if (event.getNewValue() != null) { try { if (EsbViewsRepository.MessageStoreParameter.Properties.parameterName == event.getAffectedEditor()) { Object newValue = event.getNewValue(); if (newValue instanceof String) { newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterName().getEAttributeType(), (String)newValue); } ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterName().getEAttributeType(), newValue); } if (EsbViewsRepository.MessageStoreParameter.Properties.parameterValue == event.getAffectedEditor()) { Object newValue = event.getNewValue(); if (newValue instanceof String) { newValue = EEFConverterUtil.createFromString(EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterValue().getEAttributeType(), (String)newValue); } ret = Diagnostician.INSTANCE.validate(EsbPackage.eINSTANCE.getMessageStoreParameter_ParameterValue().getEAttributeType(), newValue); } } catch (IllegalArgumentException iae) { ret = BasicDiagnostic.toDiagnostic(iae); } catch (WrappedException we) { ret = BasicDiagnostic.toDiagnostic(we); } } return ret; } }
apache-2.0
prabushi/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/commands/CacheMediatorCreateCommand.java
2897
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.commands; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.EObject; import org.eclipse.gmf.runtime.common.core.command.CommandResult; import org.eclipse.gmf.runtime.common.core.command.ICommand; import org.eclipse.gmf.runtime.emf.type.core.IElementType; import org.eclipse.gmf.runtime.emf.type.core.commands.EditElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.ConfigureRequest; import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest; import org.eclipse.gmf.runtime.notation.View; import org.wso2.developerstudio.eclipse.gmf.esb.CacheMediator; import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory; import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow; /** * @generated */ public class CacheMediatorCreateCommand extends EditElementCommand { /** * @generated */ public CacheMediatorCreateCommand(CreateElementRequest req) { super(req.getLabel(), null, req); } /** * FIXME: replace with setElementToEdit() * * @generated */ protected EObject getElementToEdit() { EObject container = ((CreateElementRequest) getRequest()).getContainer(); if (container instanceof View) { container = ((View) container).getElement(); } return container; } /** * @generated */ public boolean canExecute() { return true; } /** * @generated */ protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { CacheMediator newElement = EsbFactory.eINSTANCE.createCacheMediator(); MediatorFlow owner = (MediatorFlow) getElementToEdit(); owner.getChildren().add(newElement); doConfigure(newElement, monitor, info); ((CreateElementRequest) getRequest()).setNewElement(newElement); return CommandResult.newOKCommandResult(newElement); } /** * @generated */ protected void doConfigure(CacheMediator newElement, IProgressMonitor monitor, IAdaptable info) throws ExecutionException { IElementType elementType = ((CreateElementRequest) getRequest()).getElementType(); ConfigureRequest configureRequest = new ConfigureRequest(getEditingDomain(), newElement, elementType); configureRequest.setClientContext(((CreateElementRequest) getRequest()).getClientContext()); configureRequest.addParameters(getRequest().getParameters()); ICommand configureCommand = elementType.getEditCommand(configureRequest); if (configureCommand != null && configureCommand.canExecute()) { configureCommand.execute(monitor, info); } } }
apache-2.0
apache/uima-sandbox
CasViewerEclipsePlugin/uimaj-ep-casviewer-core/src/main/java/org/apache/uima/casviewer/ui/internal/style/DefaultColorTreeLabelProvider.java
12274
package org.apache.uima.casviewer.ui.internal.style; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.uima.casviewer.core.internal.IItemTypeConstants; import org.apache.uima.casviewer.core.internal.TypeNode; import org.apache.uima.resource.metadata.TypeDescription; import org.apache.uima.tools.common.internal.images.ImageLoader; import org.apache.uima.tools.debug.util.Trace; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.viewers.IFontProvider; import org.eclipse.jface.viewers.ITableColorProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; public class DefaultColorTreeLabelProvider extends LabelProvider implements ITableLabelProvider, ITableColorProvider, IFontProvider { final static int COLUMN_FOREGROUND_COLOR = 2; final static int COLUMN_BACKGROUND_COLOR = 4; final static int COLUMN_PRE_SELECTED = 5; final static int COLUMN_HIDDEN = 6; private StructuredViewer _viewer = null; private Map imageCache = new HashMap(11); private boolean _showFullName = false; // If true, will show "full name" protected DefaultColorTreeLabelProvider () { } public DefaultColorTreeLabelProvider (StructuredViewer viewer) { super(); _viewer = viewer; } public DefaultColorTreeLabelProvider (StructuredViewer viewer, boolean showFullName) { super(); _viewer = viewer; _showFullName = showFullName; } /*************************************************************************/ // public void showFullName (boolean showFullName, boolean refresh) // { // if ( _showFullName != showFullName ) { // _showFullName = showFullName; // if (refresh) { // _viewer.refresh(); // } // } // } /** * * @return true if Full Name View */ public boolean switchNameView (boolean refresh) { Trace.trace(); _showFullName = !_showFullName; if (refresh) { _viewer.refresh(); } return _showFullName; } /*************************************************************************/ /* * @see ILabelProvider#getImage(Object) */ public Image getImage(Object element) { String imageFile = null; ImageDescriptor descriptor = null; if (element instanceof TypeNode || element instanceof TypeDescription) { // Object object = ((TypeNode)element).getObject(); if ( element instanceof TypeDescription || ((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_TYPE ) { TypeDescription t; if (element instanceof TypeDescription) { t = (TypeDescription) element; } else { t = (TypeDescription)((TypeNode)element).getObject(); } imageFile = "type.gif"; descriptor = ImageLoader.getInstance().getImageDescriptor(imageFile); } else if ( ((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_LABEL_FEATURES ) { // return PlatformUI.getWorkbench().getSharedImages().getImage( // ISharedImages.IMG_OBJ_FOLDER); } else { // throw unknownElement(element); // Trace.err("unknownElement"); return null; } } else { // throw unknownElement(element); return null; } //obtain the cached image corresponding to the descriptor if (descriptor != null) { Image image = (Image)imageCache.get(descriptor); if (image == null) { image = descriptor.createImage(); if (image != null) { imageCache.put(descriptor, image); } } return image; } else { return null; } } /* * @see ILabelProvider#getText(Object) */ public String getText(Object element) { if (element instanceof TypeNode) { if ( ((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_TYPE ) { if (((TypeNode)element).getObject() != null) { String ioText = ""; if (_showFullName) { return ((TypeDescription)((TypeNode)element).getObject()).getName()+ioText + " [" + ((TypeNode)element).getFsTotal() + "]"; } else { // System.out.println(((TypeDescription)((TypeNode)element).getObject()).getShortName()); return ((TypeDescription)((TypeNode)element).getObject()).getName()+ioText + " [" + ((TypeNode)element).getFsTotal() + "]"; } } else { return ((TypeNode)element).getLabel(); } } else if ( ((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_LABEL_FEATURES ) { return ((TypeNode)element).getLabel(); // new String("features"); } else if ( ((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_FEATURE ) { // return ((TreeFeatureNode)element).getLabel(); // if (_showFullName) { // // System.err.println("[_showFullName]"); // return ((FeatureMetadata)((TypeNode)element).getObject()).getFullName(); // } else { // return ((FeatureMetadata)((TypeNode)element).getObject()).getName(); // } } else { // Trace.err("Unknown element.getObjectType() (= " // + ((TypeNode)element).getObjectType() // + ") for label: " + ((TypeNode)element).getLabel()); return ((TypeNode)element).getLabel(); // "Unknow element.getObjectType()"; } } else if (element instanceof TypeDescription) { return ((TypeDescription)element).getName(); // } else if (element instanceof FeatureMetadata) { // // System.err.println("[0 FeatureMetadata _showFullName]"); // if (_showFullName) { // // System.err.println("[FeatureMetadata _showFullName]"); // return ((FeatureMetadata)element).getFullName(); // } else { // return ((FeatureMetadata)element).getName(); // } } else if (element instanceof String) { return (String) element; } System.out.println("Unknown element: " + element.getClass().getName()); return "Unknow"; } // getText /* (non-Javadoc) * @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.getObject()) */ public Font getFont(Object element) { // TODO Auto-generated method stub return null; } public String getColumnText(Object element, int index) { if (element instanceof TypeNode) { Object obj = ((TypeNode) element).getObject(); if ( obj instanceof TypeStyle ) { if (index == 0) { // Display type's name from node's label return ((TypeNode)element).getLabel(); } else if (index == COLUMN_PRE_SELECTED) { if ( ((TypeStyle) obj).isChecked() ) { return "selected"; } return ""; } else if (index == COLUMN_HIDDEN) { if ( ((TypeStyle) obj).isHidden() ) { return "hidden"; } return ""; } else { return ""; } } else { Trace.trace("Unknown obj: " + obj.getClass().getName()); } // return getText(element); } // Trace.trace("Unknown element: " + element.getClass().getName()); return "???"; } public Image getColumnImage(Object element, int columnIndex) { // TODO Auto-generated method stub return null; } public void dispose() { for (Iterator i = imageCache.values().iterator(); i.hasNext();) { ((Image) i.next()).dispose(); } imageCache.clear(); } protected RuntimeException unknownElement(Object element) { return new RuntimeException("Unknown type of element in tree of type " + element.getClass().getName()); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.getObject()) */ public Color getForeground (Object element) { if ( element instanceof TypeNode ) { int color = -1; if (((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_LABEL_FEATURES) { color = SWT.COLOR_BLUE; } else if (((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_TYPE) { } else if (((TypeNode)element).getObjectType() == IItemTypeConstants.ITEM_TYPE_FEATURE) { } if (color != -1) { return _viewer.getControl().getDisplay().getSystemColor(color); } } return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.getObject()) */ public Color getBackground(Object element) { // System.out.println("getBackground: "); if ( element instanceof TypeNode ) { if ( ((TypeNode) element).getBgColor() != null ) { return (Color) ((TypeNode) element).getBgColor(); } } else { // ((TreeViewer)_viewer).getTree().tes } return null; } public Color getBackground(Object element, int columnIndex) { if ( element instanceof TypeNode ) { Object obj = ((TypeNode) element).getObject(); if ( obj instanceof TypeStyle ) { if (columnIndex == 0 || columnIndex == 4) { return (Color) ((TypeNode) element).getBgColor(); } else if (columnIndex == 2) { if ( obj instanceof TypeStyle ) { TypeStyle typeColor = (TypeStyle) obj; if (typeColor != null) { return (Color) typeColor.fgColor; } // } else if ( obj instanceof ColoredType ) { // return ((ColoredType) obj).getColor().fgColor; } } // } else if ( (obj instanceof TypeColor) || (obj instanceof ColoredType) ) { // if (columnIndex == 0 || columnIndex == 4) { // return (Color) ((TypeNode) element).getBgColor(); // } else if (columnIndex == 2) { // if ( obj instanceof TypeColor ) { // TypeColor typeColor = (TypeColor) obj; // if (typeColor != null) { // return (Color) typeColor.fgColor; // } // } else if ( obj instanceof ColoredType ) { // // Some types may NOT have color // if (((ColoredType) obj).getColor() != null) { // return ((ColoredType) obj).getColor().fgColor; // } // } // } } } return null; } public Color getForeground(Object element, int columnIndex) { if ( element instanceof TypeNode ) { if (columnIndex == 0) { Object obj = ((TypeNode) element).getObject(); if ( obj instanceof TypeStyle ) { return ((TypeStyle) obj).fgColor; } } } return null; } }
apache-2.0
Orange-OpenSource/cf-java-client
cloudfoundry-operations/src/main/java/org/cloudfoundry/operations/applications/_GetApplicationManifestRequest.java
927
/* * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.operations.applications; import org.immutables.value.Value; /** * The request options for the get application manifest operation */ @Value.Immutable abstract class _GetApplicationManifestRequest { /** * The applicaiton name */ abstract String getName(); }
apache-2.0
thisisdhaas/CookEase
WekaForAndroidModelTrainer/src/edu/berkeley/cs160/DeansOfDesign/wekamodeltrainer/AudioFeatures.java
2583
package edu.berkeley.cs160.DeansOfDesign.wekamodeltrainer; import java.util.ArrayList; import java.util.HashMap; import weka.core.Attribute; public class AudioFeatures { public static String BOILING = "0"; public static String MICRO_DONE = "1"; public static String MICRO_EXPL = "2"; public static String NO_EVENT = "3"; public static enum Feature { RMS0, MFCC0, MFCC1, MFCC2, MFCC3, MFCC4, MFCC5, MFCC6, MFCC7, MFCC8, MFCC9, MFCC10, MFCC11, MFCC12, MFCC13, MFCC14, MFCC15, MFCC16, MFCC17, MFCC18, MFCC19, MFCC20, MFCC21, MFCC22, MFCC23, MFCC24, MFCC25, MFCC26, MFCC27, MFCC28, MFCC29, }; public static final HashMap<Feature,String> FeatureNames; static { FeatureNames = new HashMap<Feature, String>(); FeatureNames.put(Feature.RMS0, "Root Mean Square0"); FeatureNames.put(Feature.MFCC0, "MFCC0"); FeatureNames.put(Feature.MFCC1, "MFCC1"); FeatureNames.put(Feature.MFCC2, "MFCC2"); FeatureNames.put(Feature.MFCC3, "MFCC3"); FeatureNames.put(Feature.MFCC4, "MFCC4"); FeatureNames.put(Feature.MFCC5, "MFCC5"); FeatureNames.put(Feature.MFCC6, "MFCC6"); FeatureNames.put(Feature.MFCC7, "MFCC7"); FeatureNames.put(Feature.MFCC8, "MFCC8"); FeatureNames.put(Feature.MFCC9, "MFCC9"); FeatureNames.put(Feature.MFCC10, "MFCC10"); FeatureNames.put(Feature.MFCC11, "MFCC11"); FeatureNames.put(Feature.MFCC12, "MFCC12"); FeatureNames.put(Feature.MFCC13, "MFCC13"); FeatureNames.put(Feature.MFCC14, "MFCC14"); FeatureNames.put(Feature.MFCC15, "MFCC15"); FeatureNames.put(Feature.MFCC16, "MFCC16"); FeatureNames.put(Feature.MFCC17, "MFCC17"); FeatureNames.put(Feature.MFCC18, "MFCC18"); FeatureNames.put(Feature.MFCC19, "MFCC19"); FeatureNames.put(Feature.MFCC20, "MFCC20"); FeatureNames.put(Feature.MFCC21, "MFCC21"); FeatureNames.put(Feature.MFCC22, "MFCC22"); FeatureNames.put(Feature.MFCC23, "MFCC23"); FeatureNames.put(Feature.MFCC24, "MFCC24"); FeatureNames.put(Feature.MFCC25, "MFCC25"); FeatureNames.put(Feature.MFCC26, "MFCC26"); FeatureNames.put(Feature.MFCC27, "MFCC27"); FeatureNames.put(Feature.MFCC28, "MFCC28"); FeatureNames.put(Feature.MFCC29, "MFCC29"); } public static final Feature[] Features = Feature.values(); public static final Attribute ClassFeature; static { ArrayList<String> attrValues = new ArrayList<String>(); attrValues.add(BOILING); attrValues.add(MICRO_DONE); attrValues.add(MICRO_EXPL); attrValues.add(NO_EVENT); ClassFeature = new Attribute("Kitchen Event", attrValues); } }
apache-2.0
koo-taejin/pinpoint
agent-testweb/jdk-http-plugin-testweb/src/main/java/com/pinpointest/plugin/CertService.java
3919
package com.pinpointest.plugin; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import java.io.InputStream; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Objects; @Component public class CertService { private final Logger logger = LogManager.getLogger(this.getClass()); private final Resource keyStorePath; private final String password; private final String keyStoreType; private SSLContext sslContext; public CertService(@Value("${server.ssl.key-store-type}") String keyStoreType, @Value("${server.ssl.key-store}") Resource keyStorePath, @Value("${server.ssl.key-store-password}") String password) { this.keyStoreType = Objects.requireNonNull(keyStoreType, "keyStoreType"); this.keyStorePath = Objects.requireNonNull(keyStorePath, "keyStorePath"); this.password = Objects.requireNonNull(password, "password"); } @PostConstruct public void importCertForLocalCall() throws Exception { KeyStore keyStore = KeyStore.getInstance(keyStoreType); logger.info("KeyStore type:{}", keyStore.getType()); try (InputStream inputStream = keyStorePath.getInputStream()) { keyStore.load(inputStream, password.toCharArray()); } Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); logger.info("KeyStore aliases:{}", alias); Certificate certificate = keyStore.getCertificate(alias); logger.debug("Certificate:{}", certificate); } KeyManagerFactory kmf = newKeyManagerFactory(keyStore); TrustManagerFactory tmf = newTrustManagerFactory(keyStore); logger.info("KeyManagerFactory Algorithm:{} Provider:{}", kmf.getAlgorithm(), kmf.getProvider()); logger.info("TrustManagerFactory Algorithm:{} Provider:{}", tmf.getAlgorithm(), tmf.getProvider()); this.sslContext = newSSLContext(kmf, tmf); } private SSLContext newSSLContext(KeyManagerFactory kmf, TrustManagerFactory tmf) throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); KeyManager[] keyManagers = kmf.getKeyManagers(); TrustManager[] trustManagers = tmf.getTrustManagers(); sslContext.init(keyManagers, trustManagers, new SecureRandom()); return sslContext; } private TrustManagerFactory newTrustManagerFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); return tmf; } private KeyManagerFactory newKeyManagerFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, password.toCharArray()); return kmf; } @Bean public SSLContext getSslContext() { return sslContext; } }
apache-2.0
tonykwok/leonardosketch.amino
src/org/joshy/gfx/test/jogl/AAPolygonTest.java
7591
package org.joshy.gfx.test.jogl; import com.sun.opengl.util.Animator; import javax.media.opengl.*; import javax.media.opengl.awt.GLCanvas; import javax.media.opengl.glu.GLU; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * Created by IntelliJ IDEA. * User: josh * Date: Feb 2, 2010 * Time: 8:06:04 PM * To change this template use File | Settings | File Templates. */ public class AAPolygonTest extends JFrame { final static int WIDTH = 300; final static int HEIGHT = 300; Animator animator; public AAPolygonTest () { super ("JOGLDemo #3"); addWindowListener (new WindowAdapter() { public void windowClosing (WindowEvent we) { new Thread () { public void run () { animator.stop (); System.exit (0); } }.start (); } }); GLCapabilities caps = new GLCapabilities (null); caps.setSampleBuffers(true); caps.setNumSamples(4); System.out.println("caps = " + caps); caps.setAlphaBits (8); SceneRenderer sr = new SceneRenderer (caps); sr.setPreferredSize (new Dimension(WIDTH, HEIGHT)); getContentPane ().add (sr); pack (); setVisible (true); animator = new Animator (sr); // animator.setRunAsFastAsPossible (true); animator.start (); } public static void main (String [] args) { Runnable r = new Runnable () { public void run () { new AAPolygonTest(); } }; EventQueue.invokeLater (r); } } class SceneRenderer extends GLCanvas implements GLEventListener { // The constants below identify the number of units between the viewpoint // and the near and far clipping planes. private final static double NEAR = 0.5; // Z values < NEAR are clipped private final static double FAR = 4.0; // Z values > FAR are clipped private GLU glu = new GLU (); // Degrees to rotate. private float rotAngle; SceneRenderer (GLCapabilities caps) { super (caps); addGLEventListener (this); } public void init (GLAutoDrawable drawable) { GL2 gl = drawable.getGL ().getGL2(); int buf[] = new int[1]; int sbuf[] = new int[1]; gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glGetIntegerv(GL.GL_SAMPLE_BUFFERS, buf, 0); System.out.println("number of sample buffers is " + buf[0]); gl.glGetIntegerv(GL.GL_SAMPLES, sbuf, 0); System.out.println("number of samples is " + sbuf[0]); // Enable polygon antialiasing. gl.glEnable (GL.GL_BLEND); gl.glBlendFunc (GL.GL_SRC_ALPHA_SATURATE, GL.GL_ONE); gl.glEnable (GL2.GL_POLYGON_SMOOTH); gl.glHint (GL2.GL_POLYGON_SMOOTH_HINT, GL.GL_NICEST); gl.glShadeModel(GL2.GL_SMOOTH); } public void dispose(GLAutoDrawable glAutoDrawable) { } public void display (GLAutoDrawable drawable) { GL2 gl = drawable.getGL ().getGL2(); // Clear the drawing surface to the background color, which defaults to // black. gl.glClear (GL.GL_COLOR_BUFFER_BIT); // Reset the modelview matrix. gl.glLoadIdentity (); // The camera is currently positioned at the (0, 0, 0) origin, its lens // is pointing along the negative Z axis (0, 0, -1) into the screen, and // its orientation up-vector is (0, 1, 0). The following call positions // the camera at (0, 0, 2), points the lens towards the origin, and // keeps the same up-vector. glu.gluLookAt (0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // Rotate the scene rotAngle degrees around the Y axis. gl.glRotatef (rotAngle, 0.0f, 1.0f, 0.0f); // Render the scene, manually performing depth buffer testing by // determining what gets drawn first. //gl.glBlendFunc (GL.GL_SRC_ALPHA_SATURATE, GL.GL_ONE); //gl.glEnable (GL.GL_BLEND); //gl.glShadeModel(GL2.GL_SMOOTH); gl.glEnable(GL.GL_MULTISAMPLE); if (rotAngle < 158.0 || rotAngle > 202.0) { drawTriangle (gl); drawSquare (gl); } else { // Triangle is partially eclipsed by the square. Make sure that // square appears on top. drawSquare (gl); drawTriangle (gl); } // Increment the rotation angle by 0.5 degrees, making sure that it // doesn't exceed 360 degrees. // rotAngle += 0.5f; // rotAngle %= 360.0f; } void drawSquare (GL2 gl) { // Color the square red via flat shading, in contrast to the triangle's // smooth shading. gl.glColor3f (1.0f, 0.0f, 0.0f); gl.glShadeModel (GL2.GL_FLAT); // Render a square one unit behind the origin along the negative Z axis. gl.glBegin (GL2.GL_QUADS); gl.glVertex3d (-0.25, 0.25, -1.0); gl.glVertex3d (-0.25, -0.25, -1.0); gl.glVertex3d (0.25, -0.25, -1.0); gl.glVertex3d (0.25, 0.25, -1.0); gl.glEnd (); } void drawTriangle (GL2 gl) { // Make sure that smooth shading is enabled. This type of shading is // the default the first time display() is invoked. Because flat shading // is enabled later on, it becomes the new default. Without the // following method call, the triangle would also be flat shaded on // subsequent display() method invocations. gl.glShadeModel (GL2.GL_SMOOTH); // Render a triangle one unit in front of the origin along the positive // Z axis. gl.glBegin (GL.GL_TRIANGLES); gl.glColor3f (1.0f, 0.0f, 0.0f); // red at the top gl.glVertex3d (0.0, 1.0, 1.0); gl.glColor3f (0.0f, 1.0f, 0.0f); // green at the lower left gl.glVertex3d (-1.0, -1.0, 1.0); gl.glColor3f (0.0f, 0.0f, 1.0f); // blue at the lower right gl.glVertex3d (1.0, -1.0, 1.0); gl.glEnd (); } public void reshape (GLAutoDrawable drawable, int x, int y, int width, int height) { GL2 gl = drawable.getGL ().getGL2(); // We don't need to invoke gl.glViewport(x, y, width, height) because // this is done automatically by JOGL prior to invoking reshape(). // Because the modelview matrix is currently in effect, we need to // switch to the projection matrix before we can establish a perspective // view. gl.glMatrixMode (GL2.GL_PROJECTION); // Reset the projection matrix. gl.glLoadIdentity (); // Establish a perspective view in which any drawing in front of the // NEAR clipping plane or behind the FAR clipping plane is discarded. // The frustum is assigned the same aspect ratio as the viewport, to // prevent distortion. float aspect = (float) width/(float) height; gl.glFrustum (-aspect, aspect, -1.0f, 1.0f, NEAR, FAR); // From now on, we'll work with the modelview matrix. gl.glMatrixMode (GL2.GL_MODELVIEW); } public void displayChanged (GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { }}
bsd-2-clause
SigmoidFreud/clearnlp
src/main/java/com/googlecode/clearnlp/dependency/factory/DefaultDEPTreeDatum.java
2635
/** * Copyright (c) 2009/09-2012/08, Regents of the University of Colorado * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ /** * Copyright 2012/09-2013/04, University of Massachusetts Amherst * Copyright 2013/05-Present, IPSoft Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.clearnlp.dependency.factory; import java.io.Serializable; import java.util.List; /** * @since 2.0.0 * @author Jinho D. Choi ({@code jdchoi77@gmail.com}) */ public class DefaultDEPTreeDatum implements IDEPTreeDatum, Serializable { private static final long serialVersionUID = -5754158957446073494L; List<IDEPNodeDatum> nodeData; @Override public List<IDEPNodeDatum> getDEPNodeData() { return nodeData; } @Override public void setDEPNodeData(List<IDEPNodeDatum> nodeData) { this.nodeData = nodeData; } }
bsd-2-clause
Sethtroll/runelite
runelite-client/src/main/java/net/runelite/client/plugins/chatboxperformance/ChatboxPerformancePlugin.java
4677
/* * Copyright (c) 2018, Woox <https://github.com/wooxsolo> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 net.runelite.client.plugins.chatboxperformance; import javax.inject.Inject; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.ScriptID; import net.runelite.api.events.ScriptCallbackEvent; import net.runelite.api.widgets.WidgetType; import net.runelite.api.widgets.Widget; import net.runelite.api.widgets.WidgetInfo; import net.runelite.api.widgets.WidgetPositionMode; import net.runelite.api.widgets.WidgetSizeMode; import net.runelite.client.callback.ClientThread; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; @PluginDescriptor( name = "Chatbox performance", hidden = true ) public class ChatboxPerformancePlugin extends Plugin { @Inject private Client client; @Inject private ClientThread clientThread; @Override public void startUp() { if (client.getGameState() == GameState.LOGGED_IN) { clientThread.invokeLater(() -> client.runScript(ScriptID.MESSAGE_LAYER_CLOSE, 0, 0)); } } @Override public void shutDown() { if (client.getGameState() == GameState.LOGGED_IN) { clientThread.invokeLater(() -> client.runScript(ScriptID.MESSAGE_LAYER_CLOSE, 0, 0)); } } @Subscribe private void onScriptCallbackEvent(ScriptCallbackEvent ev) { if (!"chatboxBackgroundBuilt".equals(ev.getEventName())) { return; } fixDarkBackground(); fixWhiteLines(true); fixWhiteLines(false); } private void fixDarkBackground() { int currOpacity = 256; int prevY = 0; Widget[] children = client.getWidget(WidgetInfo.CHATBOX_TRANSPARENT_BACKGROUND).getDynamicChildren(); Widget prev = null; for (Widget w : children) { if (w.getType() != WidgetType.RECTANGLE) { continue; } if (prev != null) { int relY = w.getRelativeY(); prev.setHeightMode(WidgetSizeMode.ABSOLUTE); prev.setYPositionMode(WidgetPositionMode.ABSOLUTE_TOP); prev.setRelativeY(prevY); prev.setOriginalY(prev.getRelativeY()); prev.setHeight(relY - prevY); prev.setOriginalHeight(prev.getHeight()); prev.setOpacity(currOpacity); } prevY = w.getRelativeY(); currOpacity -= 3; // Rough number, can't get exactly the same as Jagex because of rounding prev = w; } if (prev != null) { prev.setOpacity(currOpacity); } } private void fixWhiteLines(boolean upperLine) { int currOpacity = 256; int prevWidth = 0; Widget[] children = client.getWidget(WidgetInfo.CHATBOX_TRANSPARENT_LINES).getDynamicChildren(); Widget prev = null; for (Widget w : children) { if (w.getType() != WidgetType.RECTANGLE) { continue; } if ((w.getRelativeY() == 0 && !upperLine) || (w.getRelativeY() != 0 && upperLine)) { continue; } if (prev != null) { int width = w.getWidth(); prev.setWidthMode(WidgetSizeMode.ABSOLUTE); prev.setRelativeX(width); prev.setOriginalX(width); prev.setWidth(prevWidth - width); prev.setOriginalWidth(prev.getWidth()); prev.setOpacity(currOpacity); } prevWidth = w.getWidth(); currOpacity -= upperLine ? 3 : 4; // Rough numbers, can't get exactly the same as Jagex because of rounding prev = w; } if (prev != null) { prev.setOpacity(currOpacity); } } }
bsd-2-clause
ucsd-progsys/ml2
eval/sherrloc/src/sherrloc/constraint/ast/Constructor.java
2573
package sherrloc.constraint.ast; import java.util.ArrayList; import java.util.List; /** * A constructor (e.g., list(1), pair(2)) has a name, an arity and the variance * of parameters */ public class Constructor extends Element { private final int arity; private final boolean contraVariant; /** * @param name Constructor name * @param arity Arity of the constructor * @param contravariant False if all parameters are covariant; true if all parameters are contravariant * @param p Position of the element in source code */ public Constructor(String name, int arity, boolean contravariant, Position p) { super(name, p); this.arity = arity; this.contraVariant = contravariant; } /** * @return Arity of the constructor */ public int getArity () { return arity; } /** * @return False if all parameters are covariant; true if all parameters are * contravariant (all parameters must have the same variance in the * current implementation) */ public boolean isContraVariant() { return contraVariant; } @Override public String toString () { if (name.equals("arrow")) return "->"; if (name.equals("larrow")) return "<-"; else if (name.equals("pair")) return "*"; else return name; } @Override public String toSnippetString () { if (!pos.isEmpty()) return pos.getSnippet(); else return toString(); } @Override public String toDotString () { return toString(); } @Override public List<Variable> getVars () { return new ArrayList<Variable>(); } @Override public boolean hasVars() { return false; } @Override /** * Same constructor used at different positions are treated as different elements to improve the precision of error diagnosis */ public boolean equals(Object o) { if (o instanceof Constructor) { Constructor c = (Constructor)o; return arity==c.arity && this.name.equals(c.name) && this.contraVariant==c.contraVariant && this.pos.equals(c.pos); } return false; } @Override public int hashCode() { return arity * 85751 + name.hashCode()*1913 + pos.hashCode()*3 + (this.contraVariant?1:0); } @Override public Constructor clone ( ) { return new Constructor(name, arity, contraVariant, pos); } @Override public boolean isBottom() { return false; } @Override public boolean isTop() { return false; } @Override public boolean trivialEnd() { return false; } @Override public Element getBaseElement() { return new Constructor(name, arity, contraVariant, Position.EmptyPosition()); } }
bsd-3-clause
ClearTK/cleartk
cleartk-corpus/src/main/java/org/cleartk/corpus/genia/pos/util/GeniaParse.java
3061
/** * Copyright (c) 2007-2008, Regents of the University of Colorado * 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 the University of Colorado at Boulder 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 org.cleartk.corpus.genia.pos.util; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * <br> * Copyright (c) 2007-2008, Regents of the University of Colorado <br> * All rights reserved. */ public class GeniaParse { String medline; String text; String xml; List<GeniaTag> posTags; List<GeniaTag> semTags; List<GeniaSentence> sentences; public GeniaParse() { posTags = new ArrayList<GeniaTag>(); semTags = new ArrayList<GeniaTag>(); sentences = new ArrayList<GeniaSentence>(); } public String getMedline() { return medline; } public void setMedline(String medline) { this.medline = medline; } public List<GeniaTag> getPosTags() { return Collections.unmodifiableList(posTags); } public void addPosTags(List<GeniaTag> pTags) { this.posTags.addAll(pTags); } public List<GeniaTag> getSemTags() { return Collections.unmodifiableList(semTags); } public void addSemTags(List<GeniaTag> sTags) { this.semTags.addAll(sTags); } public String getText() { return text; } public void setText(String text) { this.text = text; } public void addSentence(GeniaSentence sentence) { sentences.add(sentence); } public List<GeniaSentence> getSentences() { return Collections.unmodifiableList(sentences); } public String getXml() { return xml; } public void setXml(String xml) { this.xml = xml; } }
bsd-3-clause
leriomaggio/code-coherence-evaluation-tool
code_comments_coherence/media/jfreechart/0.7.1/jfreechart-071zip/extracted/jfreechart-0.7.1/source/com/jrefinery/chart/CategoryItemRenderer.java
2676
/* ======================================= * JFreeChart : a Java Chart Class Library * ======================================= * * Project Info: http://www.jrefinery.com/jfreechart; * Project Lead: David Gilbert (david.gilbert@jrefinery.com); * * (C) Copyright 2000-2002, by Simba Management Limited and Contributors. * * This library is free software; you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Foundation; * either version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this * library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. * * ------------------------- * CategoryItemRenderer.java * ------------------------- * * (C) Copyright 2001, 2002, by Simba Management Limited and Contributors. * * Original Author: David Gilbert (for Simba Management Limited); * Contributor(s): Mark Watson (www.markwatson.com); * * $Id: HorizontalCategoryItemRenderer.java,v 1.2 2001/11/16 19:48:47 mungady Exp $ * * Changes * ------- * 23-Oct-2001 : Initial implementation (DG); * 16-Jan-2002 : Renamed HorizontalCategoryItemRenderer.java --> CategoryItemRenderer.java (DG); * */ package com.jrefinery.chart; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import com.jrefinery.data.CategoryDataset; /** * Defines the interface for a category item renderer. */ public interface CategoryItemRenderer { /** * Draw a single data item. * @param g2 The graphics device. * @param plotArea The data plot area. * @param plot The plot. * @param axis The range axis. * @param data The data. * @param series The series number (zero-based index). * @param category The category. * @param categoryIndex The category number (zero-based index). * @param previousCategory The previous category (will be null when the first category is * drawn). */ public void drawCategoryItem(Graphics2D g2, Rectangle2D plotArea, CategoryPlot plot, ValueAxis axis, CategoryDataset data, int series, Object category, int categoryIndex, Object previousCategory); }
bsd-3-clause
Qihoo360/poseidon
builder/index/src/main/java/InvertedIndex/LogParser.java
2294
package InvertedIndex; import java.io.IOException; import java.nio.charset.Charset; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import util.MurmurHash3; public abstract class LogParser { public abstract void ParseLine(String line, long docid, int line_offset, Mapper<LongWritable, Text, Text, Text>.Context context); static { System.err.println("LogParser-Encoding: " + Charset.defaultCharset().displayName()); } protected void Write(String token, String type, long docid, int line_offset, Mapper<LongWritable, Text, Text, Text>.Context context) { if (token.isEmpty() || token.compareTo("null") == 0) { return; } byte[] token_buf = token.getBytes(); int token_hash = MurmurHash3.murmurhash3_x86_32(token_buf, 0, token_buf.length, 0); if (token_hash < 0) { token_hash = 0 - token_hash; } int partition_hash = token_hash / 200; String new_key = String.format("%08d", partition_hash); //String line = token + "\t" + type +"\t" + docid +"\t" + line_offset; //StringBuffer ss = new StringBuffer(); //ss.append(token).append("\t").append(type).append("\t").append("1").append("\t").append(docid).append(",").append(line_offset); String ss = token + "\t" + type + "\t" + docid + "," + line_offset + "\t" + 1; try { //context.write(new Text(new_key), new Text(line)); context.write(new Text(new_key), new Text(ss)); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block // e.printStackTrace(); } catch (Exception e) { // 可能会有异常java.io.IOException: Map Task output too many bytes! which shouldn't be more than 21474836480 // 全部输出的话会产生ERROR org.apache.hadoop.mapred.Child: Error in syncLogs: java.io.IOException: Tasklog stderr size 1096750402 exceeded limit 1073741824 //e.printStackTrace(); } //System.err.println(ss); } }
bsd-3-clause
martiner/gooddata-java
gooddata-java-model/src/main/java/com/gooddata/sdk/model/md/dashboard/Kpi.java
6360
/* * Copyright (C) 2004-2019, GoodData(R) Corporation. All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE.txt file in the root directory of this source tree. */ package com.gooddata.sdk.model.md.dashboard; import static com.gooddata.sdk.common.util.Validate.notEmpty; import static com.gooddata.sdk.common.util.Validate.notNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.gooddata.sdk.model.md.AbstractObj; import com.gooddata.sdk.model.md.Meta; import com.gooddata.sdk.model.md.Queryable; import com.gooddata.sdk.model.md.Updatable; import com.gooddata.sdk.model.md.dashboard.filter.FilterReference; import java.io.Serializable; import java.util.Collections; import java.util.List; /** * Represents KPI (key performance indicator) for analytical dashboard. */ @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME) @JsonTypeName("kpi") @JsonIgnoreProperties(ignoreUnknown = true) public class Kpi extends AbstractObj implements Queryable, Updatable { private static final long serialVersionUID = -7747260758488157192L; private static final String NONE_COMPARISON_TYPE = "none"; private final Content content; /** * Creates new KPI for a given metric with some date filter and comparison * @param title title of KPI * @param metricUri URI of the KPI metric * @param comparisonType KPI comparison type (e.g. {@code "lastYear"}) * @param comparisonDirection KPI comparison direction (e.g. {@code "growIsGood"}) * @param ignoreDashboardFilters list of filters which should be ignored for this KPI (can be empty) * @param dateDatasetUri KPI date filter dataset URI (optional) */ public Kpi(final String title, final String metricUri, final String comparisonType, final String comparisonDirection, final List<FilterReference> ignoreDashboardFilters, final String dateDatasetUri) { this(new Meta(title), new Content( notEmpty(metricUri, "metricUri"), notEmpty(comparisonType, "comparisonType"), checkDirection(comparisonType, comparisonDirection), null, dateDatasetUri, notNull(ignoreDashboardFilters, "ignoreDashboardFilters"))); } private static String checkDirection(final String comparisonType, final String comparisonDirection) { if (NONE_COMPARISON_TYPE.equalsIgnoreCase(notEmpty(comparisonType, "comparisonType"))) { return notEmpty(comparisonDirection, "comparisonDirection"); } else { return comparisonDirection; } } @JsonCreator private Kpi(@JsonProperty("meta") final Meta meta, @JsonProperty("content") final Content content) { super(meta); this.content = content; } /** * @return KPI metric URI string */ @JsonIgnore public String getMetricUri() { return getContent().getMetric(); } /** * @return KPI comparison type */ @JsonIgnore public String getComparisonType() { return getContent().getComparisonType(); } /** * @return KPI comparison direction */ @JsonIgnore public String getComparisonDirection() { return getContent().getComparisonDirection(); } /** * @return KPI date filter dataset URI */ @JsonIgnore public String getDateDatasetUri() { final String dateDatasetUri = getContent().getDateDataSet(); return dateDatasetUri != null ? dateDatasetUri : getContent().getDateDimension(); } /** * @return list of filter references (containing URIs) of filters which should be ignored for this KPI */ @JsonIgnore public List<FilterReference> getIgnoreDashboardFilters() { return Collections.unmodifiableList(getContent().getIgnoreDashboardFilters()); } @JsonProperty private Content getContent() { return content; } @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) private static class Content implements Serializable { private final String metric; private final String comparisonType; private final String comparisonDirection; private final String dateDimension; private final String dateDataset; private final List<FilterReference> ignoreDashboardFilters; @JsonCreator private Content( @JsonProperty("metric") final String metric, @JsonProperty("comparisonType") final String comparisonType, @JsonProperty("comparisonDirection") final String comparisonDirection, @JsonProperty("dateDimension") final String dateDimension, @JsonProperty("dateDataSet") final String dateDataset, @JsonProperty("ignoreDashboardFilters") final List<FilterReference> ignoreDashboardFilters) { this.metric = metric; this.comparisonType = comparisonType; this.comparisonDirection = comparisonDirection; this.dateDimension = dateDimension; this.dateDataset = dateDataset; this.ignoreDashboardFilters = ignoreDashboardFilters; } public String getMetric() { return metric; } public String getComparisonType() { return comparisonType; } public String getComparisonDirection() { return comparisonDirection; } /** * @return URI of the date dimension * @deprecated if not null, {@link #getDateDataSet()} should be used instead */ @Deprecated public String getDateDimension() { return dateDimension; } public String getDateDataSet() { return dateDataset; } public List<FilterReference> getIgnoreDashboardFilters() { return ignoreDashboardFilters; } } }
bsd-3-clause
swhgoon/scaled
api/src/main/java/scaled/Fn.java
818
// // Scaled - a scalable editor extensible via JVM languages // http://github.com/scaled/scaled/blob/master/LICENSE package scaled; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Defines an fn binding. An fn binding is a function that is associated with a name and * descriptive documentation, which can be invoked interactively by the user either by being bound * to a key sequence, or directly by name. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Fn { /** A documentary description of the effects of this fn. This will be shown to the user when * they ask to describe the fn, so don't hold back on the details. */ String value (); }
bsd-3-clause
roth1002/infer
infer/models/java/src/com/squareup/okhttp/internal/Util.java
409
package com.squareup.okhttp.internal; import com.facebook.infer.models.InferCloseables; import java.io.Closeable; import java.io.IOException; import java.nio.charset.Charset; public class Util { public static final Charset US_ASCII = Charset.forName("US-ASCII"); public static void closeQuietly(Closeable closeable) throws IOException { InferCloseables.closeQuietly(closeable); } }
bsd-3-clause
NCIP/common-security-module
software/api/src/gov/nih/nci/security/authentication/principal/LastNamePrincipal.java
906
/*L * Copyright Ekagra Software Technologies Ltd. * Copyright SAIC, SAIC-Frederick * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/common-security-module/LICENSE.txt for details. */ package gov.nih.nci.security.authentication.principal; import java.security.Principal; import javax.security.auth.Subject; /** * This class holds the Last Name of the user retrieved. It would be returned as part of the <code>JAAS</code> * {@link Subject} to the calling application * * @author Kunal Modi (Ekagra Software Technologies Ltd.) */ public class LastNamePrincipal extends BasePrincipal { /** * This Constructor accepts the last name value which would be stored in this {@link Principal} * @param name the last name value to be stored */ public LastNamePrincipal(String name) { super(name); // TODO Auto-generated constructor stub } }
bsd-3-clause
NCIP/cadsr-semantic-tools
software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/ui/ApplyException.java
284
package gov.nih.nci.ncicb.cadsr.loader.ui; /** * Thrown by an Applyable Panel if, for some reason, it could not apply. */ public class ApplyException extends Exception { public ApplyException(String msg) { super(msg); } public ApplyException() { super(); } }
bsd-3-clause
weskerhluffy/cacas-server-3.4.7
cas-server-core/src/main/java/org/jasig/cas/authentication/principal/UsernamePasswordCredentialsToPrincipalResolver.java
1454
/* * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license * distributed with this file and available online at * http://www.ja-sig.org/products/cas/overview/license/ */ package org.jasig.cas.authentication.principal; /** * Implementation of CredentialsToPrincipalResolver for Credentials based on * UsernamePasswordCredentials when a SimplePrincipal (username only) is * sufficient. * <p> * Implementation extracts the username from the Credentials provided and * constructs a new SimplePrincipal with the unique id set to the username. * </p> * * @author Scott Battaglia * @version $Revision: 1.2 $ $Date: 2007/01/22 20:35:26 $ * @since 3.0 * @see org.jasig.cas.authentication.principal.SimplePrincipal */ public final class UsernamePasswordCredentialsToPrincipalResolver extends AbstractPersonDirectoryCredentialsToPrincipalResolver { protected String extractPrincipalId(final Credentials credentials) { final UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) credentials; return usernamePasswordCredentials.getUsername(); } /** * Return true if Credentials are UsernamePasswordCredentials, false * otherwise. */ public boolean supports(final Credentials credentials) { return credentials != null && UsernamePasswordCredentials.class.isAssignableFrom(credentials .getClass()); } }
bsd-3-clause
iamedu/dari
util/src/main/java/com/psddev/dari/util/Transformer.java
2163
package com.psddev.dari.util; import java.lang.reflect.Array; import java.util.HashMap; import java.util.Map; /** * Transforms an arbitrary object into another object. * * @deprecated No replacement. */ @Deprecated public class Transformer { private final Map<Class<?>, TransformationFunction<?>> functions = new HashMap<Class<?>, TransformationFunction<?>>(); /** * Returns the function used to transform an instance of the given * {@code fromClass}. */ @SuppressWarnings("unchecked") public <F> TransformationFunction<F> getFunction(Class<F> fromClass) { TransformationFunction<?> function = null; if (fromClass == null) { function = functions.get(null); } else { for (Class<?> assignable : TypeDefinition.getInstance(fromClass).getAssignableClassesAndInterfaces()) { function = functions.get(assignable); if (function != null) { break; } } } return (TransformationFunction<F>) function; } /** * Puts the given {@code function} to be used to transform an instance * of the given {@code fromClass}. */ public <F> void putFunction(Class<F> fromClass, TransformationFunction<F> function) { functions.put(fromClass, function); } /** Transforms the given {@code object} into another object. */ public Object transform(Object object) { Class<?> objectClass = object != null ? object.getClass() : null; if (objectClass != null && objectClass.isArray()) { int length = Array.getLength(object); Object returnArray = Array.newInstance(Object.class, length); for (int i = 0; i < length; ++ i) { Array.set(returnArray, i, transform(Array.get(object, i))); } return returnArray; } else { @SuppressWarnings("unchecked") TransformationFunction<Object> function = (TransformationFunction<Object>) getFunction(objectClass); return function != null ? function.transform(object) : object; } } }
bsd-3-clause
dushmis/Oracle-Cloud
PaaS_SaaS_Accelerator_RESTFulFacade/FusionProxy_SalesLeadsService/src/com/oracle/xmlns/apps/marketing/leadmgmt/leads/leadservice/types/GetSalesLeadResponse.java
1703
package com.oracle.xmlns.apps.marketing.leadmgmt.leads.leadservice.types; 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; import com.oracle.xmlns.oracle.apps.marketing.leadmgmt.leads.leadservice.MklLead; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="result" type="{http://xmlns.oracle.com/oracle/apps/marketing/leadMgmt/leads/leadService/}MklLead"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result" }) @XmlRootElement(name = "getSalesLeadResponse") public class GetSalesLeadResponse { @XmlElement(required = true) protected MklLead result; /** * Gets the value of the result property. * * @return * possible object is * {@link MklLead } * */ public MklLead getResult() { return result; } /** * Sets the value of the result property. * * @param value * allowed object is * {@link MklLead } * */ public void setResult(MklLead value) { this.result = value; } }
bsd-3-clause
GeoscienceAustralia/Geodesy-Web-Services
gws-core/src/test/java/au/gov/ga/geodesy/support/TestResources.java
4296
package au.gov.ga.geodesy.support; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.List; /** * A collection of static methods to access regression test data. */ public class TestResources { private static final PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); /** * Don't instantiate, use the static methods. */ private TestResources() { } /** * Original production SOPAC site logs directory relative to classpath root. */ public static String originalSopacSiteLogsDirectory() { return "/sitelog/sopac/original/"; } /** * Original production SOPAC site logs, with errors, directory relative to classpath root. */ public static String originalBadSopacSiteLogsDirectory() { return "/sitelog/sopac/original/bad/"; } /** * Custom GeodesyML site logs directory relative to classpath root. */ private static String customGeodesyMLSiteLogsDirectory() { return "/sitelog/geodesyml/custom/"; } /** * Custom SOPAC site logs directory relative to classpath root. */ public static String customSopacSiteLogsDirectory() { return "/sitelog/sopac/custom/"; } /** * Given a site id, return an original SOPAC site log test file. */ public static File originalSopacSiteLog(String siteId) throws IOException { return resourceAsFile(originalSopacSiteLogResourceName(siteId)); } /** * Given a site id, return a custom SOPAC site log test file. */ public static File customSopacSiteLog(String siteId) throws IOException { return resourceAsFile(customSiteLogResourceName(siteId)); } /** * Given a site id, return an original SOPAC site log test file reader. */ public static Reader originalSopacSiteLogReader(String siteId) throws IOException { return new FileReader(resourceAsFile(originalSopacSiteLogResourceName(siteId))); } /** * Given a site id, return a custom GeodesyML site log test file reader. File from resources:/sitelog/sopac/ */ public static Reader customGeodesyMLSiteLogReader(String siteId) throws IOException { return new FileReader(resourceAsFile(customGeodesyMLSiteLogResourceName(siteId))); } /** * Return all original SOPAC site log test files. */ public static List<File> originalSopacSiteLogs() throws IOException { return originalSopacSiteLogs("*"); } /** * Given a site id pattern return all matching original SOPAC site log test files. */ public static List<File> originalSopacSiteLogs(String siteIdPattern) throws IOException { Resource[] resources = resourceResolver.getResources("classpath:" + originalSopacSiteLogsDirectory() + siteIdPattern + ".xml"); List<File> files = new ArrayList<>(resources.length); for (Resource r : resources) { files.add(r.getFile()); } return files; } /** * Original production SOPAC site log resource name relative to classpath root. */ private static String originalSopacSiteLogResourceName(String id) { return originalSopacSiteLogsDirectory() + id + ".xml"; } /** * Custom GeodesyML site log resource name relative to classpath root. */ private static String customGeodesyMLSiteLogResourceName(String id) { return customGeodesyMLSiteLogsDirectory() + id + ".xml"; } private static String customSiteLogResourceName(String id) { return customSopacSiteLogsDirectory() + id + ".xml"; } /** * Find a resource relative to classpath root. */ public static File resourceAsFile(String resourceName) throws IOException { Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath:" + resourceName); if (resource == null) { throw new IllegalArgumentException("Resource " + resourceName + " must exist."); } return resource.getFile(); } }
bsd-3-clause
emaze/emaze-dysfunctional
src/test/java/net/emaze/dysfunctional/iterations/InterleavingIteratorTest.java
1953
package net.emaze.dysfunctional.iterations; import net.emaze.dysfunctional.multiplexing.InterposingIterator; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.Assert; import org.junit.Test; /** * * @author rferranti */ public class InterleavingIteratorTest { @Test public void canInterleaveStrings() { final List<String> values = Arrays.asList("1", "2", "3"); final List<String> separators = Arrays.asList("a", "b"); final InterposingIterator<String> iter = new InterposingIterator<String>(values.iterator(), separators.iterator()); final List<String> got = new ArrayList<String>(); while (iter.hasNext()) { got.add(iter.next()); } final List<String> expected = Arrays.asList("1", "a", "2", "b", "3"); Assert.assertEquals(expected, got); } @Test public void canInterleaveSingleElements() { final List<String> values = Arrays.asList("1"); final List<String> separators = Arrays.asList(); final InterposingIterator<String> iter = new InterposingIterator<String>(values.iterator(), separators.iterator()); final List<String> got = new ArrayList<String>(); while (iter.hasNext()) { got.add(iter.next()); } final List<String> expected = Arrays.asList("1"); Assert.assertEquals(expected, got); } @Test public void canInterleaveSingleElementsWithList() { final List<String> values = Arrays.asList("1", "2", "3"); final InterposingIterator<String> iter = new InterposingIterator<String>(values.iterator(), new ConstantIterator<String>("")); final List<String> got = new ArrayList<String>(); while (iter.hasNext()) { got.add(iter.next()); } final List<String> expected = Arrays.asList("1", "", "2", "", "3"); Assert.assertEquals(expected, got); } }
bsd-3-clause
luminousfennell/jgs
DynamicAnalyzer/src/test/java/analyzer/level2/ReturnStmtFail.java
2433
package analyzer.level2; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import tests.testclasses.TestSubClass; import util.exceptions.IFCError; import util.logging.L2Logger; import java.util.logging.Level; import java.util.logging.Logger; public class ReturnStmtFail { Logger logger = L2Logger.getLogger(); @Before public void init() { HandleStmt.init(); } /** * Tests the NSU policy: * hs = LOW, int_res1 = LOW, localPC = HIGH. * * the line "hs.assignReturnLevelToLocal("int_res1") is instrumented to assigns like: * res1 = ExternalClass.returnSometing(): The local variable res1 needs to be upgraded with the * sec-value of ExternalClass.returnSometing(). But before that can happen, we need to check * if NSU policy holds (remeber: we mustn upgrade low-sec vars in high-sec PC environment. * Thus, in assignReturnLevelToLocal, we perform the adequate NSU check (checkLocalPC), and since * we have here: local < PC => IFCError! */ @Test(expected = IFCError.class) public void returnStmtTestFail() { logger.log(Level.INFO, "RETURN TEST STARTED"); HandleStmt hs = new HandleStmt(); hs.initHandleStmtUtils(false, 0); hs.addObjectToObjectMap(this); hs.pushLocalPC(CurrentSecurityDomain.top(), 123); hs.addLocal("int_res1"); // Initialize int_res1 ! hs.setLocal("int_res1", CurrentSecurityDomain.bottom()); @SuppressWarnings("unused") int res1; TestSubClass tsc = new TestSubClass(); res1 = tsc.methodWithConstReturn(); assertEquals(CurrentSecurityDomain.bottom(), hs.getActualReturnLevel()); hs.assignReturnLevelToLocal("int_res1"); // IFexception thrown here hs.popLocalPC(123); hs.close(); logger.log(Level.INFO, "RETURN TEST FINISHED"); } @Test public void returnStmtTestSuccess() { logger.log(Level.INFO, "RETURN TEST STARTED"); HandleStmt hs = new HandleStmt(); hs.initHandleStmtUtils(false, 0); hs.addObjectToObjectMap(this); hs.pushLocalPC(CurrentSecurityDomain.top(), 123); hs.addLocal("int_res1"); @SuppressWarnings("unused") int res1; TestSubClass tsc = new TestSubClass(); res1 = tsc.methodWithConstReturn(); assertEquals(CurrentSecurityDomain.bottom(), hs.getActualReturnLevel()); hs.assignReturnLevelToLocal("int_res1"); hs.popLocalPC(123); hs.close(); logger.log(Level.INFO, "RETURN TEST FINISHED"); } }
bsd-3-clause
axxter99/RSFUtil
test/uk/org/ponder/rsf/test/selection/TestSelection.java
6647
/* * Created on 8 Jan 2008 */ package uk.org.ponder.rsf.test.selection; import java.util.Arrays; import uk.org.ponder.conversion.GeneralLeafParser; import uk.org.ponder.conversion.VectorCapableParser; import uk.org.ponder.rsf.bare.ActionResponse; import uk.org.ponder.rsf.bare.RenderResponse; import uk.org.ponder.rsf.bare.RequestLauncher; import uk.org.ponder.rsf.bare.junit.MultipleRSFTests; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.test.selection.params.CategoryViewParams; import uk.org.ponder.rsf.test.selection.params.MultipleViewParams; import uk.org.ponder.rsf.test.selection.producers.TestMultipleProducer; import uk.org.ponder.rsf.test.selection.producers.TestNullProducer; /** * Test for general operation of EL context, including fieldGetter, IDDefunnelingReshaper, * UISelect edge cases */ public class TestSelection extends MultipleRSFTests { public TestSelection() { contributeRequestConfigLocation("classpath:uk/org/ponder/rsf/test/selection/selection-request-context.xml"); contributeConfigLocation("classpath:uk/org/ponder/rsf/test/selection/selection-application-context.xml"); } private void setCategorySize(RequestLauncher launch, int size) { CategoriesAll all = (CategoriesAll) launch.getRSACBeanLocator().getBeanLocator() .locateBean("&categories-all"); all.setSize(1); } private void testOneSelection(int initsize, Integer initselection, int userindex, boolean nullview) { String viewID = nullview ? TestNullProducer.VIEW_ID : RequestLauncher.TEST_VIEW; RequestLauncher launch1 = getRequestLauncher(); setCategorySize(launch1, initsize); RenderResponse response = launch1.renderView(new CategoryViewParams(viewID, initselection)); UIForm form = (UIForm) response.viewWrapper.queryComponent(new UIForm()); UISelect selection = (UISelect) response.viewWrapper.queryComponent(new UISelect()); String userselection = selection.optionlist.getValue()[userindex]; if (userselection == null) { // we need to fake up this natural operation of the renderer here userselection = GeneralLeafParser.NULL_STRING; } selection.selection.updateValue(userselection); ActionResponse response2 = getRequestLauncher().submitForm(form, null); Recipe recipe = (Recipe) response2.requestContext.locateBean("recipe"); assertActionError(response2, false); if (userselection.equals(GeneralLeafParser.NULL_STRING)) { // if the user made the null selection, the effect will be to fetch the recipe, // but the nested category will remain null assertNotNull(recipe); assertNull(recipe.category); } else { boolean differ = !(initselection == null && userselection == null) && (initselection == null ^ userselection == null) || !userselection.equals(initselection.toString()); if (differ) { assertEquals(recipe.category.id, userselection); assertNotNull(recipe.category.name); } else { assertNull(recipe); } } } private VectorCapableParser vcp; public void onSetUp() throws Exception { super.onSetUp(); vcp = (VectorCapableParser) applicationContext.getBean("vectorCapableParser"); } public void testOneMultipleSelection(int initsize, Integer[] initselection, int[] userindexes, boolean primitive) { RequestLauncher launch1 = getRequestLauncher(); RenderResponse response = launch1.renderView(new MultipleViewParams( TestMultipleProducer.VIEW_ID, initsize, initselection, primitive)); UIForm form = (UIForm) response.viewWrapper.queryComponent(new UIForm()); UISelect selection = (UISelect) response.viewWrapper.queryComponent(new UISelect()); String[] userselection = new String[userindexes.length]; String[] optionlist = selection.optionlist.getValue(); for (int i = 0; i < userselection.length; ++ i) { userselection[i] = optionlist[userindexes[i]]; // matches fixer code in HTMLRenderer if (userselection[i] == null) { userselection[i] = GeneralLeafParser.NULL_STRING; } } selection.selection.updateValue(userselection); ActionResponse response2 = getRequestLauncher().submitForm(form, null); assertActionError(response2, false); IntBean intBean = (IntBean) response2.requestContext.locateBean("intBean"); Integer[] converted = new Integer[userselection.length]; vcp.parse(userselection, converted, null); boolean unchanged = Arrays.equals(initselection, converted); if (primitive) { if (unchanged) { assertNull(intBean.primitive); } else { assertNotNull(intBean.primitive); for (int i = 0; i < userselection.length; ++i) { assertEquals(intBean.primitive[i], Integer.parseInt(userselection[i])); } } } else { if (unchanged) { assertNull(intBean.reference); } else { assertNotNull(intBean.reference); for (int i = 0; i < userselection.length; ++i) { if (userselection[i].equals(GeneralLeafParser.NULL_STRING)) { assertNull(intBean.reference[i]); } else { assertEquals(intBean.reference[i], new Integer(userselection[i])); } } } } } public void testMultiple() { // test primitive list testOneMultipleSelection(3, new Integer[] { new Integer(1) }, new int[] {0, 1}, true); // test empty list with empty selection testOneMultipleSelection(0, new Integer[] {}, new int [] {}, false); // unchanged list with null entry testOneMultipleSelection(3, new Integer[] { new Integer(1) , null}, new int[] {1, 2}, false); // test list with null entry testOneMultipleSelection(3, new Integer[] { new Integer(1) }, new int[] {1, 2} , false); // test unchanged list testOneMultipleSelection(3, new Integer[] { new Integer(1) }, new int[] {1}, false); testOneMultipleSelection(3, new Integer[] { new Integer(1) }, new int[] {0, 1}, false); } public void testSelection() { testOneSelection(3, new Integer(1), 2, true); testOneSelection(1, null, 0, false); testOneSelection(1, new Integer(1), 0, false); testOneSelection(3, null, 0, true); testOneSelection(3, new Integer(1), 0, true); } }
bsd-3-clause
samarjit/mywapama
designer/src/main/java/de/hpi/bpmn2_0/model/activity/resource/package-info.java
339
@javax.xml.bind.annotation.XmlSchema( namespace = "http://www.omg.org/spec/BPMN/20100524/MODEL", xmlns = { @javax.xml.bind.annotation.XmlNs(prefix = "bpmndi", namespaceURI = "http://www.omg.org/spec/BPMN/20100524/DI") }, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package de.hpi.bpmn2_0.model.activity.resource;
mit
hovsepm/azure-sdk-for-java
storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/UsageUnit.java
1599
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.storage.v2018_03_01_preview; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; /** * Defines values for UsageUnit. */ public enum UsageUnit { /** Enum value Count. */ COUNT("Count"), /** Enum value Bytes. */ BYTES("Bytes"), /** Enum value Seconds. */ SECONDS("Seconds"), /** Enum value Percent. */ PERCENT("Percent"), /** Enum value CountsPerSecond. */ COUNTS_PER_SECOND("CountsPerSecond"), /** Enum value BytesPerSecond. */ BYTES_PER_SECOND("BytesPerSecond"); /** The actual serialized value for a UsageUnit instance. */ private String value; UsageUnit(String value) { this.value = value; } /** * Parses a serialized value to a UsageUnit instance. * * @param value the serialized value to parse. * @return the parsed UsageUnit object, or null if unable to parse. */ @JsonCreator public static UsageUnit fromString(String value) { UsageUnit[] items = UsageUnit.values(); for (UsageUnit item : items) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return null; } @JsonValue @Override public String toString() { return this.value; } }
mit
vandersonmaroni/java-design-patterns
TemplateMethod/src/com/ibanheiz/GeradorMensagemXml.java
583
package com.ibanheiz; import java.util.Map; public class GeradorMensagemXml extends GeradorMensagem { @Override protected String gerarConteudo(Map<String, String> pessoa) { StringBuilder builder = new StringBuilder(); builder.append("<pessoa>"); for (String tag : pessoa.keySet()) { builder.append("<" + tag + ">" + pessoa.get(tag) + "</" + tag + ">"); } builder.append("</pessoa>"); return builder.toString(); } @Override protected void exibirCoteudo(String conteudo) { System.out.println("Gerando conteúdo em XML"); System.out.println(conteudo); } }
mit
sauliusg/jabref
src/main/java/org/jabref/cli/CrossrefFetcherEvaluator.java
4362
package org.jabref.cli; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.jabref.gui.Globals; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fetcher.CrossRef; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.preferences.JabRefPreferences; /** * Useful for checking out new algorithm improvements and thresholds. Not used inside the JabRef code itself. */ public class CrossrefFetcherEvaluator { private CrossrefFetcherEvaluator() { } public static void main(String[] args) throws IOException, InterruptedException { Globals.prefs = JabRefPreferences.getInstance(); try (FileReader reader = new FileReader(args[0])) { BibtexParser parser = new BibtexParser(Globals.prefs.getImportFormatPreferences(), Globals.getFileUpdateMonitor()); ParserResult result = parser.parse(reader); BibDatabase db = result.getDatabase(); List<BibEntry> entries = db.getEntries(); AtomicInteger dois = new AtomicInteger(); AtomicInteger doiFound = new AtomicInteger(); AtomicInteger doiNew = new AtomicInteger(); AtomicInteger doiIdentical = new AtomicInteger(); int total = entries.size(); CountDownLatch countDownLatch = new CountDownLatch(total); ExecutorService executorService = Executors.newFixedThreadPool(5); for (BibEntry entry : entries) { executorService.execute(new Runnable() { @Override public void run() { Optional<DOI> origDOI = entry.getField(StandardField.DOI).flatMap(DOI::parse); if (origDOI.isPresent()) { dois.incrementAndGet(); try { Optional<DOI> crossrefDOI = new CrossRef().findIdentifier(entry); if (crossrefDOI.isPresent()) { doiFound.incrementAndGet(); if (origDOI.get().getDOI().equalsIgnoreCase(crossrefDOI.get().getDOI())) { doiIdentical.incrementAndGet(); } else { System.out.println("DOI not identical for : " + entry); } } else { System.out.println("DOI not found for: " + entry); } } catch (FetcherException e) { e.printStackTrace(); } } else { try { Optional<DOI> crossrefDOI = new CrossRef().findIdentifier(entry); if (crossrefDOI.isPresent()) { System.out.println("New DOI found for: " + entry); doiNew.incrementAndGet(); } } catch (FetcherException e) { e.printStackTrace(); } } countDownLatch.countDown(); } }); } countDownLatch.await(); System.out.println("---------------------------------"); System.out.println("Total DB size: " + total); System.out.println("Total DOIs: " + dois); System.out.println("DOIs found: " + doiFound); System.out.println("DOIs identical: " + doiIdentical); System.out.println("New DOIs found: " + doiNew); executorService.shutdown(); } } }
mit
valcol/BattleCraft
src/gameframework/core/DrawableImage.java
707
package gameframework.core; import java.awt.Canvas; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.Toolkit; public class DrawableImage implements Drawable { protected Image image; protected Canvas canvas; public DrawableImage(String filename, Canvas canvas) { this.canvas = canvas; Toolkit toolkit = Toolkit.getDefaultToolkit(); image = toolkit.createImage(filename); MediaTracker tracker = new MediaTracker(canvas); tracker.addImage(image, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { } } public Image getImage() { return image; } public void draw(Graphics g) { g.drawImage(image, 0, 0, canvas); } }
mit
brunobg/jxm
JavaClient/Samples/test/socketTest.java
4016
/** * license (MIT) Copyright Nubisa Inc. 2014 */ import jxm.*; import javax.xml.bind.DatatypeConverter; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.concurrent.atomic.AtomicInteger; public class socketTest { public static int total = 1; public static int port = 8000; public static String ip = "127.0.0.1"; /** * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage:java -jar jxm [numberOfClients] url/ip port"); return; } else total = DatatypeConverter.parseInt(args[0]); if(args.length>1){ ip = args[1]; } if(args.length>2){ port = DatatypeConverter.parseInt(args[2]); } System.out.println("Connecting to target " + ip + ":" + port); drawMenu(); Test test = new Test(); initClient(test); Client client = clients[0]; for (int i = 1; i < total; i++) clients[i].Connect(); if (clients[0].Connect()) { String code = ""; System.out.println("ready!"); while (!code.equalsIgnoreCase("q")) { if (code.length() > 0) { if (code.equals("1")) { callMethod1(); } } System.out.println(":"); code = readMenuCode(); } System.out.println("exiting application.."); exitApp = true; } } static boolean exitApp = false; static String readMenuCode() throws Exception { int n = System.in.read(); return new String(new char[]{(char) n}); } static void drawMenu() { String menus[] = { "1 - Call Server.testCall", "q - Exit" }; for (String m : menus) System.out.println(m); } static void callMethod1() { Test.counter = new AtomicInteger(0); Calendar now = GregorianCalendar.getInstance(); System.out.println("Sending to "+total+" clients"); long tm = now.getTimeInMillis(); Test.timer = tm; for(int q=0;q<20;q++){ for (int i = 0; i < total; i++) { clients[i].Call("chatMessage", "Samples/test" + i + "-" + tm, null); } try{ Thread.sleep(1000); // for local tests 1 instead 1000 }catch(Exception e){ } System.out.println("ANOTHER SET IS ON THE WAY! " + q); } } static Client[] clients; public static AtomicInteger opens; public static void initClient(Test test) { opens = new AtomicInteger(0); clients = new Client[total]; ClientEvents dev = new ClientEvents() { @Override public void OnError(Client c, String Message) { System.out.println("Error received:" + Message); } @Override public void OnConnect(Client c) { int n = opens.incrementAndGet(); System.out.println("Total :" + n); } @Override public void OnClose(Client c) { int n = opens.decrementAndGet(); System.out.println("Total :" + n); } @Override public void OnEventLog(Client c, String log, LogLevel level) { if(level == LogLevel.Critical) System.out.println("WARNING:" + c.GetClientId() + ":" + log); } @Override public void OnSubscription(Client c, Boolean subscribe, String group) { } }; for (int i = 0; i < total; i++) { clients[i] = new Client(new Test(), "chat", "NUBISA-STANDARD-KEY-CHANGE-THIS" , ip, port, false, true); clients[i].Events = dev; } } }
mit
wang27jing/coding-android
app/src/main/java/net/coding/program/third/EmojiFilter.java
2819
package net.coding.program.third; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by chaochen on 14-9-25. */ public class EmojiFilter { /** * 检测是否有emoji字符 * * @param source * @return 一旦含有就抛出 */ final static Pattern mPattern = Pattern.compile("[^@\\s<>::,,。…~!!°??'‘\"()\\u0800-\\u9fa5^\\u0020-\\u007e\\s\\t\\n\\r\\n\\u3002\\uff1b\\\\uff0c\\\\uff1a\\\\u201c\\\\u201d\\\\uff08\\\\uff09\\\\u3001\\\\uff1f\\\\u300a\\\\u300b\\\\uff01\\\\u2019\\\\u2018\\\\u2026\\u2014\\uff5e\\uffe5]+"); public static boolean containsEmoji(String source) { Matcher matcher = mPattern.matcher(source); return matcher.find(); } // if (source.isEmpty()) { // return false; // } // // int len = source.length(); // // for (int i = 0; i < len; i++) { // char codePoint = source.charAt(i); // // if (isEmojiCharacter(codePoint)) { // //do nothing,判断到了这里表明,确认有表情字符 // return true; // } // } // // return false; // } // private static boolean isEmojiCharacter(char codePoint) { // return (codePoint == 0x0) || // (codePoint == 0x9) || // (codePoint == 0xA) || // (codePoint == 0xD) || // ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || // ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || // ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)); // // // } // // /** // * 过滤emoji 或者 其他非文字类型的字符 // * @param source // * @return // */ // public static String filterEmoji(String source) { // // if (!containsEmoji(source)) { // return source;//如果不包含,直接返回 // } // //到这里铁定包含 // StringBuilder buf = null; // // int len = source.length(); // // for (int i = 0; i < len; i++) { // char codePoint = source.charAt(i); // // if (isEmojiCharacter(codePoint)) { // if (buf == null) { // buf = new StringBuilder(source.length()); // } // // buf.append(codePoint); // } else { // } // } // // if (buf == null) { // return source;//如果没有找到 emoji表情,则返回源字符串 // } else { // if (buf.length() == len) {//这里的意义在于尽可能少的toString,因为会重新生成字符串 // buf = null; // return source; // } else { // return buf.toString(); // } // } // // } }
mit
wolfired/flex_ant_project_template
ext/ant_flex/src/flex/ant/CompcTask.java
19107
//////////////////////////////////////////////////////////////////////////////// // // ADOBE SYSTEMS INCORPORATED // Copyright 2006-2007 Adobe Systems Incorporated // All Rights Reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// package flex.ant; import flex.ant.config.ConfigBoolean; import flex.ant.config.ConfigInt; import flex.ant.config.ConfigString; import flex.ant.config.ConfigVariable; import flex.ant.config.NestedAttributeElement; import flex.ant.config.OptionSource; import flex.ant.config.OptionSpec; import flex.ant.config.RepeatableConfigString; import flex.ant.types.DefaultScriptLimits; import flex.ant.types.DefaultSize; import flex.ant.types.FlexFileSet; import flex.ant.types.FlexSwcFileSet; import flex.ant.types.Fonts; import flex.ant.types.Metadata; import flex.ant.types.RuntimeSharedLibraryPath; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DynamicConfigurator; import java.util.ArrayList; import java.util.Iterator; import java.io.File; /** * Implements the &lt;compc&gt; Ant task. For example: * <p> * <pre> * &lt;compc fork="true" * output="${FLEX_HOME}/frameworks/libs/sparkskins.swc" * resource-bundle-list="${basedir}/bundles.properties"&gt; * &lt;target-player&gt;10&lt;/target-player&gt; * &lt;jvmarg line="${compc.jvm.args}"/&gt; * &lt;include-classes&gt;SparkSkinsClasses&lt;/include-classes&gt; * &lt;source-path path-element="${basedir}/src"/&gt; * &lt;library-path/&gt; * &lt;external-library-path dir="${FLEX_HOME}/frameworks/libs"&gt; * &lt;include name="player/${local.playerglobal.version}/playerglobal.swc"/&gt; * &lt;include name="framework.swc"/&gt; * &lt;include name="spark.swc" /&gt; * &lt;include name="textLayout.swc"/&gt; * &lt;/external-library-path&gt; * &lt;locale/&gt; * &lt;accessible&gt;true&lt;/accessible&gt; * &lt;/compc&gt; * </pre> * <p> * All the simple compc configuration parameters are supported as tag * attributes. Complex configuration options, like * -compiler.namespaces.namespace, are implemented as child tags. For * example: * <p> * </code> * &lt;namespace uri="http://www.adobe.com/2006/mxml" manifest="${basedir}/manifest.xml"/&gt; * </code> */ public final class CompcTask extends FlexTask implements DynamicConfigurator { /*=======================================================================* * Static variables and initializer * *=======================================================================*/ private static OptionSpec nsSpec = new OptionSpec("compiler", "namespaces.namespace", "namespace"); private static OptionSpec liSpec = new OptionSpec("licenses", "license"); private static OptionSpec exSpec = new OptionSpec("externs"); private static OptionSpec inSpec = new OptionSpec("includes"); private static OptionSpec rsSpec = new OptionSpec(null, "runtime-shared-libraries", "rsl"); private static OptionSpec frSpec = new OptionSpec("frames", "frame"); private static OptionSpec ccSpec = new OptionSpec("compiler", "define"); private static OptionSpec elSpec = new OptionSpec("compiler", "external-library-path", "el"); private static OptionSpec ilSpec = new OptionSpec("compiler", "include-libraries"); private static OptionSpec lpSpec = new OptionSpec("compiler", "library-path", "l"); private static OptionSpec spSpec = new OptionSpec("compiler", "source-path", "sp"); private static OptionSpec thSpec = new OptionSpec("compiler", "theme"); private static OptionSpec kmSpec = new OptionSpec("compiler", "keep-as3-metadata"); private static OptionSpec lcSpec = new OptionSpec("load-config"); private static OptionSpec icSpec = new OptionSpec(null, "include-classes", "ic"); private static OptionSpec ifSpec = new OptionSpec(null, "include-file", "if"); private static OptionSpec insSpec = new OptionSpec(null, "include-namespaces", "in"); private static OptionSpec irSpec = new OptionSpec(null, "include-resource-bundles", "ir"); private static OptionSpec isSpec = new OptionSpec(null, "include-sources", "is"); /*=======================================================================* * *=======================================================================*/ private final ArrayList<OptionSource> nestedFileSets; private final ConfigString outString; private final RepeatableConfigString icStrings; private Metadata metadata; private Fonts fonts; private DefaultScriptLimits dLimits; private DefaultSize dSize; /** * */ public CompcTask() { super("compc", "flex2.tools.Compc", "compc.jar", new ConfigVariable[] { //Basic Booleans new ConfigBoolean(new OptionSpec("benchmark")), new ConfigBoolean(new OptionSpec("compiler", "accessible")), new ConfigBoolean(new OptionSpec("compiler", "debug")), new ConfigBoolean(new OptionSpec("compiler", "incremental")), new ConfigBoolean(new OptionSpec("compiler", "mobile")), new ConfigBoolean(new OptionSpec("compiler", "optimize")), new ConfigBoolean(new OptionSpec("compiler", "report-invalid-styles-as-warnings")), new ConfigBoolean(new OptionSpec("compiler", "report-missing-required-skin-parts-as-warnings")), new ConfigBoolean(new OptionSpec("compiler", "show-actionscript-warnings")), new ConfigBoolean(new OptionSpec("compiler", "show-binding-warnings")), new ConfigBoolean(new OptionSpec("compiler", "show-deprecation-warnings")), new ConfigBoolean(new OptionSpec("compiler", "show-invalid-css-property-warnings")), new ConfigBoolean(new OptionSpec("compiler", "strict")), new ConfigBoolean(new OptionSpec("compiler", "use-resource-bundle-metadata")), new ConfigBoolean(new OptionSpec("directory")), new ConfigBoolean(new OptionSpec("use-network")), new ConfigBoolean(new OptionSpec("warnings")), //Advanced Booleans new ConfigBoolean(new OptionSpec("compiler", "allow-source-path-overlap")), new ConfigBoolean(new OptionSpec("compiler", "as3")), new ConfigBoolean(new OptionSpec("compiler", "doc")), new ConfigBoolean(new OptionSpec("compiler", "es")), new ConfigBoolean(new OptionSpec("compiler", "generate-abstract-syntax-tree")), new ConfigBoolean(new OptionSpec("compiler", "headless-server")), new ConfigBoolean(new OptionSpec("compiler", "isolate-styles")), new ConfigBoolean(new OptionSpec("compiler", "keep-all-type-selectors")), new ConfigBoolean(new OptionSpec("compiler", "keep-generated-actionscript", "keep")), new ConfigBoolean(new OptionSpec("compiler", "verbose-stacktraces")), new ConfigBoolean(new OptionSpec("compiler", "warn-array-tostring-changes")), new ConfigBoolean(new OptionSpec("compiler", "warn-assignment-within-conditional")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-array-cast")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-bool-assignment")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-date-cast")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-es3-type-method")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-es3-type-prop")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-nan-comparison")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-null-assignment")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-null-comparison")), new ConfigBoolean(new OptionSpec("compiler", "warn-bad-undefined-comparison")), new ConfigBoolean(new OptionSpec("compiler", "warn-boolean-constructor-with-no-args")), new ConfigBoolean(new OptionSpec("compiler", "warn-changes-in-resolve")), new ConfigBoolean(new OptionSpec("compiler", "warn-class-is-sealed")), new ConfigBoolean(new OptionSpec("compiler", "warn-const-not-initialized")), new ConfigBoolean(new OptionSpec("compiler", "warn-constructor-returns-value")), new ConfigBoolean(new OptionSpec("compiler", "warn-deprecated-event-handler-error")), new ConfigBoolean(new OptionSpec("compiler", "warn-deprecated-function-error")), new ConfigBoolean(new OptionSpec("compiler", "warn-deprecated-property-error")), new ConfigBoolean(new OptionSpec("compiler", "warn-duplicate-argument-names")), new ConfigBoolean(new OptionSpec("compiler", "warn-duplicate-variable-def")), new ConfigBoolean(new OptionSpec("compiler", "warn-for-var-in-changes")), new ConfigBoolean(new OptionSpec("compiler", "warn-import-hides-classes")), new ConfigBoolean(new OptionSpec("compiler", "warn-instance-of-changes")), new ConfigBoolean(new OptionSpec("compiler", "warn-internal-error")), new ConfigBoolean(new OptionSpec("compiler", "warn-level-not-supported")), new ConfigBoolean(new OptionSpec("compiler", "warn-missing-namespace-decl")), new ConfigBoolean(new OptionSpec("compiler", "warn-negative-uint-literal")), new ConfigBoolean(new OptionSpec("compiler", "warn-no-constructor")), new ConfigBoolean(new OptionSpec("compiler", "warn-no-explicit-super-call-in-constructor")), new ConfigBoolean(new OptionSpec("compiler", "warn-no-type-decl")), new ConfigBoolean(new OptionSpec("compiler", "warn-number-from-string-changes")), new ConfigBoolean(new OptionSpec("compiler", "warn-scoping-change-in-this")), new ConfigBoolean(new OptionSpec("compiler", "warn-slow-text-field-addition")), new ConfigBoolean(new OptionSpec("compiler", "warn-unlikely-function-value")), new ConfigBoolean(new OptionSpec("compiler", "warn-xml-class-has-changed")), new ConfigBoolean(new OptionSpec("compiler", "generate-abstract-syntax-tree")), new ConfigBoolean(new OptionSpec("include-inheritance-dependencies-only")), new ConfigBoolean(new OptionSpec("include-lookup-only")), new ConfigBoolean(new OptionSpec("compute-digest")), new ConfigBoolean(new OptionSpec(null, "static-link-runtime-shared-libraries", "static-rsls")), new ConfigBoolean(new OptionSpec("use-direct-blit")), new ConfigBoolean(new OptionSpec("use-gpu")), //String Variables new ConfigString(new OptionSpec("compiler", "actionscript-file-encoding")), new ConfigString(new OptionSpec("compiler", "context-root")), new ConfigString(new OptionSpec("compiler", "defaults-css-url")), new ConfigString(new OptionSpec("compiler", "locale")), new ConfigString(new OptionSpec("compiler", "services")), new ConfigString(new OptionSpec("debug-password")), new ConfigString(new OptionSpec("dump-config")), new ConfigString(new OptionSpec("link-report")), new ConfigString(new OptionSpec("load-externs")), new ConfigString(new OptionSpec("raw-metadata")), new ConfigString(new OptionSpec("resource-bundle-list")), new ConfigString(new OptionSpec("size-report")), new ConfigString(new OptionSpec("target-player")), new ConfigString(new OptionSpec("compiler", "minimum-supported-version", "msv")), new ConfigString(new OptionSpec("compiler", "enable-swc-version-filtering", "esvf")), new ConfigString(new OptionSpec("tools-locale")), //Int Variables new ConfigInt(new OptionSpec("default-background-color")), new ConfigInt(new OptionSpec("default-frame-rate")), new ConfigInt(new OptionSpec("swf-version")) }); nestedAttribs = new ArrayList<OptionSource>(); nestedFileSets = new ArrayList<OptionSource>(); outString = new ConfigString(new OptionSpec(null, "output", "o")); icStrings = new RepeatableConfigString(new OptionSpec(null, "include-classes", "ic")); } /*=======================================================================* * Required Attributes * *=======================================================================*/ /* Necessary to override inherited setOutput method since ant gives * priority to parameter types more specific than String. */ public void setOutput(File o) { setDynamicAttribute("output", o.getAbsolutePath()); } public void setDynamicAttribute(String name, String value) { /* Handle required attributes and then delegate to super */ if (outString.matches(name)) { outString.set(value); } else if (icStrings.matches(name)) icStrings.addAll(value.split(" ")); else super.setDynamicAttribute(name, value); } /*=======================================================================* * Child Elements * *=======================================================================*/ public Metadata createMetadata() { if (metadata == null) return metadata = new Metadata(); else throw new BuildException("Only one nested <metadata> element is allowed in an <compc> task."); } public Fonts createFonts() { if (fonts == null) return fonts = new Fonts(this); else throw new BuildException("Only one nested <fonts> element is allowed in an <compc> task."); } public NestedAttributeElement createNamespace() { return createElem(new String[] { "uri", "manifest" }, nsSpec); } public NestedAttributeElement createLicense() { return createElem(new String[] { "product", "serial-number" }, liSpec); } public NestedAttributeElement createExterns() { return createElem("symbol", exSpec); } public NestedAttributeElement createIncludes() { return createElem("symbol", inSpec); } public NestedAttributeElement createFrame() { return createElem(new String[] { "label", "classname" }, frSpec); } public Object createDynamicElement(String name) { if (kmSpec.matches(name)) { return createElem("name", kmSpec); } else if (rsSpec.matches(name)) { return createElem("url", rsSpec); } else if (rslpSpec.matches(name)) { RuntimeSharedLibraryPath runtimeSharedLibraryPath = new RuntimeSharedLibraryPath(); nestedAttribs.add(runtimeSharedLibraryPath); return runtimeSharedLibraryPath; } else if (ccSpec.matches(name)) { return createElem(new String[] { "name", "value" }, ccSpec); } else if (lcSpec.matches(name)) { return createElemAllowAppend(new String[] {"filename"} , lcSpec); } else if (spSpec.matches(name)) { return createElem("path-element", spSpec); } else if (DefaultScriptLimits.spec.matches(name)) { if (dLimits == null) return dLimits = new DefaultScriptLimits(); else throw new BuildException("Only one nested <default-script-limits> element is allowed in an <compc> task."); } else if (DefaultSize.spec.matches(name)) { if (dSize == null) return dSize = new DefaultSize(); else throw new BuildException("Only one nested <default-size> element is allowed in an <compc> task."); } else if (elSpec.matches(name)) { FlexFileSet fs = new FlexSwcFileSet(elSpec, true); nestedFileSets.add(fs); return fs; } else if (ilSpec.matches(name)) { FlexFileSet fs = new FlexSwcFileSet(ilSpec, true); nestedFileSets.add(fs); return fs; } else if (lpSpec.matches(name)) { FlexFileSet fs = new FlexSwcFileSet(lpSpec, true); nestedFileSets.add(fs); return fs; } else if (thSpec.matches(name)) { FlexFileSet fs = new FlexFileSet(thSpec); nestedFileSets.add(fs); return fs; } else if (exSpec.matches(name)) { return createExterns(); } /* The following are unique to compc */ else if (icSpec.matches(name)) { return createElem("class", icSpec); } else if (ifSpec.matches(name)) { return createElem(new String[] { "name", "path" }, ifSpec); } else if (insSpec.matches(name)) { return createElemAllowAppend(new String[] { "uri" }, insSpec); } else if (isSpec.matches(name)) { FlexFileSet fs = new FlexFileSet(isSpec, true); nestedFileSets.add(fs); return fs; } else if (irSpec.matches(name)) { return createElem("bundle", irSpec); } return super.createDynamicElement(name); } /*=======================================================================* * Execute and Related Functions * *=======================================================================*/ protected void prepareCommandline() throws BuildException { for (int i = 0; i < variables.length; i++) { variables[i].addToCommandline(cmdl); } if (metadata != null) metadata.addToCommandline(cmdl); if(fonts != null) fonts.addToCommandline(cmdl); if (dLimits != null) dLimits.addToCommandline(cmdl); if (dSize != null) dSize.addToCommandline(cmdl); icStrings.addToCommandline(cmdl); Iterator<OptionSource> it = nestedAttribs.iterator(); while (it.hasNext()) it.next().addToCommandline(cmdl); it = nestedFileSets.iterator(); while (it.hasNext()) it.next().addToCommandline(cmdl); if (outString.isSet()) outString.addToCommandline(cmdl); else throw new BuildException(outString.getSpec().getFullName() + " attribute must be set!", getLocation()); } } //End of CompcTask
mit
VasuDroid/MaterialTabsAdavanced
MaterialTabsModule/src/main/java/it/neokree/materialtabs/MaterialTabHost.java
20768
package it.neokree.materialtabs; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Point; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RelativeLayout; import java.util.LinkedList; import java.util.List; /** * A Toolbar that contains multiple tabs * * @author neokree */ @SuppressLint("InflateParams") public class MaterialTabHost extends RelativeLayout implements View.OnClickListener, MlistenrInternal { public static final int BESTFIT = 1, ITEMBASE = 2; private int primaryColor; private int accentColor; private int textColor; private int iconColor; private List<MaterialTab> tabs; private boolean hasIcons; private boolean isTablet; private float density; private boolean scrollable; private int fixtablimit; private HorizontalScrollView scrollView; private LinearLayout layout; private ImageButton left; private ImageButton right; private int custom_tab_layout_id; private static int tabSelected; private int borderwidth, borderColor; private boolean borderEdge = false, outterBorderEnable = false; private int fittype = ITEMBASE; public MaterialTabHost(Context context) { this(context, null); } public MaterialTabHost(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MaterialTabHost(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); scrollView = new HorizontalScrollView(context); scrollView.setOverScrollMode(HorizontalScrollView.OVER_SCROLL_NEVER); scrollView.setHorizontalScrollBarEnabled(false); layout = new LinearLayout(context); scrollView.addView(layout); // get attributes if (attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MaterialTabHost, 0, 0); try { // custom attributes hasIcons = a.getBoolean(R.styleable.MaterialTabHost_advtabs_hasIcons, false); primaryColor = a.getColor(R.styleable.MaterialTabHost_advtabs_materialTabsPrimaryColor, Color.parseColor("#009688")); accentColor = a.getColor(R.styleable.MaterialTabHost_advtabs_accentColor, Color.parseColor("#00b0ff")); iconColor = a.getColor(R.styleable.MaterialTabHost_advtabs_iconColor, Color.WHITE); textColor = a.getColor(R.styleable.MaterialTabHost_advtabs_textColor, Color.WHITE); int defaultFixTabsLimit = getResources().getInteger(R.integer.defaultNonFixTabsCountStart); fixtablimit = a.getColor(R.styleable.MaterialTabHost_advtabs_nonFixTabsCountStart, defaultFixTabsLimit); custom_tab_layout_id = a.getResourceId(R.styleable.MaterialTabHost_advtabs_customTabLayout, -1); } finally { a.recycle(); } } else { hasIcons = false; } this.isInEditMode(); scrollable = false; isTablet = this.getResources().getBoolean(R.bool.isTablet); density = this.getResources().getDisplayMetrics().density; // setOverScrollMode(SCROLL_AXIS_NONE); tabSelected = 0; // initialize tabs list tabs = new LinkedList<MaterialTab>(); // set background color super.setBackgroundColor(primaryColor); } /** * this will only work if you have setup the layout attribute in the xml component * please also check if you have put layout reference id in the xml @customTabLayout * * @param label_text the label of the tab in string * @return Return in material tab object */ public MaterialTab createCustomTextTab(String label_text) { final MaterialTab mattab = new MaterialTab(this.getContext(), new tabBuilder(tabBuilder.layout.TAB_CUSTOM_TEXT) .with(getContext()) .setLayout(custom_tab_layout_id) .initInstance()); mattab.setText(label_text); return mattab; } /** * Programmatically select the layout id and have it reference in the runtime * * @param custom_tab_layout_id the layout resource id of the tab item for custom use * @param label_text the label of the tab in string * @param withBubble the bool to show whether it has a bubble like presentation * @return Return in material tab object */ public MaterialTab createCustomTextTab(int custom_tab_layout_id, String label_text, boolean withBubble) { final MaterialTab mattab = new MaterialTab(this.getContext(), new tabBuilder(withBubble ? tabBuilder.layout.TAB_CUSTOM_TEXT : tabBuilder.layout.TAB_CUSTOM_NO_BUBBLE) .with(getContext()) .setLayout(custom_tab_layout_id) .initInstance()); mattab.setText(label_text); return mattab; } /** * initialize the interactive tab during the run time * * @param label_text the label of the tab in string * @return Return in material tab object */ public MaterialTab createInteractiveTab(String label_text) { final MaterialTab mattab = new MaterialTab(this.getContext(), new tabBuilder(tabBuilder.layout.TAB_MATERIAL) .with(getContext()) .initInstance()); mattab.setText(label_text); return mattab; } /** * just a classic material tab for * * @param label_text the label of the tab in string * @return Return in material tab object */ public MaterialTab createInteractiveTab(CharSequence label_text) { final MaterialTab mattab = new MaterialTab(this.getContext(), new tabBuilder(tabBuilder.layout.TAB_MATERIAL) .with(getContext()) .initInstance()); mattab.setText(label_text); return mattab; } /** * every thing with the default design * * @param label_text the label of the tab in string * @return Return in material tab object */ public MaterialTab createTabText(String label_text) { final MaterialTab mattab = new MaterialTab(this.getContext(), new tabBuilder(tabBuilder.layout.TAB_CLASSIC).with(getContext()).initInstance()); mattab.setText(label_text); return mattab; } public MaterialTab createTab(tabBuilder n) { return new MaterialTab(this.getContext(), n); } /** * added by Hesk for dynamically setting the tab sizes. * * @param n the set limit of the tab in length count */ public void setFixTabLimit(int n) { fixtablimit = n; scrollable = false; if (tabs.size() > n && !hasIcons) { scrollable = true; } if (tabs.size() > 6 && hasIcons) { scrollable = true; } notifyDataSetChanged(); } public void setBorder(int borderWidth, int color) { borderEdge = true; borderwidth = borderWidth; borderColor = color; } public void setMeasurementType(int n) { fittype = n; } @SuppressLint("ResourceAsColor") public void setBorderReferenceColor(int borderWidth, int ResId) { borderEdge = true; borderwidth = borderWidth; borderColor = layout.getContext().getResources().getColor(ResId); } /** * @param color the resource id for color */ @SuppressLint("ResourceAsColor") public void setPrimaryColor(int color) { this.primaryColor = color; this.setBackgroundColor(primaryColor); for (MaterialTab tab : tabs) { tab.setPrimaryColor(color); } } /** * the custom background * * @param resId the resource id of the drawable */ public void setCustomBackground(int resId) { super.setBackground(getContext().getResources().getDrawable(resId)); } /** * @param color the resource id for color */ @SuppressLint("ResourceAsColor") public void setAccentColor(int color) { this.accentColor = color; for (MaterialTab tab : tabs) { tab.setAccentColor(color); } } @SuppressLint("ResourceAsColor") public void setTextColor(int color) { this.textColor = color; for (MaterialTab tab : tabs) { tab.setTextColor(color); } } @SuppressLint("ResourceAsColor") public void setIconColor(int color) { this.iconColor = color; for (MaterialTab tab : tabs) { tab.setIconColor(color); } } public void addTab(MaterialTab tab) { // add properties to tab tab.setAccentColor(accentColor); tab.setPrimaryColor(primaryColor); tab.setTextColor(textColor); tab.setIconColor(iconColor); tab.setPosition(tabs.size()); tab.setInternalTabListener(this); // insert new tab in list tabs.add(tab); if (tabs.size() == fixtablimit && !hasIcons) { // switch tabs to scrollable before its draw scrollable = true; } if (tabs.size() == fixtablimit && hasIcons) { scrollable = true; } if (tabs.size() < fixtablimit) { scrollable = false; } } /** * jump to the tab selection item * * @param position specific integer at the selected item */ public void setSelectedNavigationItem(int position) { if (position < 0 || position > tabs.size()) { throw new RuntimeException("Index overflow"); } else { // tab at position will select, other will deselect for (int i = 0; i < tabs.size(); i++) { MaterialTab tab = tabs.get(i); if (i == position) { tab.activateTab(); } else { tabs.get(i).disableTab(); } } // move the tab if it is slidable if (scrollable) { scrollTo(position); } tabSelected = position; } } /** * jump to the tab selection item * * @param position specific integer at the selected item */ private void scrollTo(int position) { int totalWidth = 0;//(int) ( 60 * density); for (int i = 0; i < position; i++) { int width = tabs.get(i).getView().getWidth(); if (width == 0) { if (!isTablet) width = (int) (tabs.get(i).getTabMinWidth() + (24 * density)); else width = (int) (tabs.get(i).getTabMinWidth() + (48 * density)); } totalWidth += width; } scrollView.smoothScrollTo(totalWidth, 0); } @Override public void removeAllViews() { for (int i = 0; i < tabs.size(); i++) { tabs.remove(i); } layout.removeAllViews(); super.removeAllViews(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (this.getWidth() != 0 && tabs.size() != 0) notifyDataSetChanged(); } private View prepareBorderView() { LinearLayout.LayoutParams separator = new LinearLayout.LayoutParams((int) (borderwidth * density), HorizontalScrollView.LayoutParams.MATCH_PARENT); //border set View borderVertical = new View(layout.getContext()); borderVertical.setBackgroundColor(borderColor); borderVertical.setLayoutParams(separator); return borderVertical; } private LinearLayout.LayoutParams genlayoutParams(int tabWidth) { return new LinearLayout.LayoutParams(tabWidth, HorizontalScrollView.LayoutParams.MATCH_PARENT); } private int screen_width; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { screen_width = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // Restrict the aspect ratio to 1:1, fitting within original specified dimensions /* int chosenDimension = Math.min(widthSize, heightSize); widthMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST); heightMeasureSpec = MeasureSpec.makeMeasureSpec(chosenDimension, MeasureSpec.AT_MOST); getLayoutParams().height = chosenDimension; getLayoutParams().width = chosenDimension; */ super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** * set to reinitialize the tab view */ public void notifyDataSetChanged() { super.removeAllViews(); layout.removeAllViews(); //invalidate(); final Point s = new Point(); getDisplay().getSize(s); int screen_width = s.x; final int last_item = tabs.size() - 1; int tabWidth = screen_width / tabs.size() - (borderEdge ? (int) (borderwidth * density) : 0); // set params for resizing tabs width LinearLayout.LayoutParams params = genlayoutParams(tabWidth); if (!scrollable) { // not scrollable tabs for (int i = 0; i < tabs.size(); i++) { MaterialTab t = tabs.get(i); //if (i == 0 && borderEdge) { // first tab // layout.addView(prepareBorderView()); //} if (!outterBorderEnable && borderEdge && i == last_item) { params = genlayoutParams(tabWidth + (int) density); } layout.addView(t.getView(), params); if (borderEdge && i < last_item && !outterBorderEnable) layout.addView(prepareBorderView()); if (borderEdge && outterBorderEnable) layout.addView(prepareBorderView()); } } else { //scrollable tabs if (!isTablet) { for (int i = 0; i < tabs.size(); i++) { MaterialTab tab = tabs.get(i); tabWidth = (int) (tab.getTabMinWidth() + (24 * density)); // 12dp + text/icon width + 12dp if (i == 0) { // first tab View view = new View(layout.getContext()); view.setMinimumWidth((int) (60 * density)); layout.addView(view); } params = genlayoutParams(tabWidth); if (!outterBorderEnable && borderEdge && i == last_item) { params = genlayoutParams(tabWidth + (int) density); } //add tha tab layout.addView(tab.getView(), params); //add separator if (borderEdge && i < last_item && !outterBorderEnable) layout.addView(prepareBorderView()); if (borderEdge && outterBorderEnable) layout.addView(prepareBorderView()); //add separator if (i == tabs.size() - 1) { // last tab View view = new View(layout.getContext()); view.setMinimumWidth((int) (60 * density)); layout.addView(view); } } } else { // is a tablet for (int i = 0; i < tabs.size(); i++) { MaterialTab tab = tabs.get(i); tabWidth = (int) (tab.getTabMinWidth() + (48 * density)); // 24dp + text/icon width + 24dp params = genlayoutParams(tabWidth); if (!outterBorderEnable && borderEdge && i == last_item) { params = genlayoutParams(tabWidth + (int) density); } layout.addView(tab.getView(), params); //add separator if (borderEdge && i < last_item && !outterBorderEnable) layout.addView(prepareBorderView()); if (borderEdge && outterBorderEnable) layout.addView(prepareBorderView()); } } } if (isTablet && scrollable) { // if device is a tablet and have scrollable tabs add right and left arrows Resources res = getResources(); left = new ImageButton(this.getContext()); left.setId(R.id.left); left.setImageDrawable(res.getDrawable(R.drawable.left_arrow)); left.setBackgroundColor(Color.TRANSPARENT); left.setOnClickListener(this); // set 56 dp width and 48 dp height RelativeLayout.LayoutParams paramsLeft = new LayoutParams((int) (56 * density), (int) (48 * density)); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_LEFT); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_TOP); paramsLeft.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); this.addView(left, paramsLeft); right = new ImageButton(this.getContext()); right.setId(R.id.right); right.setImageDrawable(res.getDrawable(R.drawable.right_arrow)); right.setBackgroundColor(Color.TRANSPARENT); right.setOnClickListener(this); RelativeLayout.LayoutParams paramsRight = new LayoutParams((int) (56 * density), (int) (48 * density)); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_TOP); paramsRight.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); this.addView(right, paramsRight); RelativeLayout.LayoutParams paramsScroll = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); paramsScroll.addRule(RelativeLayout.LEFT_OF, R.id.right); paramsScroll.addRule(RelativeLayout.RIGHT_OF, R.id.left); this.addView(scrollView, paramsScroll); } else { // if is not a tablet add only scrollable content RelativeLayout.LayoutParams paramsScroll = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); this.addView(scrollView, paramsScroll); } this.setSelectedNavigationItem(tabSelected); } private boolean autoUnselect = false; public MaterialTabHost setOnlySetectOneTab(boolean t) { autoUnselect = t; return this; } public MaterialTab getCurrentTab() { for (MaterialTab tab : tabs) { if (tab.isSelected()) return tab; } return null; } @Override public void onClick(View v) { // on tablet left/right button clicked int currentPosition = this.getCurrentTab().getPosition(); if (v.getId() == R.id.right && currentPosition < tabs.size() - 1) { currentPosition++; // set next tab selected this.setSelectedNavigationItem(currentPosition); // change fragment tabs.get(currentPosition).getTabListener().onTabSelected(tabs.get(currentPosition)); return; } if (v.getId() == R.id.left && currentPosition > 0) { currentPosition--; // set previous tab selected this.setSelectedNavigationItem(currentPosition); // change fragment tabs.get(currentPosition).getTabListener().onTabSelected(tabs.get(currentPosition)); return; } } private void interaction(MaterialTab tab) { if (autoUnselect && getCurrentTab() != tab) { getCurrentTab().disableTab(); tab.activateTab(); } } @Override public void onTabSelected(MaterialTab tab) { interaction(tab); } @Override public void onTabReselected(MaterialTab tab) { interaction(tab); } @Override public void onTabUnselected(MaterialTab tab) { interaction(tab); } }
mit
farkas-arpad/KROKI-mockup-tool
WebApp/src_gen/adapt/util/converters/ConverterUtil.java
5605
package adapt.util.converters; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; import adapt.model.ejb.ColumnAttribute; /**** * Class that handles all converting issues between strings and objects. * Includes BigDecimalConverter, IntegerConverter, BooleanConverter, * DateConverter and StringConverter * @author Darko * */ public class ConverterUtil { /*** * BigDecimal converter */ private static BigDecimalConverter bigDecimalConverter = new BigDecimalConverter(); /*** * Integer converter */ private static IntegerConverter integerConverter = new IntegerConverter(); /*** * Boolean converter */ private static BooleanConverter booleanConverter = new BooleanConverter(); /*** * Date converter */ private static DateConverter dateConverter = new DateConverter(); /*** * String converter */ private static StringConverter stringConverter = new StringConverter(); /*** * Long converter */ private static LongConverter longConverter = new LongConverter(); @SuppressWarnings("serial") /*** * Static map which contains all the converters */ private static Map<Class<?>, AbstractConverter> converters = new HashMap<Class<?>, AbstractConverter>() { { put(BigDecimal.class, bigDecimalConverter); put(Integer.class, integerConverter); put(Boolean.class, booleanConverter); put(Date.class, dateConverter); put(String.class, stringConverter); put(Long.class, longConverter); } }; /*** * Converts string value of an object to type that is contained in * ColumnAttribute object. * * @param value * String value * @param column * ColumnAttribute that has given value * @return Object form from value */ public static Object convert(String value, ColumnAttribute column) { System.out.println("konvertujem " + value + " u " + column.getDataType()); value = value.trim(); Class<?> classType = getType(column); if(classType == null) { System.out.println("classType = null"); }else { System.out.println("nije null: " + classType.getName()); } try { return converters.get(classType).convert(value); } catch (NullPointerException e) { e.printStackTrace(); return null; } } /*** * Converts string value into object for the given ColumnAttribute column. * * @param value * String for conversion * @param column * ColumnAttribute column that contains the class type * @return Object value of the string */ public static Object convert(String value, Class<?> classType) { value = value.trim(); try { return converters.get(classType).convert(value); } catch (NullPointerException e) { return null; } } public static String convertBack(Object value, Class<?> classType) { try { return converters.get(classType).convertBack(value); } catch (NullPointerException e) { return null; } } /*** * Converts object into it's string value * * @param value * Object for conversion * @param column * ColumnAttribute column that contains the class type * @return String value of the object */ public static String convertBack(Object value, ColumnAttribute column) { Class<?> classType = getType(column); try { return converters.get(classType).convertBack(value); } catch (NullPointerException e) { return ""; } } /*** * Converts object's value into string for panel's component viewing. * * @param value * Object for conversion * @param column * ColumnAttribute column that contains the class type * @return String value of the object */ public static String convertForViewing(Object value, ColumnAttribute column) { Class<?> classType = getType(column); try { converters.get(converters.get(classType)); return converters.get(classType).convertForViewing(value); } catch (NullPointerException e) { return ""; } } /*** * Converts object's value into string for SQL query. * * @param value * Object for conversion * @param column * ColumnAttribute column that contains the class type * @return String value of the object */ public static String convertForSQL(String value, ColumnAttribute column) { Class<?> classType = getType(column); try { System.out.println("ConverterUtil.convertForSQL()"); return converters.get(classType).convertForSQL(value, column); } catch (NullPointerException e) { return ""; } } /*** * Prepares the type of class from column. If it has no type and it is an * enumeration, then it returns as type class Integer. * * @param column * ColumnAttribute * @return */ private static Class<?> getType(ColumnAttribute column) { Class<?> classType = null; if (column.getDataType() != null && !column.getDataType().equals("")) { try { classType = Class.forName(column.getDataType().split(":")[0]); } catch (Exception e) { return null; } } else if (column.getEnumeration() != null && !column.getEnumeration().equals("")) { classType = Integer.class; } else { return null; } return classType; } public static String convertForViewing(Object value, Class<?> classType) { try { return converters.get(classType).convertForViewing(value); } catch (NullPointerException e) { return ""; } } }
mit
beluchin/jmockit1
main/src/mockit/integration/junit4/internal/JUnit4TestRunnerDecorator.java
4904
/* * Copyright (c) 2006-2015 Rogério Liesenfeld * This file is subject to the terms of the MIT license (see LICENSE.txt). */ package mockit.integration.junit4.internal; import java.lang.reflect.*; import javax.annotation.*; import org.junit.*; import org.junit.runners.model.*; import mockit.integration.internal.*; import mockit.internal.expectations.*; import mockit.internal.mockups.*; import mockit.internal.state.*; import static mockit.internal.util.StackTrace.*; final class JUnit4TestRunnerDecorator extends TestRunnerDecorator { @Nullable Object invokeExplosively(@Nonnull MockInvocation invocation, @Nullable Object target, Object... params) throws Throwable { FrameworkMethod it = invocation.getInvokedInstance(); // A @BeforeClass/@AfterClass method: if (target == null) { return executeClassMethod(invocation, params); } handleMockingOutsideTestMethods(target); // A @Before/@After method: if (it.getAnnotation(Test.class) == null) { if (shouldPrepareForNextTest && it.getAnnotation(Before.class) != null) { prepareToExecuteSetupMethod(target); } TestRun.setRunningIndividualTest(target); try { invocation.prepareToProceedFromNonRecursiveMock(); return it.invokeExplosively(target, params); } catch (Throwable t) { RecordAndReplayExecution.endCurrentReplayIfAny(); filterStackTrace(t); throw t; } finally { if (it.getAnnotation(After.class) != null) { shouldPrepareForNextTest = true; } } } if (shouldPrepareForNextTest) { prepareForNextTest(); } shouldPrepareForNextTest = true; try { executeTestMethod(invocation, target, params); return null; // it's a test method, therefore has void return type } catch (Throwable t) { filterStackTrace(t); throw t; } finally { TestRun.finishCurrentTestExecution(); } } @Nullable private static Object executeClassMethod(@Nonnull MockInvocation inv, @Nonnull Object[] params) throws Throwable { FrameworkMethod method = inv.getInvokedInstance(); handleMockingOutsideTests(method); TestRun.setRunningIndividualTest(null); inv.prepareToProceedFromNonRecursiveMock(); return method.invokeExplosively(null, params); } private void prepareToExecuteSetupMethod(@Nonnull Object target) { discardTestLevelMockedTypes(); prepareForNextTest(); shouldPrepareForNextTest = false; createInstancesForTestedFields(target, true); } private static void handleMockingOutsideTests(@Nonnull FrameworkMethod it) { Class<?> testClass = it.getMethod().getDeclaringClass(); TestRun.enterNoMockingZone(); try { Class<?> currentTestClass = TestRun.getCurrentTestClass(); if ( currentTestClass != null && testClass.isAssignableFrom(currentTestClass) && it.getAnnotation(AfterClass.class) != null ) { cleanUpMocksFromPreviousTest(); } if (it.getAnnotation(BeforeClass.class) != null) { updateTestClassState(null, testClass); } } finally { TestRun.exitNoMockingZone(); } } private static void handleMockingOutsideTestMethods(@Nonnull Object target) { Class<?> testClass = target.getClass(); TestRun.enterNoMockingZone(); try { updateTestClassState(target, testClass); } finally { TestRun.exitNoMockingZone(); } } private static void executeTestMethod( @Nonnull MockInvocation invocation, @Nonnull Object target, @Nullable Object... parameters) throws Throwable { SavePoint savePoint = new SavePoint(); TestRun.setRunningIndividualTest(target); FrameworkMethod it = invocation.getInvokedInstance(); Method testMethod = it.getMethod(); Throwable testFailure = null; boolean testFailureExpected = false; try { Object[] mockParameters = createInstancesForMockParameters(testMethod, parameters); createInstancesForTestedFields(target, false); invocation.prepareToProceedFromNonRecursiveMock(); Object[] params = mockParameters == null ? parameters : mockParameters; it.invokeExplosively(target, params); } catch (Throwable thrownByTest) { testFailure = thrownByTest; Class<?> expectedType = testMethod.getAnnotation(Test.class).expected(); testFailureExpected = expectedType.isAssignableFrom(thrownByTest.getClass()); } finally { concludeTestMethodExecution(savePoint, testFailure, testFailureExpected); } } }
mit
Springrbua/typescript.java
core/ts.core/src/ts/client/CommandCapability.java
620
package ts.client; import ts.utils.VersionHelper; public enum CommandCapability implements ISupportable { DiagnosticWithCategory("2.3.1"); private String sinceVersion; private CommandCapability(String version) { this.sinceVersion = version; } /** * Return true if the tsc compiler option support the given version and * false otherwise. * * @param version * @return true if the tsc compiler option support the given version and * false otherwise. */ public boolean canSupport(String version) { return VersionHelper.canSupport(version, sinceVersion); } }
mit
DSG-UniFE/spf
src/java/dissemination/us/ihmc/aci/util/dspro/soi/ARLExchangeFormat.java
1843
package us.ihmc.aci.util.dspro.soi; /** * Class containing fields parsed from <code>InformationObject</code> instances of general ARL data types * @author Rita Lenzi (rlenzi@ihmc.us) */ public class ARLExchangeFormat extends ExchangeFormat { public static final String INR_ID = "inr.id"; public static final String INF_ID = "inf.id"; public static final String RECIPIENTS_COUNT = "recipients.count"; public static final String RECIPIENTS_ALERT_PRIORITY = "recipients.missionAlert.priority.number."; public static final String RECIPIENTS_CHANGE_PRIORITY = "recipients.change.priority.number."; public static final String RECIPIENTS_INITIAL_PRIORITY = "recipients.initial.priority.number."; public static final String RECIPIENTS_BILLET = "recipients.billet.number."; public static final String RECIPIENTS_ROLE = "recipients.role.number."; public static final String RECIPIENTS_UIC = "recipients.uic.number."; public static final String RECIPIENTS_FUNCTION = "recipients.function.number."; public static final String RECIPIENTS_USERNAME_COUNT = ExchangeFormat.TARGET_IDS_COUNT; // Do not change this public static final String RECIPIENTS_USERNAME = ExchangeFormat.TARGET_ID; // Do not change this public static final String ARL_OBJECT_TYPE = "arl.object.type"; public static final String NAME = "ghub.data.name"; public static final String MIL_STD_2525_SYMBOL_ID = "milStd2525SymbolId"; public static final String LOCATION_LATITUDE = "latitude"; public static final String LOCATION_LONGITUDE = "longitude"; public static final String IMAGES_URL_NUMBER = ImagesExchangeFormat.IMAGES_URL_NUMBER; public static final String PRIORITY_LEVEL = "priority.level"; public static final String TIMESTAMP = "timestamp"; public static final String UIC = "uic"; }
mit
kashifiqb/Aspose.Email-for-Java
Examples/src/main/java/com/aspose/email/examples/outlook/msg/SetColorCategoryForOutlookMessageFile.java
992
package com.aspose.email.examples.outlook.msg; import com.aspose.email.FollowUpManager; import com.aspose.email.MapiMessage; import com.aspose.email.examples.Utils; import com.aspose.email.system.collections.IList; public class SetColorCategoryForOutlookMessageFile { public static void main(String[] args) { // The path to the resource directory. String dataDir = Utils.getSharedDataDir(SetColorCategoryForOutlookMessageFile.class) + "outlook/"; MapiMessage msg = MapiMessage.fromFile(dataDir + "message.msg"); // Add category FollowUpManager.addCategory(msg, "Purple Category"); // Add another category FollowUpManager.addCategory(msg, "Red Category"); // Retrieve the list of available categories IList categories = FollowUpManager.getCategories(msg); System.out.println(categories.size()); // Remove the specified category FollowUpManager.removeCategory(msg, "Red Category"); // Clear all categories FollowUpManager.clearCategories(msg); } }
mit
pdeboer/wikilanguage
lib/jung2/jung-visualization/src/main/java/edu/uci/ics/jung/visualization/decorators/PickableVertexPaintTransformer.java
1656
/* * Created on Mar 10, 2005 * * Copyright (c) 2005, the JUNG Project and the Regents of the University * of California * All rights reserved. * * This software is open-source under the BSD license; see either * "license.txt" or * http://jung.sourceforge.net/license.txt for a description. */ package edu.uci.ics.jung.visualization.decorators; import java.awt.Paint; import org.apache.commons.collections15.Transformer; import edu.uci.ics.jung.visualization.picking.PickedInfo; /** * Paints each vertex according to the <code>Paint</code> * parameters given in the constructor, so that picked and * non-picked vertices can be made to look different. */ public class PickableVertexPaintTransformer<V> implements Transformer<V,Paint> { protected Paint fill_paint; protected Paint picked_paint; protected PickedInfo<V> pi; /** * * @param pi specifies which vertices report as "picked" * @param draw_paint <code>Paint</code> used to draw vertex shapes * @param fill_paint <code>Paint</code> used to fill vertex shapes * @param picked_paint <code>Paint</code> used to fill picked vertex shapes */ public PickableVertexPaintTransformer(PickedInfo<V> pi, Paint fill_paint, Paint picked_paint) { if (pi == null) throw new IllegalArgumentException("PickedInfo instance must be non-null"); this.pi = pi; this.fill_paint = fill_paint; this.picked_paint = picked_paint; } public Paint transform(V v) { if (pi.isPicked(v)) return picked_paint; else return fill_paint; } }
mit
ctron/kura
kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/client/ui/wires/ValidationInputCell.java
4555
/******************************************************************************* * Copyright (c) 2016, 2020 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech * Amit Kumar Mondal *******************************************************************************/ package org.eclipse.kura.web.client.ui.wires; import com.google.gwt.cell.client.AbstractInputCell; import com.google.gwt.cell.client.ValueUpdater; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.InputElement; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.safecss.shared.SafeStyles; import com.google.gwt.safecss.shared.SafeStylesUtils; import com.google.gwt.safehtml.client.SafeHtmlTemplates; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; /** * A custom Input Cell which is inherently used to validate its data based on * validation provided from Metatype */ public final class ValidationInputCell extends AbstractInputCell<String, ValidationData> { interface ValidationInputTemplate extends SafeHtmlTemplates { @Template("<input type=\"text\" value=\"{0}\" style=\"{1}\" class=\"{2}\" tabindex=\"-1\"/>") SafeHtml input(String value, SafeStyles color, String cssClassName); } private static final String CHANGE_EVENT = "change"; private static final String VALIDATED_COLOR = "black"; private static final String NONVALIDATED_COLOR = "red"; private static final String NONVALIDATED_CSS_CLASS_NAME = "error-text-box"; private static final String VALIDATED_CSS_CLASS_NAME = "noerror-text-box"; private ValidationInputTemplate validationTemplate; public ValidationInputCell() { super(CHANGE_EVENT); if (this.validationTemplate == null) { this.validationTemplate = GWT.create(ValidationInputTemplate.class); } } /** {@inheritDoc} */ @Override public void onBrowserEvent(final Context context, final Element parent, final String value, final NativeEvent event, final ValueUpdater<String> valueUpdater) { super.onBrowserEvent(context, parent, value, event, valueUpdater); final Element target = event.getEventTarget().cast(); if (!parent.getFirstChildElement().isOrHasChild(target)) { return; } final Object key = context.getKey(); ValidationData viewData = getViewData(key); final String eventType = event.getType(); if (CHANGE_EVENT.equals(eventType)) { final InputElement input = parent.getFirstChild().cast(); if (viewData == null) { viewData = new ValidationData(); setViewData(key, viewData); } final String newValue = input.getValue(); viewData.setValue(newValue); finishEditing(parent, newValue, key, valueUpdater); if (valueUpdater != null) { valueUpdater.update(newValue); } } } /** {@inheritDoc} */ @Override protected void onEnterKeyDown(final Context context, final Element parent, final String value, final NativeEvent event, final ValueUpdater<String> valueUpdater) { final Element target = event.getEventTarget().cast(); if (getInputElement(parent).isOrHasChild(target)) { finishEditing(parent, value, context.getKey(), valueUpdater); } else { super.onEnterKeyDown(context, parent, value, event, valueUpdater); } } /** {@inheritDoc} */ @Override public void render(final Context context, String value, final SafeHtmlBuilder shb) { final Object key = context.getKey(); ValidationData validationViewData = getViewData(key); if (value == null) { value = ""; } final boolean invalid = validationViewData != null && validationViewData.isInvalid(); final String color = invalid ? NONVALIDATED_COLOR : VALIDATED_COLOR; final SafeStyles safeColor = SafeStylesUtils.fromTrustedString("color: " + color + ";"); shb.append(this.validationTemplate.input(value, safeColor, invalid ? NONVALIDATED_CSS_CLASS_NAME : VALIDATED_CSS_CLASS_NAME)); } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/handler/ChannelBridgeFirmware.java
2746
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.velux.internal.handler; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.velux.internal.bridge.VeluxBridgeGetFirmware; import org.openhab.core.thing.ChannelUID; import org.openhab.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <B>Channel-specific retrieval and modification.</B> * <P> * This class implements the Channel <B>firmware</B> of the Thing <B>klf200</B> : * <UL> * <LI><I>Velux</I> <B>bridge</B> &rarr; <B>OpenHAB</B>: * <P> * Information retrieval by method {@link #handleRefresh}.</LI> * </UL> * * @author Guenther Schreiner - Initial contribution. */ @NonNullByDefault final class ChannelBridgeFirmware extends ChannelHandlerTemplate { private static final Logger LOGGER = LoggerFactory.getLogger(ChannelBridgeFirmware.class); /* * ************************ * ***** Constructors ***** */ // Suppress default constructor for non-instantiability private ChannelBridgeFirmware() { throw new AssertionError(); } /** * Communication method to retrieve information to update the channel value. * * @param channelUID The item passed as type {@link ChannelUID} for which a refresh is intended. * @param channelId The same item passed as type {@link String} for which a refresh is intended. * @param thisBridgeHandler The Velux bridge handler with a specific communication protocol which provides * information for this channel. * @return newState The value retrieved for the passed channel, or <I>null</I> in case if there is no (new) value. */ static @Nullable State handleRefresh(ChannelUID channelUID, String channelId, VeluxBridgeHandler thisBridgeHandler) { LOGGER.debug("handleRefresh({},{},{}) called.", channelUID, channelId, thisBridgeHandler); State newState = null; thisBridgeHandler.bridgeParameters.firmware = new VeluxBridgeGetFirmware() .retrieve(thisBridgeHandler.thisBridge); if (thisBridgeHandler.bridgeParameters.firmware.isRetrieved) { newState = thisBridgeHandler.bridgeParameters.firmware.firmwareVersion; } LOGGER.trace("handleRefresh() returns {}.", newState); return newState; } }
epl-1.0
cdjackson/openhab2-addons
addons/binding/org.openhab.binding.milight/src/main/java/org/openhab/binding/milight/handler/MilightBridgeV3Handler.java
6915
/** * 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.milight.handler; import java.math.BigDecimal; import java.net.InetAddress; import java.net.SocketException; import java.util.Map; import org.eclipse.smarthome.config.core.Configuration; import org.eclipse.smarthome.core.thing.Bridge; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.ThingUID; import org.openhab.binding.milight.MilightBindingConstants; import org.openhab.binding.milight.internal.protocol.MilightDiscover; import org.openhab.binding.milight.internal.protocol.MilightDiscover.DiscoverResult; /** * The {@link MilightBridgeV3Handler} is responsible for handling commands, which are * sent to one of the channels. * * @author David Graeff <david.graeff@web.de> */ public class MilightBridgeV3Handler extends AbstractMilightBridgeHandler implements DiscoverResult { private MilightDiscover discover; public MilightBridgeV3Handler(Bridge bridge) { super(bridge); } @Override public void handleConfigurationUpdate(Map<String, Object> configurationParameters) { super.handleConfigurationUpdate(configurationParameters); if (com == null) { return; } BigDecimal refresh_time = (BigDecimal) thing.getConfiguration().get(MilightBindingConstants.CONFIG_REFRESH_SEC); if (refresh_time != null && refresh_time.intValue() != refrehIntervalSec) { setupRefreshTimer(refresh_time.intValue()); } } @Override public void thingUpdated(Thing thing) { super.thingUpdated(thing); } @Override protected Runnable getKeepAliveRunnable() { return new Runnable() { @Override public void run() { discover.sendDiscover(scheduler); } }; } /** * Creates a discovery object and the send queue. The initial IP address may be null * or is not matching with the real IP address of the bridge. The discovery class will send * a broadcast packet to find the bridge with the respective bridge ID. The response in bridgeDetected() * may lead to a recreation of the send queue object. * * The keep alive timer that is also setup here, will send keep alive packets periodically. * If the bridge doesn't respond anymore (e.g. DHCP IP change), the initial session handshake * starts all over again. */ @Override protected void startConnectAndKeepAlive(InetAddress addr) { dispose(); int port = getPort(MilightBindingConstants.PORT_VER3); if (port == 0) { return; } com.setAddress(addr); com.setPort(port); com.start(); // We recycle the discovery class and reuse it as a keep alive here. try { discover = new MilightDiscover(this, 1000, 3); discover.setFixedAddr(addr); discover.start(); } catch (SocketException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage()); return; } discover.sendDiscover(scheduler); BigDecimal refresh_sec = (BigDecimal) thing.getConfiguration().get(MilightBindingConstants.CONFIG_REFRESH_SEC); setupRefreshTimer(refresh_sec == null ? 0 : refresh_sec.intValue()); } @Override public void dispose() { if (discover != null) { discover.dispose(); } super.dispose(); } // A bridge may be connected/paired to white/rgbw/rgb bulbs. Unfortunately the bridge does // not know which bulbs are present and the bulbs do not have a bidirectional communication. // Therefore we present the user all possible bulbs // (4 groups each for white/rgbw and 1 for the obsolete rgb bulb ). private void addBulbsToDiscovery() { thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.WHITE_THING_TYPE, this.getThing().getUID(), "0"), "All white"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.WHITE_THING_TYPE, this.getThing().getUID(), "1"), "White (Zone 1)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.WHITE_THING_TYPE, this.getThing().getUID(), "2"), "White (Zone 2)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.WHITE_THING_TYPE, this.getThing().getUID(), "3"), "White (Zone 3)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.WHITE_THING_TYPE, this.getThing().getUID(), "4"), "White (Zone 4)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.RGB_THING_TYPE, this.getThing().getUID(), "0"), "All color"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.RGB_THING_TYPE, this.getThing().getUID(), "1"), "Color (Zone 1)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.RGB_THING_TYPE, this.getThing().getUID(), "2"), "Color (Zone 2)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.RGB_THING_TYPE, this.getThing().getUID(), "3"), "Color (Zone 3)"); thingDiscoveryService.addDevice( new ThingUID(MilightBindingConstants.RGB_THING_TYPE, this.getThing().getUID(), "4"), "Color (Zone 4)"); // thingDiscoveryService.addDevice( // new ThingUID(MilightBindingConstants.RGB_V2_THING_TYPE, this.getThing().getUID(), "0"), // "Color Led (without white channel)"); } @Override public void bridgeDetected(InetAddress addr, String id, int version) { if (!bridgeid.equals(id)) { logger.error("Bridges are not supposed to change their ID"); dispose(); return; } // IP address has changed, reestablish communication if (!addr.equals(com.getAddr())) { com.setAddress(addr); Configuration c = editConfiguration(); c.put(MilightBindingConstants.CONFIG_HOST_NAME, addr.getHostAddress()); updateConfiguration(c); } addBulbsToDiscovery(); updateStatus(ThingStatus.ONLINE); } @Override public void noBridgeDetected() { updateStatus(ThingStatus.OFFLINE); } }
epl-1.0
belkassaby/dawnsci
org.eclipse.dawnsci.analysis.dataset/src/org/eclipse/dawnsci/analysis/dataset/MockDynamicLazyDataset.java
2776
package org.eclipse.dawnsci.analysis.dataset; import java.io.IOException; import org.eclipse.january.IMonitor; import org.eclipse.january.dataset.Dataset; import org.eclipse.january.dataset.IDataListener; import org.eclipse.january.dataset.IDataset; import org.eclipse.january.dataset.IDatasetChangeChecker; import org.eclipse.january.dataset.IDynamicDataset; import org.eclipse.january.dataset.LazyDynamicDataset; import org.eclipse.january.dataset.ShapeUtils; import org.eclipse.january.dataset.SliceND; import org.eclipse.january.io.ILazyLoader; public class MockDynamicLazyDataset extends LazyDynamicDataset { private static final long serialVersionUID = 1L; private int[][] shapeArrays; private int count = 1; private Dataset parent; private boolean allowIncrement = false; public MockDynamicLazyDataset(int[][] shapes, Dataset parent) { super("mock", parent.getDType(), parent.getElementsPerItem(), shapes[0], parent.getShape(), null); this.parent = parent; loader = new DynamicLazyLoader(); shapeArrays = shapes; this.maxShape = parent.getShape(); } public void setAllowIncrement(boolean allow) { allowIncrement = allow; } public Dataset getParent() { return parent; } @Override public IDynamicDataset getDataset() { return this; } @Override public void setMaxShape(int... maxShape) { //do nothing } @Override public void startUpdateChecker(int milliseconds, IDatasetChangeChecker checker) { //do nothing } @Override public boolean refreshShape() { if (!allowIncrement) return true; if (count < shapeArrays.length) { int[] s = shapeArrays[count++]; size = ShapeUtils.calcLongSize(s); shape = s.clone(); oShape = shape; oShape.toString(); } return true; } @Override public void addDataListener(IDataListener l) { //do nothing } @Override public void removeDataListener(IDataListener l) { //do nothing } @Override public void fireDataListeners() { //do nothing } @Override public MockDynamicLazyDataset clone() { MockDynamicLazyDataset ret = new MockDynamicLazyDataset(shapeArrays, this.parent); ret.loader = this.loader; ret.oShape = oShape; ret.shape = shape; ret.size = size; ret.prepShape = prepShape; ret.postShape = postShape; ret.begSlice = begSlice; ret.delSlice = delSlice; ret.map = map; ret.base = base; ret.metadata = copyMetadata(); ret.oMetadata = oMetadata; ret.name = this.name; return ret; } private class DynamicLazyLoader implements ILazyLoader { private static final long serialVersionUID = 1L; @Override public boolean isFileReadable() { return true; } @Override public IDataset getDataset(IMonitor mon, SliceND slice) throws IOException { return parent.getSlice(slice); } } }
epl-1.0
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineTemp/cannotInline/A_testFail6.java
111
//assigned to more than once package p; class A{ int m(int y){ /*[*/int i= 0;/*]*/ return y + (i--); }; }
epl-1.0
akurtakov/Pydev
plugins/org.python.pydev.core/src/org/python/pydev/core/docutils/StringSubstitution.java
17380
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.core.docutils; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import org.eclipse.core.resources.IPathVariableManager; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.variables.VariablesPlugin; import org.python.pydev.core.IPythonNature; import org.python.pydev.core.IPythonPathNature; import org.python.pydev.core.log.Log; import org.python.pydev.shared_core.string.StringUtils; /** * Implements a part of IStringVariableManager (just the performStringSubstitution methods). */ public class StringSubstitution { private Map<String, String> variableSubstitution = null; public StringSubstitution(IPythonNature nature) { if (nature != null) { try { IPythonPathNature pythonPathNature = nature.getPythonPathNature(); IProject project = nature.getProject(); //note: project can be null when creating a new project and receiving a system nature. variableSubstitution = pythonPathNature.getVariableSubstitution(); try { IPathVariableManager projectPathVarManager = null; try { if (project != null) { projectPathVarManager = project.getPathVariableManager(); } } catch (Throwable e1) { //Ignore: getPathVariableManager not available on earlier Eclipse versions. } String[] pathVarNames = null; if (projectPathVarManager != null) { pathVarNames = projectPathVarManager.getPathVariableNames(); } //The usual path var names are: //ECLIPSE_HOME, PARENT_LOC, WORKSPACE_LOC, PROJECT_LOC //Other possible variables may be defined in General > Workspace > Linked Resources. //We also add PROJECT_DIR_NAME (so, we can define a source folder with /${PROJECT_DIR_NAME} if (project != null && !variableSubstitution.containsKey("PROJECT_DIR_NAME")) { IPath location = project.getFullPath(); if (location != null) { variableSubstitution.put("PROJECT_DIR_NAME", location.lastSegment()); } } if (pathVarNames != null) { URI uri = null; String var = null; String path = null; for (int i = 0; i < pathVarNames.length; i++) { try { var = pathVarNames[i]; uri = projectPathVarManager.getURIValue(var); if (uri != null) { String scheme = uri.getScheme(); if (scheme != null && scheme.equalsIgnoreCase("file")) { path = uri.getPath(); if (path != null && !variableSubstitution.containsKey(var)) { variableSubstitution.put(var, new File(uri).toString()); } } } } catch (Exception e) { Log.log(e); } } } } catch (Throwable e) { Log.log(e); } } catch (Exception e) { Log.log(e); } } } /** * Replaces with all variables (the ones for this class and the ones in the VariablesPlugin) * * * Recursively resolves and replaces all variable references in the given * expression with their corresponding values. Allows the client to control * whether references to undefined variables are reported as an error (i.e. * an exception is thrown). * * @param expression expression referencing variables * @param reportUndefinedVariables whether a reference to an undefined variable * is to be considered an error (i.e. throw an exception) * @return expression with variable references replaced with variable values * @throws CoreException if unable to resolve the value of one or more variables */ public String performStringSubstitution(String expression, boolean reportUndefinedVariables) throws CoreException { VariablesPlugin plugin = VariablesPlugin.getDefault(); expression = performPythonpathStringSubstitution(expression); expression = plugin.getStringVariableManager().performStringSubstitution(expression, reportUndefinedVariables); return expression; } /** * String substitution for the pythonpath does not use the default eclipse string substitution (only variables * defined explicitly in this class) */ public String performPythonpathStringSubstitution(String expression) throws CoreException { if (variableSubstitution != null && variableSubstitution.size() > 0 && expression != null && expression.length() > 0) { //Only throw exception here if the expression = new StringSubstitutionEngine().performStringSubstitution(expression, true, variableSubstitution); } return expression; } /** * Recursively resolves and replaces all variable references in the given * expression with their corresponding values. Reports errors for references * to undefined variables (equivalent to calling * <code>performStringSubstitution(expression, true)</code>). * * @param expression expression referencing variables * @return expression with variable references replaced with variable values * @throws CoreException if unable to resolve the value of one or more variables */ public String performStringSubstitution(String expression) throws CoreException { return performStringSubstitution(expression, true); } /** * Performs string substitution for context and value variables. */ class StringSubstitutionEngine { // delimiters private static final String VARIABLE_START = "${"; //$NON-NLS-1$ private static final char VARIABLE_END = '}'; private static final char VARIABLE_ARG = ':'; // parsing states private static final int SCAN_FOR_START = 0; private static final int SCAN_FOR_END = 1; /** * Resulting string */ private StringBuffer fResult; /** * Whether substitutions were performed */ private boolean fSubs; /** * Stack of variables to resolve */ private Stack<VariableReference> fStack; class VariableReference { // the text inside the variable reference private StringBuffer fText; public VariableReference() { fText = new StringBuffer(); } public void append(String text) { fText.append(text); } public String getText() { return fText.toString(); } } /** * Performs recursive string substitution and returns the resulting string. * * @param expression expression to resolve * @param reportUndefinedVariables whether to report undefined variables as an error * @param variableSubstitution registry of variables * @return the resulting string with all variables recursively * substituted * @exception CoreException if unable to resolve a referenced variable or if a cycle exists * in referenced variables */ public String performStringSubstitution(String expression, boolean resolveVariables, Map<String, String> variableSubstitution) throws CoreException { substitute(expression, resolveVariables, variableSubstitution); List<HashSet<String>> resolvedVariableSets = new ArrayList<HashSet<String>>(); while (fSubs) { HashSet<String> resolved = substitute(fResult.toString(), true, variableSubstitution); for (int i = resolvedVariableSets.size() - 1; i >= 0; i--) { HashSet<String> prevSet = resolvedVariableSets.get(i); if (prevSet.equals(resolved)) { HashSet<String> conflictingSet = new HashSet<String>(); for (; i < resolvedVariableSets.size(); i++) { conflictingSet.addAll(resolvedVariableSets.get(i)); } StringBuffer problemVariableList = new StringBuffer(); for (Iterator<?> it = conflictingSet.iterator(); it.hasNext();) { problemVariableList.append(it.next().toString()); problemVariableList.append(", "); //$NON-NLS-1$ } problemVariableList.setLength(problemVariableList.length() - 2); //truncate the last ", " throw new CoreException(new Status(IStatus.ERROR, VariablesPlugin.getUniqueIdentifier(), VariablesPlugin.REFERENCE_CYCLE_ERROR, StringUtils.format("Cycle error on:", problemVariableList.toString()), null)); } } resolvedVariableSets.add(resolved); } return fResult.toString(); } /** * Makes a substitution pass of the given expression returns a Set of the variables that were resolved in this * pass * * @param expression source expression * @param resolveVariables whether to resolve the value of any variables * @exception CoreException if unable to resolve a variable */ private HashSet<String> substitute(String expression, boolean resolveVariables, Map<String, String> variableSubstitution) throws CoreException { fResult = new StringBuffer(expression.length()); fStack = new Stack<VariableReference>(); fSubs = false; HashSet<String> resolvedVariables = new HashSet<String>(); int pos = 0; int state = SCAN_FOR_START; while (pos < expression.length()) { switch (state) { case SCAN_FOR_START: int start = expression.indexOf(VARIABLE_START, pos); if (start >= 0) { int length = start - pos; // copy non-variable text to the result if (length > 0) { fResult.append(expression.substring(pos, start)); } pos = start + 2; state = SCAN_FOR_END; fStack.push(new VariableReference()); } else { // done - no more variables fResult.append(expression.substring(pos)); pos = expression.length(); } break; case SCAN_FOR_END: // be careful of nested variables start = expression.indexOf(VARIABLE_START, pos); int end = expression.indexOf(VARIABLE_END, pos); if (end < 0) { // variables are not completed VariableReference tos = fStack.peek(); tos.append(expression.substring(pos)); pos = expression.length(); } else { if (start >= 0 && start < end) { // start of a nested variable int length = start - pos; if (length > 0) { VariableReference tos = fStack.peek(); tos.append(expression.substring(pos, start)); } pos = start + 2; fStack.push(new VariableReference()); } else { // end of variable reference VariableReference tos = fStack.pop(); String substring = expression.substring(pos, end); tos.append(substring); resolvedVariables.add(substring); pos = end + 1; String value = resolve(tos, resolveVariables, variableSubstitution); if (value == null) { value = ""; //$NON-NLS-1$ } if (fStack.isEmpty()) { // append to result fResult.append(value); state = SCAN_FOR_START; } else { // append to previous variable tos = fStack.peek(); tos.append(value); } } } break; } } // process incomplete variable references while (!fStack.isEmpty()) { VariableReference tos = fStack.pop(); if (fStack.isEmpty()) { fResult.append(VARIABLE_START); fResult.append(tos.getText()); } else { VariableReference var = fStack.peek(); var.append(VARIABLE_START); var.append(tos.getText()); } } return resolvedVariables; } /** * Resolve and return the value of the given variable reference, * possibly <code>null</code>. * * @param var * @param resolveVariables whether to resolve the variables value or just to validate that this variable is valid * @param variableSubstitution variable registry * @return variable value, possibly <code>null</code> * @exception CoreException if unable to resolve a value */ private String resolve(VariableReference var, boolean resolveVariables, Map<String, String> variableSubstitution) throws CoreException { String text = var.getText(); int pos = text.indexOf(VARIABLE_ARG); String name = null; String arg = null; if (pos > 0) { name = text.substring(0, pos); pos++; if (pos < text.length()) { arg = text.substring(pos); } } else { name = text; } String valueVariable = variableSubstitution.get(name); if (valueVariable == null) { //leave as is return getOriginalVarText(var); } if (arg == null) { if (resolveVariables) { fSubs = true; return valueVariable; } //leave as is return getOriginalVarText(var); } // error - an argument specified for a value variable throw new CoreException(new Status(IStatus.ERROR, VariablesPlugin.getUniqueIdentifier(), VariablesPlugin.INTERNAL_ERROR, "Error substituting: " + name + " var: " + valueVariable, null)); } private String getOriginalVarText(VariableReference var) { StringBuffer res = new StringBuffer(var.getText()); res.insert(0, VARIABLE_START); res.append(VARIABLE_END); return res.toString(); } } }
epl-1.0
akervern/che
ide/commons-gwt/src/main/java/org/eclipse/che/ide/websocket/impl/WebSocketConnectionManager.java
3774
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.websocket.impl; import com.google.inject.Inject; import java.util.HashMap; import java.util.Map; import javax.inject.Singleton; import org.eclipse.che.ide.util.loging.Log; /** * Manages all connection related high level processes. Acts as a facade to low level web socket * components. * * @author Dmitry Kuleshov */ @Singleton public class WebSocketConnectionManager { private final WebSocketFactory webSocketFactory; private final Map<String, WebSocketConnection> connectionsRegistry = new HashMap<>(); @Inject public WebSocketConnectionManager(WebSocketFactory webSocketFactory) { this.webSocketFactory = webSocketFactory; } /** * Initialize a connection. Performs all necessary preparations except for properties management. * Must be called before any interactions with a web socket connection. * * @param url url of a web socket connection that is to be initialized */ public void initializeConnection(String url) { connectionsRegistry.put(url, webSocketFactory.create(url)); } /** * Establishes a web socket connection to an endpoint defined by a URL parameter * * @param url url of a web socket connection that is to be established */ public void establishConnection(String url) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); if (webSocketConnection == null) { final String error = "No connection with url: " + url + "is initialized. Run 'initializedConnection' first."; Log.error(getClass(), error); throw new IllegalStateException(error); } webSocketConnection.open(); Log.debug(getClass(), "Opening connection. Url: " + url); } /** * Close a web socket connection to an endpoint defined by a URL parameter * * @param url url of a connection to be closed */ public void closeConnection(String url) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); if (webSocketConnection == null) { final String warning = "Closing connection that is not registered and seem like does not exist"; Log.warn(getClass(), warning); throw new IllegalStateException(warning); } webSocketConnection.close(); Log.debug(WebSocketConnectionManager.class, "Closing connection."); } /** * Sends a message to a specified endpoint over web socket connection. * * @param url url of an endpoint the message is adressed to * @param message plain text message */ public void sendMessage(String url, String message) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); if (webSocketConnection == null) { final String error = "No connection with url: " + url + "is initialized. Run 'initializedConnection' first."; Log.error(getClass(), error); throw new IllegalStateException(error); } webSocketConnection.send(message); Log.debug(getClass(), "Sending message: " + message); } /** * Checks if a connection is opened at the moment * * @param url url of a web socket connection to be checked * @return connection status: true if opened, false if else */ public boolean isConnectionOpen(String url) { final WebSocketConnection webSocketConnection = connectionsRegistry.get(url); return webSocketConnection != null && webSocketConnection.isOpen(); } }
epl-1.0
rajul/Pydev
plugins/org.python.pydev.parser/src/org/python/pydev/parser/grammarcommon/NullTreeBuilder.java
1279
/****************************************************************************** * Copyright (C) 2012 Fabio Zadrozny * * 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: * Fabio Zadrozny <fabiofz@gmail.com> - initial API and implementation ******************************************************************************/ package org.python.pydev.parser.grammarcommon; import org.python.pydev.parser.jython.SimpleNode; import org.python.pydev.parser.jython.ast.Name; public final class NullTreeBuilder implements ITreeBuilder { private final Name nameConstant = new Name("", Name.Load, false); public SimpleNode closeNode(SimpleNode sn, int num) throws Exception { return null; } public SimpleNode openNode(int id) { switch (id) { case ITreeConstants.JJTNAME: case ITreeConstants.JJTDOTTED_NAME: //If null is returned here, we may have an NPE. return nameConstant; } return null; } public SimpleNode getLastOpened() { return null; } }
epl-1.0
ModelWriter/Source
plugins/eu.modelwriter.semantic.parser/src/synalp/commons/grammar/Grammar.java
10008
package synalp.commons.grammar; import java.util.*; import synalp.commons.derivations.GornAddress; import synalp.commons.unification.FeatureConstant; /** * A LTAG grammar indexed by entry name. It also provides a way to access to entries by their family * name once the families cache has been computed. */ @SuppressWarnings("serial") public class Grammar extends HashMap<String, GrammarEntry> { private Map<String, Set<GrammarEntry>> families; // <family name, entries in family> /** * Prints on stdout the given grammar. * @param grammar */ public static void print(Grammar grammar) { print(grammar.values()); } /** * Prints on stdout the given grammar. * @param grammar */ public static void printShort(Grammar grammar) { printShort(grammar.values()); } /** * Prints on stdout the given entries. * @param entries */ public static void print(Collection<GrammarEntry> entries) { List<GrammarEntry> sorted = new ArrayList<GrammarEntry>(entries); sortByFamilies(sorted); for(GrammarEntry entry : sorted) System.out.println(entry + "\n"); } /** * Prints on stdout a short representation of the given entries. * @param entries */ public static void printShort(Collection<GrammarEntry> entries) { List<GrammarEntry> sorted = new ArrayList<GrammarEntry>(entries); sortByFamilies(sorted); for(GrammarEntry entry : sorted) System.out.println(entry.toShortString()); } /** * Prints on stdout a short representation of the given entries. * @param entries * @return the names of entries separated by spaces */ public static String printNames(Collection<GrammarEntry> entries) { List<GrammarEntry> sorted = new ArrayList<GrammarEntry>(entries); sortByFamilies(sorted); StringBuilder ret = new StringBuilder(); for(GrammarEntry entry : sorted) ret.append(entry.getName()).append(" "); return ret.toString().trim(); } /** * Sorts the given list of entries by the number of nodes their tree contains. * @param entries */ public static void sortByNames(List<GrammarEntry> entries) { Collections.sort(entries, new Comparator<GrammarEntry>() { @Override public int compare(GrammarEntry arg0, GrammarEntry arg1) { return arg0.getName().compareTo(arg1.getName()); } }); } /** * Sorts the given list of entries by the number of nodes their tree contains. * @param entries */ public static void sortByTreeSize(List<GrammarEntry> entries) { final Map<GrammarEntry, Integer> treeSizes = new HashMap<GrammarEntry, Integer>(); for(GrammarEntry entry : entries) treeSizes.put(entry, entry.getTree().getNodes().size()); Collections.sort(entries, new Comparator<GrammarEntry>() { @Override public int compare(GrammarEntry arg0, GrammarEntry arg1) { return treeSizes.get(arg0).compareTo(treeSizes.get(arg1)); } }); } /** * Sorts the given list of entries by their family names. * @param entries */ public static void sortByFamilies(List<GrammarEntry> entries) { Collections.sort(entries, new Comparator<GrammarEntry>() { @Override public int compare(GrammarEntry arg0, GrammarEntry arg1) { return arg0.getFamily().compareTo(arg1.getFamily()); } }); } /** * Sorts the given list of entries by their family names and tree size. * @param entries */ public static void sortByFamiliesAndTreeSize(List<GrammarEntry> entries) { final Map<GrammarEntry, Integer> treeSizes = new HashMap<GrammarEntry, Integer>(); for(GrammarEntry entry : entries) treeSizes.put(entry, entry.getTree().getNodes().size()); Collections.sort(entries, new Comparator<GrammarEntry>() { @Override public int compare(GrammarEntry arg0, GrammarEntry arg1) { int fam = arg0.getFamily().compareTo(arg1.getFamily()); if (fam == 0) return treeSizes.get(arg0).compareTo(treeSizes.get(arg1)); else return fam; } }); } /** * Returns the set of unique families given a collection of entries. * @param entries * @return a set of families names */ public static Set<String> getFamilies(Collection<GrammarEntry> entries) { Set<String> ret = new HashSet<String>(); for(GrammarEntry entry : entries) ret.add(entry.getFamily()); return ret; } /** * Returns the set of entries among given entries that do not have semantics. * @param entries * @return a set of entries with an empty semantics */ public static GrammarEntries getEmptySemanticsEntries(Collection<GrammarEntry> entries) { GrammarEntries ret = new GrammarEntries(); for(GrammarEntry entry : entries) if (entry.getSemantics().isEmpty()) ret.add(entry); return ret; } /** * Creates a new empty Grammar. */ public Grammar() { this.families = new HashMap<String, Set<GrammarEntry>>(); } /** * Adds the given entry to this Grammar. If the grammar already contains an entry with the same * name, it is overriden. * @param entry */ public void add(GrammarEntry entry) { put(entry.getName(), entry); } /** * Returns all the entries of this Grammar. Warning: this method creates a new GrammarEntries * instance, prefer this.values(). * @return entries of this Grammar */ public GrammarEntries getEntries() { return new GrammarEntries(values()); } /** * Returns the entries that belong to the given families. * @param families * @return a set of entries, empty set if no entries are found in the given family. */ public GrammarEntries getEntriesByFamilies(String... families) { GrammarEntries ret = new GrammarEntries(); for(String family : families) if (this.families.containsKey(family)) ret.addAll(this.families.get(family)); return ret; } /** * Returns the entries that are anchored by given category. * @param category * @return a set of entries */ public GrammarEntries getEntriesByAnchorCategory(FeatureConstant category) { return getEntriesByAnchorCategory(values(), category); } /** * Returns the entries from the given entries that are anchored by given category. * @param entries * @param category * @return a set of entries */ public static GrammarEntries getEntriesByAnchorCategory(Collection<GrammarEntry> entries, FeatureConstant category) { GrammarEntries ret = new GrammarEntries(); for(GrammarEntry entry : entries) if (entry.getTree().getMainAnchor().hasCategory(category)) ret.add(entry); return ret; } /** * Returns the entries of this Grammar that adjunct on the given category. * @param category * @return a set of entries */ public GrammarEntries getEntriesByFootCategory(FeatureConstant category) { return getEntriesByFootCategory(values(), category); } /** * Returns the entries from the given entries that adjunct on the given category. * @param entries * @param category * @return a set of entries */ public static GrammarEntries getEntriesByFootCategory(Collection<GrammarEntry> entries, FeatureConstant category) { GrammarEntries ret = new GrammarEntries(); for(GrammarEntry entry : entries) { Node foot = entry.getTree().getFoot(); if (foot != null && foot.hasCategory(category)) ret.add(entry); } return ret; } /** * Returns the auxiliaries entries from this Grammar given the foot category and the position of * foot with regards to anchor. * @param category * @param footType * @return a set of entries */ public GrammarEntries getEntriesByFoot(FeatureConstant category, FootType footType) { return getEntriesByFoot(values(), category, footType); } /** * Returns the auxiliaries entries from the given entries given the foot category and the * position of foot with regards to anchor. * @param entries * @param category * @param footType * @return a set of entries */ public static GrammarEntries getEntriesByFoot(Collection<GrammarEntry> entries, FeatureConstant category, FootType footType) { GrammarEntries ret = new GrammarEntries(); for(GrammarEntry entry : entries) { Node foot = entry.getTree().getFoot(); if (foot != null && foot.hasCategory(category)) { Node anchor = entry.getTree().getMainAnchor(); GornAddress footAddress = GornAddress.getAddress(foot, entry.getTree()); GornAddress anchorAddress = GornAddress.getAddress(anchor, entry.getTree()); boolean leftOf = footAddress.isLeftOf(anchorAddress); if (footType == FootType.LEFT && leftOf) ret.add(entry); if (footType == FootType.RIGHT && !leftOf) ret.add(entry); } } return ret; } /** * Returns the entries whose trace contains entirely the given trace. * @param trace * @return a set of entries */ public GrammarEntries getEntriesContainingTrace(Trace trace) { return getEntriesContainingTrace(values(), trace); } /** * Returns the entries from the given entries whose trace contains entirely the given trace. * @param entries * @param trace * @return a set of entries */ public static GrammarEntries getEntriesContainingTrace(Collection<GrammarEntry> entries, Trace trace) { GrammarEntries ret = new GrammarEntries(); for(GrammarEntry entry : entries) if (entry.getTrace().containsAll(trace)) ret.add(entry); return ret; } /** * Returns the whole set of categories used by this Grammar. Disjunctive categories are exploded * and returned as strings. * @return a set of strings */ public Set<String> getAllCategories() { Set<String> ret = new HashSet<String>(); for(GrammarEntry entry : values()) for(Node node : entry.getTree().getNodes()) ret.addAll(node.getCategory().getValues()); return ret; } public Map<String, Set<GrammarEntry>> getFamilies() { return families; } /** * Computes the families cache. */ public void computeFamiliesCache() { for(GrammarEntry entry : values()) { if (!families.containsKey(entry.getFamily())) families.put(entry.getFamily(), new HashSet<GrammarEntry>()); families.get(entry.getFamily()).add(entry); } } }
epl-1.0
rgladwell/m2e-android
me.gladwell.eclipse.m2e.android.test/src/me/gladwell/eclipse/m2e/android/test/FileMatchers.java
2328
/******************************************************************************* * Copyright (c) 2015 Ricardo Gladwell, Csaba Kozák * 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 me.gladwell.eclipse.m2e.android.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.eclipse.core.resources.IFile; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; public class FileMatchers { private FileMatchers() { } public static Matcher<IFile> containsString(final String expected) { return new BaseMatcher<IFile>() { @Override public boolean matches(Object target) { return getContents((IFile) target).contains(expected); } @Override public void describeTo(Description description) { description.appendText("file containing "); description.appendText(expected); } @Override public void describeMismatch(Object item, Description description) { description.appendText("was ").appendValue(item).appendText(" with content:\n") .appendText(getContents((IFile) item)); } }; } private static String getContents(IFile file) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(file.getContents())); StringBuilder builder = new StringBuilder(); while (reader.ready()) { String line = reader.readLine(); builder.append(line).append('\n'); } return builder.toString(); } catch (Exception e) { } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } return ""; } }
epl-1.0
sguan-actuate/birt
chart/org.eclipse.birt.chart.ui.extension/src/org/eclipse/birt/chart/ui/swt/composites/FillChooserComposite.java
39819
/*********************************************************************** * Copyright (c) 2004 Actuate 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: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.chart.ui.swt.composites; import java.text.MessageFormat; import java.util.Vector; import org.eclipse.birt.chart.model.attribute.AttributeFactory; import org.eclipse.birt.chart.model.attribute.ColorDefinition; import org.eclipse.birt.chart.model.attribute.Fill; import org.eclipse.birt.chart.model.attribute.Gradient; import org.eclipse.birt.chart.model.attribute.MultipleFill; import org.eclipse.birt.chart.model.attribute.PatternImage; import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl; import org.eclipse.birt.chart.ui.extension.i18n.Messages; import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext; import org.eclipse.birt.chart.ui.util.ChartUIUtil; import org.eclipse.birt.chart.ui.util.UIHelper; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.jface.window.Window; import org.eclipse.swt.SWT; import org.eclipse.swt.accessibility.ACC; import org.eclipse.swt.accessibility.AccessibleAdapter; import org.eclipse.swt.accessibility.AccessibleControlAdapter; import org.eclipse.swt.accessibility.AccessibleControlEvent; import org.eclipse.swt.accessibility.AccessibleEvent; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.ColorDialog; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Slider; /** * FillChooserComposite */ public class FillChooserComposite extends Composite implements SelectionListener, DisposeListener, Listener { private Composite cmpContentInner = null; private Composite cmpContentOuter = null; private Composite cmpDropDown = null; private Composite cmpButtons = null; private FillCanvas cnvSelection = null; private Button btnDown = null; private Label lblTransparency = null; private Slider srTransparency = null; private Button btnCustom = null; private Button btnGradient = null; private Button btnImage = null; private Button btnPN = null; private Button btnPatternFill; private Button btnReset = null; private Button btnAuto = null; private static Color[] colorArray = null; private boolean bGradientEnabled = true; private boolean bGradientAngleEnabled = true; private boolean bImageEnabled = true; private boolean bEmbeddedImageEnabled = true; private boolean bResourceImageEnabled = false; private boolean bTransparentEnabled = true; private boolean bAutoEnabled = false; private Fill fCurrent = null; private boolean bTransparencyChanged = false; /** It indicates if the transparency slider is visible. */ private boolean bTransparencySliderEnable = true; private boolean bPositiveNegativeEnabled = false; private boolean bPatternFillEnabled = true; private int iTransparency = 0; private Vector<Listener> vListeners = null; public static final int FILL_CHANGED_EVENT = 1; public static final int MOUSE_CLICKED_EVENT = 2; private boolean bEnabled = true; private int iSize = 18; private boolean bJustFocusLost = false; private ChartWizardContext wizardContext; // Indicates the last operation is fired by keyboard or not boolean isPressingKey = false; // Save the index of selected color private int selectedIndex = -1; public static final int ENABLE_GRADIENT = 1; public static final int ENABLE_IMAGE = 1 << 1; public static final int ENABLE_AUTO = 1 << 2; public static final int ENABLE_TRANSPARENT = 1 << 3; public static final int ENABLE_TRANSPARENT_SLIDER = 1 << 4; public static final int ENABLE_POSITIVE_NEGATIVE = 1 << 5; public static final int DISABLE_GRADIENT_ANGLE = 1 << 6; public static final int DISABLE_PATTERN_FILL = 1 << 7; public static final int DISABLE_EMBEDDED_IMAGE = 1 << 8; public static final int ENABLE_RESOURCE_IMAGE = 1 << 9; /** * @param parent * @param style * @param optionalStyle * @param wizardContext * @param fCurrent */ public FillChooserComposite( Composite parent, int style, int optionalStyle, ChartWizardContext wizardContext, Fill fCurrent ) { this( parent, style, wizardContext, fCurrent, ( ( ENABLE_GRADIENT & optionalStyle ) == ENABLE_GRADIENT ), ( ( ENABLE_IMAGE & optionalStyle ) == ENABLE_IMAGE ), ( ( ENABLE_AUTO & optionalStyle ) == ENABLE_AUTO ), ( ( ENABLE_TRANSPARENT & optionalStyle ) == ENABLE_TRANSPARENT ), ( ( ENABLE_POSITIVE_NEGATIVE & optionalStyle ) == ENABLE_POSITIVE_NEGATIVE ), !( ( DISABLE_PATTERN_FILL & optionalStyle ) == DISABLE_PATTERN_FILL ) ); this.bTransparencySliderEnable = ( ( ENABLE_TRANSPARENT_SLIDER & optionalStyle ) == ENABLE_TRANSPARENT_SLIDER ); this.bGradientAngleEnabled = !( ( DISABLE_GRADIENT_ANGLE & optionalStyle ) == DISABLE_GRADIENT_ANGLE ); this.bEmbeddedImageEnabled = !( ( DISABLE_EMBEDDED_IMAGE & optionalStyle ) == DISABLE_EMBEDDED_IMAGE ); this.bResourceImageEnabled = ( ENABLE_RESOURCE_IMAGE & optionalStyle ) == ENABLE_RESOURCE_IMAGE; } /** * * @param parent * @param style * @param wizardContext * @param fCurrent * If null, create a Fill using adapters from wizard context * @param bEnableGradient * @param bEnableImage * @param bEnableAuto * Indicates whether auto button will be displayed. * @param bEnableTransparent * Indicates whether transparent button will be displayed. */ public FillChooserComposite( Composite parent, int style, ChartWizardContext wizardContext, Fill fCurrent, boolean bEnableGradient, boolean bEnableImage, boolean bEnableAuto, boolean bEnableTransparent ) { super( parent, style ); this.fCurrent = fCurrent; this.bGradientEnabled = bEnableGradient; this.bImageEnabled = bEnableImage; this.bAutoEnabled = bEnableAuto; this.bTransparentEnabled = bEnableTransparent; this.wizardContext = wizardContext; this.bPatternFillEnabled = bEnableImage; init( ); placeComponents( ); initAccessible( ); } /** * * @param parent * @param style * @param wizardContext * @param fCurrent * If null, create a Fill using adapters from wizard context * @param bEnableGradient * @param bEnableImage */ public FillChooserComposite( Composite parent, int style, ChartWizardContext wizardContext, Fill fCurrent, boolean bEnableGradient, boolean bEnableImage ) { this( parent, style, wizardContext, fCurrent, bEnableGradient, bEnableImage, true ); } /** * * @param parent * @param style * @param wizardContext * @param fCurrent * If null, create a Fill using adapters from wizard context * @param bEnableGradient * @param bEnableImage */ public FillChooserComposite( Composite parent, int style, ChartWizardContext wizardContext, Fill fCurrent, boolean bEnableGradient, boolean bEnableImage, boolean bEnablePattern ) { super( parent, style ); this.fCurrent = fCurrent; this.bGradientEnabled = bEnableGradient; this.bImageEnabled = bEnableImage; this.bPatternFillEnabled = bEnablePattern; this.wizardContext = wizardContext; init( ); placeComponents( ); initAccessible( ); } /** * * @param parent * @param style * @param wizardContext * @param fCurrent * If null, create a Fill using adapters from wizard context * @param bEnableGradient * @param bEnableImage * @param bEnableAuto * Indicates whether auto button will be displayed. * @param bEnableTransparent * Indicates whether transparent button will be displayed. * @param bPositiveNegative * Indicates whether positive/negative button will be displayed. */ public FillChooserComposite( Composite parent, int style, ChartWizardContext wizardContext, Fill fCurrent, boolean bEnableGradient, boolean bEnableImage, boolean bEnableAuto, boolean bEnableTransparent, boolean bPositiveNegative, boolean bEnablePattern ) { super( parent, style ); this.fCurrent = fCurrent; this.bGradientEnabled = bEnableGradient; this.bImageEnabled = bEnableImage; this.bAutoEnabled = bEnableAuto; this.bTransparentEnabled = bEnableTransparent; this.bPositiveNegativeEnabled = bPositiveNegative; this.bPatternFillEnabled = bEnablePattern; this.wizardContext = wizardContext; init( ); placeComponents( ); initAccessible( ); } /** * */ private void init( ) { if ( Display.getCurrent( ).getHighContrast( ) ) { GC gc = new GC( this ); iSize = gc.getFontMetrics( ).getHeight( ) + 2; } this.setSize( getParent( ).getClientArea( ).width, getParent( ).getClientArea( ).height ); Display display = Display.getDefault( ); colorArray = this.createColorMap( display ); vListeners = new Vector<Listener>( ); } /** * */ private void placeComponents( ) { // THE LAYOUT OF THIS COMPOSITE (FILLS EVERYTHING INSIDE IT) FillLayout flMain = new FillLayout( ); flMain.marginHeight = 0; flMain.marginWidth = 0; setLayout( flMain ); // THE LAYOUT OF THE OUTER COMPOSITE (THAT GROWS VERTICALLY BUT ANCHORS // ITS CONTENT NORTH) cmpContentOuter = new Composite( this, SWT.NONE ); GridLayout glContentOuter = new GridLayout( ); glContentOuter.verticalSpacing = 0; glContentOuter.horizontalSpacing = 0; glContentOuter.marginHeight = 0; glContentOuter.marginWidth = 0; glContentOuter.numColumns = 1; cmpContentOuter.setLayout( glContentOuter ); // THE LAYOUT OF THE INNER COMPOSITE (ANCHORED NORTH AND ENCAPSULATES // THE CANVAS + BUTTON) cmpContentInner = new Composite( cmpContentOuter, SWT.BORDER ); GridLayout glContentInner = new GridLayout( ); glContentInner.verticalSpacing = 0; glContentInner.horizontalSpacing = 0; glContentInner.marginHeight = 0; glContentInner.marginWidth = 0; glContentInner.numColumns = 2; cmpContentInner.setLayout( glContentInner ); GridData gdContentInner = new GridData( GridData.FILL_HORIZONTAL ); cmpContentInner.setLayoutData( gdContentInner ); // THE CANVAS cnvSelection = new FillCanvas( cmpContentInner, SWT.NONE, this.bAutoEnabled, wizardContext == null ? null : wizardContext.getImageServiceProvider( ) ); cnvSelection.setTextIndent( 8 ); GridData gdCNVSelection = new GridData( GridData.FILL_BOTH ); gdCNVSelection.heightHint = iSize; cnvSelection.setLayoutData( gdCNVSelection ); initFill( ); // THE BUTTON btnDown = new Button( cmpContentInner, SWT.ARROW | SWT.DOWN ); GridData gdBDown = new GridData( GridData.FILL ); gdBDown.verticalAlignment = GridData.BEGINNING; gdBDown.widthHint = iSize - 2; gdBDown.heightHint = iSize; btnDown.setLayoutData( gdBDown ); btnDown.addSelectionListener( this ); addDisposeListener( this ); Listener listener = new Listener( ) { public void handleEvent( Event event ) { handleEventCanvas( event ); } }; int[] textEvents = { SWT.KeyDown, SWT.MouseDown, SWT.Traverse, SWT.FocusIn, SWT.FocusOut }; for ( int i = 0; i < textEvents.length; i++ ) { cnvSelection.addListener( textEvents[i], listener ); } } private void initFill( ) { if ( ( !this.bPatternFillEnabled && fCurrent instanceof PatternImage ) ) { cnvSelection.setFill( null ); } else { cnvSelection.setFill( fCurrent ); } } void handleEventCanvas( Event event ) { switch ( event.type ) { case SWT.FocusIn : { cnvSelection.redraw( ); break; } case SWT.FocusOut : { cnvSelection.redraw( ); break; } case SWT.KeyDown : { if ( event.keyCode == SWT.KEYPAD_CR || event.keyCode == SWT.CR || event.keyCode == ' ' ) { event.doit = true; toggleDropDown( ); } break; } case SWT.MouseDown : if ( !bEnabled ) { return; } // fireHandleEvent( MOUSE_CLICKED_EVENT ); toggleDropDown( ); break; case SWT.Traverse : { switch ( event.detail ) { case SWT.TRAVERSE_ESCAPE : getShell( ).close( ); break; case SWT.TRAVERSE_RETURN : case SWT.TRAVERSE_TAB_NEXT : case SWT.TRAVERSE_TAB_PREVIOUS : case SWT.TRAVERSE_ARROW_PREVIOUS : case SWT.TRAVERSE_ARROW_NEXT : event.doit = true; cnvSelection.redraw( ); } break; } } } private Color[] createColorMap( Display display ) { return new Color[]{ new Color( display, 0, 0, 0 ), new Color( display, 154, 50, 0 ), new Color( display, 51, 51, 0 ), new Color( display, 0, 50, 0 ), new Color( display, 0, 50, 100 ), new Color( display, 0, 0, 128 ), new Color( display, 51, 51, 153 ), new Color( display, 51, 51, 51 ), new Color( display, 128, 0, 0 ), new Color( display, 255, 102, 0 ), new Color( display, 124, 124, 0 ), new Color( display, 0, 128, 0 ), new Color( display, 0, 128, 128 ), new Color( display, 0, 0, 255 ), new Color( display, 102, 102, 153 ), new Color( display, 128, 128, 128 ), new Color( display, 255, 0, 0 ), new Color( display, 255, 153, 0 ), new Color( display, 154, 204, 0 ), new Color( display, 51, 153, 102 ), new Color( display, 51, 204, 204 ), new Color( display, 51, 102, 255 ), new Color( display, 128, 0, 128 ), new Color( display, 145, 145, 145 ), new Color( display, 255, 0, 255 ), new Color( display, 255, 204, 0 ), new Color( display, 255, 255, 0 ), new Color( display, 0, 255, 0 ), new Color( display, 0, 255, 255 ), new Color( display, 0, 204, 255 ), new Color( display, 154, 50, 102 ), new Color( display, 192, 192, 192 ), new Color( display, 253, 153, 204 ), new Color( display, 255, 204, 153 ), new Color( display, 255, 255, 153 ), new Color( display, 204, 255, 204 ), new Color( display, 204, 255, 255 ), new Color( display, 153, 204, 255 ), new Color( display, 204, 153, 255 ), new Color( display, 255, 255, 255 ) }; } /** * */ private void createDropDownComponent( int iXLoc, int iYLoc ) { if ( !bEnabled ) { return; } int iShellHeight = 170; int iShellWidth = 190; // Reduce the height based on which buttons are to be shown. if ( bGradientEnabled ) { iShellHeight += 30; } if ( bImageEnabled ) { iShellHeight += 30; } if ( bAutoEnabled ) { iShellHeight += 30; } if ( bTransparentEnabled ) { iShellHeight += 30; } if ( bPositiveNegativeEnabled ) { iShellHeight += 30; } if ( bPatternFillEnabled ) { iShellHeight += 30; } Shell shell = new Shell( this.getShell( ), SWT.NO_FOCUS ); shell.setLayout( new FillLayout( ) ); shell.setSize( iShellWidth, iShellHeight ); if ( ( getStyle( ) & SWT.RIGHT_TO_LEFT ) != 0 ) { iXLoc -= iShellWidth; } shell.setLocation( iXLoc, iYLoc ); shell.addShellListener( new ShellAdapter( ) { @Override public void shellClosed( ShellEvent e ) { clearColorSelection( ); } } ); cmpDropDown = new Composite( shell, SWT.NO_FOCUS ); GridLayout glDropDown = new GridLayout( ); glDropDown.marginHeight = 2; glDropDown.marginWidth = 2; glDropDown.horizontalSpacing = 1; glDropDown.verticalSpacing = 4; cmpDropDown.setLayout( glDropDown ); if ( colorArray == null ) { colorArray = createColorMap( getDisplay( ) ); } ColorSelectionCanvas cnv = new ColorSelectionCanvas( cmpDropDown, SWT.BORDER, colorArray ); GridData gdCnv = new GridData( GridData.FILL_BOTH ); gdCnv.widthHint = 190; gdCnv.heightHint = 110; cnv.setLayoutData( gdCnv ); cnv.addListener( SWT.Traverse, this ); cnv.addListener( SWT.FocusOut, this ); if ( this.fCurrent instanceof ColorDefinition ) { cnv.setColor( new Color( this.getDisplay( ), ( (ColorDefinition) fCurrent ).getRed( ), ( (ColorDefinition) fCurrent ).getGreen( ), ( (ColorDefinition) fCurrent ).getBlue( ) ) ); } cmpButtons = new Composite( cmpDropDown, SWT.NO_FOCUS ); GridLayout glButtons = new GridLayout( ); glButtons.marginHeight = 3; glButtons.marginWidth = 4; glButtons.horizontalSpacing = 1; glButtons.verticalSpacing = 4; glButtons.numColumns = 2; cmpButtons.setLayout( glButtons ); GridData gdButtons = new GridData( GridData.FILL_HORIZONTAL ); cmpButtons.setLayoutData( gdButtons ); // Layout for Transparency Composite GridLayout glTransparency = new GridLayout( ); glTransparency.numColumns = 1; glTransparency.horizontalSpacing = 5; glTransparency.verticalSpacing = 3; glTransparency.marginHeight = 4; glTransparency.marginWidth = 0; Composite cmpTransparency = new Composite( cmpButtons, SWT.NONE | SWT.NO_FOCUS ); GridData gdTransparency = new GridData( GridData.FILL_BOTH ); gdTransparency.horizontalSpan = 2; cmpTransparency.setLayoutData( gdTransparency ); cmpTransparency.setLayout( glTransparency ); if ( bTransparencySliderEnable ) { lblTransparency = new Label( cmpTransparency, SWT.NONE ); GridData gdLBLTransparency = new GridData( GridData.FILL_HORIZONTAL ); gdLBLTransparency.horizontalIndent = 2; lblTransparency.setLayoutData( gdLBLTransparency ); lblTransparency.setText( Messages.getString( "FillChooserComposite.Lbl.Opacity" ) ); //$NON-NLS-1$ srTransparency = new Slider( cmpTransparency, SWT.HORIZONTAL | SWT.NO_FOCUS ); GridData gdTransparent = new GridData( GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL ); gdTransparent.horizontalSpan = 2; srTransparency.setLayoutData( gdTransparent ); if ( fCurrent == null ) { srTransparency.setValues( 0, 0, 256, 1, 1, 10 ); srTransparency.setEnabled( false ); } else { int iValue = 0; if ( fCurrent instanceof ColorDefinition ) { iValue = ( (ColorDefinition) fCurrent ).getTransparency( ); srTransparency.setValues( iValue, 0, 256, 1, 1, 10 ); } else if ( fCurrent instanceof Gradient ) { iValue = ( (Gradient) fCurrent ).getTransparency( ); srTransparency.setValues( iValue, 0, 256, 1, 1, 10 ); } else { srTransparency.setEnabled( false ); } } lblTransparency.setText( new MessageFormat( Messages.getString( "FillChooserComposite.Lbl.Opacity" ) ) //$NON-NLS-1$ .format( new Object[]{ Integer.valueOf( srTransparency.getSelection( ) ) } ) ); srTransparency.setToolTipText( String.valueOf( srTransparency.getSelection( ) ) ); srTransparency.addSelectionListener( this ); srTransparency.addListener( SWT.FocusOut, this ); srTransparency.addListener( SWT.KeyDown, this ); srTransparency.addListener( SWT.Traverse, this ); } final int BUTTON_HEIGHTHINT = 28; if ( this.bTransparentEnabled ) { btnReset = new Button( cmpButtons, SWT.NONE ); GridData gdReset = new GridData( GridData.FILL_BOTH ); gdReset.heightHint = BUTTON_HEIGHTHINT; gdReset.horizontalSpan = 2; btnReset.setLayoutData( gdReset ); btnReset.setText( Messages.getString( "FillChooserComposite.Lbl.Transparent" ) ); //$NON-NLS-1$ btnReset.addSelectionListener( this ); btnReset.addListener( SWT.FocusOut, this ); btnReset.addListener( SWT.KeyDown, this ); btnReset.addListener( SWT.Traverse, this ); } if ( this.bAutoEnabled ) { btnAuto = new Button( cmpButtons, SWT.NONE ); GridData gdGradient = new GridData( GridData.FILL_BOTH ); gdGradient.heightHint = BUTTON_HEIGHTHINT; gdGradient.horizontalSpan = 2; btnAuto.setLayoutData( gdGradient ); btnAuto.setText( Messages.getString( "FillChooserComposite.Lbl.Auto" ) ); //$NON-NLS-1$ btnAuto.addSelectionListener( this ); btnAuto.addListener( SWT.FocusOut, this ); btnAuto.addListener( SWT.KeyDown, this ); btnAuto.addListener( SWT.Traverse, this ); } if ( this.bGradientEnabled ) { btnGradient = new Button( cmpButtons, SWT.NONE ); GridData gdGradient = new GridData( GridData.FILL_BOTH ); gdGradient.heightHint = BUTTON_HEIGHTHINT; gdGradient.horizontalSpan = 2; btnGradient.setLayoutData( gdGradient ); btnGradient.setText( Messages.getString( "FillChooserComposite.Lbl.Gradient" ) ); //$NON-NLS-1$ btnGradient.addSelectionListener( this ); btnGradient.addListener( SWT.FocusOut, this ); btnGradient.addListener( SWT.KeyDown, this ); btnGradient.addListener( SWT.Traverse, this ); } btnCustom = new Button( cmpButtons, SWT.NONE ); GridData gdCustom = new GridData( GridData.FILL_BOTH ); gdCustom.heightHint = BUTTON_HEIGHTHINT; gdCustom.horizontalSpan = 2; btnCustom.setLayoutData( gdCustom ); btnCustom.setText( Messages.getString( "FillChooserComposite.Lbl.CustomColor" ) ); //$NON-NLS-1$ btnCustom.addSelectionListener( this ); btnCustom.addListener( SWT.FocusOut, this ); btnCustom.addListener( SWT.KeyDown, this ); btnCustom.addListener( SWT.Traverse, this ); if ( this.bImageEnabled ) { btnImage = new Button( cmpButtons, SWT.NONE ); GridData gdImage = new GridData( GridData.FILL_BOTH ); gdImage.heightHint = BUTTON_HEIGHTHINT; gdImage.horizontalSpan = 2; btnImage.setLayoutData( gdImage ); btnImage.setText( Messages.getString( "FillChooserComposite.Lbl.Image" ) ); //$NON-NLS-1$ btnImage.addSelectionListener( this ); btnImage.addListener( SWT.FocusOut, this ); btnImage.addListener( SWT.KeyDown, this ); btnImage.addListener( SWT.Traverse, this ); } if ( this.bPositiveNegativeEnabled ) { btnPN = new Button( cmpButtons, SWT.NONE ); GridData gdPN = new GridData( GridData.FILL_BOTH ); gdPN.heightHint = BUTTON_HEIGHTHINT; gdPN.horizontalSpan = 2; btnPN.setLayoutData( gdPN ); btnPN.setText( Messages.getString( "FillChooserComposite.Lbl.PositiveNegative" ) ); //$NON-NLS-1$ btnPN.addSelectionListener( this ); btnPN.addListener( SWT.FocusOut, this ); btnPN.addListener( SWT.KeyDown, this ); btnPN.addListener( SWT.Traverse, this ); } if ( bPatternFillEnabled ) { btnPatternFill = new Button( cmpButtons, SWT.NONE ); GridData gd = new GridData( GridData.FILL_BOTH ); gd.heightHint = BUTTON_HEIGHTHINT; gd.horizontalSpan = 2; btnPatternFill.setLayoutData( gd ); btnPatternFill.setText( Messages.getString( "FillChooserComposite.Button.Pattern" ) ); //$NON-NLS-1$ btnPatternFill.addSelectionListener( this ); btnPatternFill.addListener( SWT.FocusOut, this ); btnPatternFill.addListener( SWT.KeyDown, this ); btnPatternFill.addListener( SWT.Traverse, this ); } shell.pack( ); shell.layout( ); shell.open( ); } public void setFill( Fill fill ) { fCurrent = fill; cnvSelection.setFill( fill ); cnvSelection.redraw( ); } public Fill getFill( ) { return this.fCurrent; } @Override public void setEnabled( boolean bState ) { btnDown.setEnabled( bState ); cnvSelection.setEnabled( bState ); cnvSelection.redraw( ); this.bEnabled = bState; } @Override public boolean isEnabled( ) { return this.bEnabled; } public Point getPreferredSize( ) { return new Point( 160, 24 ); } public void addListener( Listener listener ) { vListeners.add( listener ); } private void toggleDropDown( ) { // fix for Linux, since it not send the event correctly to other than // current shell. if ( bJustFocusLost ) { bJustFocusLost = false; return; } if ( cmpDropDown == null || cmpDropDown.isDisposed( ) || !cmpDropDown.isVisible( ) ) { Point pLoc = UIHelper.getScreenLocation( cnvSelection ); createDropDownComponent( pLoc.x, pLoc.y + cnvSelection.getSize( ).y + 1 ); cmpDropDown.setFocus( ); } else { cmpDropDown.getShell( ).close( ); } } /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt * .events.SelectionEvent) */ public void widgetSelected( SelectionEvent e ) { Object oSource = e.getSource( ); if ( oSource.equals( btnDown ) ) { fireHandleEvent( MOUSE_CLICKED_EVENT ); toggleDropDown( ); } else if ( oSource.equals( this.btnImage ) ) { ImageDialog idlg = (ImageDialog) wizardContext.getUIFactory( ) .createChartImageDialog( this.getShell( ), fCurrent, wizardContext, bEmbeddedImageEnabled,bResourceImageEnabled ); cmpDropDown.getShell( ).close( ); if ( idlg.open( ) == Window.OK ) { Fill imgFill = idlg.getResult( ); if ( imgFill != null ) { addAdapters( imgFill ); this.setFill( imgFill ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } } } else if ( oSource.equals( this.btnPN ) ) { PositiveNegativeColorDialog pncd = null; cmpDropDown.getShell( ).close( ); if ( fCurrent instanceof MultipleFill ) { pncd = new PositiveNegativeColorDialog( this.getShell( ), wizardContext, (MultipleFill) fCurrent ); } else if ( fCurrent instanceof ColorDefinition ) { ColorDefinition newCD = ( (ColorDefinition) fCurrent ).copyInstance( ); newCD.eAdapters( ).addAll( fCurrent.eAdapters( ) ); pncd = new PositiveNegativeColorDialog( this.getShell( ), wizardContext, null, newCD ); } else { pncd = new PositiveNegativeColorDialog( this.getShell( ), wizardContext, null ); } if ( pncd.open( ) == Window.OK ) { Fill fTmp = pncd.getMultipleColor( ); addAdapters( fTmp ); if ( fCurrent == null || !( fCurrent.equals( fTmp ) ) ) { this.setFill( fTmp ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } } } else if ( oSource == btnPatternFill ) { PatternImageEditorDialog dialog = new PatternImageEditorDialog( getShell( ), fCurrent ); cmpDropDown.getShell( ).close( ); if ( dialog.open( ) == Window.OK ) { Fill fTmp = dialog.getPatternImage( ); addAdapters( fTmp ); this.setFill( dialog.getPatternImage( ) ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } } else if ( oSource.equals( this.btnReset ) ) { this.setFill( ColorDefinitionImpl.TRANSPARENT( ) ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); cmpDropDown.getShell( ).close( ); } else if ( oSource.equals( this.btnAuto ) ) { setFill( null ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); cmpDropDown.getShell( ).close( ); } else if ( oSource.equals( this.btnCustom ) ) { ColorDialog cDlg = new ColorDialog( this.getShell( ), SWT.APPLICATION_MODAL ); cmpDropDown.getShell( ).close( ); int iTrans = 255; if ( fCurrent instanceof ColorDefinition ) { if ( !fCurrent.equals( ColorDefinitionImpl.TRANSPARENT( ) ) ) { iTransparency = ( (ColorDefinition) fCurrent ).getTransparency( ); } cDlg.setRGB( new RGB( ( (ColorDefinition) this.fCurrent ).getRed( ), ( (ColorDefinition) this.fCurrent ).getGreen( ), ( (ColorDefinition) this.fCurrent ).getBlue( ) ) ); } RGB rgb = cDlg.open( ); if ( rgb != null ) { ColorDefinition cdNew = AttributeFactory.eINSTANCE.createColorDefinition( ); cdNew.set( rgb.red, rgb.green, rgb.blue ); cdNew.setTransparency( bTransparencyChanged ? this.iTransparency : iTrans ); addAdapters( cdNew ); this.setFill( cdNew ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } } else if ( oSource.equals( this.btnGradient ) ) { GradientEditorDialog ged = null; cmpDropDown.getShell( ).close( ); if ( fCurrent instanceof Gradient ) { ged = new GradientEditorDialog( this.getShell( ), wizardContext, (Gradient) fCurrent, bGradientAngleEnabled ); } else if ( fCurrent instanceof ColorDefinition ) { ColorDefinition newCD = (ColorDefinition) fCurrent.copyInstance( ); newCD.eAdapters( ).addAll( fCurrent.eAdapters( ) ); ged = new GradientEditorDialog( this.getShell( ), wizardContext, newCD, bGradientAngleEnabled ); } else { ged = new GradientEditorDialog( this.getShell( ), wizardContext, ColorDefinitionImpl.create( 0, 0, 254 ), bGradientAngleEnabled ); } if ( ged.open( ) == Window.OK ) { Fill fTmp = ged.getGradient( ); addAdapters( fTmp ); if ( fCurrent == null || !( fCurrent.equals( fTmp ) ) ) { this.setFill( fTmp ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } } } else if ( oSource.equals( srTransparency ) ) { iTransparency = srTransparency.getSelection( ); lblTransparency.setText( new MessageFormat( Messages.getString( "FillChooserComposite.Lbl.Opacity" ) ) //$NON-NLS-1$ .format( new Object[]{ Integer.valueOf( srTransparency.getSelection( ) ) } ) ); srTransparency.setToolTipText( String.valueOf( srTransparency.getSelection( ) ) ); if ( fCurrent instanceof ColorDefinition ) { ( (ColorDefinition) fCurrent ).setTransparency( srTransparency.getSelection( ) ); } setFill( fCurrent ); bTransparencyChanged = true; fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } } /* * (non-Javadoc) * * @see * org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse * .swt.events.SelectionEvent) */ public void widgetDefaultSelected( SelectionEvent e ) { } private void fireHandleEvent( int iType ) { for ( int iL = 0; iL < vListeners.size( ); iL++ ) { Event se = new Event( ); se.widget = this; se.data = fCurrent; se.type = iType; vListeners.get( iL ).handleEvent( se ); } } /* * (non-Javadoc) * * @see * org.eclipse.swt.events.DisposeListener#widgetDisposed(org.eclipse.swt * .events.DisposeEvent) */ public void widgetDisposed( DisposeEvent e ) { if ( colorArray != null ) { for ( int iC = 0; iC < colorArray.length; iC++ ) { colorArray[iC].dispose( ); } colorArray = null; } } private boolean isPopupControl( Object control ) { return control != null && control instanceof Control && ( (Control) control ).getShell( ) == cmpDropDown.getShell( ); } private void addAdapters( Notifier notifier ) { if ( wizardContext != null ) { notifier.eAdapters( ) .addAll( wizardContext.getModel( ).eAdapters( ) ); } } void initAccessible( ) { getAccessible( ).addAccessibleListener( new AccessibleAdapter( ) { public void getHelp( AccessibleEvent e ) { e.result = getToolTipText( ); } } ); getAccessible( ).addAccessibleControlListener( new AccessibleControlAdapter( ) { public void getChildAtPoint( AccessibleControlEvent e ) { Point testPoint = toControl( new Point( e.x, e.y ) ); if ( getBounds( ).contains( testPoint ) ) { e.childID = ACC.CHILDID_SELF; } } public void getLocation( AccessibleControlEvent e ) { Rectangle location = getBounds( ); Point pt = toDisplay( new Point( location.x, location.y ) ); e.x = pt.x; e.y = pt.y; e.width = location.width; e.height = location.height; } public void getChildCount( AccessibleControlEvent e ) { e.detail = 0; } public void getRole( AccessibleControlEvent e ) { e.detail = ACC.ROLE_COMBOBOX; } public void getState( AccessibleControlEvent e ) { e.detail = ACC.STATE_NORMAL; } } ); ChartUIUtil.addScreenReaderAccessibility( this, cnvSelection ); } public void handleEvent( Event event ) { switch ( event.type ) { case SWT.FocusOut : if ( event.widget instanceof ColorSelectionCanvas ) { ( (ColorSelectionCanvas) event.widget ).redraw( ); } if ( isPopupControl( event.widget ) ) { Control cTmp = isPressingKey ? getDisplay( ).getFocusControl( ) : getDisplay( ).getCursorControl( ); // Set default value back isPressingKey = false; if ( cTmp != null ) { // Condition added to handle behavior under Linux if ( isPopupControl( cTmp ) || SWT.getPlatform( ).indexOf( "win32" ) == 0//$NON-NLS-1$ && ( cTmp.equals( cnvSelection ) || cTmp.equals( btnDown ) ) ) { return; } if ( cTmp.equals( cnvSelection ) || cTmp.equals( btnDown ) ) { bJustFocusLost = true; } } cmpDropDown.getShell( ).close( ); } break; case SWT.KeyDown : if ( cmpDropDown != null && !cmpDropDown.getShell( ).isDisposed( ) ) { if ( event.keyCode == SWT.ARROW_UP ) { cmpDropDown.getShell( ).close( ); } else if ( event.keyCode == SWT.CR || event.keyCode == SWT.KEYPAD_CR ) { if ( srTransparency != null ) { this.iTransparency = srTransparency.getSelection( ); } if ( fCurrent instanceof ColorDefinition && bTransparencyChanged ) { ( (ColorDefinition) fCurrent ).setTransparency( this.iTransparency ); } this.setFill( fCurrent ); cmpDropDown.getShell( ).close( ); } } break; case SWT.Traverse : switch ( event.detail ) { case SWT.TRAVERSE_TAB_NEXT : case SWT.TRAVERSE_TAB_PREVIOUS : // Indicates getting focus control rather than cursor // control isPressingKey = true; event.doit = true; } break; } } private void setColorToModel( Color clrTmp ) { ColorDefinition cTmp = AttributeFactory.eINSTANCE.createColorDefinition( ); cTmp.set( clrTmp.getRed( ), clrTmp.getGreen( ), clrTmp.getBlue( ) ); int iTransparency = 255; if ( fCurrent instanceof ColorDefinition && this.iTransparency != 0 ) { iTransparency = ( bTransparencyChanged ) ? this.iTransparency : ( (ColorDefinition) fCurrent ).getTransparency( ); } cTmp.setTransparency( iTransparency ); addAdapters( cTmp ); setFill( cTmp ); fireHandleEvent( FillChooserComposite.FILL_CHANGED_EVENT ); } private void clearColorSelection( ) { selectedIndex = -1; } /** * Sets text indent of fill canvas. * * @param indent */ public void setTextIndent( int indent ) { if ( this.cnvSelection != null ) { this.cnvSelection.setTextIndent( indent ); } } private class ColorSelectionCanvas extends Canvas implements Listener { static final int ROW_SIZE = 8; static final int COLUMN_SIZE = 5; final Color[] colorMap; Color colorSelection = null; public ColorSelectionCanvas( Composite parent, int iStyle, final Color[] colorMap ) { super( parent, iStyle ); this.colorMap = colorMap; this.addListener( SWT.Paint, this ); this.addListener( SWT.KeyDown, this ); this.addListener( SWT.MouseDown, this ); this.addListener( SWT.FocusIn, this ); } // public Color getColor( ) // { // return colorSelection; // } public void setColor( Color color ) { this.colorSelection = color; } void paintControl( PaintEvent pe ) { Color cBlack = new Color( this.getDisplay( ), 0, 0, 0 ); Color cWhite = new Color( this.getDisplay( ), 255, 255, 255 ); GC gc = pe.gc; gc.setForeground( cBlack ); int iCellWidth = this.getSize( ).x / ROW_SIZE; int iCellHeight = this.getSize( ).y / COLUMN_SIZE; boolean isFound = false; for ( int iR = 0; iR < COLUMN_SIZE; iR++ ) { for ( int iC = 0; iC < ROW_SIZE; iC++ ) { int index = iR * ROW_SIZE + iC; try { gc.setBackground( colorMap[index] ); } catch ( Throwable e ) { e.printStackTrace( ); } gc.fillRectangle( iC * iCellWidth, iR * iCellHeight, iCellWidth, iCellHeight ); // Highlight currently selected color if it exists in this // list if ( selectedIndex == index || !isFound && colorSelection != null && colorSelection.equals( colorMap[index] ) ) { isFound = true; selectedIndex = index; if ( colorSelection == null ) { colorSelection = colorMap[index]; } if ( isFocusControl( ) ) { gc.setLineStyle( SWT.LINE_DOT ); } gc.drawRectangle( iC * iCellWidth, iR * iCellHeight, iCellWidth - 2, iCellHeight - 2 ); gc.setForeground( cWhite ); gc.drawRectangle( iC * iCellWidth + 1, iR * iCellHeight + 1, iCellWidth - 3, iCellHeight - 3 ); gc.setForeground( cBlack ); } } } if ( !isFound ) { clearColorSelection( ); } cBlack.dispose( ); cWhite.dispose( ); gc.dispose( ); } /** * This method assumes a color array of 40 color arranged with equal * sizes in a 8x5 grid. * * @param x * @param y */ public Color getColorAt( int x, int y ) { int iCellWidth = this.getSize( ).x / 8; int iCellHeight = this.getSize( ).y / 5; int iHCell = x / iCellWidth; int iVCell = y / iCellHeight; int iArrayIndex = ( ( iVCell ) * 8 ) + iHCell; return this.colorMap[iArrayIndex]; } public void handleEvent( Event event ) { switch ( event.type ) { case SWT.Paint : paintControl( new PaintEvent( event ) ); break; case SWT.FocusIn : redraw( ); break; case SWT.KeyDown : keyDown( event ); break; case SWT.MouseDown : if ( !bEnabled ) { return; } fireHandleEvent( MOUSE_CLICKED_EVENT ); setColorToModel( this.getColorAt( event.x, event.y ) ); cmpDropDown.getShell( ).close( ); break; } } void keyDown( Event event ) { if ( event.keyCode == SWT.ESC ) { cmpDropDown.getShell( ).close( ); return; } if ( selectedIndex == -1 ) { if ( event.keyCode == SWT.ARROW_LEFT || event.keyCode == SWT.ARROW_RIGHT || event.keyCode == SWT.ARROW_UP || event.keyCode == SWT.ARROW_DOWN ) { selectedIndex = 0; } } else { switch ( event.keyCode ) { case SWT.ARROW_LEFT : if ( selectedIndex - 1 >= 0 ) { selectedIndex -= 1; } break; case SWT.ARROW_RIGHT : if ( selectedIndex + 1 < ROW_SIZE * COLUMN_SIZE ) { selectedIndex += 1; } break; case SWT.ARROW_UP : if ( selectedIndex - ROW_SIZE >= 0 ) { selectedIndex -= ROW_SIZE; } break; case SWT.ARROW_DOWN : if ( selectedIndex + ROW_SIZE < ROW_SIZE * COLUMN_SIZE ) { selectedIndex += ROW_SIZE; } break; case SWT.CR : case SWT.KEYPAD_CR : setColorToModel( colorMap[selectedIndex] ); cmpDropDown.getShell( ).close( ); break; } } if ( !cmpDropDown.isDisposed( ) ) { colorSelection = null; redraw( ); } } } public void addScreenReaderAccessibility( String description ) { ChartUIUtil.addScreenReaderAccessbility( cnvSelection, description ); } }
epl-1.0
openhab/openhab2
bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaCurtainHandler.java
1589
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.somfytahoma.internal.handler; import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.thing.Thing; /** * The {@link SomfyTahomaCurtainHandler} is responsible for handling commands, * which are sent to one of the channels of the curtain thing. * * @author Tobias Ammann - Initial contribution * @author Ondrej Pecta - Code optimization */ @NonNullByDefault public class SomfyTahomaCurtainHandler extends SomfyTahomaRollerShutterHandler { public SomfyTahomaCurtainHandler(Thing thing) { super(thing); } @Override protected String getTahomaCommand(String command) { switch (command) { case "OFF": case "DOWN": case "CLOSE": return COMMAND_CLOSE; case "ON": case "UP": case "OPEN": return COMMAND_OPEN; case "MOVE": case "MY": return COMMAND_MY; case "STOP": return COMMAND_STOP; default: return COMMAND_SET_CLOSURE; } } }
epl-1.0
theanuradha/debrief
org.mwc.debrief.satc.core/src/com/planetmayo/debrief/satc_rcp/ui/contributions/StraightLegForecastContributionView.java
1654
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package com.planetmayo.debrief.satc_rcp.ui.contributions; import org.eclipse.core.databinding.DataBindingContext; import org.eclipse.swt.widgets.Composite; import com.planetmayo.debrief.satc.model.contributions.StraightLegForecastContribution; import com.planetmayo.debrief.satc.model.generator.IContributions; public class StraightLegForecastContributionView extends BaseContributionView<StraightLegForecastContribution> { public StraightLegForecastContributionView(Composite parent, StraightLegForecastContribution contribution, IContributions contributions) { super(parent, contribution, contributions); initUI(); } @Override protected void createLimitAndEstimateSliders() { } @Override protected String getTitlePrefix() { return "Straight Leg Forecast - "; } @Override protected void bindValues(DataBindingContext context) { bindCommonHeaderWidgets(context, null, null, null); bindCommonDates(context); } @Override protected void initializeWidgets() { hardConstraintLabel.setText("n/a"); estimateLabel.setText("n/a"); } }
epl-1.0
Mark-Booth/daq-eclipse
uk.ac.diamond.org.apache.activemq/org/apache/activemq/security/SecurityAdminMBean.java
1545
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.security; /** * An MBean for adding and removing users, roles * and destinations. * * */ public interface SecurityAdminMBean { String OPERATION_READ = "read"; String OPERATION_WRITE = "write"; String OPERATION_ADMIN = "admin"; void addRole(String role); void removeRole(String role); void addUserRole(String user, String role); void removeUserRole(String user, String role); void addTopicRole(String topic, String operation, String role); void removeTopicRole(String topic, String operation, String role); void addQueueRole(String queue, String operation, String role); void removeQueueRole(String queue, String operation, String role); }
epl-1.0
fabienjammet001/FormationRCP_new
com.sogeti.rental.rcp/src/com/sogeti/rental/rcp/Application.java
1268
package com.sogeti.rental.rcp; import org.eclipse.equinox.app.IApplication; import org.eclipse.equinox.app.IApplicationContext; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PlatformUI; /** * This class controls all aspects of the application's execution */ public class Application implements IApplication { /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext) */ public Object start(IApplicationContext context) throws Exception { Display display = PlatformUI.createDisplay(); try { int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor()); if (returnCode == PlatformUI.RETURN_RESTART) return IApplication.EXIT_RESTART; else return IApplication.EXIT_OK; } finally { display.dispose(); } } /* (non-Javadoc) * @see org.eclipse.equinox.app.IApplication#stop() */ public void stop() { if (!PlatformUI.isWorkbenchRunning()) return; final IWorkbench workbench = PlatformUI.getWorkbench(); final Display display = workbench.getDisplay(); display.syncExec(new Runnable() { public void run() { if (!display.isDisposed()) workbench.close(); } }); } }
gpl-2.0
georgenicoll/esper
esper/src/test/java/com/espertech/esper/support/bean/SupportBean.java
6195
/* * ************************************************************************************* * Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. * * http://www.espertech.com/esper * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.support.bean; import java.io.Serializable; import java.math.BigDecimal; public class SupportBean implements Serializable { private String theString; private boolean boolPrimitive; private int intPrimitive; private long longPrimitive; private char charPrimitive; private short shortPrimitive; private byte bytePrimitive; private float floatPrimitive; private double doublePrimitive; private Boolean boolBoxed; private Integer intBoxed; private Long longBoxed; private Character charBoxed; private Short shortBoxed; private Byte byteBoxed; private Float floatBoxed; private Double doubleBoxed; private BigDecimal bigDecimal; private SupportEnum enumValue; public SupportBean() { } public SupportBean(String theString, int intPrimitive) { this.theString = theString; this.intPrimitive = intPrimitive; } public String getTheString() { return theString; } public boolean isBoolPrimitive() { return boolPrimitive; } public int getIntPrimitive() { return intPrimitive; } public long getLongPrimitive() { return longPrimitive; } public char getCharPrimitive() { return charPrimitive; } public short getShortPrimitive() { return shortPrimitive; } public byte getBytePrimitive() { return bytePrimitive; } public float getFloatPrimitive() { return floatPrimitive; } public double getDoublePrimitive() { return doublePrimitive; } public Boolean getBoolBoxed() { return boolBoxed; } public Integer getIntBoxed() { return intBoxed; } public Long getLongBoxed() { return longBoxed; } public Character getCharBoxed() { return charBoxed; } public Short getShortBoxed() { return shortBoxed; } public Byte getByteBoxed() { return byteBoxed; } public Float getFloatBoxed() { return floatBoxed; } public Double getDoubleBoxed() { return doubleBoxed; } public void setTheString(String theString) { this.theString = theString; } public void setBoolPrimitive(boolean boolPrimitive) { this.boolPrimitive = boolPrimitive; } public void setIntPrimitive(int intPrimitive) { this.intPrimitive = intPrimitive; } public void setLongPrimitive(long longPrimitive) { this.longPrimitive = longPrimitive; } public void setCharPrimitive(char charPrimitive) { this.charPrimitive = charPrimitive; } public void setShortPrimitive(short shortPrimitive) { this.shortPrimitive = shortPrimitive; } public void setBytePrimitive(byte bytePrimitive) { this.bytePrimitive = bytePrimitive; } public void setFloatPrimitive(float floatPrimitive) { this.floatPrimitive = floatPrimitive; } public void setDoublePrimitive(double doublePrimitive) { this.doublePrimitive = doublePrimitive; } public void setBoolBoxed(Boolean boolBoxed) { this.boolBoxed = boolBoxed; } public void setIntBoxed(Integer intBoxed) { this.intBoxed = intBoxed; } public void setLongBoxed(Long longBoxed) { this.longBoxed = longBoxed; } public void setCharBoxed(Character charBoxed) { this.charBoxed = charBoxed; } public void setShortBoxed(Short shortBoxed) { this.shortBoxed = shortBoxed; } public void setByteBoxed(Byte byteBoxed) { this.byteBoxed = byteBoxed; } public void setFloatBoxed(Float floatBoxed) { this.floatBoxed = floatBoxed; } public void setDoubleBoxed(Double doubleBoxed) { this.doubleBoxed = doubleBoxed; } public SupportEnum getEnumValue() { return enumValue; } public void setEnumValue(SupportEnum enumValue) { this.enumValue = enumValue; } public SupportBean getThis() { return this; } public String toString() { return this.getClass().getSimpleName() + "(" + theString + ", " + intPrimitive + ")"; } public BigDecimal getBigDecimal() { return bigDecimal; } public void setBigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; } public static SupportBean[] getBeansPerIndex(SupportBean[] beans, int[] indexes) { if (indexes == null) { return null; } SupportBean[] array = new SupportBean[indexes.length]; for (int i = 0; i < indexes.length; i++) { array[i] = beans[indexes[i]]; } return array; } public static Object[] getOAStringAndIntPerIndex(SupportBean[] beans, int[] indexes) { SupportBean[] arr = getBeansPerIndex(beans, indexes); if (arr == null) { return null; } return toOAStringAndInt(arr); } private static Object[] toOAStringAndInt(SupportBean[] arr) { Object[][] values = new Object[arr.length][]; for (int i = 0; i < values.length; i++) { values[i] = new Object[] {arr[i].getTheString(), arr[i].getIntPrimitive()}; } return values; } }
gpl-2.0
JetBrains/jdk8u_jdk
src/share/classes/com/sun/security/sasl/digest/DigestMD5Client.java
27122
/* * Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.security.sasl.digest; import java.security.NoSuchAlgorithmException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.StringTokenizer; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Arrays; import java.util.logging.Level; import javax.security.sasl.*; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.Callback; import javax.security.auth.callback.UnsupportedCallbackException; /** * An implementation of the DIGEST-MD5 * (<a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a>) SASL * (<a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a>) mechanism. * * The DIGEST-MD5 SASL mechanism specifies two modes of authentication. * - Initial Authentication * - Subsequent Authentication - optional, (currently unsupported) * * Required callbacks: * - RealmChoiceCallback * shows user list of realms server has offered; handler must choose one * from list * - RealmCallback * shows user the only realm server has offered or none; handler must * enter realm to use * - NameCallback * handler must enter username to use for authentication * - PasswordCallback * handler must enter password for username to use for authentication * * Environment properties that affect behavior of implementation: * * javax.security.sasl.qop * quality of protection; list of auth, auth-int, auth-conf; default is "auth" * javax.security.sasl.strength * auth-conf strength; list of high, medium, low; default is highest * available on platform ["high,medium,low"]. * high means des3 or rc4 (128); medium des or rc4-56; low is rc4-40; * choice of cipher depends on its availablility on platform * javax.security.sasl.maxbuf * max receive buffer size; default is 65536 * javax.security.sasl.sendmaxbuffer * max send buffer size; default is 65536; (min with server max recv size) * * com.sun.security.sasl.digest.cipher * name a specific cipher to use; setting must be compatible with the * setting of the javax.security.sasl.strength property. * * @see <a href="http://www.ietf.org/rfc/rfc2222.txt">RFC 2222</a> * - Simple Authentication and Security Layer (SASL) * @see <a href="http://www.ietf.org/rfc/rfc2831.txt">RFC 2831</a> * - Using Digest Authentication as a SASL Mechanism * @see <a href="http://java.sun.com/products/jce">Java(TM) * Cryptography Extension 1.2.1 (JCE)</a> * @see <a href="http://java.sun.com/products/jaas">Java(TM) * Authentication and Authorization Service (JAAS)</a> * * @author Jonathan Bruce * @author Rosanna Lee */ final class DigestMD5Client extends DigestMD5Base implements SaslClient { private static final String MY_CLASS_NAME = DigestMD5Client.class.getName(); // Property for specifying cipher explicitly private static final String CIPHER_PROPERTY = "com.sun.security.sasl.digest.cipher"; /* Directives encountered in challenges sent by the server. */ private static final String[] DIRECTIVE_KEY = { "realm", // >= 0 times "qop", // atmost once; default is "auth" "algorithm", // exactly once "nonce", // exactly once "maxbuf", // atmost once; default is 65536 "charset", // atmost once; default is ISO 8859-1 "cipher", // exactly once if qop is "auth-conf" "rspauth", // exactly once in 2nd challenge "stale", // atmost once for in subsequent auth (not supported) }; /* Indices into DIRECTIVE_KEY */ private static final int REALM = 0; private static final int QOP = 1; private static final int ALGORITHM = 2; private static final int NONCE = 3; private static final int MAXBUF = 4; private static final int CHARSET = 5; private static final int CIPHER = 6; private static final int RESPONSE_AUTH = 7; private static final int STALE = 8; private int nonceCount; // number of times nonce has been used/seen /* User-supplied/generated information */ private String specifiedCipher; // cipher explicitly requested by user private byte[] cnonce; // client generated nonce private String username; private char[] passwd; private byte[] authzidBytes; // byte repr of authzid /** * Constructor for DIGEST-MD5 mechanism. * * @param authzid A non-null String representing the principal * for which authorization is being granted.. * @param digestURI A non-null String representing detailing the * combined protocol and host being used for authentication. * @param props The possibly null properties to be used by the SASL * mechanism to configure the authentication exchange. * @param cbh The non-null CallbackHanlder object for callbacks * @throws SaslException if no authentication ID or password is supplied */ DigestMD5Client(String authzid, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { super(props, MY_CLASS_NAME, 2, protocol + "/" + serverName, cbh); // authzID can only be encoded in UTF8 - RFC 2222 if (authzid != null) { this.authzid = authzid; try { authzidBytes = authzid.getBytes("UTF8"); } catch (UnsupportedEncodingException e) { throw new SaslException( "DIGEST-MD5: Error encoding authzid value into UTF-8", e); } } if (props != null) { specifiedCipher = (String)props.get(CIPHER_PROPERTY); logger.log(Level.FINE, "DIGEST60:Explicitly specified cipher: {0}", specifiedCipher); } } /** * DIGEST-MD5 has no initial response * * @return false */ public boolean hasInitialResponse() { return false; } /** * Process the challenge data. * * The server sends a digest-challenge which the client must reply to * in a digest-response. When the authentication is complete, the * completed field is set to true. * * @param challengeData A non-null byte array containing the challenge * data from the server. * @return A possibly null byte array containing the response to * be sent to the server. * * @throws SaslException If the platform does not have MD5 digest support * or if the server sends an invalid challenge. */ public byte[] evaluateChallenge(byte[] challengeData) throws SaslException { if (challengeData.length > MAX_CHALLENGE_LENGTH) { throw new SaslException( "DIGEST-MD5: Invalid digest-challenge length. Got: " + challengeData.length + " Expected < " + MAX_CHALLENGE_LENGTH); } /* Extract and process digest-challenge */ byte[][] challengeVal; switch (step) { case 2: /* Process server's first challenge (from Step 1) */ /* Get realm, qop, maxbuf, charset, algorithm, cipher, nonce directives */ List<byte[]> realmChoices = new ArrayList<byte[]>(3); challengeVal = parseDirectives(challengeData, DIRECTIVE_KEY, realmChoices, REALM); try { processChallenge(challengeVal, realmChoices); checkQopSupport(challengeVal[QOP], challengeVal[CIPHER]); ++step; return generateClientResponse(challengeVal[CHARSET]); } catch (SaslException e) { step = 0; clearPassword(); throw e; // rethrow } catch (IOException e) { step = 0; clearPassword(); throw new SaslException("DIGEST-MD5: Error generating " + "digest response-value", e); } case 3: try { /* Process server's step 3 (server response to digest response) */ /* Get rspauth directive */ challengeVal = parseDirectives(challengeData, DIRECTIVE_KEY, null, REALM); validateResponseValue(challengeVal[RESPONSE_AUTH]); /* Initialize SecurityCtx implementation */ if (integrity && privacy) { secCtx = new DigestPrivacy(true /* client */); } else if (integrity) { secCtx = new DigestIntegrity(true /* client */); } return null; // Mechanism has completed. } finally { clearPassword(); step = 0; // Set to invalid state completed = true; } default: // No other possible state throw new SaslException("DIGEST-MD5: Client at illegal state"); } } /** * Record information from the challengeVal array into variables/fields. * Check directive values that are multi-valued and ensure that mandatory * directives not missing from the digest-challenge. * * @throws SaslException if a sasl is a the mechanism cannot * correcly handle a callbacks or if a violation in the * digest challenge format is detected. */ private void processChallenge(byte[][] challengeVal, List<byte[]> realmChoices) throws SaslException, UnsupportedEncodingException { /* CHARSET: optional atmost once */ if (challengeVal[CHARSET] != null) { if (!"utf-8".equals(new String(challengeVal[CHARSET], encoding))) { throw new SaslException("DIGEST-MD5: digest-challenge format " + "violation. Unrecognised charset value: " + new String(challengeVal[CHARSET])); } else { encoding = "UTF8"; useUTF8 = true; } } /* ALGORITHM: required exactly once */ if (challengeVal[ALGORITHM] == null) { throw new SaslException("DIGEST-MD5: Digest-challenge format " + "violation: algorithm directive missing"); } else if (!"md5-sess".equals(new String(challengeVal[ALGORITHM], encoding))) { throw new SaslException("DIGEST-MD5: Digest-challenge format " + "violation. Invalid value for 'algorithm' directive: " + challengeVal[ALGORITHM]); } /* NONCE: required exactly once */ if (challengeVal[NONCE] == null) { throw new SaslException("DIGEST-MD5: Digest-challenge format " + "violation: nonce directive missing"); } else { nonce = challengeVal[NONCE]; } try { /* REALM: optional, if multiple, stored in realmChoices */ String[] realmTokens = null; if (challengeVal[REALM] != null) { if (realmChoices == null || realmChoices.size() <= 1) { // Only one realm specified negotiatedRealm = new String(challengeVal[REALM], encoding); } else { realmTokens = new String[realmChoices.size()]; for (int i = 0; i < realmTokens.length; i++) { realmTokens[i] = new String(realmChoices.get(i), encoding); } } } NameCallback ncb = authzid == null ? new NameCallback("DIGEST-MD5 authentication ID: ") : new NameCallback("DIGEST-MD5 authentication ID: ", authzid); PasswordCallback pcb = new PasswordCallback("DIGEST-MD5 password: ", false); if (realmTokens == null) { // Server specified <= 1 realm // If 0, RFC 2831: the client SHOULD solicit a realm from the user. RealmCallback tcb = (negotiatedRealm == null? new RealmCallback("DIGEST-MD5 realm: ") : new RealmCallback("DIGEST-MD5 realm: ", negotiatedRealm)); cbh.handle(new Callback[] {tcb, ncb, pcb}); /* Acquire realm from RealmCallback */ negotiatedRealm = tcb.getText(); if (negotiatedRealm == null) { negotiatedRealm = ""; } } else { RealmChoiceCallback ccb = new RealmChoiceCallback( "DIGEST-MD5 realm: ", realmTokens, 0, false); cbh.handle(new Callback[] {ccb, ncb, pcb}); // Acquire realm from RealmChoiceCallback int[] selected = ccb.getSelectedIndexes(); if (selected == null || selected[0] < 0 || selected[0] >= realmTokens.length) { throw new SaslException("DIGEST-MD5: Invalid realm chosen"); } negotiatedRealm = realmTokens[selected[0]]; } passwd = pcb.getPassword(); pcb.clearPassword(); username = ncb.getName(); } catch (SaslException se) { throw se; } catch (UnsupportedCallbackException e) { throw new SaslException("DIGEST-MD5: Cannot perform callback to " + "acquire realm, authentication ID or password", e); } catch (IOException e) { throw new SaslException( "DIGEST-MD5: Error acquiring realm, authentication ID or password", e); } if (username == null || passwd == null) { throw new SaslException( "DIGEST-MD5: authentication ID and password must be specified"); } /* MAXBUF: optional atmost once */ int srvMaxBufSize = (challengeVal[MAXBUF] == null) ? DEFAULT_MAXBUF : Integer.parseInt(new String(challengeVal[MAXBUF], encoding)); sendMaxBufSize = (sendMaxBufSize == 0) ? srvMaxBufSize : Math.min(sendMaxBufSize, srvMaxBufSize); } /** * Parses the 'qop' directive. If 'auth-conf' is specified by * the client and offered as a QOP option by the server, then a check * is client-side supported ciphers is performed. * * @throws IOException */ private void checkQopSupport(byte[] qopInChallenge, byte[] ciphersInChallenge) throws IOException { /* QOP: optional; if multiple, merged earlier */ String qopOptions; if (qopInChallenge == null) { qopOptions = "auth"; } else { qopOptions = new String(qopInChallenge, encoding); } // process String[] serverQopTokens = new String[3]; byte[] serverQop = parseQop(qopOptions, serverQopTokens, true /* ignore unrecognized tokens */); byte serverAllQop = combineMasks(serverQop); switch (findPreferredMask(serverAllQop, qop)) { case 0: throw new SaslException("DIGEST-MD5: No common protection " + "layer between client and server"); case NO_PROTECTION: negotiatedQop = "auth"; // buffer sizes not applicable break; case INTEGRITY_ONLY_PROTECTION: negotiatedQop = "auth-int"; integrity = true; rawSendSize = sendMaxBufSize - 16; break; case PRIVACY_PROTECTION: negotiatedQop = "auth-conf"; privacy = integrity = true; rawSendSize = sendMaxBufSize - 26; checkStrengthSupport(ciphersInChallenge); break; } if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "DIGEST61:Raw send size: {0}", new Integer(rawSendSize)); } } /** * Processes the 'cipher' digest-challenge directive. This allows the * mechanism to check for client-side support against the list of * supported ciphers send by the server. If no match is found, * the mechanism aborts. * * @throws SaslException If an error is encountered in processing * the cipher digest-challenge directive or if no client-side * support is found. */ private void checkStrengthSupport(byte[] ciphersInChallenge) throws IOException { /* CIPHER: required exactly once if qop=auth-conf */ if (ciphersInChallenge == null) { throw new SaslException("DIGEST-MD5: server did not specify " + "cipher to use for 'auth-conf'"); } // First determine ciphers that server supports String cipherOptions = new String(ciphersInChallenge, encoding); StringTokenizer parser = new StringTokenizer(cipherOptions, ", \t\n"); int tokenCount = parser.countTokens(); String token = null; byte[] serverCiphers = { UNSET, UNSET, UNSET, UNSET, UNSET }; String[] serverCipherStrs = new String[serverCiphers.length]; // Parse ciphers in challenge; mark each that server supports for (int i = 0; i < tokenCount; i++) { token = parser.nextToken(); for (int j = 0; j < CIPHER_TOKENS.length; j++) { if (token.equals(CIPHER_TOKENS[j])) { serverCiphers[j] |= CIPHER_MASKS[j]; serverCipherStrs[j] = token; // keep for replay to server logger.log(Level.FINE, "DIGEST62:Server supports {0}", token); } } } // Determine which ciphers are available on client byte[] clntCiphers = getPlatformCiphers(); // Take intersection of server and client supported ciphers byte inter = 0; for (int i = 0; i < serverCiphers.length; i++) { serverCiphers[i] &= clntCiphers[i]; inter |= serverCiphers[i]; } if (inter == UNSET) { throw new SaslException( "DIGEST-MD5: Client supports none of these cipher suites: " + cipherOptions); } // now have a clear picture of user / client; client / server // cipher options. Leverage strength array against what is // supported to choose a cipher. negotiatedCipher = findCipherAndStrength(serverCiphers, serverCipherStrs); if (negotiatedCipher == null) { throw new SaslException("DIGEST-MD5: Unable to negotiate " + "a strength level for 'auth-conf'"); } logger.log(Level.FINE, "DIGEST63:Cipher suite: {0}", negotiatedCipher); } /** * Steps through the ordered 'strength' array, and compares it with * the 'supportedCiphers' array. The cipher returned represents * the best possible cipher based on the strength preference and the * available ciphers on both the server and client environments. * * @param tokens The array of cipher tokens sent by server * @return The agreed cipher. */ private String findCipherAndStrength(byte[] supportedCiphers, String[] tokens) { byte s; for (int i = 0; i < strength.length; i++) { if ((s=strength[i]) != 0) { for (int j = 0; j < supportedCiphers.length; j++) { // If user explicitly requested cipher, then it // must be the one we choose if (s == supportedCiphers[j] && (specifiedCipher == null || specifiedCipher.equals(tokens[j]))) { switch (s) { case HIGH_STRENGTH: negotiatedStrength = "high"; break; case MEDIUM_STRENGTH: negotiatedStrength = "medium"; break; case LOW_STRENGTH: negotiatedStrength = "low"; break; } return tokens[j]; } } } } return null; // none found } /** * Returns digest-response suitable for an initial authentication. * * The following are qdstr-val (quoted string values) as per RFC 2831, * which means that any embedded quotes must be escaped. * realm-value * nonce-value * username-value * cnonce-value * authzid-value * @returns {@code digest-response} in a byte array * @throws SaslException if there is an error generating the * response value or the cnonce value. */ private byte[] generateClientResponse(byte[] charset) throws IOException { ByteArrayOutputStream digestResp = new ByteArrayOutputStream(); if (useUTF8) { digestResp.write("charset=".getBytes(encoding)); digestResp.write(charset); digestResp.write(','); } digestResp.write(("username=\"" + quotedStringValue(username) + "\",").getBytes(encoding)); if (negotiatedRealm.length() > 0) { digestResp.write(("realm=\"" + quotedStringValue(negotiatedRealm) + "\",").getBytes(encoding)); } digestResp.write("nonce=\"".getBytes(encoding)); writeQuotedStringValue(digestResp, nonce); digestResp.write('"'); digestResp.write(','); nonceCount = getNonceCount(nonce); digestResp.write(("nc=" + nonceCountToHex(nonceCount) + ",").getBytes(encoding)); cnonce = generateNonce(); digestResp.write("cnonce=\"".getBytes(encoding)); writeQuotedStringValue(digestResp, cnonce); digestResp.write("\",".getBytes(encoding)); digestResp.write(("digest-uri=\"" + digestUri + "\",").getBytes(encoding)); digestResp.write("maxbuf=".getBytes(encoding)); digestResp.write(String.valueOf(recvMaxBufSize).getBytes(encoding)); digestResp.write(','); try { digestResp.write("response=".getBytes(encoding)); digestResp.write(generateResponseValue("AUTHENTICATE", digestUri, negotiatedQop, username, negotiatedRealm, passwd, nonce, cnonce, nonceCount, authzidBytes)); digestResp.write(','); } catch (Exception e) { throw new SaslException( "DIGEST-MD5: Error generating response value", e); } digestResp.write(("qop=" + negotiatedQop).getBytes(encoding)); if (negotiatedCipher != null) { digestResp.write((",cipher=\"" + negotiatedCipher + "\"").getBytes(encoding)); } if (authzidBytes != null) { digestResp.write(",authzid=\"".getBytes(encoding)); writeQuotedStringValue(digestResp, authzidBytes); digestResp.write("\"".getBytes(encoding)); } if (digestResp.size() > MAX_RESPONSE_LENGTH) { throw new SaslException ("DIGEST-MD5: digest-response size too " + "large. Length: " + digestResp.size()); } return digestResp.toByteArray(); } /** * From RFC 2831, Section 2.1.3: Step Three * [Server] sends a message formatted as follows: * response-auth = "rspauth" "=" response-value * where response-value is calculated as above, using the values sent in * step two, except that if qop is "auth", then A2 is * * A2 = { ":", digest-uri-value } * * And if qop is "auth-int" or "auth-conf" then A2 is * * A2 = { ":", digest-uri-value, ":00000000000000000000000000000000" } */ private void validateResponseValue(byte[] fromServer) throws SaslException { if (fromServer == null) { throw new SaslException("DIGEST-MD5: Authenication failed. " + "Expecting 'rspauth' authentication success message"); } try { byte[] expected = generateResponseValue("", digestUri, negotiatedQop, username, negotiatedRealm, passwd, nonce, cnonce, nonceCount, authzidBytes); if (!Arrays.equals(expected, fromServer)) { /* Server's rspauth value does not match */ throw new SaslException( "Server's rspauth value does not match what client expects"); } } catch (NoSuchAlgorithmException e) { throw new SaslException( "Problem generating response value for verification", e); } catch (IOException e) { throw new SaslException( "Problem generating response value for verification", e); } } /** * Returns the number of requests (including current request) * that the client has sent in response to nonceValue. * This is 1 the first time nonceValue is seen. * * We don't cache nonce values seen, and we don't support subsequent * authentication, so the value is always 1. */ private static int getNonceCount(byte[] nonceValue) { return 1; } private void clearPassword() { if (passwd != null) { for (int i = 0; i < passwd.length; i++) { passwd[i] = 0; } passwd = null; } } }
gpl-2.0
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/pm/lidt_o16_M_mem.java
1918
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.pm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class lidt_o16_M_mem extends Executable { final Pointer op1; public lidt_o16_M_mem(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); op1 = Modrm.getPointer(prefices, modrm, input); } public Branch execute(Processor cpu) { int limit = 0xffff & op1.get16(cpu, 0); int base = 0x00ffffff & op1.get32(cpu, 2); cpu.idtr = cpu.createDescriptorTableSegment(base, limit); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
gpl-2.0
sdtabilit/Scada-LTS
src/org/scada_lts/dao/error/ParseErrorResult.java
920
package org.scada_lts.dao.error; import java.util.Locale; import javax.annotation.Resource; import org.springframework.context.MessageSource; public class ParseErrorResult { private boolean notErr = true; private String messageOrgin; private String message; public boolean getNotErr() { return notErr; } /** * @param notErr the notErr to set */ public void setNotErr(boolean notErr) { this.notErr = notErr; } /** * @param messageOrgin the messageOrgin to set */ public void setMessageOrgin(String messageOrgin) { this.messageOrgin = messageOrgin; } /** * @return the message */ public String getMessage() { if (notErr) { //return msgSource.getMessage(message,null, Locale.getDefault()); return message; } else { return messageOrgin; } } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } }
gpl-2.0
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/eltnen/_3319AnOrderforGojirunerk.java
4878
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.eltnen; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.network.aion.serverpackets.SM_DIALOG_WINDOW; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.utils.PacketSendUtility; /** * @author Balthazar */ public class _3319AnOrderforGojirunerk extends QuestHandler { private final static int questId = 3319; public _3319AnOrderforGojirunerk() { super(questId); } @Override public void register() { qe.registerQuestNpc(798050).addOnQuestStart(questId); qe.registerQuestNpc(798050).addOnTalkEvent(questId); qe.registerQuestNpc(798138).addOnTalkEvent(questId); } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); int targetId = 0; if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 798050) { if (env.getDialog() == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 1011); } else { return sendQuestStartDialog(env); } } } if (qs == null) { return false; } if (qs.getStatus() == QuestStatus.START) { switch (targetId) { case 798138: { switch (env.getDialog()) { case QUEST_SELECT: { return sendQuestDialog(env, 1352); } case SETPRO1: { qs.setQuestVarById(0, qs.getQuestVarById(0) + 1); updateQuestStatus(env); PacketSendUtility.sendPacket(player, new SM_DIALOG_WINDOW(env.getVisibleObject().getObjectId(), 10)); return true; } } } case 798050: { switch (env.getDialog()) { case QUEST_SELECT: { return sendQuestDialog(env, 2375); } case SELECT_QUEST_REWARD: { qs.setQuestVar(2); qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return sendQuestEndDialog(env); } default: return sendQuestEndDialog(env); } } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 798050) { switch (env.getDialog()) { case SELECT_QUEST_REWARD: { return sendQuestDialog(env, 5); } default: return sendQuestEndDialog(env); } } } return false; } }
gpl-2.0
JetBrains/jdk8u_jdk
src/solaris/classes/sun/nio/ch/FileDispatcherImpl.java
5199
/* * Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.nio.ch; import java.io.FileDescriptor; import java.io.IOException; class FileDispatcherImpl extends FileDispatcher { static { IOUtil.load(); init(); } FileDispatcherImpl(boolean append) { /* append is ignored */ } FileDispatcherImpl() { } int read(FileDescriptor fd, long address, int len) throws IOException { return read0(fd, address, len); } int pread(FileDescriptor fd, long address, int len, long position) throws IOException { return pread0(fd, address, len, position); } long readv(FileDescriptor fd, long address, int len) throws IOException { return readv0(fd, address, len); } int write(FileDescriptor fd, long address, int len) throws IOException { return write0(fd, address, len); } int pwrite(FileDescriptor fd, long address, int len, long position) throws IOException { return pwrite0(fd, address, len, position); } long writev(FileDescriptor fd, long address, int len) throws IOException { return writev0(fd, address, len); } long seek(FileDescriptor fd, long offset) throws IOException { return seek0(fd, offset); } int force(FileDescriptor fd, boolean metaData) throws IOException { return force0(fd, metaData); } int truncate(FileDescriptor fd, long size) throws IOException { return truncate0(fd, size); } long size(FileDescriptor fd) throws IOException { return size0(fd); } int lock(FileDescriptor fd, boolean blocking, long pos, long size, boolean shared) throws IOException { return lock0(fd, blocking, pos, size, shared); } void release(FileDescriptor fd, long pos, long size) throws IOException { release0(fd, pos, size); } void close(FileDescriptor fd) throws IOException { close0(fd); } void preClose(FileDescriptor fd) throws IOException { preClose0(fd); } FileDescriptor duplicateForMapping(FileDescriptor fd) { // file descriptor not required for mapping operations; okay // to return invalid file descriptor. return new FileDescriptor(); } boolean canTransferToDirectly(java.nio.channels.SelectableChannel sc) { return true; } boolean transferToDirectlyNeedsPositionLock() { return false; } // -- Native methods -- static native int read0(FileDescriptor fd, long address, int len) throws IOException; static native int pread0(FileDescriptor fd, long address, int len, long position) throws IOException; static native long readv0(FileDescriptor fd, long address, int len) throws IOException; static native int write0(FileDescriptor fd, long address, int len) throws IOException; static native int pwrite0(FileDescriptor fd, long address, int len, long position) throws IOException; static native long writev0(FileDescriptor fd, long address, int len) throws IOException; static native int force0(FileDescriptor fd, boolean metaData) throws IOException; static native long seek0(FileDescriptor fd, long size) throws IOException; static native int truncate0(FileDescriptor fd, long size) throws IOException; static native long size0(FileDescriptor fd) throws IOException; static native int lock0(FileDescriptor fd, boolean blocking, long pos, long size, boolean shared) throws IOException; static native void release0(FileDescriptor fd, long pos, long size) throws IOException; static native void close0(FileDescriptor fd) throws IOException; static native void preClose0(FileDescriptor fd) throws IOException; static native void closeIntFD(int fd) throws IOException; static native void init(); }
gpl-2.0
Debian/openjfx
modules/graphics/src/main/java/javafx/scene/effect/Glow.java
5881
/* * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.effect; import javafx.beans.property.DoubleProperty; import javafx.beans.property.DoublePropertyBase; import javafx.beans.property.ObjectProperty; import javafx.scene.Node; import com.sun.javafx.util.Utils; import com.sun.javafx.effect.EffectDirtyBits; import com.sun.javafx.geom.BaseBounds; import com.sun.javafx.geom.transform.BaseTransform; import com.sun.javafx.scene.BoundsAccessor; /** * A high-level effect that makes the input image appear to glow, * based on a configurable threshold. * * <p> * Example: * <pre><code> * Image image = new Image("boat.jpg"); * ImageView imageView = new ImageView(image); * imageView.setFitWidth(200); * imageView.setPreserveRatio(true); * * imageView.setEffect(new Glow(0.8)); * </pre></code> * <p> * <p> The code above applied on this image: </p> * <p> * <img src="doc-files/photo.png"/> * </p> * <p> produces the following: </p> * <p> * <img src="doc-files/glow.png"/> * </p> * @since JavaFX 2.0 */ public class Glow extends Effect { /** * Creates a new instance of Glow with default parameters. */ public Glow() {} /** * Creates a new instance of Glow with specified level. * @param level the level value, which controls the intensity * of the glow effect */ public Glow(double level) { setLevel(level); } @Override com.sun.scenario.effect.Glow impl_createImpl() { return new com.sun.scenario.effect.Glow(); }; /** * The input for this {@code Effect}. * If set to {@code null}, or left unspecified, a graphical image of * the {@code Node} to which the {@code Effect} is attached will be * used as the input. * @defaultValue null */ private ObjectProperty<Effect> input; public final void setInput(Effect value) { inputProperty().set(value); } public final Effect getInput() { return input == null ? null : input.get(); } public final ObjectProperty<Effect> inputProperty() { if (input == null) { input = new EffectInputProperty("input"); } return input; } @Override boolean impl_checkChainContains(Effect e) { Effect localInput = getInput(); if (localInput == null) return false; if (localInput == e) return true; return localInput.impl_checkChainContains(e); } /** * The level value, which controls the intensity of the glow effect. * <pre> * Min: 0.0 * Max: 1.0 * Default: 0.3 * Identity: 0.0 * </pre> * @defaultValue 0.3 */ private DoubleProperty level; public final void setLevel(double value) { levelProperty().set(value); } public final double getLevel() { return level == null ? 0.3 : level.get(); } public final DoubleProperty levelProperty() { if (level == null) { level = new DoublePropertyBase(0.3) { @Override public void invalidated() { markDirty(EffectDirtyBits.EFFECT_DIRTY); } @Override public Object getBean() { return Glow.this; } @Override public String getName() { return "level"; } }; } return level; } @Override void impl_update() { Effect localInput = getInput(); if (localInput != null) { localInput.impl_sync(); } com.sun.scenario.effect.Glow peer = (com.sun.scenario.effect.Glow) impl_getImpl(); peer.setInput(localInput == null ? null : localInput.impl_getImpl()); peer.setLevel((float)Utils.clamp(0, getLevel(), 1)); } /** * @treatAsPrivate implementation detail * @deprecated This is an internal API that is not intended for use and will be removed in the next version */ @Deprecated @Override public BaseBounds impl_getBounds(BaseBounds bounds, BaseTransform tx, Node node, BoundsAccessor boundsAccessor) { return getInputBounds(bounds, tx, node, boundsAccessor, getInput()); } /** * @treatAsPrivate implementation detail * @deprecated This is an internal API that is not intended for use and will be removed in the next version */ @Deprecated @Override public Effect impl_copy() { return new Glow(this.getLevel()); } }
gpl-2.0
SpoonLabs/astor
examples/Math-issue-340/src/main/java/org/apache/commons/math/linear/ArrayRealVector.java
38089
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.math.linear; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import org.apache.commons.math.MathRuntimeException; import org.apache.commons.math.util.MathUtils; /** * This class implements the {@link RealVector} interface with a double array. * @version $Revision$ $Date$ * @since 2.0 */ public class ArrayRealVector extends AbstractRealVector implements Serializable { /** Message for non fitting position and size. */ private static final String NON_FITTING_POSITION_AND_SIZE_MESSAGE = "position {0} and size {1} don't fit to the size of the input array {2}"; /** Serializable version identifier. */ private static final long serialVersionUID = -1097961340710804027L; /** Default format. */ private static final RealVectorFormat DEFAULT_FORMAT = RealVectorFormat.getInstance(); /** Entries of the vector. */ protected double data[]; /** * Build a 0-length vector. * <p>Zero-length vectors may be used to initialized construction of vectors * by data gathering. We start with zero-length and use either the {@link * #ArrayRealVector(ArrayRealVector, ArrayRealVector)} constructor * or one of the <code>append</code> method ({@link #append(double)}, {@link * #append(double[])}, {@link #append(ArrayRealVector)}) to gather data * into this vector.</p> */ public ArrayRealVector() { data = new double[0]; } /** * Construct a (size)-length vector of zeros. * @param size size of the vector */ public ArrayRealVector(int size) { data = new double[size]; } /** * Construct an (size)-length vector with preset values. * @param size size of the vector * @param preset fill the vector with this scalar value */ public ArrayRealVector(int size, double preset) { data = new double[size]; Arrays.fill(data, preset); } /** * Construct a vector from an array, copying the input array. * @param d array of doubles. */ public ArrayRealVector(double[] d) { data = d.clone(); } /** * Create a new ArrayRealVector using the input array as the underlying * data array. * <p>If an array is built specially in order to be embedded in a * ArrayRealVector and not used directly, the <code>copyArray</code> may be * set to <code>false</code. This will prevent the copying and improve * performance as no new array will be built and no data will be copied.</p> * @param d data for new vector * @param copyArray if true, the input array will be copied, otherwise * it will be referenced * @throws IllegalArgumentException if <code>d</code> is empty * @throws NullPointerException if <code>d</code> is null * @see #ArrayRealVector(double[]) */ public ArrayRealVector(double[] d, boolean copyArray) throws NullPointerException, IllegalArgumentException { if (d == null) { throw new NullPointerException(); } if (d.length == 0) { throw MathRuntimeException.createIllegalArgumentException("vector must have at least one element"); } data = copyArray ? d.clone() : d; } /** * Construct a vector from part of a array. * @param d array of doubles. * @param pos position of first entry * @param size number of entries to copy */ public ArrayRealVector(double[] d, int pos, int size) { if (d.length < pos + size) { throw MathRuntimeException.createIllegalArgumentException( NON_FITTING_POSITION_AND_SIZE_MESSAGE, pos, size, d.length); } data = new double[size]; System.arraycopy(d, pos, data, 0, size); } /** * Construct a vector from an array. * @param d array of Doubles. */ public ArrayRealVector(Double[] d) { data = new double[d.length]; for (int i = 0; i < d.length; i++) { data[i] = d[i].doubleValue(); } } /** * Construct a vector from part of a Double array * @param d array of Doubles. * @param pos position of first entry * @param size number of entries to copy */ public ArrayRealVector(Double[] d, int pos, int size) { if (d.length < pos + size) { throw MathRuntimeException.createIllegalArgumentException( NON_FITTING_POSITION_AND_SIZE_MESSAGE, pos, size, d.length); } data = new double[size]; for (int i = pos; i < pos + size; i++) { data[i-pos] = d[i].doubleValue(); } } /** * Construct a vector from another vector, using a deep copy. * @param v vector to copy */ public ArrayRealVector(RealVector v) { data = new double[v.getDimension()]; for (int i = 0; i < data.length; ++i) { data[i] = v.getEntry(i); } } /** * Construct a vector from another vector, using a deep copy. * @param v vector to copy */ public ArrayRealVector(ArrayRealVector v) { this(v, true); } /** * Construct a vector from another vector. * @param v vector to copy * @param deep if true perform a deep copy otherwise perform a shallow copy */ public ArrayRealVector(ArrayRealVector v, boolean deep) { data = deep ? v.data.clone() : v.data; } /** * Construct a vector by appending one vector to another vector. * @param v1 first vector (will be put in front of the new vector) * @param v2 second vector (will be put at back of the new vector) */ public ArrayRealVector(ArrayRealVector v1, ArrayRealVector v2) { data = new double[v1.data.length + v2.data.length]; System.arraycopy(v1.data, 0, data, 0, v1.data.length); System.arraycopy(v2.data, 0, data, v1.data.length, v2.data.length); } /** * Construct a vector by appending one vector to another vector. * @param v1 first vector (will be put in front of the new vector) * @param v2 second vector (will be put at back of the new vector) */ public ArrayRealVector(ArrayRealVector v1, RealVector v2) { final int l1 = v1.data.length; final int l2 = v2.getDimension(); data = new double[l1 + l2]; System.arraycopy(v1.data, 0, data, 0, l1); for (int i = 0; i < l2; ++i) { data[l1 + i] = v2.getEntry(i); } } /** * Construct a vector by appending one vector to another vector. * @param v1 first vector (will be put in front of the new vector) * @param v2 second vector (will be put at back of the new vector) */ public ArrayRealVector(RealVector v1, ArrayRealVector v2) { final int l1 = v1.getDimension(); final int l2 = v2.data.length; data = new double[l1 + l2]; for (int i = 0; i < l1; ++i) { data[i] = v1.getEntry(i); } System.arraycopy(v2.data, 0, data, l1, l2); } /** * Construct a vector by appending one vector to another vector. * @param v1 first vector (will be put in front of the new vector) * @param v2 second vector (will be put at back of the new vector) */ public ArrayRealVector(ArrayRealVector v1, double[] v2) { final int l1 = v1.getDimension(); final int l2 = v2.length; data = new double[l1 + l2]; System.arraycopy(v1.data, 0, data, 0, l1); System.arraycopy(v2, 0, data, l1, l2); } /** * Construct a vector by appending one vector to another vector. * @param v1 first vector (will be put in front of the new vector) * @param v2 second vector (will be put at back of the new vector) */ public ArrayRealVector(double[] v1, ArrayRealVector v2) { final int l1 = v1.length; final int l2 = v2.getDimension(); data = new double[l1 + l2]; System.arraycopy(v1, 0, data, 0, l1); System.arraycopy(v2.data, 0, data, l1, l2); } /** * Construct a vector by appending one vector to another vector. * @param v1 first vector (will be put in front of the new vector) * @param v2 second vector (will be put at back of the new vector) */ public ArrayRealVector(double[] v1, double[] v2) { final int l1 = v1.length; final int l2 = v2.length; data = new double[l1 + l2]; System.arraycopy(v1, 0, data, 0, l1); System.arraycopy(v2, 0, data, l1, l2); } /** {@inheritDoc} */ @Override public AbstractRealVector copy() { return new ArrayRealVector(this, true); } /** {@inheritDoc} */ @Override public RealVector add(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return add((ArrayRealVector) v); } else { checkVectorDimensions(v); double[] out = data.clone(); Iterator<Entry> it = v.sparseIterator(); Entry e; while (it.hasNext() && (e = it.next()) != null) { out[e.getIndex()] += e.getValue(); } return new ArrayRealVector(out, false); } } /** {@inheritDoc} */ @Override public RealVector add(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double[] out = data.clone(); for (int i = 0; i < data.length; i++) { out[i] += v[i]; } return new ArrayRealVector(out, false); } /** * Compute the sum of this and v. * @param v vector to be added * @return this + v * @throws IllegalArgumentException if v is not the same size as this */ public ArrayRealVector add(ArrayRealVector v) throws IllegalArgumentException { return (ArrayRealVector) add(v.data); } /** {@inheritDoc} */ @Override public RealVector subtract(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return subtract((ArrayRealVector) v); } else { checkVectorDimensions(v); double[] out = data.clone(); Iterator<Entry> it = v.sparseIterator(); Entry e; while(it.hasNext() && (e = it.next()) != null) { out[e.getIndex()] -= e.getValue(); } return new ArrayRealVector(out, false); } } /** {@inheritDoc} */ @Override public RealVector subtract(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double[] out = data.clone(); for (int i = 0; i < data.length; i++) { out[i] -= v[i]; } return new ArrayRealVector(out, false); } /** * Compute this minus v. * @param v vector to be subtracted * @return this + v * @throws IllegalArgumentException if v is not the same size as this */ public ArrayRealVector subtract(ArrayRealVector v) throws IllegalArgumentException { return (ArrayRealVector) subtract(v.data); } /** {@inheritDoc} */ @Override public RealVector mapAddToSelf(double d) { for (int i = 0; i < data.length; i++) { data[i] = data[i] + d; } return this; } /** {@inheritDoc} */ @Override public RealVector mapSubtractToSelf(double d) { for (int i = 0; i < data.length; i++) { data[i] = data[i] - d; } return this; } /** {@inheritDoc} */ @Override public RealVector mapMultiplyToSelf(double d) { for (int i = 0; i < data.length; i++) { data[i] = data[i] * d; } return this; } /** {@inheritDoc} */ @Override public RealVector mapDivideToSelf(double d) { for (int i = 0; i < data.length; i++) { data[i] = data[i] / d; } return this; } /** {@inheritDoc} */ @Override public RealVector mapPowToSelf(double d) { for (int i = 0; i < data.length; i++) { data[i] = Math.pow(data[i], d); } return this; } /** {@inheritDoc} */ @Override public RealVector mapExpToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.exp(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapExpm1ToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.expm1(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapLogToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.log(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapLog10ToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.log10(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapLog1pToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.log1p(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapCoshToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.cosh(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapSinhToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.sinh(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapTanhToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.tanh(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapCosToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.cos(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapSinToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.sin(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapTanToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.tan(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapAcosToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.acos(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapAsinToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.asin(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapAtanToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.atan(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapInvToSelf() { for (int i = 0; i < data.length; i++) { data[i] = 1.0 / data[i]; } return this; } /** {@inheritDoc} */ @Override public RealVector mapAbsToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.abs(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapSqrtToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.sqrt(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapCbrtToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.cbrt(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapCeilToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.ceil(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapFloorToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.floor(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapRintToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.rint(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapSignumToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.signum(data[i]); } return this; } /** {@inheritDoc} */ @Override public RealVector mapUlpToSelf() { for (int i = 0; i < data.length; i++) { data[i] = Math.ulp(data[i]); } return this; } /** {@inheritDoc} */ public RealVector ebeMultiply(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return ebeMultiply((ArrayRealVector) v); } else { checkVectorDimensions(v); double[] out = data.clone(); for (int i = 0; i < data.length; i++) { out[i] *= v.getEntry(i); } return new ArrayRealVector(out, false); } } /** {@inheritDoc} */ @Override public RealVector ebeMultiply(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double[] out = data.clone(); for (int i = 0; i < data.length; i++) { out[i] *= v[i]; } return new ArrayRealVector(out, false); } /** * Element-by-element multiplication. * @param v vector by which instance elements must be multiplied * @return a vector containing this[i] * v[i] for all i * @exception IllegalArgumentException if v is not the same size as this */ public ArrayRealVector ebeMultiply(ArrayRealVector v) throws IllegalArgumentException { return (ArrayRealVector) ebeMultiply(v.data); } /** {@inheritDoc} */ public RealVector ebeDivide(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return ebeDivide((ArrayRealVector) v); } else { checkVectorDimensions(v); double[] out = data.clone(); for (int i = 0; i < data.length; i++) { out[i] /= v.getEntry(i); } return new ArrayRealVector(out, false); } } /** {@inheritDoc} */ @Override public RealVector ebeDivide(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double[] out = data.clone(); for (int i = 0; i < data.length; i++) { out[i] /= v[i]; } return new ArrayRealVector(out, false); } /** * Element-by-element division. * @param v vector by which instance elements must be divided * @return a vector containing this[i] / v[i] for all i * @throws IllegalArgumentException if v is not the same size as this */ public ArrayRealVector ebeDivide(ArrayRealVector v) throws IllegalArgumentException { return (ArrayRealVector) ebeDivide(v.data); } /** {@inheritDoc} */ @Override public double[] getData() { return data.clone(); } /** * Returns a reference to the underlying data array. * <p>Does not make a fresh copy of the underlying data.</p> * @return array of entries */ public double[] getDataRef() { return data; } /** {@inheritDoc} */ @Override public double dotProduct(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return dotProduct((ArrayRealVector) v); } else { checkVectorDimensions(v); double dot = 0; Iterator<Entry> it = v.sparseIterator(); Entry e; while(it.hasNext() && (e = it.next()) != null) { dot += data[e.getIndex()] * e.getValue(); } return dot; } } /** {@inheritDoc} */ @Override public double dotProduct(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double dot = 0; for (int i = 0; i < data.length; i++) { dot += data[i] * v[i]; } return dot; } /** * Compute the dot product. * @param v vector with which dot product should be computed * @return the scalar dot product between instance and v * @exception IllegalArgumentException if v is not the same size as this */ public double dotProduct(ArrayRealVector v) throws IllegalArgumentException { return dotProduct(v.data); } /** {@inheritDoc} */ @Override public double getNorm() { double sum = 0; for (double a : data) { sum += a * a; } return Math.sqrt(sum); } /** {@inheritDoc} */ @Override public double getL1Norm() { double sum = 0; for (double a : data) { sum += Math.abs(a); } return sum; } /** {@inheritDoc} */ @Override public double getLInfNorm() { double max = 0; for (double a : data) { max = Math.max(max, Math.abs(a)); } return max; } /** {@inheritDoc} */ @Override public double getDistance(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return getDistance((ArrayRealVector) v); } else { checkVectorDimensions(v); double sum = 0; for (int i = 0; i < data.length; ++i) { final double delta = data[i] - v.getEntry(i); sum += delta * delta; } return Math.sqrt(sum); } } /** {@inheritDoc} */ @Override public double getDistance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double sum = 0; for (int i = 0; i < data.length; ++i) { final double delta = data[i] - v[i]; sum += delta * delta; } return Math.sqrt(sum); } /** * Distance between two vectors. * <p>This method computes the distance consistent with the * L<sub>2</sub> norm, i.e. the square root of the sum of * elements differences, or euclidian distance.</p> * @param v vector to which distance is requested * @return distance between two vectors. * @exception IllegalArgumentException if v is not the same size as this * @see #getDistance(RealVector) * @see #getL1Distance(ArrayRealVector) * @see #getLInfDistance(ArrayRealVector) * @see #getNorm() */ public double getDistance(ArrayRealVector v) throws IllegalArgumentException { return getDistance(v.data); } /** {@inheritDoc} */ @Override public double getL1Distance(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return getL1Distance((ArrayRealVector) v); } else { checkVectorDimensions(v); double sum = 0; for (int i = 0; i < data.length; ++i) { final double delta = data[i] - v.getEntry(i); sum += Math.abs(delta); } return sum; } } /** {@inheritDoc} */ @Override public double getL1Distance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double sum = 0; for (int i = 0; i < data.length; ++i) { final double delta = data[i] - v[i]; sum += Math.abs(delta); } return sum; } /** * Distance between two vectors. * <p>This method computes the distance consistent with * L<sub>1</sub> norm, i.e. the sum of the absolute values of * elements differences.</p> * @param v vector to which distance is requested * @return distance between two vectors. * @exception IllegalArgumentException if v is not the same size as this * @see #getDistance(RealVector) * @see #getL1Distance(ArrayRealVector) * @see #getLInfDistance(ArrayRealVector) * @see #getNorm() */ public double getL1Distance(ArrayRealVector v) throws IllegalArgumentException { return getL1Distance(v.data); } /** {@inheritDoc} */ @Override public double getLInfDistance(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return getLInfDistance((ArrayRealVector) v); } else { checkVectorDimensions(v); double max = 0; for (int i = 0; i < data.length; ++i) { final double delta = data[i] - v.getEntry(i); max = Math.max(max, Math.abs(delta)); } return max; } } /** {@inheritDoc} */ @Override public double getLInfDistance(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); double max = 0; for (int i = 0; i < data.length; ++i) { final double delta = data[i] - v[i]; max = Math.max(max, Math.abs(delta)); } return max; } /** * Distance between two vectors. * <p>This method computes the distance consistent with * L<sub>&infin;</sub> norm, i.e. the max of the absolute values of * elements differences.</p> * @param v vector to which distance is requested * @return distance between two vectors. * @exception IllegalArgumentException if v is not the same size as this * @see #getDistance(RealVector) * @see #getL1Distance(ArrayRealVector) * @see #getLInfDistance(ArrayRealVector) * @see #getNorm() */ public double getLInfDistance(ArrayRealVector v) throws IllegalArgumentException { return getLInfDistance(v.data); } /** {@inheritDoc} */ @Override public RealVector unitVector() throws ArithmeticException { final double norm = getNorm(); if (norm == 0) { throw MathRuntimeException.createArithmeticException("zero norm"); } return mapDivide(norm); } /** {@inheritDoc} */ @Override public void unitize() throws ArithmeticException { final double norm = getNorm(); if (norm == 0) { throw MathRuntimeException.createArithmeticException("cannot normalize a zero norm vector"); } mapDivideToSelf(norm); } /** {@inheritDoc} */ public RealVector projection(RealVector v) { return v.mapMultiply(dotProduct(v) / v.dotProduct(v)); } /** {@inheritDoc} */ @Override public RealVector projection(double[] v) { return projection(new ArrayRealVector(v, false)); } /** Find the orthogonal projection of this vector onto another vector. * @param v vector onto which instance must be projected * @return projection of the instance onto v * @throws IllegalArgumentException if v is not the same size as this */ public ArrayRealVector projection(ArrayRealVector v) { return (ArrayRealVector) v.mapMultiply(dotProduct(v) / v.dotProduct(v)); } /** {@inheritDoc} */ @Override public RealMatrix outerProduct(RealVector v) throws IllegalArgumentException { if (v instanceof ArrayRealVector) { return outerProduct((ArrayRealVector) v); } else { checkVectorDimensions(v); final int m = data.length; final RealMatrix out = MatrixUtils.createRealMatrix(m, m); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length; j++) { out.setEntry(i, j, data[i] * v.getEntry(j)); } } return out; } } /** * Compute the outer product. * @param v vector with which outer product should be computed * @return the square matrix outer product between instance and v * @exception IllegalArgumentException if v is not the same size as this */ public RealMatrix outerProduct(ArrayRealVector v) throws IllegalArgumentException { return outerProduct(v.data); } /** {@inheritDoc} */ @Override public RealMatrix outerProduct(double[] v) throws IllegalArgumentException { checkVectorDimensions(v.length); final int m = data.length; final RealMatrix out = MatrixUtils.createRealMatrix(m, m); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data.length; j++) { out.setEntry(i, j, data[i] * v[j]); } } return out; } /** {@inheritDoc} */ public double getEntry(int index) throws MatrixIndexException { return data[index]; } /** {@inheritDoc} */ public int getDimension() { return data.length; } /** {@inheritDoc} */ public RealVector append(RealVector v) { try { return new ArrayRealVector(this, (ArrayRealVector) v); } catch (ClassCastException cce) { return new ArrayRealVector(this, v); } } /** * Construct a vector by appending a vector to this vector. * @param v vector to append to this one. * @return a new vector */ public ArrayRealVector append(ArrayRealVector v) { return new ArrayRealVector(this, v); } /** {@inheritDoc} */ public RealVector append(double in) { final double[] out = new double[data.length + 1]; System.arraycopy(data, 0, out, 0, data.length); out[data.length] = in; return new ArrayRealVector(out, false); } /** {@inheritDoc} */ public RealVector append(double[] in) { return new ArrayRealVector(this, in); } /** {@inheritDoc} */ public RealVector getSubVector(int index, int n) { ArrayRealVector out = new ArrayRealVector(n); try { System.arraycopy(data, index, out.data, 0, n); } catch (IndexOutOfBoundsException e) { checkIndex(index); checkIndex(index + n - 1); } return out; } /** {@inheritDoc} */ public void setEntry(int index, double value) { try { data[index] = value; } catch (IndexOutOfBoundsException e) { checkIndex(index); } } /** {@inheritDoc} */ @Override public void setSubVector(int index, RealVector v) { try { try { set(index, (ArrayRealVector) v); } catch (ClassCastException cce) { for (int i = index; i < index + v.getDimension(); ++i) { data[i] = v.getEntry(i-index); } } } catch (IndexOutOfBoundsException e) { checkIndex(index); checkIndex(index + v.getDimension() - 1); } } /** {@inheritDoc} */ @Override public void setSubVector(int index, double[] v) { try { System.arraycopy(v, 0, data, index, v.length); } catch (IndexOutOfBoundsException e) { checkIndex(index); checkIndex(index + v.length - 1); } } /** * Set a set of consecutive elements. * * @param index index of first element to be set. * @param v vector containing the values to set. * @exception MatrixIndexException if the index is * inconsistent with vector size */ public void set(int index, ArrayRealVector v) throws MatrixIndexException { setSubVector(index, v.data); } /** {@inheritDoc} */ @Override public void set(double value) { Arrays.fill(data, value); } /** {@inheritDoc} */ @Override public double[] toArray(){ return data.clone(); } /** {@inheritDoc} */ @Override public String toString(){ return DEFAULT_FORMAT.format(this); } /** * Check if instance and specified vectors have the same dimension. * @param v vector to compare instance with * @exception IllegalArgumentException if the vectors do not * have the same dimension */ @Override protected void checkVectorDimensions(RealVector v) throws IllegalArgumentException { checkVectorDimensions(v.getDimension()); } /** * Check if instance dimension is equal to some expected value. * * @param n expected dimension. * @exception IllegalArgumentException if the dimension is * inconsistent with vector size */ @Override protected void checkVectorDimensions(int n) throws IllegalArgumentException { if (data.length != n) { throw MathRuntimeException.createIllegalArgumentException( "vector length mismatch: got {0} but expected {1}", data.length, n); } } /** * Returns true if any coordinate of this vector is NaN; false otherwise * @return true if any coordinate of this vector is NaN; false otherwise */ public boolean isNaN() { for (double v : data) { if (Double.isNaN(v)) { return true; } } return false; } /** * Returns true if any coordinate of this vector is infinite and none are NaN; * false otherwise * @return true if any coordinate of this vector is infinite and none are NaN; * false otherwise */ public boolean isInfinite() { if (isNaN()) { return false; } for (double v : data) { if (Double.isInfinite(v)) { return true; } } return false; } /** * Test for the equality of two real vectors. * <p> * If all coordinates of two real vectors are exactly the same, and none are * <code>Double.NaN</code>, the two real vectors are considered to be equal. * </p> * <p> * <code>NaN</code> coordinates are considered to affect globally the vector * and be equals to each other - i.e, if either (or all) coordinates of the * real vector are equal to <code>Double.NaN</code>, the real vector is equal to * a vector with all <code>Double.NaN</code> coordinates. * </p> * * @param other Object to test for equality to this * @return true if two vector objects are equal, false if * object is null, not an instance of RealVector, or * not equal to this RealVector instance * */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || !(other instanceof RealVector)) { return false; } RealVector rhs = (RealVector) other; if (data.length != rhs.getDimension()) { return false; } if (rhs.isNaN()) { return this.isNaN(); } for (int i = 0; i < data.length; ++i) { if (data[i] != rhs.getEntry(i)) { return false; } } return true; } /** * Get a hashCode for the real vector. * <p>All NaN values have the same hash code.</p> * @return a hash code value for this object */ @Override public int hashCode() { if (isNaN()) { return 9; } return MathUtils.hash(data); } }
gpl-2.0
jried31/SSKB
sensite/src/main/java/com/MetaData/QoIQuantitativeMetricType.java
6482
//////////////////////////////////////////////////////////////////////// // // QoIQuantitativeMetricType.java // // This file was generated by XMLSpy 2014 Enterprise Edition. // // YOU SHOULD NOT MODIFY THIS FILE, BECAUSE IT WILL BE // OVERWRITTEN WHEN YOU RE-RUN CODE GENERATION. // // Refer to the XMLSpy Documentation for further details. // http://www.altova.com/xmlspy // //////////////////////////////////////////////////////////////////////// package com.MetaData; public class QoIQuantitativeMetricType extends com.altova.xml.TypeBase { public static com.altova.xml.meta.ComplexType getStaticInfo() { return new com.altova.xml.meta.ComplexType(com.MetaData.MetaData_TypeInfo.binder.getTypes()[com.MetaData.MetaData_TypeInfo._altova_ti_altova_QoIQuantitativeMetricType]); } public QoIQuantitativeMetricType(org.w3c.dom.Node init) { super(init); instantiateMembers(); } private void instantiateMembers() { uofm = new MemberAttribute_uofm (this, com.MetaData.MetaData_TypeInfo.binder.getMembers()[com.MetaData.MetaData_TypeInfo._altova_mi_altova_QoIQuantitativeMetricType._uofm]); errorRange= new MemberElement_errorRange (this, com.MetaData.MetaData_TypeInfo.binder.getMembers()[com.MetaData.MetaData_TypeInfo._altova_mi_altova_QoIQuantitativeMetricType._errorRange]); biasError= new MemberElement_biasError (this, com.MetaData.MetaData_TypeInfo.binder.getMembers()[com.MetaData.MetaData_TypeInfo._altova_mi_altova_QoIQuantitativeMetricType._biasError]); } // Attributes public MemberAttribute_uofm uofm; public static class MemberAttribute_uofm { private com.altova.xml.TypeBase owner; private com.altova.typeinfo.MemberInfo info; public MemberAttribute_uofm (com.altova.xml.TypeBase owner, com.altova.typeinfo.MemberInfo info) {this.owner = owner; this.info = info;} public String getValue() { return (String)com.altova.xml.XmlTreeOperations.castToString(com.altova.xml.XmlTreeOperations.findAttribute(owner.getNode(), info), info); } public void setValue(String value) { com.altova.xml.XmlTreeOperations.setValue(owner.getNode(), info, value); } public boolean exists() {return owner.getAttribute(info) != null;} public void remove() {owner.removeAttribute(info);} public com.altova.xml.meta.Attribute getInfo() {return new com.altova.xml.meta.Attribute(info);} } // Elements public MemberElement_errorRange errorRange; public static class MemberElement_errorRange { public static class MemberElement_errorRange_Iterator implements java.util.Iterator { private org.w3c.dom.Node nextNode; private MemberElement_errorRange member; public MemberElement_errorRange_Iterator(MemberElement_errorRange member) {this.member=member; nextNode=member.owner.getElementFirst(member.info);} public boolean hasNext() { while (nextNode != null) { if (com.altova.xml.TypeBase.memberEqualsNode(member.info, nextNode)) return true; nextNode = nextNode.getNextSibling(); } return false; } public Object next() { com.MetaData.xs.anyType nx = new com.MetaData.xs.anyType(nextNode); nextNode = nextNode.getNextSibling(); return nx; } public void remove () {} } protected com.altova.xml.TypeBase owner; protected com.altova.typeinfo.MemberInfo info; public MemberElement_errorRange (com.altova.xml.TypeBase owner, com.altova.typeinfo.MemberInfo info) { this.owner = owner; this.info = info;} public com.MetaData.xs.anyType at(int index) {return new com.MetaData.xs.anyType(owner.getElementAt(info, index));} public com.MetaData.xs.anyType first() {return new com.MetaData.xs.anyType(owner.getElementFirst(info));} public com.MetaData.xs.anyType last(){return new com.MetaData.xs.anyType(owner.getElementLast(info));} public com.MetaData.xs.anyType append(){return new com.MetaData.xs.anyType(owner.createElement(info));} public boolean exists() {return count() > 0;} public int count() {return owner.countElement(info);} public void remove() {owner.removeElement(info);} public void removeAt(int index) {owner.removeElementAt(info, index);} public java.util.Iterator iterator() {return new MemberElement_errorRange_Iterator(this);} public com.altova.xml.meta.Element getInfo() { return new com.altova.xml.meta.Element(info); } } public MemberElement_biasError biasError; public static class MemberElement_biasError { public static class MemberElement_biasError_Iterator implements java.util.Iterator { private org.w3c.dom.Node nextNode; private MemberElement_biasError member; public MemberElement_biasError_Iterator(MemberElement_biasError member) {this.member=member; nextNode=member.owner.getElementFirst(member.info);} public boolean hasNext() { while (nextNode != null) { if (com.altova.xml.TypeBase.memberEqualsNode(member.info, nextNode)) return true; nextNode = nextNode.getNextSibling(); } return false; } public Object next() { com.MetaData.xs.anyType nx = new com.MetaData.xs.anyType(nextNode); nextNode = nextNode.getNextSibling(); return nx; } public void remove () {} } protected com.altova.xml.TypeBase owner; protected com.altova.typeinfo.MemberInfo info; public MemberElement_biasError (com.altova.xml.TypeBase owner, com.altova.typeinfo.MemberInfo info) { this.owner = owner; this.info = info;} public com.MetaData.xs.anyType at(int index) {return new com.MetaData.xs.anyType(owner.getElementAt(info, index));} public com.MetaData.xs.anyType first() {return new com.MetaData.xs.anyType(owner.getElementFirst(info));} public com.MetaData.xs.anyType last(){return new com.MetaData.xs.anyType(owner.getElementLast(info));} public com.MetaData.xs.anyType append(){return new com.MetaData.xs.anyType(owner.createElement(info));} public boolean exists() {return count() > 0;} public int count() {return owner.countElement(info);} public void remove() {owner.removeElement(info);} public void removeAt(int index) {owner.removeElementAt(info, index);} public java.util.Iterator iterator() {return new MemberElement_biasError_Iterator(this);} public com.altova.xml.meta.Element getInfo() { return new com.altova.xml.meta.Element(info); } } }
gpl-2.0
dvolkow/hpcourse
csc/2016/sns/sns_1/src/main/java/server/Server.java
4793
package server; import communication.Protocol; import server.processors.BaseTaskProcessor; import server.processors.BaseTaskProcessorFactory; import server.processors.NoProcessorForTaskException; import util.ConcurrentStorage; import util.ProtocolUtils; import util.TaskAndResult; import util.ThreadPool; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; /** * Created by nikita.sokeran@gmail.com */ public final class Server { private static final Logger LOGGER = Logger.getLogger(Server.class.getName()); final ConcurrentStorage<TaskAndResult> concurrentStorage = new ConcurrentStorage<>(); private final Set<Socket> openSockets = new HashSet<>(); private final ServerSocket serverSocket; private final ThreadPool threadPool; private final Thread waitSocketsThread = new Thread(new WaitSocketThread()); private final Thread readSocketsThread = new Thread(new ReadSocketThread()); /** * @param port * @throws IOException if an I/O error occurs when opening the socket for server */ public Server(final int port) throws IOException { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(1000); threadPool = new ThreadPool(); waitSocketsThread.start(); readSocketsThread.start(); } public void stop() { waitSocketsThread.interrupt(); readSocketsThread.interrupt(); try { waitSocketsThread.join(); readSocketsThread.join(); } catch (InterruptedException e) { LOGGER.info("Join was interrupted"); } try { serverSocket.close(); } catch (IOException e) { LOGGER.info("Can't close server socket"); } } private class WaitSocketThread implements Runnable { @Override public void run() { LOGGER.info("Server starting..."); while (!Thread.currentThread().isInterrupted()) { try { final Socket socket = serverSocket.accept(); synchronized (openSockets) { openSockets.add(socket); } LOGGER.info("Socket accepted"); } catch (SocketTimeoutException ste) { //Nothing to do } catch (IOException e) { LOGGER.warning("Can't accept socket: " + e); } } } } private class ReadSocketThread implements Runnable { @Override public void run() { LOGGER.info("Server starting..."); while (!Thread.currentThread().isInterrupted()) { try { final Set<Socket> forRemove = new HashSet<>(); final Set<Socket> openSocketsCopy = new HashSet<>(); synchronized (openSockets) { openSocketsCopy.addAll(openSockets); } for (final Socket socket : openSocketsCopy) { if (socket.isClosed()) { forRemove.add(socket); continue; } final Protocol.WrapperMessage message = ProtocolUtils.readWrappedMessage(socket); if (message == null) { continue; } if (!message.hasRequest()) { LOGGER.warning("Got message without request. Ignore it and continue work"); continue; } final Protocol.ServerRequest request = message.getRequest(); LOGGER.info("Server read request: " + request.getClientId() + ' ' + request.getRequestId()); final BaseTaskProcessor taskProcessor = new BaseTaskProcessorFactory(concurrentStorage, socket, request).getProcessor(); threadPool.execute(taskProcessor); } synchronized (openSockets) { openSockets.removeAll(forRemove); } } catch (IOException e) { LOGGER.warning("Can't read message from socket"); } catch (NoProcessorForTaskException e) { LOGGER.warning("No processor for retrieved task"); } catch (InterruptedException e) { return; } } LOGGER.info("Server detect that client socket closed"); } } }
gpl-2.0
mvehar/zanata-server
zanata-war/src/main/java/org/zanata/service/ConfigurationService.java
1952
/* * Copyright 2010, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.zanata.service; import org.zanata.model.HLocale; public interface ConfigurationService { /** * Get a standard config file for a project-version. * * @return contents of the config file */ String getGeneralConfig(String projectSlug, String iterationSlug); /** * Get a standard config file for dealing with a single locale for a * project-version. * * @return contents of the config file */ String getSingleLocaleConfig(String projectSlug, String versionSlug, HLocale locale); /** * Get a config file for a single locale, with project type adjusted to be * appropriate for offline translation. * * @return contents of the config file */ String getConfigForOfflineTranslation(String projectSlug, String versionSlug, HLocale locale); /** * Returns the default configuration file Name. */ String getConfigurationFileName(); }
gpl-2.0
calimero-project/calimero
src/tuwien/auto/calimero/xml/XmlOutputFactory.java
5067
/* Calimero 2 - A library for KNX network access Copyright (c) 2015, 2018 B. Malinowsky This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package tuwien.auto.calimero.xml; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Creates XML stream writers for working with XML resources. The factory tries to obtain a platform * writer implementation; if that fails, it might fall back on an internal minimal stream writer * implementation. * * @author B. Malinowsky */ public class XmlOutputFactory // extends XMLOutputFactory { private static final Logger l = LoggerFactory.getLogger("calimero.xml"); private final Map<String, Object> config = new HashMap<>(); public static XmlOutputFactory newInstance() { return new XmlOutputFactory(); } /** * Creates a {@link XmlWriter} to write into the XML resource located by the specified identifier. * * @param systemId location identifier of the XML resource * @return XML writer * @throws KNXMLException if creation of the writer failed or XML resource can't be resolved */ public XmlWriter createXMLWriter(final String systemId) throws KNXMLException { final XmlResolver res = new XmlResolver(); final OutputStream os = res.resolveOutput(systemId); return create(os, true); } public XmlWriter createXMLStreamWriter(final Writer stream) { try { final XmlStreamWriterProxy w = XmlStreamWriterProxy.createXmlStreamWriter(stream); l.trace("using StaX XMLStreamWriter {}", w.w.getClass().getName()); return w; } catch (Exception | Error e) { l.trace("no StaX implementation found ({}), using internal XMLStreamWriter", e.toString()); // fall-through to minimal writer implementation } return new DefaultXmlWriter(stream, false); } public XmlWriter createXMLStreamWriter(final OutputStream stream) { return create(stream, false); } private static XmlWriter create(final OutputStream stream, final boolean closeStream) { try { final XmlStreamWriterProxy w = XmlStreamWriterProxy.createXmlStreamWriter(stream, closeStream ? stream : () -> {}); l.trace("using StaX XMLStreamWriter {}", w.w.getClass().getName()); return w; } catch (Exception | Error e) { l.trace("no StaX implementation found ({}), using internal XMLStreamWriter", e.toString()); // fall-through to minimal writer implementation } try { return new DefaultXmlWriter(new OutputStreamWriter(stream, "UTF-8"), closeStream); } catch (final UnsupportedEncodingException e) { throw new KNXMLException("encoding UTF-8 unknown", e); } } public XmlWriter createXMLStreamWriter(final OutputStream stream, final String encoding) { try { return createXMLStreamWriter(new OutputStreamWriter(stream, encoding)); } catch (final UnsupportedEncodingException e) { throw new KNXMLException("encoding", e); } } public void setProperty(final String name, final Object value) throws IllegalArgumentException { config.put(name, value); } public Object getProperty(final String name) throws IllegalArgumentException { return config.get(name); } public boolean isPropertySupported(final String name) { return config.containsKey(name) && config.get(name).equals(Boolean.TRUE); } }
gpl-2.0
ongo360/Mycat-Server
src/main/java/io/mycat/net/AIOConnector.java
2525
/* * Copyright (c) 2013, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.net; import java.nio.channels.CompletionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.mycat.MycatServer; import java.util.concurrent.atomic.AtomicLong; /** * @author mycat */ public final class AIOConnector implements SocketConnector, CompletionHandler<Void, BackendAIOConnection> { private static final Logger LOGGER = LoggerFactory.getLogger(AIOConnector.class); private static final ConnectIdGenerator ID_GENERATOR = new ConnectIdGenerator(); public AIOConnector() { } @Override public void completed(Void result, BackendAIOConnection attachment) { finishConnect(attachment); } @Override public void failed(Throwable exc, BackendAIOConnection conn) { conn.onConnectFailed(exc); } private void finishConnect(BackendAIOConnection c) { try { if (c.finishConnect()) { c.setId(ID_GENERATOR.getId()); NIOProcessor processor = MycatServer.getInstance() .nextProcessor(); c.setProcessor(processor); c.register(); } } catch (Exception e) { c.onConnectFailed(e); LOGGER.info("connect err " + e); c.close(e.toString()); } } /** * 后端连接ID生成器 * * @author mycat */ private static class ConnectIdGenerator { private static final long MAX_VALUE = Long.MAX_VALUE; private AtomicLong connectId = new AtomicLong(0); private long getId() { return connectId.incrementAndGet(); } } }
gpl-2.0
karambir252/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/accounts/helpers/FetchBlogListWPCom.java
3900
package org.wordpress.android.ui.accounts.helpers; import android.content.Context; import com.android.volley.VolleyError; import com.wordpress.rest.RestRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.wordpress.android.WordPress; import org.wordpress.android.networking.RestClientUtils; import org.wordpress.android.util.AppLog; import org.wordpress.android.util.AppLog.T; import org.wordpress.android.util.JSONUtils; import org.wordpress.android.util.VolleyUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FetchBlogListWPCom extends FetchBlogListAbstract { private Context mContext; public FetchBlogListWPCom(Context context) { super(null, null); mContext = context; } protected void fetchBlogList(final Callback callback) { getUsersBlogsRequestREST(callback); } private List<Map<String, Object>> convertJSONObjectToSiteList(JSONObject jsonObject, boolean keepJetpackSites) { List<Map<String, Object>> sites = new ArrayList<Map<String, Object>>(); JSONArray jsonSites = jsonObject.optJSONArray("sites"); if (jsonSites != null) { for (int i = 0; i < jsonSites.length(); i++) { JSONObject jsonSite = jsonSites.optJSONObject(i); Map<String, Object> site = new HashMap<String, Object>(); try { // skip if it's a jetpack site and we don't keep them if (jsonSite.getBoolean("jetpack") && !keepJetpackSites) { continue; } site.put("blogName", jsonSite.get("name")); site.put("url", jsonSite.get("URL")); site.put("blogid", jsonSite.get("ID")); site.put("isAdmin", jsonSite.get("user_can_manage")); site.put("isVisible", jsonSite.get("visible")); // store capabilities as a json string site.put("capabilities", jsonSite.getString("capabilities")); JSONObject plan = jsonSite.getJSONObject("plan"); site.put("planID", plan.get("product_id")); site.put("plan_product_name_short", plan.get("product_name_short")); JSONObject jsonLinks = JSONUtils.getJSONChild(jsonSite, "meta/links"); if (jsonLinks != null) { site.put("xmlrpc", jsonLinks.getString("xmlrpc")); sites.add(site); } else { AppLog.e(T.NUX, "xmlrpc links missing from the me/sites REST response"); } } catch (JSONException e) { AppLog.e(T.NUX, e); } } } return sites; } private void getUsersBlogsRequestREST(final FetchBlogListAbstract.Callback callback) { WordPress.getRestClientUtils().get("me/sites", RestClientUtils.getRestLocaleParams(mContext), null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { if (response != null) { List<Map<String, Object>> userBlogListReceiver = convertJSONObjectToSiteList(response, true); callback.onSuccess(userBlogListReceiver); } else { callback.onSuccess(null); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { JSONObject errorObject = VolleyUtils.volleyErrorToJSON(volleyError); callback.onError(LoginWPCom.restLoginErrorToMsgId(errorObject), false, false, false, ""); } }); } }
gpl-2.0
erpcya/adempierePOS
base/src/org/compiere/model/X_M_CostDetail.java
28060
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 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 * *****************************************************************************/ /** Generated Model - DO NOT CHANGE */ package org.compiere.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.Properties; import org.compiere.util.Env; /** Generated Model for M_CostDetail * @author Adempiere (generated) * @version Release 3.8.0 - $Id$ */ public class X_M_CostDetail extends PO implements I_M_CostDetail, I_Persistent { /** * */ private static final long serialVersionUID = 20150101L; /** Standard Constructor */ public X_M_CostDetail (Properties ctx, int M_CostDetail_ID, String trxName) { super (ctx, M_CostDetail_ID, trxName); /** if (M_CostDetail_ID == 0) { setAmt (Env.ZERO); setAmtLL (Env.ZERO); setC_AcctSchema_ID (0); setIsSOTrx (false); setM_AttributeSetInstance_ID (0); setM_CostDetail_ID (0); setM_Product_ID (0); setProcessed (false); setQty (Env.ZERO); } */ } /** Load Constructor */ public X_M_CostDetail (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 3 - Client - Org */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_CostDetail[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Amount. @param Amt Amount */ public void setAmt (BigDecimal Amt) { set_Value (COLUMNNAME_Amt, Amt); } /** Get Amount. @return Amount */ public BigDecimal getAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Amt); if (bd == null) return Env.ZERO; return bd; } /** Set Amount LL. @param AmtLL Amount Lower Level Cost */ public void setAmtLL (BigDecimal AmtLL) { set_Value (COLUMNNAME_AmtLL, AmtLL); } /** Get Amount LL. @return Amount Lower Level Cost */ public BigDecimal getAmtLL () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_AmtLL); if (bd == null) return Env.ZERO; return bd; } public org.compiere.model.I_C_AcctSchema getC_AcctSchema() throws RuntimeException { return (org.compiere.model.I_C_AcctSchema)MTable.get(getCtx(), org.compiere.model.I_C_AcctSchema.Table_Name) .getPO(getC_AcctSchema_ID(), get_TrxName()); } /** Set Accounting Schema. @param C_AcctSchema_ID Rules for accounting */ public void setC_AcctSchema_ID (int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID)); } /** Get Accounting Schema. @return Rules for accounting */ public int getC_AcctSchema_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_InvoiceLine getC_InvoiceLine() throws RuntimeException { return (org.compiere.model.I_C_InvoiceLine)MTable.get(getCtx(), org.compiere.model.I_C_InvoiceLine.Table_Name) .getPO(getC_InvoiceLine_ID(), get_TrxName()); } /** Set Invoice Line. @param C_InvoiceLine_ID Invoice Detail Line */ public void setC_InvoiceLine_ID (int C_InvoiceLine_ID) { if (C_InvoiceLine_ID < 1) set_Value (COLUMNNAME_C_InvoiceLine_ID, null); else set_Value (COLUMNNAME_C_InvoiceLine_ID, Integer.valueOf(C_InvoiceLine_ID)); } /** Get Invoice Line. @return Invoice Detail Line */ public int getC_InvoiceLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_InvoiceLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_LandedCostAllocation getC_LandedCostAllocation() throws RuntimeException { return (org.compiere.model.I_C_LandedCostAllocation)MTable.get(getCtx(), org.compiere.model.I_C_LandedCostAllocation.Table_Name) .getPO(getC_LandedCostAllocation_ID(), get_TrxName()); } /** Set Landed Cost Allocation. @param C_LandedCostAllocation_ID Allocation for Land Costs */ public void setC_LandedCostAllocation_ID (int C_LandedCostAllocation_ID) { if (C_LandedCostAllocation_ID < 1) set_Value (COLUMNNAME_C_LandedCostAllocation_ID, null); else set_Value (COLUMNNAME_C_LandedCostAllocation_ID, Integer.valueOf(C_LandedCostAllocation_ID)); } /** Get Landed Cost Allocation. @return Allocation for Land Costs */ public int getC_LandedCostAllocation_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_LandedCostAllocation_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_OrderLine getC_OrderLine() throws RuntimeException { return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name) .getPO(getC_OrderLine_ID(), get_TrxName()); } /** Set Sales Order Line. @param C_OrderLine_ID Sales Order Line */ public void setC_OrderLine_ID (int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_Value (COLUMNNAME_C_OrderLine_ID, null); else set_Value (COLUMNNAME_C_OrderLine_ID, Integer.valueOf(C_OrderLine_ID)); } /** Get Sales Order Line. @return Sales Order Line */ public int getC_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_C_ProjectIssue getC_ProjectIssue() throws RuntimeException { return (org.compiere.model.I_C_ProjectIssue)MTable.get(getCtx(), org.compiere.model.I_C_ProjectIssue.Table_Name) .getPO(getC_ProjectIssue_ID(), get_TrxName()); } /** Set Project Issue. @param C_ProjectIssue_ID Project Issues (Material, Labor) */ public void setC_ProjectIssue_ID (int C_ProjectIssue_ID) { if (C_ProjectIssue_ID < 1) set_Value (COLUMNNAME_C_ProjectIssue_ID, null); else set_Value (COLUMNNAME_C_ProjectIssue_ID, Integer.valueOf(C_ProjectIssue_ID)); } /** Get Project Issue. @return Project Issues (Material, Labor) */ public int getC_ProjectIssue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ProjectIssue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Cost Adjustment. @param CostAdjustment Product Cost Adjustment */ public void setCostAdjustment (BigDecimal CostAdjustment) { set_Value (COLUMNNAME_CostAdjustment, CostAdjustment); } /** Get Cost Adjustment. @return Product Cost Adjustment */ public BigDecimal getCostAdjustment () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CostAdjustment); if (bd == null) return Env.ZERO; return bd; } /** Set Cost Adjustment Date. @param CostAdjustmentDate Product Cost Adjustment */ public void setCostAdjustmentDate (Timestamp CostAdjustmentDate) { set_Value (COLUMNNAME_CostAdjustmentDate, CostAdjustmentDate); } /** Get Cost Adjustment Date. @return Product Cost Adjustment */ public Timestamp getCostAdjustmentDate () { return (Timestamp)get_Value(COLUMNNAME_CostAdjustmentDate); } /** Set Cost Adjustment Date. @param CostAdjustmentDateLL Date Product Cost Adjustment Lower Level */ public void setCostAdjustmentDateLL (Timestamp CostAdjustmentDateLL) { set_Value (COLUMNNAME_CostAdjustmentDateLL, CostAdjustmentDateLL); } /** Get Cost Adjustment Date. @return Date Product Cost Adjustment Lower Level */ public Timestamp getCostAdjustmentDateLL () { return (Timestamp)get_Value(COLUMNNAME_CostAdjustmentDateLL); } /** Set Cost Adjustment LL. @param CostAdjustmentLL Product Cost Adjustment Lower Level */ public void setCostAdjustmentLL (BigDecimal CostAdjustmentLL) { set_Value (COLUMNNAME_CostAdjustmentLL, CostAdjustmentLL); } /** Get Cost Adjustment LL. @return Product Cost Adjustment Lower Level */ public BigDecimal getCostAdjustmentLL () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CostAdjustmentLL); if (bd == null) return Env.ZERO; return bd; } /** Set Cost Value. @param CostAmt Value with Cost */ public void setCostAmt (BigDecimal CostAmt) { set_Value (COLUMNNAME_CostAmt, CostAmt); } /** Get Cost Value. @return Value with Cost */ public BigDecimal getCostAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CostAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Cost Value LL. @param CostAmtLL Value with Cost Lower Level */ public void setCostAmtLL (BigDecimal CostAmtLL) { set_Value (COLUMNNAME_CostAmtLL, CostAmtLL); } /** Get Cost Value LL. @return Value with Cost Lower Level */ public BigDecimal getCostAmtLL () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CostAmtLL); if (bd == null) return Env.ZERO; return bd; } /** CostingMethod AD_Reference_ID=122 */ public static final int COSTINGMETHOD_AD_Reference_ID=122; /** Standard Costing = S */ public static final String COSTINGMETHOD_StandardCosting = "S"; /** Average PO = A */ public static final String COSTINGMETHOD_AveragePO = "A"; /** Lifo = L */ public static final String COSTINGMETHOD_Lifo = "L"; /** Fifo = F */ public static final String COSTINGMETHOD_Fifo = "F"; /** Last PO Price = p */ public static final String COSTINGMETHOD_LastPOPrice = "p"; /** Average Invoice = I */ public static final String COSTINGMETHOD_AverageInvoice = "I"; /** Last Invoice = i */ public static final String COSTINGMETHOD_LastInvoice = "i"; /** User Defined = U */ public static final String COSTINGMETHOD_UserDefined = "U"; /** _ = x */ public static final String COSTINGMETHOD__ = "x"; /** Set Costing Method. @param CostingMethod Indicates how Costs will be calculated */ public void setCostingMethod (String CostingMethod) { set_Value (COLUMNNAME_CostingMethod, CostingMethod); } /** Get Costing Method. @return Indicates how Costs will be calculated */ public String getCostingMethod () { return (String)get_Value(COLUMNNAME_CostingMethod); } /** Set Accumulated Amt. @param CumulatedAmt Total Amount */ public void setCumulatedAmt (BigDecimal CumulatedAmt) { set_Value (COLUMNNAME_CumulatedAmt, CumulatedAmt); } /** Get Accumulated Amt. @return Total Amount */ public BigDecimal getCumulatedAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CumulatedAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Accumulated Amt LL. @param CumulatedAmtLL Total Amount */ public void setCumulatedAmtLL (BigDecimal CumulatedAmtLL) { set_Value (COLUMNNAME_CumulatedAmtLL, CumulatedAmtLL); } /** Get Accumulated Amt LL. @return Total Amount */ public BigDecimal getCumulatedAmtLL () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CumulatedAmtLL); if (bd == null) return Env.ZERO; return bd; } /** Set Accumulated Qty. @param CumulatedQty Total Quantity */ public void setCumulatedQty (BigDecimal CumulatedQty) { set_Value (COLUMNNAME_CumulatedQty, CumulatedQty); } /** Get Accumulated Qty. @return Total Quantity */ public BigDecimal getCumulatedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CumulatedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Current Cost Price. @param CurrentCostPrice The currently used cost price */ public void setCurrentCostPrice (BigDecimal CurrentCostPrice) { set_Value (COLUMNNAME_CurrentCostPrice, CurrentCostPrice); } /** Get Current Cost Price. @return The currently used cost price */ public BigDecimal getCurrentCostPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CurrentCostPrice); if (bd == null) return Env.ZERO; return bd; } /** Set Current Cost Price LL. @param CurrentCostPriceLL Current Price Lower Level Is the sum of the costs of the components of this product manufactured for this level. */ public void setCurrentCostPriceLL (BigDecimal CurrentCostPriceLL) { set_Value (COLUMNNAME_CurrentCostPriceLL, CurrentCostPriceLL); } /** Get Current Cost Price LL. @return Current Price Lower Level Is the sum of the costs of the components of this product manufactured for this level. */ public BigDecimal getCurrentCostPriceLL () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CurrentCostPriceLL); if (bd == null) return Env.ZERO; return bd; } /** Set Current Quantity. @param CurrentQty Current Quantity */ public void setCurrentQty (BigDecimal CurrentQty) { set_Value (COLUMNNAME_CurrentQty, CurrentQty); } /** Get Current Quantity. @return Current Quantity */ public BigDecimal getCurrentQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_CurrentQty); if (bd == null) return Env.ZERO; return bd; } /** Set Account Date. @param DateAcct Accounting Date */ public void setDateAcct (Timestamp DateAcct) { set_Value (COLUMNNAME_DateAcct, DateAcct); } /** Get Account Date. @return Accounting Date */ public Timestamp getDateAcct () { return (Timestamp)get_Value(COLUMNNAME_DateAcct); } /** Set Delta Amount. @param DeltaAmt Difference Amount */ public void setDeltaAmt (BigDecimal DeltaAmt) { set_Value (COLUMNNAME_DeltaAmt, DeltaAmt); } /** Get Delta Amount. @return Difference Amount */ public BigDecimal getDeltaAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DeltaAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Delta Quantity. @param DeltaQty Quantity Difference */ public void setDeltaQty (BigDecimal DeltaQty) { set_Value (COLUMNNAME_DeltaQty, DeltaQty); } /** Get Delta Quantity. @return Quantity Difference */ public BigDecimal getDeltaQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DeltaQty); if (bd == null) return Env.ZERO; return bd; } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Reversal. @param IsReversal This is a reversing transaction */ public void setIsReversal (boolean IsReversal) { set_Value (COLUMNNAME_IsReversal, Boolean.valueOf(IsReversal)); } /** Get Reversal. @return This is a reversing transaction */ public boolean isReversal () { Object oo = get_Value(COLUMNNAME_IsReversal); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_M_AttributeSetInstance getM_AttributeSetInstance() throws RuntimeException { return (I_M_AttributeSetInstance)MTable.get(getCtx(), I_M_AttributeSetInstance.Table_Name) .getPO(getM_AttributeSetInstance_ID(), get_TrxName()); } /** Set Attribute Set Instance. @param M_AttributeSetInstance_ID Product Attribute Set Instance */ public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID) { if (M_AttributeSetInstance_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID)); } /** Get Attribute Set Instance. @return Product Attribute Set Instance */ public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Cost Detail. @param M_CostDetail_ID Cost Detail Information */ public void setM_CostDetail_ID (int M_CostDetail_ID) { if (M_CostDetail_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostDetail_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostDetail_ID, Integer.valueOf(M_CostDetail_ID)); } /** Get Cost Detail. @return Cost Detail Information */ public int getM_CostDetail_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostDetail_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_CostElement getM_CostElement() throws RuntimeException { return (org.compiere.model.I_M_CostElement)MTable.get(getCtx(), org.compiere.model.I_M_CostElement.Table_Name) .getPO(getM_CostElement_ID(), get_TrxName()); } /** Set Cost Element. @param M_CostElement_ID Product Cost Element */ public void setM_CostElement_ID (int M_CostElement_ID) { if (M_CostElement_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID)); } /** Get Cost Element. @return Product Cost Element */ public int getM_CostElement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_CostType getM_CostType() throws RuntimeException { return (org.compiere.model.I_M_CostType)MTable.get(getCtx(), org.compiere.model.I_M_CostType.Table_Name) .getPO(getM_CostType_ID(), get_TrxName()); } /** Set Cost Type. @param M_CostType_ID Type of Cost (e.g. Current, Plan, Future) */ public void setM_CostType_ID (int M_CostType_ID) { if (M_CostType_ID < 1) set_Value (COLUMNNAME_M_CostType_ID, null); else set_Value (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID)); } /** Get Cost Type. @return Type of Cost (e.g. Current, Plan, Future) */ public int getM_CostType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InOutLine getM_InOutLine() throws RuntimeException { return (org.compiere.model.I_M_InOutLine)MTable.get(getCtx(), org.compiere.model.I_M_InOutLine.Table_Name) .getPO(getM_InOutLine_ID(), get_TrxName()); } /** Set Shipment/Receipt Line. @param M_InOutLine_ID Line on Shipment or Receipt document */ public void setM_InOutLine_ID (int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_Value (COLUMNNAME_M_InOutLine_ID, null); else set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID)); } /** Get Shipment/Receipt Line. @return Line on Shipment or Receipt document */ public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_InventoryLine getM_InventoryLine() throws RuntimeException { return (org.compiere.model.I_M_InventoryLine)MTable.get(getCtx(), org.compiere.model.I_M_InventoryLine.Table_Name) .getPO(getM_InventoryLine_ID(), get_TrxName()); } /** Set Phys.Inventory Line. @param M_InventoryLine_ID Unique line in an Inventory document */ public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_Value (COLUMNNAME_M_InventoryLine_ID, null); else set_Value (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Phys.Inventory Line. @return Unique line in an Inventory document */ public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_MovementLine getM_MovementLine() throws RuntimeException { return (org.compiere.model.I_M_MovementLine)MTable.get(getCtx(), org.compiere.model.I_M_MovementLine.Table_Name) .getPO(getM_MovementLine_ID(), get_TrxName()); } /** Set Move Line. @param M_MovementLine_ID Inventory Move document Line */ public void setM_MovementLine_ID (int M_MovementLine_ID) { if (M_MovementLine_ID < 1) set_Value (COLUMNNAME_M_MovementLine_ID, null); else set_Value (COLUMNNAME_M_MovementLine_ID, Integer.valueOf(M_MovementLine_ID)); } /** Get Move Line. @return Inventory Move document Line */ public int getM_MovementLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return (org.compiere.model.I_M_Product)MTable.get(getCtx(), org.compiere.model.I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_ProductionLine getM_ProductionLine() throws RuntimeException { return (org.compiere.model.I_M_ProductionLine)MTable.get(getCtx(), org.compiere.model.I_M_ProductionLine.Table_Name) .getPO(getM_ProductionLine_ID(), get_TrxName()); } /** Set Production Line. @param M_ProductionLine_ID Document Line representing a production */ public void setM_ProductionLine_ID (int M_ProductionLine_ID) { if (M_ProductionLine_ID < 1) set_Value (COLUMNNAME_M_ProductionLine_ID, null); else set_Value (COLUMNNAME_M_ProductionLine_ID, Integer.valueOf(M_ProductionLine_ID)); } /** Get Production Line. @return Document Line representing a production */ public int getM_ProductionLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductionLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Inventory Transaction. @param M_Transaction_ID Inventory Transaction */ public void setM_Transaction_ID (int M_Transaction_ID) { if (M_Transaction_ID < 1) set_Value (COLUMNNAME_M_Transaction_ID, null); else set_Value (COLUMNNAME_M_Transaction_ID, Integer.valueOf(M_Transaction_ID)); } /** Get Inventory Transaction. @return Inventory Transaction */ public int getM_Transaction_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Transaction_ID); if (ii == null) return 0; return ii.intValue(); } public org.compiere.model.I_M_Warehouse getM_Warehouse() throws RuntimeException { return (org.compiere.model.I_M_Warehouse)MTable.get(getCtx(), org.compiere.model.I_M_Warehouse.Table_Name) .getPO(getM_Warehouse_ID(), get_TrxName()); } /** Set Warehouse. @param M_Warehouse_ID Storage Warehouse and Service Point */ public void setM_Warehouse_ID (int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Warehouse_ID, Integer.valueOf(M_Warehouse_ID)); } /** Get Warehouse. @return Storage Warehouse and Service Point */ public int getM_Warehouse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Warehouse_ID); if (ii == null) return 0; return ii.intValue(); } public org.eevolution.model.I_PP_Cost_Collector getPP_Cost_Collector() throws RuntimeException { return (org.eevolution.model.I_PP_Cost_Collector)MTable.get(getCtx(), org.eevolution.model.I_PP_Cost_Collector.Table_Name) .getPO(getPP_Cost_Collector_ID(), get_TrxName()); } /** Set Manufacturing Cost Collector. @param PP_Cost_Collector_ID Manufacturing Cost Collector */ public void setPP_Cost_Collector_ID (int PP_Cost_Collector_ID) { if (PP_Cost_Collector_ID < 1) set_Value (COLUMNNAME_PP_Cost_Collector_ID, null); else set_Value (COLUMNNAME_PP_Cost_Collector_ID, Integer.valueOf(PP_Cost_Collector_ID)); } /** Get Manufacturing Cost Collector. @return Manufacturing Cost Collector */ public int getPP_Cost_Collector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PP_Cost_Collector_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Price. @param Price Price */ public void setPrice (BigDecimal Price) { throw new IllegalArgumentException ("Price is virtual column"); } /** Get Price. @return Price */ public BigDecimal getPrice () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price); if (bd == null) return Env.ZERO; return bd; } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Quantity. @param Qty Quantity */ public void setQty (BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Quantity. @return Quantity */ public BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
gpl-2.0
CarstenHollmann/series-rest-api
io/src/test/java/org/n52/io/handler/DatasetFactoryTest.java
4852
/* * Copyright (C) 2013-2020 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public License * version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ package org.n52.io.handler; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class DatasetFactoryTest { private ConfigTypedFactory<Collection<Object>> factory; @BeforeEach public void setUp() throws URISyntaxException { File config = getConfigFile("dataset-collection-factory.properties"); factory = createCollectionFactory(config); } @Test public void when_created_then_hasMappings() throws DatasetFactoryException { assertTrue(factory.create("arraylist") .getClass() == ArrayList.class); } @Test public void when_created_then_initHaveBeenCalled() throws DatasetFactoryException { assertThat(factory.create("arraylist") .isEmpty(), Matchers.is(false)); } @Test public void when_createdWithNullConfig_then_configureWithFallback() { ConfigTypedFactory<Collection<Object>> f = createCollectionFactory(null); assertTrue(f.isKnown("test_target")); } @Test public void when_havingInvalidEntry_then_throwException() throws URISyntaxException, DatasetFactoryException { DatasetFactoryException thrown = assertThrows(DatasetFactoryException.class, () -> { File configFile = getConfigFile("dataset-collection-factory-invalid-entry.properties"); new DefaultIoFactory<>(configFile).create("invalid"); }); assertTrue(thrown.getMessage().equals("No datasets available for 'invalid'.")); } @Test public void when_creatingOfInvalidType_then_throwException() throws DatasetFactoryException { DatasetFactoryException thrown = assertThrows(DatasetFactoryException.class, () -> { factory.create("invalid"); }); assertTrue(thrown.getMessage().equals("No datasets available for 'invalid'.")); } private File getConfigFile(String name) throws URISyntaxException { Path root = Paths.get(getClass().getResource("/") .toURI()); return root.resolve(name) .toFile(); } private ConfigTypedFactory<Collection<Object>> createCollectionFactory(File config) { return new ConfigTypedFactory<Collection<Object>>(config) { @Override protected String getFallbackConfigResource() { return "/dataset-collection-factory-fallback.properties"; } @Override protected Collection<Object> initInstance(Collection<Object> instance) { instance.add(new Object()); return instance; } @Override protected Class<TestTarget> getTargetType() { // make sure the classloader finds the fallback config return TestTarget.class; } }; } /** * Provide a target type from where the classloader can find a fallback configuration. */ public static class TestTarget extends ArrayList<String> { private static final long serialVersionUID = -607687051283050368L; } }
gpl-2.0
smarr/graal
src/share/tools/ProjectCreator/WinGammaPlatformVC10.java
16253
/* * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.file.FileSystems; import java.util.Iterator; import java.util.LinkedList; import java.util.UUID; import java.util.Vector; public class WinGammaPlatformVC10 extends WinGammaPlatformVC7 { LinkedList <String>filters = new LinkedList<String>(); LinkedList <String[]>filterDeps = new LinkedList<String[]>(); @Override protected String getProjectExt() { return ".vcxproj"; } @Override public void writeProjectFile(String projectFileName, String projectName, Vector<BuildConfig> allConfigs) throws IOException { System.out.println(); System.out.println(" Writing .vcxproj file: " + projectFileName); String projDir = Util.normalize(new File(projectFileName).getParent()); printWriter = new PrintWriter(projectFileName, "UTF-8"); printWriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); startTag("Project", "DefaultTargets", "Build", "ToolsVersion", "4.0", "xmlns", "http://schemas.microsoft.com/developer/msbuild/2003"); startTag("ItemGroup", "Label", "ProjectConfigurations"); for (BuildConfig cfg : allConfigs) { startTag("ProjectConfiguration", "Include", cfg.get("Name")); tagData("Configuration", cfg.get("Id")); tagData("Platform", cfg.get("PlatformName")); endTag(); } endTag(); startTag("PropertyGroup", "Label", "Globals"); tagData("ProjectGuid", "{8822CB5C-1C41-41C2-8493-9F6E1994338B}"); tag("SccProjectName"); tag("SccLocalPath"); endTag(); tag("Import", "Project", "$(VCTargetsPath)\\Microsoft.Cpp.Default.props"); for (BuildConfig cfg : allConfigs) { startTag(cfg, "PropertyGroup", "Label", "Configuration"); tagData("ConfigurationType", "DynamicLibrary"); tagData("UseOfMfc", "false"); endTag(); } tag("Import", "Project", "$(VCTargetsPath)\\Microsoft.Cpp.props"); startTag("ImportGroup", "Label", "ExtensionSettings"); endTag(); for (BuildConfig cfg : allConfigs) { startTag(cfg, "ImportGroup", "Label", "PropertySheets"); tag("Import", "Project", "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props", "Condition", "exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')", "Label", "LocalAppDataPlatform"); endTag(); } tag("PropertyGroup", "Label", "UserMacros"); startTag("PropertyGroup"); tagData("_ProjectFileVersion", "10.0.30319.1"); for (BuildConfig cfg : allConfigs) { tagData(cfg, "OutDir", cfg.get("OutputDir") + Util.sep); tagData(cfg, "IntDir", cfg.get("OutputDir") + Util.sep); tagData(cfg, "LinkIncremental", "false"); } for (BuildConfig cfg : allConfigs) { tagData(cfg, "CodeAnalysisRuleSet", "AllRules.ruleset"); tag(cfg, "CodeAnalysisRules"); tag(cfg, "CodeAnalysisRuleAssemblies"); } endTag(); for (BuildConfig cfg : allConfigs) { startTag(cfg, "ItemDefinitionGroup"); startTag("ClCompile"); tagV(cfg.getV("CompilerFlags")); endTag(); startTag("Link"); tagV(cfg.getV("LinkerFlags")); endTag(); startTag("PreLinkEvent"); tagData("Message", BuildConfig.getFieldString(null, "PrelinkDescription")); tagData("Command", cfg.expandFormat(BuildConfig.getFieldString(null, "PrelinkCommand").replace("\t", "\r\n"))); endTag(); endTag(); } writeFiles(allConfigs, projDir); tag("Import", "Project", "$(VCTargetsPath)\\Microsoft.Cpp.targets"); startTag("ImportGroup", "Label", "ExtensionTargets"); endTag(); endTag(); printWriter.close(); System.out.println(" Done writing .vcxproj file."); writeFilterFile(projectFileName, projectName, allConfigs, projDir); writeUserFile(projectFileName, allConfigs); } private void writeUserFile(String projectFileName, Vector<BuildConfig> allConfigs) throws FileNotFoundException, UnsupportedEncodingException { String userFileName = projectFileName + ".user"; if (new File(userFileName).exists()) { return; } System.out.print(" Writing .vcxproj.user file: " + userFileName); printWriter = new PrintWriter(userFileName, "UTF-8"); printWriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); startTag("Project", "ToolsVersion", "4.0", "xmlns", "http://schemas.microsoft.com/developer/msbuild/2003"); for (BuildConfig cfg : allConfigs) { startTag(cfg, "PropertyGroup"); tagData("LocalDebuggerCommand", cfg.get("JdkTargetRoot") + "\\bin\\java.exe"); tagData("LocalDebuggerCommandArguments", "-XXaltjvm=$(TargetDir) -Dsun.java.launcher=gamma"); tagData("LocalDebuggerEnvironment", "JAVA_HOME=" + cfg.get("JdkTargetRoot")); endTag(); } endTag(); printWriter.close(); System.out.println(" Done."); } public void addFilter(String rPath) { filters.add(rPath); } public void addFilterDependency(String fileLoc, String filter) { filterDeps.add(new String[] {fileLoc, filter}); } private void writeFilterFile(String projectFileName, String projectName, Vector<BuildConfig> allConfigs, String base) throws FileNotFoundException, UnsupportedEncodingException { String filterFileName = projectFileName + ".filters"; System.out.print(" Writing .vcxproj.filters file: " + filterFileName); printWriter = new PrintWriter(filterFileName, "UTF-8"); printWriter.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); startTag("Project", "ToolsVersion", "4.0", "xmlns", "http://schemas.microsoft.com/developer/msbuild/2003"); startTag("ItemGroup"); for (String filter : filters) { startTag("Filter", "Include",filter); UUID uuid = UUID.randomUUID(); tagData("UniqueIdentifier", "{" + uuid.toString() + "}"); endTag(); } startTag("Filter", "Include", "Resource Files"); UUID uuid = UUID.randomUUID(); tagData("UniqueIdentifier", "{" + uuid.toString() + "}"); tagData("Extensions", "ico;cur;bmp;dlg;rc2;rct;bin;cnt;rtf;gif;jpg;jpeg;jpe"); endTag(); endTag(); //TODO - do I need to split cpp and hpp files? // then all files startTag("ItemGroup"); for (String[] dep : filterDeps) { String tagName = getFileTagFromSuffix(dep[0]); startTag(tagName, "Include", dep[0]); tagData("Filter", dep[1]); endTag(); } endTag(); endTag(); printWriter.close(); System.out.println(" Done."); } public String getFileTagFromSuffix(String fileName) { if (fileName.endsWith(".cpp")) { return"ClCompile"; } else if (fileName.endsWith(".c")) { return "ClCompile"; } else if (fileName.endsWith(".hpp")) { return"ClInclude"; } else if (fileName.endsWith(".h")) { return "ClInclude"; } else { return"None"; } } void writeFiles(Vector<BuildConfig> allConfigs, String projDir) { // This code assummes there are no config specific includes. startTag("ItemGroup"); String sourceBase = BuildConfig.getFieldString(null, "SourceBase"); // Use first config for all global absolute includes. BuildConfig baseConfig = allConfigs.firstElement(); Vector<String> rv = new Vector<String>(); // Then use first config for all relative includes Vector<String> ri = new Vector<String>(); baseConfig.collectRelevantVectors(ri, "RelativeSrcInclude"); for (String f : ri) { rv.add(sourceBase + Util.sep + f); } baseConfig.collectRelevantVectors(rv, "AbsoluteSrcInclude"); handleIncludes(rv, allConfigs); endTag(); } // Will visit file tree for each include private void handleIncludes(Vector<String> includes, Vector<BuildConfig> allConfigs) { for (String path : includes) { FileTreeCreatorVC10 ftc = new FileTreeCreatorVC10(FileSystems.getDefault().getPath(path) , allConfigs, this); try { ftc.writeFileTree(); } catch (IOException e) { e.printStackTrace(); } } } String buildCond(BuildConfig cfg) { return "'$(Configuration)|$(Platform)'=='"+cfg.get("Name")+"'"; } void tagV(Vector<String> v) { Iterator<String> i = v.iterator(); while(i.hasNext()) { String name = i.next(); String data = i.next(); tagData(name, data); } } void tagData(BuildConfig cfg, String name, String data) { tagData(name, data, "Condition", buildCond(cfg)); } void tag(BuildConfig cfg, String name, String... attrs) { String[] ss = new String[attrs.length + 2]; ss[0] = "Condition"; ss[1] = buildCond(cfg); System.arraycopy(attrs, 0, ss, 2, attrs.length); tag(name, ss); } void startTag(BuildConfig cfg, String name, String... attrs) { String[] ss = new String[attrs.length + 2]; ss[0] = "Condition"; ss[1] = buildCond(cfg); System.arraycopy(attrs, 0, ss, 2, attrs.length); startTag(name, ss); } } class CompilerInterfaceVC10 extends CompilerInterface { @Override Vector getBaseCompilerFlags(Vector defines, Vector includes, String outDir) { Vector rv = new Vector(); addAttr(rv, "AdditionalIncludeDirectories", Util.join(";", includes)); addAttr(rv, "PreprocessorDefinitions", Util.join(";", defines).replace("\\\"", "\"")); addAttr(rv, "PrecompiledHeaderFile", "precompiled.hpp"); addAttr(rv, "PrecompiledHeaderOutputFile", outDir+Util.sep+"vm.pch"); addAttr(rv, "AssemblerListingLocation", outDir); addAttr(rv, "ObjectFileName", outDir+Util.sep); addAttr(rv, "ProgramDataBaseFileName", outDir+Util.sep+"jvm.pdb"); // Set /nologo option addAttr(rv, "SuppressStartupBanner", "true"); // Surpass the default /Tc or /Tp. addAttr(rv, "CompileAs", "Default"); // Set /W3 option. addAttr(rv, "WarningLevel", "Level3"); // Set /WX option, addAttr(rv, "TreatWarningAsError", "true"); // Set /GS option addAttr(rv, "BufferSecurityCheck", "false"); // Set /Zi option. addAttr(rv, "DebugInformationFormat", "ProgramDatabase"); // Set /Yu option. addAttr(rv, "PrecompiledHeader", "Use"); // Set /EHsc- option addAttr(rv, "ExceptionHandling", ""); addAttr(rv, "MultiProcessorCompilation", "true"); return rv; } @Override Vector getDebugCompilerFlags(String opt) { Vector rv = new Vector(); // Set /On option addAttr(rv, "Optimization", opt); // Set /FR option. addAttr(rv, "BrowseInformation", "false"); // Set /MD option. addAttr(rv, "RuntimeLibrary", "MultiThreadedDLL"); // Set /Oy- option addAttr(rv, "OmitFramePointers", "false"); return rv; } @Override Vector getProductCompilerFlags() { Vector rv = new Vector(); // Set /O2 option. addAttr(rv, "Optimization", "MaxSpeed"); // Set /Oy- option addAttr(rv, "OmitFramePointers", "false"); // Set /Ob option. 1 is expandOnlyInline addAttr(rv, "InlineFunctionExpansion", "OnlyExplicitInline"); // Set /GF option. addAttr(rv, "StringPooling", "true"); // Set /MD option. 2 is rtMultiThreadedDLL addAttr(rv, "RuntimeLibrary", "MultiThreadedDLL"); // Set /Gy option addAttr(rv, "FunctionLevelLinking", "true"); return rv; } @Override Vector getBaseLinkerFlags(String outDir, String outDll, String platformName) { Vector rv = new Vector(); addAttr(rv, "AdditionalOptions", "/export:JNI_GetDefaultJavaVMInitArgs " + "/export:JNI_CreateJavaVM " + "/export:JVM_FindClassFromBootLoader "+ "/export:JNI_GetCreatedJavaVMs "+ "/export:jio_snprintf /export:jio_printf "+ "/export:jio_fprintf /export:jio_vfprintf "+ "/export:jio_vsnprintf "+ "/export:JVM_GetVersionInfo "+ "/export:JVM_GetThreadStateNames "+ "/export:JVM_GetThreadStateValues "+ "/export:JVM_InitAgentProperties"); addAttr(rv, "AdditionalDependencies", "kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;Wsock32.lib;winmm.lib;psapi.lib"); addAttr(rv, "OutputFile", outDll); addAttr(rv, "SuppressStartupBanner", "true"); addAttr(rv, "ModuleDefinitionFile", outDir+Util.sep+"vm.def"); addAttr(rv, "ProgramDatabaseFile", outDir+Util.sep+"jvm.pdb"); addAttr(rv, "SubSystem", "Windows"); addAttr(rv, "BaseAddress", "0x8000000"); addAttr(rv, "ImportLibrary", outDir+Util.sep+"jvm.lib"); if(platformName.equals("Win32")) { addAttr(rv, "TargetMachine", "MachineX86"); } else { addAttr(rv, "TargetMachine", "MachineX64"); } // We always want the /DEBUG option to get full symbol information in the pdb files addAttr(rv, "GenerateDebugInformation", "true"); return rv; } @Override Vector getDebugLinkerFlags() { Vector rv = new Vector(); // Empty now that /DEBUG option is used by all configs return rv; } @Override Vector getProductLinkerFlags() { Vector rv = new Vector(); // Set /OPT:REF option. addAttr(rv, "OptimizeReferences", "true"); // Set /OPT:ICF option. addAttr(rv, "EnableCOMDATFolding", "true"); return rv; } @Override void getAdditionalNonKernelLinkerFlags(Vector rv) { extAttr(rv, "AdditionalOptions", " /export:AsyncGetCallTrace"); } @Override String getOptFlag() { return "MaxSpeed"; } @Override String getNoOptFlag() { return "Disabled"; } @Override String makeCfgName(String flavourBuild, String platform) { return flavourBuild + "|" + platform; } }
gpl-2.0
teamfx/openjfx-10-dev-rt
apps/samples/Ensemble8/src/samples/java/ensemble/samples/graphics2d/brickbreaker/Bat.java
3724
/* * Copyright (c) 2008, 2013, Oracle and/or its affiliates. * All rights reserved. Use is subject to license terms. * * This file is available and licensed under the following license: * * 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 Oracle Corporation 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 ensemble.samples.graphics2d.brickbreaker; import javafx.geometry.Rectangle2D; import javafx.scene.Group; import javafx.scene.Parent; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class Bat extends Parent { public static final int DEFAULT_SIZE = 2; public static final int MAX_SIZE = 7; private static final Image LEFT = Config.getImages().get(Config.IMAGE_BAT_LEFT); private static final Image CENTER = Config.getImages().get(Config.IMAGE_BAT_CENTER); private static final Image RIGHT = Config.getImages().get(Config.IMAGE_BAT_RIGHT); private int size; private int width; private int height; private ImageView leftImageView; private ImageView centerImageView; private ImageView rightImageView; public int getSize() { return size; } public int getWidth() { return width; } public int getHeight() { return height; } public void changeSize(int newSize) { this.size = newSize; width = size * 12 + 45; double rightWidth = RIGHT.getWidth() - Config.SHADOW_WIDTH; double centerWidth = width - LEFT.getWidth() - rightWidth; centerImageView.setViewport(new Rectangle2D( (CENTER.getWidth() - centerWidth) / 2, 0, centerWidth, CENTER.getHeight())); rightImageView.setTranslateX(width - rightWidth); } public Bat() { height = (int)CENTER.getHeight() - Config.SHADOW_HEIGHT; Group group = new Group(); leftImageView = new ImageView(); leftImageView.setImage(LEFT); centerImageView = new ImageView(); centerImageView.setImage(CENTER); centerImageView.setTranslateX(LEFT.getWidth()); rightImageView = new ImageView(); rightImageView.setImage(RIGHT); changeSize(DEFAULT_SIZE); group.getChildren().addAll(leftImageView, centerImageView, rightImageView); getChildren().add(group); setMouseTransparent(true); } }
gpl-2.0
md-5/jdk10
src/jdk.aot/share/classes/jdk.tools.jaotc.binformat/src/jdk/tools/jaotc/binformat/elf/ElfRelocTable.java
2494
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.tools.jaotc.binformat.elf; import java.nio.ByteBuffer; import java.util.ArrayList; import jdk.tools.jaotc.binformat.elf.Elf.Elf64_Rela; final class ElfRelocTable { private final ArrayList<ArrayList<ElfRelocEntry>> relocEntries; ElfRelocTable(int numsects) { relocEntries = new ArrayList<>(numsects); for (int i = 0; i < numsects; i++) { relocEntries.add(new ArrayList<ElfRelocEntry>()); } } void createRelocationEntry(int sectindex, int offset, int symno, int type, int addend) { ElfRelocEntry entry = new ElfRelocEntry(offset, symno, type, addend); relocEntries.get(sectindex).add(entry); } int getNumRelocs(int sectionIndex) { return relocEntries.get(sectionIndex).size(); } // Return the relocation entries for a single section // or null if no entries added to section byte[] getRelocData(int sectionIndex) { ArrayList<ElfRelocEntry> entryList = relocEntries.get(sectionIndex); if (entryList.size() == 0) { return null; } ByteBuffer relocData = ElfByteBuffer.allocate(entryList.size() * Elf64_Rela.totalsize); // Copy each entry to a single ByteBuffer for (int i = 0; i < entryList.size(); i++) { ElfRelocEntry entry = entryList.get(i); relocData.put(entry.getArray()); } return (relocData.array()); } }
gpl-2.0
severinh/java-gnome
src/bindings/org/gnome/gdk/PixbufSimpleAnimIter.java
2442
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2007-2010 Operational Dynamics Consulting, Pty Ltd * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") 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 GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Classpath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.gdk; /* * FIXME this is a placeholder stub for what will become the public API for * this type. Replace this comment with appropriate javadoc including author * and since tags. Note that the class may need to be made abstract, implement * interfaces, or even have its parent changed. No API stability guarantees * are made about this class until it has been reviewed by a hacker and this * comment has been replaced. */ public class PixbufSimpleAnimIter extends PixbufAnimationIter { protected PixbufSimpleAnimIter(long pointer) { super(pointer); } }
gpl-2.0
bordertechorg/wcomponents
wcomponents-core/src/test/java/com/github/bordertech/wcomponents/WPasswordField_Test.java
11536
package com.github.bordertech.wcomponents; import com.github.bordertech.wcomponents.autocomplete.AutocompleteUtil; import com.github.bordertech.wcomponents.autocomplete.type.Password; import com.github.bordertech.wcomponents.util.SystemException; import com.github.bordertech.wcomponents.util.mock.MockRequest; import com.github.bordertech.wcomponents.validation.Diagnostic; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link WPasswordField}. * * @author Yiannis Paschalidis * @author Jonathan Austin * @author Mark Reeves * @since 1.0.0 */ public class WPasswordField_Test extends AbstractWComponentTestCase { @Test public void testDoHandleRequest() { WPasswordField field = new WPasswordField(); field.setLocked(true); setActiveContext(createUIContext()); // Request with Empty Value and Field is null (No Change) field.setData(null); MockRequest request = new MockRequest(); request.setParameter(field.getId(), ""); boolean changed = field.doHandleRequest(request); Assert.assertFalse( "doHandleRequest should have returned false for request with empty value and field is null", changed); Assert.assertNull("Value should still be null after empty request", field.getData()); // Request with Empty Value and Field is empty (No Change) field.setData(""); request = new MockRequest(); request.setParameter(field.getId(), ""); changed = field.doHandleRequest(request); Assert .assertFalse( "doHandleRequest should have returned false for request with empty value and field is empty", changed); Assert.assertEquals("Value should still be empty after empty request", "", field.getData()); // Request with Different Value (Change) request = new MockRequest(); request.setParameter(field.getId(), "X"); changed = field.doHandleRequest(request); Assert.assertTrue( "doHandleRequest should have returned true for request with different value", changed); Assert.assertEquals("Value not set after request", "X", field.getData()); // Request with Same Value (No Change) request = new MockRequest(); request.setParameter(field.getId(), "X"); changed = field.doHandleRequest(request); Assert.assertFalse("doHandleRequest should have returned false for request with same value", changed); Assert.assertEquals("Value should not have changed after request with same value", "X", field.getData()); // Request with Empty Value (Change) request = new MockRequest(); request.setParameter(field.getId(), ""); changed = field.doHandleRequest(request); Assert .assertTrue( "doHandleRequest should have returned true for request going back to an empty value", changed); Assert.assertNull("Value should go back to null for request with empty value", field. getData()); } @Test public void testGetRequestValue() { WPasswordField field = new WPasswordField(); field.setLocked(true); setActiveContext(createUIContext()); // Set current value field.setText("A"); // Empty Request (not present, should return current value) MockRequest request = new MockRequest(); Assert. assertEquals( "Current value of the field should have been returned for empty request", "A", field.getRequestValue(request)); // Request with "empty" value (should return null as an empty value on the request is treated as null) request = new MockRequest(); request.setParameter(field.getId(), ""); Assert .assertNull("Null should have been returned for request with empty value", field. getRequestValue(request)); // Request with value (should return the value on the request) request = new MockRequest(); request.setParameter(field.getId(), "X"); Assert.assertEquals("Value from the request should have been returned", "X", field. getRequestValue(request)); } @Test public void testGetValue() { WPasswordField field = new WPasswordField(); field.setLocked(true); setActiveContext(createUIContext()); // Set data as a null value field.setData(null); Assert.assertNull("getValue should return null when data is null", field.getValue()); // Set data as a empty string field.setData(""); Assert.assertNull("getValue should return null when data is an empty string", field. getValue()); // Set data as a String value field.setData("A"); Assert.assertEquals("getValue returned the incorrect value for the data", "A", field. getValue()); // Set data as an Object Object object = new Date(); field.setData(object); Assert. assertEquals("getValue should return the string value of the data", object. toString(), field.getValue()); } @Test public void testTextAccessors() { assertAccessorsCorrect(new WPasswordField(), WPasswordField::getText, WPasswordField::setText, null, "A", "B"); } @Test public void testColumnsAccessors() { assertAccessorsCorrect(new WPasswordField(), WPasswordField::getColumns, WPasswordField::setColumns, 0, 1, 2); } @Test public void testMaxLengthAccessors() { assertAccessorsCorrect(new WPasswordField(), WPasswordField::getMaxLength, WPasswordField::setMaxLength, 0, 1, 2); } @Test public void testMinLengthAccessors() { assertAccessorsCorrect(new WPasswordField(), WPasswordField::getMinLength, WPasswordField::setMinLength, 0, 1, 2); } @Test public void testPlaceholderAccessors() { assertAccessorsCorrect(new WPasswordField(), WPasswordField::getPlaceholder, WPasswordField::setPlaceholder, null, "A", "B"); } @Test public void testValidateMaxLength() { WPasswordField field = new WPasswordField(); field.setLocked(true); String text = "test"; List<Diagnostic> diags = new ArrayList<>(); setActiveContext(createUIContext()); field.setText(null); field.validate(diags); Assert.assertTrue("Null text with no maximum set should be valid", diags.isEmpty()); field.setText(""); field.validate(diags); Assert.assertTrue("Empty text with no maximum set should be valid", diags.isEmpty()); field.setText(text); field.validate(diags); Assert.assertTrue("Text with no maximum set should be valid", diags.isEmpty()); field.setMaxLength(1); field.setText(null); field.validate(diags); Assert.assertTrue("Null text with maximum set should be valid", diags.isEmpty()); field.setText(""); field.validate(diags); Assert.assertTrue("Empty text with maximum set should be valid", diags.isEmpty()); field.setText(text); field.setMaxLength(text.length() + 1); field.validate(diags); Assert.assertTrue("Text is less than maximum so should be valid", diags.isEmpty()); field.setMaxLength(text.length()); field.validate(diags); Assert.assertTrue("Text is the same as maximum so should be valid", diags.isEmpty()); field.setMaxLength(text.length() - 1); field.validate(diags); Assert.assertFalse("Text is longer than maximum so should be invalid", diags.isEmpty()); } @Test public void testValidateMinLength() { WPasswordField field = new WPasswordField(); field.setLocked(true); String text = "test"; List<Diagnostic> diags = new ArrayList<>(); setActiveContext(createUIContext()); field.setText(null); field.validate(diags); Assert.assertTrue("Null text with no minimum set should be valid", diags.isEmpty()); field.setText(""); field.validate(diags); Assert.assertTrue("Empty text with no minimum set should be valid", diags.isEmpty()); field.setText(text); field.validate(diags); Assert.assertTrue("Text with no minimum set should be valid", diags.isEmpty()); field.setMinLength(1); field.setText(null); field.validate(diags); Assert.assertTrue("Null text with minimum set should be valid", diags.isEmpty()); field.setText(""); field.validate(diags); Assert.assertTrue("Empty text with minimum set should be valid", diags.isEmpty()); field.setText(text); field.setMinLength(text.length() - 1); field.validate(diags); Assert.assertTrue("Text is longer than minimum so should be valid", diags.isEmpty()); field.setMinLength(text.length()); field.validate(diags); Assert.assertTrue("Text is the same as minimum so should be valid", diags.isEmpty()); field.setMinLength(text.length() + 1); field.validate(diags); Assert.assertFalse("Text is shorter than minimum so should be invalid", diags.isEmpty()); } @Test public void testAutocompleteDefaultsToNull() { WPasswordField field = new WPasswordField(); Assert.assertNull(field.getAutocomplete()); } @Test public void testSetAutocomplete() { WPasswordField field = new WPasswordField(); for (Password pword : Password.values()) { field.setAutocomplete(pword); Assert.assertEquals(pword.getValue(), field.getAutocomplete()); } } @Test public void testSetAutocompleteNullPasswordType() { WPasswordField field = new WPasswordField(); field.setAutocomplete(Password.CURRENT); Assert.assertNotNull(field.getAutocomplete()); field.setAutocomplete(null); Assert.assertNull(field.getAutocomplete()); } @Test public void testClearAutocomplete() { WPasswordField field = new WPasswordField(); field.setAutocomplete(Password.CURRENT); Assert.assertNotNull(field.getAutocomplete()); field.clearAutocomplete(); Assert.assertNull(field.getAutocomplete()); } @Test public void testSetAutocompleteOff() { WPasswordField field = new WPasswordField(); field.setAutocompleteOff(); Assert.assertTrue(field.isAutocompleteOff()); } @Test public void testSetAutocompleteOffAfterSetting() { WPasswordField field = new WPasswordField(); field.setAutocomplete(Password.CURRENT); field.setAutocompleteOff(); Assert.assertTrue(field.isAutocompleteOff()); } @Test public void testAddAutocompleteSection() { WPasswordField field = new WPasswordField(); String sectionName = "foo"; field.addAutocompleteSection(sectionName); Assert.assertEquals("section-foo", field.getAutocomplete()); } @Test public void testAddAutocompleteSectionAfterSetting() { WPasswordField field = new WPasswordField(); String sectionName = "foo"; String expected = AutocompleteUtil.getCombinedForSection(sectionName, Password.CURRENT.getValue()); field.setAutocomplete(Password.CURRENT); field.addAutocompleteSection(sectionName); Assert.assertEquals(expected, field.getAutocomplete()); } @Test public void testAddAutocompleteSectionAfterSettingWithSection() { WPasswordField field = new WPasswordField(); String sectionName = "foo"; String otherSectionName = "bar"; field.setAutocomplete(Password.CURRENT); field.addAutocompleteSection(otherSectionName); String expected = AutocompleteUtil.getCombinedForSection(sectionName, AutocompleteUtil.getNamedSection(otherSectionName), Password.CURRENT.getValue()); field.addAutocompleteSection(sectionName); Assert.assertEquals(expected, field.getAutocomplete()); } @Test(expected = IllegalArgumentException.class) public void testAddAutocompleteSectionEmpty() { WPasswordField field = new WPasswordField(); field.addAutocompleteSection(""); } @Test(expected = IllegalArgumentException.class) public void testAddAutocompleteSectionNull() { WPasswordField field = new WPasswordField(); field.addAutocompleteSection(null); } @Test(expected = SystemException.class) public void testAddAutocompleteSectionWhenOff() { WPasswordField field = new WPasswordField(); field.setAutocompleteOff(); field.addAutocompleteSection("foo"); } }
gpl-3.0