repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
alexksikes/elasticsearch
src/main/java/org/elasticsearch/search/dfs/DfsPhase.java
5655
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.search.dfs; import com.carrotsearch.hppc.ObjectObjectOpenHashMap; import com.carrotsearch.hppc.ObjectOpenHashSet; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.google.common.collect.ImmutableMap; import org.apache.lucene.index.IndexReaderContext; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermContext; import org.apache.lucene.search.CollectionStatistics; import org.apache.lucene.search.TermStatistics; import org.elasticsearch.common.collect.HppcMaps; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchPhase; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.rescore.RescoreSearchContext; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * */ public class DfsPhase implements SearchPhase { private static ThreadLocal<ObjectOpenHashSet<Term>> cachedTermsSet = new ThreadLocal<ObjectOpenHashSet<Term>>() { @Override protected ObjectOpenHashSet<Term> initialValue() { return new ObjectOpenHashSet<Term>(); } }; @Override public Map<String, ? extends SearchParseElement> parseElements() { return ImmutableMap.of(); } @Override public void preProcess(SearchContext context) { } public void execute(SearchContext context) { final ObjectOpenHashSet<Term> termsSet = cachedTermsSet.get(); try { if (!context.queryRewritten()) { context.updateRewriteQuery(context.searcher().rewrite(context.query())); } if (!termsSet.isEmpty()) { termsSet.clear(); } context.query().extractTerms(new DelegateSet(termsSet)); for (RescoreSearchContext rescoreContext : context.rescore()) { rescoreContext.rescorer().extractTerms(context, rescoreContext, new DelegateSet(termsSet)); } Term[] terms = termsSet.toArray(Term.class); TermStatistics[] termStatistics = new TermStatistics[terms.length]; IndexReaderContext indexReaderContext = context.searcher().getTopReaderContext(); for (int i = 0; i < terms.length; i++) { // LUCENE 4 UPGRADE: cache TermContext? TermContext termContext = TermContext.build(indexReaderContext, terms[i]); termStatistics[i] = context.searcher().termStatistics(terms[i], termContext); } ObjectObjectOpenHashMap<String, CollectionStatistics> fieldStatistics = HppcMaps.newNoNullKeysMap(); for (Term term : terms) { assert term.field() != null : "field is null"; if (!fieldStatistics.containsKey(term.field())) { final CollectionStatistics collectionStatistics = context.searcher().collectionStatistics(term.field()); fieldStatistics.put(term.field(), collectionStatistics); } } context.dfsResult().termsStatistics(terms, termStatistics) .fieldStatistics(fieldStatistics) .maxDoc(context.searcher().getIndexReader().maxDoc()); } catch (Exception e) { throw new DfsPhaseExecutionException(context, "Exception during dfs phase", e); } finally { termsSet.clear(); // don't hold on to terms } } // We need to bridge to JCF world, b/c of Query#extractTerms private static class DelegateSet extends AbstractSet<Term> { private final ObjectOpenHashSet<Term> delegate; private DelegateSet(ObjectOpenHashSet<Term> delegate) { this.delegate = delegate; } @Override public boolean add(Term term) { return delegate.add(term); } @Override public boolean addAll(Collection<? extends Term> terms) { boolean result = false; for (Term term : terms) { result = delegate.add(term); } return result; } @Override public Iterator<Term> iterator() { final Iterator<ObjectCursor<Term>> iterator = delegate.iterator(); return new Iterator<Term>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Term next() { return iterator.next().value; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } @Override public int size() { return delegate.size(); } } }
apache-2.0
gstevey/gradle
subprojects/core/src/integTest/groovy/org/gradle/process/internal/LoggingProcess.java
1332
/* * Copyright 2016 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.gradle.process.internal; import org.gradle.api.Action; import org.gradle.process.internal.worker.WorkerProcessContext; import java.io.Serializable; import java.util.Arrays; import java.util.List; public class LoggingProcess implements Action<WorkerProcessContext>, Serializable { private final List<SerializableLogAction> actions; public LoggingProcess(SerializableLogAction... actions){ this.actions = Arrays.asList(actions); } @Override public void execute(WorkerProcessContext workerProcessContext) { workerProcessContext.getServerConnection().connect(); for (SerializableLogAction action : actions) { action.execute(); } } }
apache-2.0
hurricup/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/OpenProjectFileChooserDescriptor.java
4291
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.ide.actions; import com.intellij.icons.AllIcons; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.IconLoader; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.projectImport.ProjectOpenProcessor; import com.intellij.util.PlatformUtils; import com.intellij.util.SystemProperties; import org.jetbrains.annotations.NotNull; import javax.swing.*; /** * Intended for use in actions related to opening or importing existing projects. * <strong>Due to a high I/O impact SHOULD NOT be used in any other cases.</strong> */ public class OpenProjectFileChooserDescriptor extends FileChooserDescriptor { private static final Icon ourProjectIcon = PlatformUtils.isJetBrainsProduct() ? AllIcons.Nodes.IdeaProject : IconLoader.getIcon(ApplicationInfoEx.getInstanceEx().getSmallIconUrl()); private static final boolean ourCanInspectDirs = SystemProperties.getBooleanProperty("idea.chooser.lookup.for.project.dirs", true); public OpenProjectFileChooserDescriptor(boolean chooseFiles) { this(chooseFiles, chooseFiles); } public OpenProjectFileChooserDescriptor(boolean chooseFiles, boolean chooseJars) { super(chooseFiles, true, chooseJars, chooseJars, false, false); setHideIgnored(false); } @Override public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) { return super.isFileVisible(file, showHiddenFiles) && (file.isDirectory() || isProjectFile(file)); } @Override public boolean isFileSelectable(VirtualFile file) { return isProjectDirectory(file) || isProjectFile(file); } @Override public Icon getIcon(VirtualFile file) { if (canInspectDirectory(file)) { if (isIprFile(file) || isIdeaDirectory(file)) { return dressIcon(file, ourProjectIcon); } Icon icon = getImporterIcon(file); if (icon != null) { return dressIcon(file, icon); } } return super.getIcon(file); } private static boolean canInspectDirectory(VirtualFile file) { VirtualFile home = VfsUtil.getUserHomeDir(); if (home == null || VfsUtilCore.isAncestor(file, home, false)) { return false; } if (ourCanInspectDirs || VfsUtilCore.isAncestor(home, file, true)) { return true; } return false; } private static Icon getImporterIcon(VirtualFile file) { ProjectOpenProcessor provider = ProjectOpenProcessor.getImportProvider(file); if (provider != null) { return file.isDirectory() && provider.lookForProjectsInDirectory() ? ourProjectIcon : provider.getIcon(file); } return null; } public static boolean isProjectFile(@NotNull VirtualFile file) { return !file.isDirectory() && file.isValid() && (isIprFile(file) || hasImportProvider(file)); } private static boolean isProjectDirectory(@NotNull VirtualFile file) { return file.isDirectory() && file.isValid() && (isIdeaDirectory(file) || hasImportProvider(file)); } private static boolean isIprFile(VirtualFile file) { return ProjectFileType.DEFAULT_EXTENSION.equalsIgnoreCase(file.getExtension()); } private static boolean isIdeaDirectory(VirtualFile file) { return file.findChild(Project.DIRECTORY_STORE_FOLDER) != null; } private static boolean hasImportProvider(VirtualFile file) { return ProjectOpenProcessor.getImportProvider(file) != null; } }
apache-2.0
fariagu/dashbuilder
dashbuilder-client/dashbuilder-renderers/dashbuilder-renderer-lienzo/src/main/java/org/dashbuilder/renderer/lienzo/client/LienzoBarChartDisplayer.java
1674
/* * Copyright 2014 Red Hat, Inc. and/or its affiliates. * * 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.dashbuilder.renderer.lienzo.client; import javax.enterprise.context.Dependent; import javax.inject.Inject; import org.dashbuilder.displayer.DisplayerSubType; @Dependent public class LienzoBarChartDisplayer extends LienzoXYChartDisplayer<LienzoBarChartDisplayer.View> { public interface View extends LienzoXYChartDisplayer.View<LienzoBarChartDisplayer> { } private View view; public LienzoBarChartDisplayer() { this(new LienzoBarChartDisplayerView()); } @Inject public LienzoBarChartDisplayer(View view) { this.view = view; this.view.init(this); } @Override public View getView() { return view; } @Override protected void createVisualization() { DisplayerSubType subType = displayerSettings.getSubtype(); getView().setHorizontal(subType != null && (DisplayerSubType.BAR.equals(subType) || DisplayerSubType.BAR_STACKED.equals(subType))); super.createVisualization(); } }
apache-2.0
sdnwiselab/onos
incubator/api/src/main/java/org/onosproject/incubator/net/l2monitoring/cfm/service/CfmConfigException.java
1116
/* * Copyright 2016-present Open Networking Foundation * * 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.onosproject.incubator.net.l2monitoring.cfm.service; /** * Exception for configuration related to Connectivity Fault Management. */ public class CfmConfigException extends Throwable { private static final long serialVersionUID = 1L; public CfmConfigException(String message) { super(message); } public CfmConfigException(Throwable t) { super(t); } public CfmConfigException(String message, Throwable t) { super(message, t); } }
apache-2.0
gcoders/gerrit
gerrit-plugin-gwtui/src/main/java/com/google/gerrit/plugin/client/rpc/RestApi.java
4615
// Copyright (C) 2013 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.plugin.client.rpc; import com.google.gerrit.client.rpc.NativeString; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.http.client.URL; import com.google.gwt.user.client.rpc.AsyncCallback; public class RestApi { private final StringBuilder path; private boolean hasQueryParams; public RestApi(String name) { path = new StringBuilder(); path.append(name); } public RestApi view(String name) { return idRaw(name); } public RestApi view(String pluginName, String name) { return idRaw(pluginName + "~" + name); } public RestApi id(String id) { return idRaw(URL.encodeQueryString(id)); } public RestApi id(int id) { return idRaw(Integer.toString(id)); } public RestApi idRaw(String name) { if (hasQueryParams) { throw new IllegalStateException(); } if (path.charAt(path.length() - 1) != '/') { path.append('/'); } path.append(name); return this; } public RestApi addParameter(String name, String value) { return addParameterRaw(name, URL.encodeQueryString(value)); } public RestApi addParameter(String name, String... value) { for (String val : value) { addParameter(name, val); } return this; } public RestApi addParameterTrue(String name) { return addParameterRaw(name, null); } public RestApi addParameter(String name, boolean value) { return addParameterRaw(name, value ? "t" : "f"); } public RestApi addParameter(String name, int value) { return addParameterRaw(name, String.valueOf(value)); } public RestApi addParameter(String name, Enum<?> value) { return addParameterRaw(name, value.name()); } public RestApi addParameterRaw(String name, String value) { if (hasQueryParams) { path.append("&"); } else { path.append("?"); hasQueryParams = true; } path.append(name); if (value != null) { path.append("=").append(value); } return this; } public String path() { return path.toString(); } public <T extends JavaScriptObject> void get(AsyncCallback<T> cb) { get(path(), wrap(cb)); } public void getString(AsyncCallback<String> cb) { get(NativeString.unwrap(cb)); } private static native void get(String p, JavaScriptObject r) /*-{ $wnd.Gerrit.get(p, r) }-*/; public <T extends JavaScriptObject> void put(AsyncCallback<T> cb) { put(path(), wrap(cb)); } private static native void put(String p, JavaScriptObject r) /*-{ $wnd.Gerrit.put(p, r) }-*/; public <T extends JavaScriptObject> void put(String content, AsyncCallback<T> cb) { put(path(), content, wrap(cb)); } private static native void put(String p, String c, JavaScriptObject r) /*-{ $wnd.Gerrit.put(p, c, r) }-*/; public <T extends JavaScriptObject> void put(JavaScriptObject content, AsyncCallback<T> cb) { put(path(), content, wrap(cb)); } private static native void put(String p, JavaScriptObject c, JavaScriptObject r) /*-{ $wnd.Gerrit.put(p, c, r) }-*/; public <T extends JavaScriptObject> void post(String content, AsyncCallback<T> cb) { post(path(), content, wrap(cb)); } private static native void post(String p, String c, JavaScriptObject r) /*-{ $wnd.Gerrit.post(p, c, r) }-*/; public <T extends JavaScriptObject> void post(JavaScriptObject content, AsyncCallback<T> cb) { post(path(), content, wrap(cb)); } private static native void post(String p, JavaScriptObject c, JavaScriptObject r) /*-{ $wnd.Gerrit.post(p, c, r) }-*/; public void delete(AsyncCallback<NoContent> cb) { delete(path(), wrap(cb)); } private static native void delete(String p, JavaScriptObject r) /*-{ $wnd.Gerrit.del(p, r) }-*/; private static native <T extends JavaScriptObject> JavaScriptObject wrap(AsyncCallback<T> b) /*-{ return function(r) { b.@com.google.gwt.user.client.rpc.AsyncCallback::onSuccess(Ljava/lang/Object;)(r) } }-*/; }
apache-2.0
dropwizard/dropwizard
dropwizard-util/src/main/java/io/dropwizard/util/JavaVersion.java
561
package io.dropwizard.util; import javax.annotation.Nullable; /** * @since 2.0 */ public final class JavaVersion { private JavaVersion() { } public static boolean isJava8() { final String specVersion = getJavaSpecVersion(); return specVersion != null && specVersion.startsWith("1.8"); } @Nullable private static String getJavaSpecVersion() { try { return System.getProperty("java.specification.version"); } catch (final SecurityException ex) { return null; } } }
apache-2.0
jeorme/OG-Platform
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/curve/exposure/SecurityAndCurrencyExposureFunction.java
4376
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.curve.exposure; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import com.opengamma.core.position.Trade; import com.opengamma.core.security.Security; import com.opengamma.core.security.SecuritySource; import com.opengamma.financial.security.CurrenciesVisitor; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.FinancialSecurityVisitorSameMethodAdapter; import com.opengamma.financial.security.future.FXFutureSecurity; import com.opengamma.financial.security.option.FxFutureOptionSecurity; import com.opengamma.id.ExternalId; import com.opengamma.id.ExternalIdBundle; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; /** * Exposure function that allows the curve lookup by security type and currency of a given trade. */ public class SecurityAndCurrencyExposureFunction implements ExposureFunction { /** * The name of the exposure function. */ public static final String NAME = "Security / Currency"; private final SecurityAndCurrencyVisitor _visitor; /** * Constructor that uses a security source to look up the underlying contract for the security type and currency, if * necessary. * @param securitySource the security source containing the security definitions. */ public SecurityAndCurrencyExposureFunction(final SecuritySource securitySource) { _visitor = new SecurityAndCurrencyVisitor(ArgumentChecker.notNull(securitySource, "security source")); } @Override public String getName() { return NAME; } @Override public List<ExternalId> getIds(Trade trade) { Security security = trade.getSecurity(); if (security instanceof FinancialSecurity) { return ((FinancialSecurity) security).accept(_visitor); } return null; } private static final class DefaultSecurityAndCurrencyVisitor implements FinancialSecurityVisitorSameMethodAdapter.Visitor<List<ExternalId>> { private final SecuritySource _securitySource; public DefaultSecurityAndCurrencyVisitor(SecuritySource securitySource) { _securitySource = ArgumentChecker.notNull(securitySource, "securitySource"); } @Override public List<ExternalId> visit(FinancialSecurity security) { final Collection<Currency> currencies = CurrenciesVisitor.getCurrencies(security, _securitySource); if (currencies == null || currencies.isEmpty()) { return null; } final List<ExternalId> result = new ArrayList<>(); final String securityType = security.getSecurityType(); for (final Currency currency : currencies) { result.add(ExternalId.of(SECURITY_IDENTIFIER, securityType + SEPARATOR + currency.getCode())); } return result; } } private static final class SecurityAndCurrencyVisitor extends FinancialSecurityVisitorSameMethodAdapter<List<ExternalId>> { private final SecuritySource _securitySource; public SecurityAndCurrencyVisitor(SecuritySource securitySource) { super(new DefaultSecurityAndCurrencyVisitor(ArgumentChecker.notNull(securitySource, "securitySource"))); _securitySource = securitySource; } @Override public List<ExternalId> visitFXFutureSecurity(final FXFutureSecurity security) { final String securityType = security.getSecurityType(); return Arrays.asList(ExternalId.of(SECURITY_IDENTIFIER, securityType + SEPARATOR + security.getDenominator().getCode()), ExternalId.of(SECURITY_IDENTIFIER, securityType + SEPARATOR + security.getNumerator().getCode())); } @Override public List<ExternalId> visitFxFutureOptionSecurity(final FxFutureOptionSecurity security) { final FXFutureSecurity fxFuture = (FXFutureSecurity) _securitySource.getSingle(ExternalIdBundle.of(security.getUnderlyingId())); final String securityType = security.getSecurityType(); return Arrays.asList(ExternalId.of(SECURITY_IDENTIFIER, securityType + SEPARATOR + fxFuture.getDenominator().getCode()), ExternalId.of(SECURITY_IDENTIFIER, securityType + SEPARATOR + fxFuture.getNumerator().getCode())); } } }
apache-2.0
titusfortner/selenium
java/src/org/openqa/selenium/NoSuchElementException.java
1393
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium; /** * Thrown by {@link WebDriver#findElement(By) WebDriver.findElement(By by)} and * {@link WebElement#findElement(By by) WebElement.findElement(By by)}. */ public class NoSuchElementException extends NotFoundException { private static final String SUPPORT_URL = BASE_SUPPORT_URL + "#no_such_element"; public NoSuchElementException(String reason) { super(reason); } public NoSuchElementException(String reason, Throwable cause) { super(reason, cause); } @Override public String getSupportUrl() { return SUPPORT_URL; } }
apache-2.0
Donnerbart/hazelcast-simulator
tests/tests-hz39/src/main/java/com/hazelcast/simulator/tests/synthetic/SyntheticTest.java
6251
/* * Copyright (c) 2008-2016, Hazelcast, 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.hazelcast.simulator.tests.synthetic; import com.hazelcast.core.ExecutionCallback; import com.hazelcast.core.ICompletableFuture; import com.hazelcast.core.Partition; import com.hazelcast.simulator.probes.Probe; import com.hazelcast.simulator.test.AbstractTest; import com.hazelcast.simulator.test.BaseThreadState; import com.hazelcast.simulator.test.annotations.BeforeRun; import com.hazelcast.simulator.test.annotations.StartNanos; import com.hazelcast.simulator.test.annotations.Teardown; import com.hazelcast.simulator.test.annotations.TimeStep; import com.hazelcast.simulator.tests.helpers.HazelcastTestUtils; import com.hazelcast.simulator.tests.helpers.KeyLocality; import com.hazelcast.simulator.tests.helpers.KeyUtils; import com.hazelcast.simulator.utils.ExceptionReporter; import com.hazelcast.spi.OperationService; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import static com.hazelcast.simulator.tests.helpers.HazelcastTestUtils.getOperationCountInformation; import static com.hazelcast.simulator.tests.helpers.HazelcastTestUtils.getPartitionDistributionInformation; import static com.hazelcast.simulator.tests.helpers.HazelcastTestUtils.isClient; import static com.hazelcast.simulator.tests.helpers.KeyLocality.SHARED; /** * The SyntheticTest can be used to test features like back pressure. * <p> * It can be configured with: * - sync invocation * - async invocation * - number of sync backups * - number of async backups * - delay of back pressing. * <p> * This test doesn't make use of any normal data-structures like an {@link com.hazelcast.core.IMap}, but uses the SPI directly to * execute operations and backups. This gives a lot of control on the behavior. * <p> * If for example we want to test back pressure on async backups, just set the asyncBackupCount to a value larger than 0 and if * you want to simulate a slow down, also set the backupDelayNanos. If this is set to a high value, on the backup you will get a * pileup of back up commands which eventually can lead to an OOME. * <p> * Another interesting scenario to test is a normal async invocation of a readonly operation (so no async/sync-backups) and see if * the system can be flooded with too many request. Normal sync operations don't cause that many problems because there is a * natural balance between the number of threads and the number of pending invocations. */ public class SyntheticTest extends AbstractTest { // properties public byte syncBackupCount = 0; public byte asyncBackupCount = 1; public long backupDelayNanos = 1000 * 1000; public boolean randomizeBackupDelay = true; public KeyLocality keyLocality = SHARED; public int keyCount = 1000; public String serviceName; @BeforeRun public void beforeRun(ThreadState state) { if (isClient(targetInstance)) { throw new IllegalArgumentException("SyntheticTest doesn't support clients at the moment"); } state.operationService = HazelcastTestUtils.getOperationService(targetInstance); int[] keys = KeyUtils.generateIntKeys(keyCount, keyLocality, targetInstance); for (int key : keys) { Partition partition = targetInstance.getPartitionService().getPartition(key); state.partitionSequence.add(partition.getPartitionId()); } Collections.shuffle(state.partitionSequence); } @TimeStep(prob = 1) public void invoke(ThreadState state) throws Exception { ICompletableFuture<Object> future = state.invokeOnNextPartition(); future.get(); } @TimeStep(prob = 0) public void invokeAsync(ThreadState state, final Probe probe, @StartNanos final long startNanos) throws Exception { ICompletableFuture<Object> future = state.invokeOnNextPartition(); future.andThen(new ExecutionCallback<Object>() { @Override public void onResponse(Object o) { probe.done(startNanos); } @Override public void onFailure(Throwable throwable) { ExceptionReporter.report(testContext.getTestId(), throwable); } }); } public class ThreadState extends BaseThreadState { private final List<Integer> partitionSequence = new ArrayList<Integer>(); private final Random random = new Random(); private OperationService operationService; private int partitionIndex; private ICompletableFuture<Object> invokeOnNextPartition() throws Exception { int partitionId = nextPartitionId(); SyntheticOperation operation = new SyntheticOperation(syncBackupCount, asyncBackupCount, getBackupDelayNanos()); return operationService.invokeOnPartition(serviceName, operation, partitionId); } private int nextPartitionId() { return partitionSequence.get(partitionIndex++ % partitionSequence.size()); } private long getBackupDelayNanos() { if (syncBackupCount == 0 && asyncBackupCount == 0) { return 0; } if (!randomizeBackupDelay) { return backupDelayNanos; } if (backupDelayNanos == 0) { return 0; } return Math.abs(random.nextLong() + 1) % backupDelayNanos; } } @Teardown public void teardown() { logger.info(getOperationCountInformation(targetInstance)); logger.info(getPartitionDistributionInformation(targetInstance)); } }
apache-2.0
jeorme/OG-Platform
projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/volatility/surface/BloombergEquityFuturePriceCurveInstrumentProvider.java
7018
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.volatility.surface; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.Validate; import org.threeten.bp.LocalDate; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.financial.analytics.model.FutureOptionExpiries; import com.opengamma.financial.convention.calendar.Calendar; import com.opengamma.financial.convention.calendar.MondayToFridayCalendar; import com.opengamma.financial.convention.expirycalc.ExchangeTradedInstrumentExpiryCalculator; import com.opengamma.id.ExternalId; import com.opengamma.util.ArgumentChecker; /** * Provider of equity Future Instrument ID's. */ public class BloombergEquityFuturePriceCurveInstrumentProvider implements FuturePriceCurveInstrumentProvider<Number> { /** * Gets the expiryRules. * @return the expiryRules */ public static Map<?, ?> getExpiryRules() { return EXPIRY_RULES; } private static final HashMap<String, FutureOptionExpiries> EXPIRY_RULES; static { //TODO: Need to check whether indexes can be supported EXPIRY_RULES = new HashMap<>(); // EXPIRY_RULES.put("NKY", FutureOptionExpiries.of(new NextExpiryAdjuster(2, DayOfWeek.THURSDAY))); // EXPIRY_RULES.put("NDX", FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.THURSDAY))); //TODO // EXPIRY_RULES.put("RUT", FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.THURSDAY))); //TODO // EXPIRY_RULES.put("DJX", FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.THURSDAY))); // EXPIRY_RULES.put("SPX", FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.THURSDAY))); // EXPIRY_RULES.put("VIX", FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.THURSDAY, -30))); // check this // EXPIRY_RULES.put("UKX", FutureOptionExpiries.of(new NextExpiryAdjuster(3, DayOfWeek.THURSDAY))); EXPIRY_RULES.put("DEFAULT", FutureOptionExpiries.EQUITY_FUTURE); //TODO DAX, EUROSTOXX 50 (SX5E) } private static final Calendar WEEKDAYS = new MondayToFridayCalendar("MTWThF"); private final String _futurePrefix; private final String _postfix; private final String _dataFieldName; private final String _tickerScheme; private final String _exchange; /** * @param futurePrefix e.g. "AAPL=" * @param postfix generally, "Equity" * @param dataFieldName expecting MarketDataRequirementNames.MARKET_VALUE * @param tickerScheme expecting BLOOMBERG_TICKER_WEAK or BLOOMBERG_TICKER * @param exchange the exchange code e.g. OC */ public BloombergEquityFuturePriceCurveInstrumentProvider(final String futurePrefix, final String postfix, final String dataFieldName, final String tickerScheme, final String exchange) { Validate.notNull(futurePrefix, "future option prefix"); Validate.notNull(postfix, "postfix"); Validate.notNull(dataFieldName, "data field name"); Validate.notNull(tickerScheme, "tickerScheme was null. Try BLOOMBERG_TICKER_WEAK or BLOOMBERG_TICKER"); _futurePrefix = futurePrefix; _postfix = postfix; _dataFieldName = dataFieldName; _tickerScheme = tickerScheme; _exchange = exchange; } /** If a 4th argument is not provided, constructor uses BLOOMBERG_TICKER_WEAK as its ExternalScheme * @param futurePrefix e.g. "AAPL=" * @param postfix generally, "Equity" * @param dataFieldName expecting MarketDataRequirementNames.MARKET_VALUE * @param exchange e.g. "OC" */ public BloombergEquityFuturePriceCurveInstrumentProvider(final String futurePrefix, final String postfix, final String dataFieldName, final String exchange) { Validate.notNull(futurePrefix, "future option prefix"); Validate.notNull(postfix, "postfix"); Validate.notNull(dataFieldName, "data field name"); _futurePrefix = futurePrefix; _postfix = postfix; _dataFieldName = dataFieldName; _tickerScheme = "BLOOMBERG_TICKER_WEAK"; _exchange = exchange; } @Override public ExternalId getInstrument(final Number futureNumber) { throw new OpenGammaRuntimeException("Provider needs a curve date to create interest rate future identifier from futureNumber"); } @Override /** * Provides an ExternalID for Bloomberg ticker, * given a reference date and an integer offset, the n'th subsequent option <p> * The format is prefix + postfix <p> * e.g. AAPL=G3 OC Equity * <p> * @param futureOptionNumber n'th future following curve date, not null * @param curveDate date of future validity; valuation date, not null * @return the id of the Bloomberg ticker */ public ExternalId getInstrument(final Number futureNumber, final LocalDate curveDate) { ArgumentChecker.notNull(futureNumber, "futureOptionNumber"); ArgumentChecker.notNull(curveDate, "curve date"); final StringBuffer ticker = new StringBuffer(); ticker.append(getFuturePrefix()); final ExchangeTradedInstrumentExpiryCalculator expiryRule = getExpiryRuleCalculator(); final LocalDate expiryDate = expiryRule.getExpiryDate(futureNumber.intValue(), curveDate, WEEKDAYS); final String expiryCode = BloombergFutureUtils.getShortExpiryCode(expiryDate); ticker.append(expiryCode); ticker.append(" "); if (getExchange() != null) { ticker.append(getExchange()); ticker.append(" "); } ticker.append(getPostfix()); return ExternalId.of(getTickerScheme(), ticker.toString()); } @Override public ExchangeTradedInstrumentExpiryCalculator getExpiryRuleCalculator() { ExchangeTradedInstrumentExpiryCalculator expiryRule = EXPIRY_RULES.get(getFuturePrefix()); if (expiryRule == null) { expiryRule = EXPIRY_RULES.get("DEFAULT"); } return expiryRule; } public String getFuturePrefix() { return _futurePrefix; } public String getPostfix() { return _postfix; } @Override public String getTickerScheme() { return _tickerScheme; } @Override public String getDataFieldName() { return _dataFieldName; } /** * Gets the exchange. * @return the exchange */ public String getExchange() { return _exchange; } @Override public int hashCode() { return getFuturePrefix().hashCode() + getPostfix().hashCode() + getDataFieldName().hashCode() + getExchange().hashCode(); } @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (!(obj instanceof BloombergEquityFuturePriceCurveInstrumentProvider)) { return false; } final BloombergEquityFuturePriceCurveInstrumentProvider other = (BloombergEquityFuturePriceCurveInstrumentProvider) obj; return getFuturePrefix().equals(other.getFuturePrefix()) && getPostfix().equals(other.getPostfix()) && getDataFieldName().equals(other.getDataFieldName()) && getExchange().equals(other.getExchange()); } }
apache-2.0
shun634501730/java_source_cn
src_en/com/sun/jmx/snmp/internal/SnmpTools.java
3631
/* * Copyright (c) 2001, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.jmx.snmp.internal; import com.sun.jmx.snmp.SnmpDefinitions; /** * Utility class used to deal with various data representations. * <p><b>This API is a Sun Microsystems internal API and is subject * to change without notice.</b></p> * @since 1.5 */ public class SnmpTools implements SnmpDefinitions { /** * Translates a binary representation in an ASCII one. The returned string is an hexadecimal string starting with 0x. * @param data Binary to translate. * @return Translated binary. */ static public String binary2ascii(byte[] data, int length) { if(data == null) return null; final int size = (length * 2) + 2; byte[] asciiData = new byte[size]; asciiData[0] = (byte) '0'; asciiData[1] = (byte) 'x'; for (int i=0; i < length; i++) { int j = i*2; int v = (data[i] & 0xf0); v = v >> 4; if (v < 10) asciiData[j+2] = (byte) ('0' + v); else asciiData[j+2] = (byte) ('A' + (v - 10)); v = ((data[i] & 0xf)); if (v < 10) asciiData[j+1+2] = (byte) ('0' + v); else asciiData[j+1+2] = (byte) ('A' + (v - 10)); } return new String(asciiData); } /** * Translates a binary representation in an ASCII one. The returned string is an hexadecimal string starting with 0x. * @param data Binary to translate. * @return Translated binary. */ static public String binary2ascii(byte[] data) { return binary2ascii(data, data.length); } /** * Translates a stringified representation in a binary one. The passed string is an hexadecimal one starting with 0x. * @param str String to translate. * @return Translated string. */ static public byte[] ascii2binary(String str) { if(str == null) return null; String val = str.substring(2); int size = val.length(); byte []buf = new byte[size/2]; byte []p = val.getBytes(); for(int i = 0; i < (size / 2); i++) { int j = i * 2; byte v = 0; if (p[j] >= '0' && p[j] <= '9') { v = (byte) ((p[j] - '0') << 4); } else if (p[j] >= 'a' && p[j] <= 'f') { v = (byte) ((p[j] - 'a' + 10) << 4); } else if (p[j] >= 'A' && p[j] <= 'F') { v = (byte) ((p[j] - 'A' + 10) << 4); } else throw new Error("BAD format :" + str); if (p[j+1] >= '0' && p[j+1] <= '9') { //System.out.println("ascii : " + p[j+1]); v += (p[j+1] - '0'); //System.out.println("binary : " + v); } else if (p[j+1] >= 'a' && p[j+1] <= 'f') { //System.out.println("ascii : " + p[j+1]); v += (p[j+1] - 'a' + 10); //System.out.println("binary : " + v+1); } else if (p[j+1] >= 'A' && p[j+1] <= 'F') { //System.out.println("ascii : " + p[j+1]); v += (p[j+1] - 'A' + 10); //System.out.println("binary : " + v); } else throw new Error("BAD format :" + str); buf[i] = v; } return buf; } }
apache-2.0
nafae/developer
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201411/LabelErrorReason.java
1382
package com.google.api.ads.dfp.jaxws.v201411; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LabelError.Reason. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="LabelError.Reason"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="INVALID_PREFIX"/> * &lt;enumeration value="NAME_INVALID_CHARS"/> * &lt;enumeration value="UNKNOWN"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "LabelError.Reason") @XmlEnum public enum LabelErrorReason { /** * * A user created label cannot begin with the Google internal system label prefix. * * */ INVALID_PREFIX, /** * * {@link Label#name} contains unsupported or reserved * characters. * * */ NAME_INVALID_CHARS, /** * * The value returned if the actual value is not exposed by the requested API version. * * */ UNKNOWN; public String value() { return name(); } public static LabelErrorReason fromValue(String v) { return valueOf(v); } }
apache-2.0
nafae/developer
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201408/LiveStreamEventAction.java
4885
/** * LiveStreamEventAction.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201408; /** * Represents the actions that can be performed on {@link LiveStreamEvent} * objects. */ public abstract class LiveStreamEventAction implements java.io.Serializable { /* Indicates that this instance is a subtype of LiveStreamEventAction. * Although this field is returned in the response, it is ignored on * input * and cannot be selected. Specify xsi:type instead. */ private java.lang.String liveStreamEventActionType; public LiveStreamEventAction() { } public LiveStreamEventAction( java.lang.String liveStreamEventActionType) { this.liveStreamEventActionType = liveStreamEventActionType; } /** * Gets the liveStreamEventActionType value for this LiveStreamEventAction. * * @return liveStreamEventActionType * Indicates that this instance is a subtype of LiveStreamEventAction. * Although this field is returned in the response, it is ignored on * input * and cannot be selected. Specify xsi:type instead. */ public java.lang.String getLiveStreamEventActionType() { return liveStreamEventActionType; } /** * Sets the liveStreamEventActionType value for this LiveStreamEventAction. * * @param liveStreamEventActionType * Indicates that this instance is a subtype of LiveStreamEventAction. * Although this field is returned in the response, it is ignored on * input * and cannot be selected. Specify xsi:type instead. */ public void setLiveStreamEventActionType(java.lang.String liveStreamEventActionType) { this.liveStreamEventActionType = liveStreamEventActionType; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof LiveStreamEventAction)) return false; LiveStreamEventAction other = (LiveStreamEventAction) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.liveStreamEventActionType==null && other.getLiveStreamEventActionType()==null) || (this.liveStreamEventActionType!=null && this.liveStreamEventActionType.equals(other.getLiveStreamEventActionType()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getLiveStreamEventActionType() != null) { _hashCode += getLiveStreamEventActionType().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(LiveStreamEventAction.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "LiveStreamEventAction")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("liveStreamEventActionType"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201408", "LiveStreamEventAction.Type")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
magicDGS/gatk
src/main/java/org/broadinstitute/hellbender/utils/genotyper/AlleleListPermutation.java
333
package org.broadinstitute.hellbender.utils.genotyper; import htsjdk.variant.variantcontext.Allele; import org.broadinstitute.hellbender.utils.collections.Permutation; /** * Marks allele list permutation implementation classes. */ public interface AlleleListPermutation<A extends Allele> extends Permutation<A>, AlleleList<A> { }
bsd-3-clause
kaloyan-raev/che
ide/che-core-ide-api/src/main/java/org/eclipse/che/ide/api/editor/texteditor/TemporaryKeyBindingsManager.java
1302
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.api.editor.texteditor; import java.util.ArrayList; import java.util.List; import org.eclipse.che.ide.api.editor.keymap.KeyBinding; import org.eclipse.che.ide.api.editor.texteditor.HasKeyBindings; /** Hold {@link KeyBinding} until the editor is ready to accept them. */ public class TemporaryKeyBindingsManager implements HasKeyBindings { private final List<KeyBinding> bindings = new ArrayList<>(); @Override public void addKeyBinding(final KeyBinding keyBinding) { this.bindings.add(keyBinding); } @Override public void addKeyBinding(KeyBinding keyBinding, String actionDescription) { this.bindings.add(keyBinding); } public List<KeyBinding> getbindings() { return this.bindings; } }
epl-1.0
gazarenkov/che-sketch
plugins/plugin-github/che-plugin-github-shared/src/main/java/org/eclipse/che/plugin/github/shared/Collaborators.java
909
/******************************************************************************* * Copyright (c) 2012-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.plugin.github.shared; import org.eclipse.che.dto.shared.DTO; import java.util.List; /** * @author <a href="mailto:vparfonov@exoplatform.com">Vitaly Parfonov</a> * @version $Id: ICollaborators.java Aug 6, 2012 */ @DTO public interface Collaborators { List<GitHubUser> getCollaborators(); void setCollaborators(List<GitHubUser> collaborators); }
epl-1.0
Twelve-60/mt4j
src/org/mt4j/util/math/Ray.java
4363
/*********************************************************************** * mt4j Copyright (c) 2008 - 2009 C.Ruff, Fraunhofer-Gesellschaft All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***********************************************************************/ package org.mt4j.util.math; /** * The Class Ray. * * @author C.Ruff */ public class Ray { /** The ray start point. */ private Vector3D rayStartPoint; /** The point in ray direction. */ private Vector3D pointInRayDirection; /** The ray direction. */ private Vector3D rayDirection; /** * Instantiates a new ray. * * @param ray the ray */ public Ray(Ray ray){ super(); this.rayStartPoint = ray.getRayStartPoint().getCopy(); this.pointInRayDirection = ray.getPointInRayDirection().getCopy(); } /** * Instantiates a new ray. * * @param rayStartPoint the ray start point * @param pointInRayDirection the point in ray direction */ public Ray(Vector3D rayStartPoint, Vector3D pointInRayDirection) { super(); this.rayStartPoint = rayStartPoint; this.pointInRayDirection = pointInRayDirection; } /** * Gets the ray direction. * * @return the ray direction */ public Vector3D getRayDirection(){ return pointInRayDirection.getSubtracted(rayStartPoint); } /** * Gets the ray direction normalized. * * @return the ray direction normalized */ public Vector3D getRayDirectionNormalized(){ return getRayDirection().normalizeLocal(); } /** * Gets the point in ray direction. * * @return the point in ray direction */ public Vector3D getPointInRayDirection() { return pointInRayDirection; } /** * Sets the point in ray direction. * * @param pointInRayDirection the new point in ray direction */ public void setPointInRayDirection(Vector3D pointInRayDirection) { this.pointInRayDirection = pointInRayDirection; } /** * Gets the ray start point. * * @return the ray start point */ public Vector3D getRayStartPoint() { return rayStartPoint; } /** * Sets the ray start point. * * @param rayStartPoint the new ray start point */ public void setRayStartPoint(Vector3D rayStartPoint) { this.rayStartPoint = rayStartPoint; } /** * Transforms the ray. * The direction vector is multiplied with the transpose of the matrix. * * @param m the m */ public void transform(Matrix m){ rayStartPoint.transform(m); // pointInRayDirection.transformNormal(m); // pointInRayDirection.normalize(); //FIXME TRIAL REMOVE? NO oder vielleicht gleich bei transformNOrmal mit rein? // // pointInRayDirection = rayStartPoint.plus(pointInRayDirection); pointInRayDirection.transform(m); } /** * Calculates and returns the direction vector. * This is calced by subtracting the rayStartpoint from the point in the rays direction. * * @return the direction */ public Vector3D getDirection(){ return pointInRayDirection.getSubtracted(rayStartPoint); } /** * Returns a new ray, transformed by the matrix. * * @param ray the ray * @param m the m * * @return the transformed ray */ public static Ray getTransformedRay(Ray ray, Matrix m){ // if (!Matrix.equalIdentity(m)){ //Get a copy of the origonal ray Ray transformedRay = new Ray(ray); transformedRay.transform(m); return transformedRay; // }else{ // return ray; // } } @Override public String toString(){ return "Ray start: " + this.rayStartPoint + " PointInRayDirection: " + this.pointInRayDirection + " " + super.toString(); } }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/vmTestbase/gc/memory/Churn/Churn3/Churn3.java
2966
/* * Copyright (c) 2002, 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. */ /* * @test * @key stress gc * * @summary converted from VM Testbase gc/memory/Churn/Churn3. * VM Testbase keywords: [gc, stress, stressopt, nonconcurrent] * * @library /vmTestbase * /test/lib * @run driver jdk.test.lib.FileInstaller . . * @run main/othervm gc.memory.Churn.Churn3.Churn3 */ package gc.memory.Churn.Churn3; import nsk.share.test.*; import nsk.share.gc.*; /** * Test that GC works with memory that is churn over. * * This test starts a number of threads that create objects, * keep references to them in array and overwrite them. * The test checks that GC is able to collect these objects. * * This test is the same as Churn1 except that it creates objects * that have empty finalizer. * * @see gc.memory.Churn.Churn1.Churn1 */ public class Churn3 extends ThreadedGCTest { private int multiplier = 10; private int sizeOfArray; class ThreadObject implements Runnable { private FinMemoryObject1 objectArray[] = new FinMemoryObject1[sizeOfArray]; public ThreadObject() { for (int i = 0; i < sizeOfArray; i ++) objectArray[i] = new FinMemoryObject1(multiplier * i); } public void run() { int index = LocalRandom.nextInt(sizeOfArray); objectArray[index] = new FinMemoryObject1(multiplier * index); } } protected Runnable createRunnable(int i) { return new ThreadObject(); } public void run() { sizeOfArray = (int) Math.min(Math.sqrt(runParams.getTestMemory() * 2 / runParams.getNumberOfThreads() / multiplier), Integer.MAX_VALUE); super.run(); } public static void main(String args[]) { GC.runTest(new Churn3(), args); } }
gpl-2.0
YouDiSN/OpenJDK-Research
jdk9/jaxws/src/java.xml.ws/share/classes/com/sun/xml/internal/messaging/saaj/soap/MessageFactoryImpl.java
5854
/* * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.messaging.saaj.soap; import java.io.*; import java.util.logging.Logger; import javax.xml.soap.*; import javax.xml.stream.XMLStreamReader; import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ContentType; import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParseException; import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl; import com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl; import com.sun.xml.internal.messaging.saaj.soap.ver1_2.Message1_2Impl; import com.sun.xml.internal.messaging.saaj.util.LogDomainConstants; import com.sun.xml.internal.messaging.saaj.util.TeeInputStream; /** * A factory for creating SOAP messages. * * Converted to a placeholder for common functionality between SOAP * implementations. * * @author Phil Goodwin (phil.goodwin@sun.com) */ public class MessageFactoryImpl extends MessageFactory { protected static final Logger log = Logger.getLogger(LogDomainConstants.SOAP_DOMAIN, "com.sun.xml.internal.messaging.saaj.soap.LocalStrings"); protected OutputStream listener; protected boolean lazyAttachments = false; public OutputStream listen(OutputStream newListener) { OutputStream oldListener = listener; listener = newListener; return oldListener; } @Override public SOAPMessage createMessage() throws SOAPException { throw new UnsupportedOperationException(); } public SOAPMessage createMessage(String protocol) throws SOAPException { if (SOAPConstants.SOAP_1_1_PROTOCOL.equals(protocol)) return new com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl(); else return new com.sun.xml.internal.messaging.saaj.soap.ver1_2.Message1_2Impl(); } public SOAPMessage createMessage(boolean isFastInfoset, boolean acceptFastInfoset) throws SOAPException { throw new UnsupportedOperationException(); } public SOAPMessage createMessage(MimeHeaders headers, XMLStreamReader reader) throws SOAPException, IOException { String contentTypeString = MessageImpl.getContentType(headers); if (listener != null) { throw new SOAPException("Listener OutputStream is not supported with XMLStreamReader"); } try { ContentType contentType = new ContentType(contentTypeString); int stat = MessageImpl.identifyContentType(contentType); if (MessageImpl.isSoap1_1Content(stat)) { return new Message1_1Impl(headers,contentType,stat,reader); } else if (MessageImpl.isSoap1_2Content(stat)) { return new Message1_2Impl(headers,contentType,stat,reader); } else { log.severe("SAAJ0530.soap.unknown.Content-Type"); throw new SOAPExceptionImpl("Unrecognized Content-Type"); } } catch (ParseException e) { log.severe("SAAJ0531.soap.cannot.parse.Content-Type"); throw new SOAPExceptionImpl( "Unable to parse content type: " + e.getMessage()); } } @Override public SOAPMessage createMessage(MimeHeaders headers, InputStream in) throws SOAPException, IOException { String contentTypeString = MessageImpl.getContentType(headers); if (listener != null) { in = new TeeInputStream(in, listener); } try { ContentType contentType = new ContentType(contentTypeString); int stat = MessageImpl.identifyContentType(contentType); if (MessageImpl.isSoap1_1Content(stat)) { return new Message1_1Impl(headers,contentType,stat,in); } else if (MessageImpl.isSoap1_2Content(stat)) { return new Message1_2Impl(headers,contentType,stat,in); } else { log.severe("SAAJ0530.soap.unknown.Content-Type"); throw new SOAPExceptionImpl("Unrecognized Content-Type"); } } catch (ParseException e) { log.severe("SAAJ0531.soap.cannot.parse.Content-Type"); throw new SOAPExceptionImpl( "Unable to parse content type: " + e.getMessage()); } } protected static final String getContentType(MimeHeaders headers) { String[] values = headers.getHeader("Content-Type"); if (values == null) return null; else return values[0]; } public void setLazyAttachmentOptimization(boolean flag) { lazyAttachments = flag; } }
gpl-2.0
nuest/SOS
coding/sos-v100/src/main/java/org/n52/sos/encode/SamplingEncoderv100.java
11985
/** * Copyright (C) 2012-2015 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.sos.encode; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import java.util.Set; import net.opengis.gml.FeaturePropertyType; import net.opengis.sampling.x10.SamplingCurveDocument; import net.opengis.sampling.x10.SamplingCurveType; import net.opengis.sampling.x10.SamplingFeatureCollectionDocument; import net.opengis.sampling.x10.SamplingFeatureCollectionType; import net.opengis.sampling.x10.SamplingFeaturePropertyType; import net.opengis.sampling.x10.SamplingFeatureType; import net.opengis.sampling.x10.SamplingPointDocument; import net.opengis.sampling.x10.SamplingPointType; import net.opengis.sampling.x10.SamplingSurfaceDocument; import net.opengis.sampling.x10.SamplingSurfaceType; import org.apache.xmlbeans.XmlObject; import org.joda.time.DateTime; import org.n52.sos.coding.CodingRepository; import org.n52.sos.exception.ows.NoApplicableCodeException; import org.n52.sos.exception.ows.concrete.UnsupportedEncoderInputException; import org.n52.sos.ogc.OGCConstants; import org.n52.sos.ogc.gml.AbstractFeature; import org.n52.sos.ogc.gml.CodeType; import org.n52.sos.ogc.gml.GmlConstants; import org.n52.sos.ogc.om.features.FeatureCollection; import org.n52.sos.ogc.om.features.SfConstants; import org.n52.sos.ogc.om.features.samplingFeatures.SamplingFeature; import org.n52.sos.ogc.ows.OwsExceptionReport; import org.n52.sos.ogc.sos.ConformanceClasses; import org.n52.sos.ogc.sos.Sos1Constants; import org.n52.sos.ogc.sos.SosConstants.HelperValues; import org.n52.sos.service.ServiceConstants.SupportedTypeKey; import org.n52.sos.util.CodingHelper; import org.n52.sos.util.CollectionHelper; import org.n52.sos.util.SosHelper; import org.n52.sos.util.XmlHelper; import org.n52.sos.util.XmlOptionsHelper; import org.n52.sos.w3c.SchemaLocation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.LineString; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.geom.Polygon; /** * @since 4.0.0 * */ public class SamplingEncoderv100 extends AbstractXmlEncoder<AbstractFeature> { private static final Logger LOGGER = LoggerFactory.getLogger(SamplingEncoderv100.class); @SuppressWarnings("unchecked") private static final Set<EncoderKey> ENCODER_KEYS = CollectionHelper.union(CodingHelper.encoderKeysForElements( SfConstants.NS_SA, AbstractFeature.class)); // TODO here also the question, sa:samplingPoint sampling/1.0 vs 2.0 mapping // or not and where and how to handle private static final Map<SupportedTypeKey, Set<String>> SUPPORTED_TYPES = Collections.singletonMap( SupportedTypeKey.FeatureType, (Set<String>) ImmutableSet.of(OGCConstants.UNKNOWN, SfConstants.EN_SAMPLINGPOINT, SfConstants.EN_SAMPLINGSURFACE, SfConstants.EN_SAMPLINGCURVE)); private static final Set<String> CONFORMANCE_CLASSES = ImmutableSet.of(ConformanceClasses.OM_V2_SPATIAL_SAMPLING, ConformanceClasses.OM_V2_SAMPLING_POINT, ConformanceClasses.OM_V2_SAMPLING_CURVE, ConformanceClasses.OM_V2_SAMPLING_SURFACE); public SamplingEncoderv100() { LOGGER.debug("Encoder for the following keys initialized successfully: {}!", Joiner.on(", ") .join(ENCODER_KEYS)); } @Override public Set<EncoderKey> getEncoderKeyType() { return Collections.unmodifiableSet(ENCODER_KEYS); } @Override public Map<SupportedTypeKey, Set<String>> getSupportedTypes() { return Collections.unmodifiableMap(SUPPORTED_TYPES); } @Override public Set<String> getConformanceClasses() { return Collections.unmodifiableSet(CONFORMANCE_CLASSES); } @Override public void addNamespacePrefixToMap(Map<String, String> nameSpacePrefixMap) { nameSpacePrefixMap.put(SfConstants.NS_SA, SfConstants.NS_SA_PREFIX); } @Override public Set<SchemaLocation> getSchemaLocations() { return Sets.newHashSet(SfConstants.SA_SCHEMA_LOCATION); } @Override public XmlObject encode(AbstractFeature abstractFeature, Map<HelperValues, String> additionalValues) throws OwsExceptionReport { XmlObject encodedObject = createFeature(abstractFeature); LOGGER.debug("Encoded object {} is valid: {}", encodedObject.schemaType().toString(), XmlHelper.validateDocument(encodedObject)); return encodedObject; } private XmlObject createFeature(AbstractFeature absFeature) throws OwsExceptionReport { if (absFeature instanceof SamplingFeature) { SamplingFeature sampFeat = (SamplingFeature) absFeature; if (sampFeat.getFeatureType().equals(SfConstants.FT_SAMPLINGPOINT) || sampFeat.getFeatureType().equals(SfConstants.SAMPLING_FEAT_TYPE_SF_SAMPLING_POINT) || sampFeat.getGeometry() instanceof Point) { SamplingPointDocument xbSamplingPointDoc = SamplingPointDocument.Factory.newInstance(XmlOptionsHelper.getInstance().getXmlOptions()); SamplingPointType xbSamplingPoint = xbSamplingPointDoc.addNewSamplingPoint(); addValuesToFeature(xbSamplingPoint, sampFeat); XmlObject xbGeomety = getEncodedGeometry(sampFeat.getGeometry(), absFeature.getGmlId()); xbSamplingPoint.addNewPosition().addNewPoint().set(xbGeomety); return xbSamplingPointDoc; } else if (sampFeat.getFeatureType().equals(SfConstants.FT_SAMPLINGCURVE) || sampFeat.getFeatureType().equals(SfConstants.SAMPLING_FEAT_TYPE_SF_SAMPLING_CURVE) || sampFeat.getGeometry() instanceof LineString) { SamplingCurveDocument xbSamplingCurveDoc = SamplingCurveDocument.Factory.newInstance(XmlOptionsHelper.getInstance().getXmlOptions()); SamplingCurveType xbSamplingCurve = xbSamplingCurveDoc.addNewSamplingCurve(); addValuesToFeature(xbSamplingCurve, sampFeat); XmlObject xbGeomety = getEncodedGeometry(sampFeat.getGeometry(), absFeature.getGmlId()); xbSamplingCurve.addNewShape().addNewCurve().set(xbGeomety); return xbSamplingCurveDoc; } else if (sampFeat.getFeatureType().equals(SfConstants.FT_SAMPLINGSURFACE) || sampFeat.getFeatureType().equals(SfConstants.SAMPLING_FEAT_TYPE_SF_SAMPLING_SURFACE) || sampFeat.getGeometry() instanceof Polygon) { SamplingSurfaceDocument xbSamplingSurfaceDoc = SamplingSurfaceDocument.Factory.newInstance(XmlOptionsHelper.getInstance().getXmlOptions()); SamplingSurfaceType xbSamplingSurface = xbSamplingSurfaceDoc.addNewSamplingSurface(); addValuesToFeature(xbSamplingSurface, sampFeat); XmlObject xbGeomety = getEncodedGeometry(sampFeat.getGeometry(), absFeature.getGmlId()); xbSamplingSurface.addNewShape().addNewSurface().set(xbGeomety); return xbSamplingSurfaceDoc; } } else if (absFeature instanceof FeatureCollection) { createFeatureCollection((FeatureCollection) absFeature); } throw new UnsupportedEncoderInputException(this, absFeature); } private XmlObject getEncodedGeometry(Geometry geometry, String gmlId) throws UnsupportedEncoderInputException, OwsExceptionReport { Encoder<XmlObject, Geometry> encoder = CodingRepository.getInstance().getEncoder(CodingHelper.getEncoderKey(GmlConstants.NS_GML, geometry)); if (encoder != null) { Map<HelperValues, String> additionalValues = new EnumMap<HelperValues, String>(HelperValues.class); additionalValues.put(HelperValues.GMLID, gmlId); return encoder.encode(geometry, additionalValues); } else { throw new NoApplicableCodeException() .withMessage("Error while encoding geometry for feature, needed encoder is missing!"); } } private void addValuesToFeature(SamplingFeatureType xbSamplingFeature, SamplingFeature sampFeat) throws OwsExceptionReport { xbSamplingFeature.setId(sampFeat.getGmlId()); if (sampFeat.isSetIdentifier() && SosHelper.checkFeatureOfInterestIdentifierForSosV2(sampFeat.getIdentifierCodeWithAuthority().getValue(), Sos1Constants.SERVICEVERSION)) { xbSamplingFeature.addNewName().set( CodingHelper.encodeObjectToXml(GmlConstants.NS_GML, sampFeat.getIdentifierCodeWithAuthority())); } if (sampFeat.isSetName()) { for (CodeType sosName : sampFeat.getName()) { xbSamplingFeature.addNewName().set(CodingHelper.encodeObjectToXml(GmlConstants.NS_GML, sosName)); } } // set sampledFeatures // TODO: CHECK if (sampFeat.getSampledFeatures() != null && !sampFeat.getSampledFeatures().isEmpty()) { for (AbstractFeature sampledFeature : sampFeat.getSampledFeatures()) { FeaturePropertyType sp = xbSamplingFeature.addNewSampledFeature(); sp.setHref(sampledFeature.getIdentifier()); if (sampFeat.isSetName() && sampFeat.getFirstName().isSetValue()) { sp.setTitle(sampFeat.getFirstName().getValue()); } // xbSamplingFeature.addNewSampledFeature().set(createFeature(sampledFeature)); } } else { xbSamplingFeature.addNewSampledFeature().setHref(GmlConstants.NIL_UNKNOWN); } } private XmlObject createFeatureCollection(FeatureCollection sosFeatureCollection) throws OwsExceptionReport { SamplingFeatureCollectionDocument xbSampFeatCollDoc = SamplingFeatureCollectionDocument.Factory.newInstance(XmlOptionsHelper.getInstance().getXmlOptions()); SamplingFeatureCollectionType xbSampFeatColl = xbSampFeatCollDoc.addNewSamplingFeatureCollection(); xbSampFeatColl.setId("sfc_" + Long.toString(new DateTime().getMillis())); for (AbstractFeature sosAbstractFeature : sosFeatureCollection.getMembers().values()) { SamplingFeaturePropertyType xbFeatMember = xbSampFeatColl.addNewMember(); xbFeatMember.set(createFeature(sosAbstractFeature)); } return xbSampFeatCollDoc; } }
gpl-2.0
rex-xxx/mt6572_x201
external/proguard/src/proguard/classfile/Method.java
1054
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2009 Eric Lafortune (eric@graphics.cornell.edu) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile; /** * Representation of a method from a class. * * @author Eric Lafortune */ public interface Method extends Member { }
gpl-2.0
bertrama/resin
modules/kernel/src/com/caucho/vfs/i18n/UTF8Writer.java
4144
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.vfs.i18n; import java.io.IOException; import com.caucho.util.ByteAppendable; import com.caucho.vfs.OutputStreamWithBuffer; /** * Implements an encoding char-to-byte writer for UTF8 and the associated * factory. */ public class UTF8Writer extends EncodingWriter { private final static UTF8Writer _writer = new UTF8Writer(); /** * Null-arg constructor for instantiation by com.caucho.vfs.Encoding only. */ public UTF8Writer() { } /** * Returns the Java encoding for the writer. */ @Override public String getJavaEncoding() { return "UTF8"; } /** * Returns the UTF8_Writer * * @return the UTF8_Writer */ @Override public EncodingWriter create(String javaEncoding) { return _writer; } /** * Returns the UTF8_Writer * * @return the UTF8_Writer */ public EncodingWriter create() { return _writer; } /** * Writes a character to the output stream with the correct encoding. * * @param ch the character to write. */ @Override public void write(ByteAppendable os, char ch) throws IOException { if (ch < 0x80) { os.write(ch); } else if (ch < 0x800) { os.write((0xc0 + (ch >> 6))); os.write((0x80 + (ch & 0x3f))); } else { os.write((0xe0 + (ch >> 12))); os.write((0x80 + ((ch >> 6) & 0x3f))); os.write((0x80 + (ch & 0x3f))); } } /** * Writes into a character buffer using the correct encoding. * * @param cbuf character array with the data to write. * @param off starting offset into the character array. * @param len the number of characters to write. */ @Override public int write(OutputStreamWithBuffer os, char []cbuf, int off, int len) throws IOException { byte []buffer = os.getBuffer(); int length = os.getBufferOffset(); int capacity = buffer.length; int tail = off + len; int head = off; while (off < tail) { while (capacity - length <= 4) { buffer = os.nextBuffer(length); length = os.getBufferOffset(); } char ch = cbuf[off++]; if (ch < 0x80) { buffer[length++] = (byte) ch; } else if (ch < 0x800) { buffer[length++] = (byte) (0xc0 + (ch >> 6)); buffer[length++] = (byte) (0x80 + (ch & 0x3f)); } else if (ch < 0xd800 || 0xdfff < ch) { // server/0815 buffer[length++] = (byte) (0xe0 + (ch >> 12)); buffer[length++] = (byte) (0x80 + ((ch >> 6) & 0x3f)); buffer[length++] = (byte) (0x80 + (ch & 0x3f)); } else if (off == tail) { off--; break; } else { char ch2 = cbuf[off++]; int v = 0x10000 + (ch & 0x3ff) * 0x400 + (ch2 & 0x3ff); buffer[length++] = (byte) (0xf0 + (v >> 18)); buffer[length++] = (byte) (0x80 + ((v >> 12) & 0x3f)); buffer[length++] = (byte) (0x80 + ((v >> 6) & 0x3f)); buffer[length++] = (byte) (0x80 + (v & 0x3f)); } } os.setBufferOffset(length); return off - head; } }
gpl-2.0
nuest/SOS
core/api/src/main/java/org/n52/sos/ogc/sensorML/elements/SmlLocation.java
2147
/** * Copyright (C) 2012-2015 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.sos.ogc.sensorML.elements; import com.vividsolutions.jts.geom.Point; /** * SOS internal representation of SensorML location * * @since 4.0.0 */ public class SmlLocation { // TODO AssociationAttributeGroup values? // TODO support _Curve? private Point point; /** * constructor * * @param point * Point */ public SmlLocation(final Point point) { super(); this.point = point; } /** * @return the point */ public Point getPoint() { return point; } /** * @return if the point is set */ public boolean isSetPoint() { return point != null; } /** * @param point * Point */ public void setPoint(final Point point) { this.point = point; } }
gpl-2.0
sbbic/core
qadevOOo/runner/lib/ExceptionStatus.java
1353
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package lib; /** * The class implements Status behaviour for exception runstate Status objects. */ class ExceptionStatus extends Status { /** * Creates an instance of Status object with EXCEPTION runstate. * * @param t the exception an activity terminated with. */ ExceptionStatus( Throwable t ) { super(EXCEPTION, FAILED); String message = t.getMessage(); if (message != null) runStateString = message; else runStateString = t.toString(); } }
gpl-3.0
sbandur84/micro-Blagajna
src-pos/com/openbravo/pos/panels/JPanelPayments.java
2301
// uniCenta oPOS - Touch Friendly Point Of Sale // Copyright (c) 2009-2014 uniCenta & previous Openbravo POS works // http://www.unicenta.com // // This file is part of uniCenta oPOS // // uniCenta oPOS 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. // // uniCenta oPOS 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 uniCenta oPOS. If not, see <http://www.gnu.org/licenses/>. package com.openbravo.pos.panels; import com.openbravo.data.user.EditorRecord; import com.openbravo.data.user.ListProvider; import com.openbravo.data.user.SaveProvider; import com.openbravo.pos.forms.AppLocal; import com.openbravo.pos.forms.DataLogicSales; /** * * @author adrianromero */ public class JPanelPayments extends JPanelTable { private PaymentsEditor jeditor; private DataLogicSales m_dlSales = null; /** Creates a new instance of JPanelPayments */ public JPanelPayments() { } /** * */ @Override protected void init() { m_dlSales = (DataLogicSales) app.getBean("com.openbravo.pos.forms.DataLogicSales"); jeditor = new PaymentsEditor(app, dirty); } /** * * @return */ @Override public ListProvider getListProvider() { return null; } /** * * @return */ @Override public SaveProvider getSaveProvider() { return new SaveProvider(null , m_dlSales.getPaymentMovementInsert() , m_dlSales.getPaymentMovementDelete()); } /** * * @return */ @Override public EditorRecord getEditor() { return jeditor; } /** * * @return */ @Override public String getTitle() { return AppLocal.getIntString("Menu.Payments"); } }
gpl-3.0
diohpix/flazr-fork
src/main/java/com/flazr/amf/Amf0Object.java
876
/* * Flazr <http://flazr.com> Copyright (C) 2009 Peter Thomas. * * This file is part of Flazr. * * Flazr 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 3 of the License, or * (at your option) any later version. * * Flazr 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 Flazr. If not, see <http://www.gnu.org/licenses/>. */ package com.flazr.amf; import java.util.LinkedHashMap; public class Amf0Object extends LinkedHashMap<String, Object> { }
gpl-3.0
eethomas/eucalyptus
clc/modules/msgs/src/main/java/com/eucalyptus/auth/policy/condition/DateGreaterThanEquals.java
4005
/************************************************************************* * Copyright 2009-2012 Eucalyptus Systems, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta * CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need * additional information or have any questions. * * This file may incorporate work covered under the following copyright * and permission notice: * * Software License Agreement (BSD License) * * Copyright (c) 2008, Regents of the University of California * All rights reserved. * * Redistribution and use of this software 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. * * 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. USERS OF THIS SOFTWARE ACKNOWLEDGE * THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE LICENSED MATERIAL, * COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS SOFTWARE, * AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING * IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, * SANTA BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, * WHICH IN THE REGENTS' DISCRETION MAY INCLUDE, WITHOUT LIMITATION, * REPLACEMENT OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO * IDENTIFIED, OR WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT * NEEDED TO COMPLY WITH ANY SUCH LICENSES OR RIGHTS. ************************************************************************/ package com.eucalyptus.auth.policy.condition; import java.text.ParseException; import javax.annotation.Nullable; import org.apache.log4j.Logger; import com.eucalyptus.auth.policy.key.Iso8601DateParser; @PolicyCondition( { Conditions.DATEGREATERTHANEQUALS, Conditions.DATEGREATERTHANEQUALS_S } ) public class DateGreaterThanEquals implements DateConditionOp { private static final Logger LOG = Logger.getLogger( DateEquals.class ); @Override public boolean check( @Nullable String key, String value ) { try { return key != null && Iso8601DateParser.parse( key ).compareTo( Iso8601DateParser.parse( value ) ) >= 0; } catch ( ParseException e ) { LOG.error( "Invalid input date input", e ); return false; } } }
gpl-3.0
acenode/jpexs-decompiler
libsrc/ffdec_lib/src/com/jpexs/decompiler/flash/AppResources.java
1221
/* * Copyright (C) 2010-2015 JPEXS, All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 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. */ package com.jpexs.decompiler.flash; import java.util.ResourceBundle; /** * * @author JPEXS */ public class AppResources { private static final ResourceBundle resourceBundle = ResourceBundle.getBundle("com.jpexs.decompiler.flash.locales.AppResources"); public static String translate(String key) { return resourceBundle.getString(key); } public static String translate(String bundle, String key) { ResourceBundle b = ResourceBundle.getBundle(bundle); return b.getString(key); } }
gpl-3.0
smba/oak
quercus/src/main/java/com/caucho/quercus/lib/zlib/GZInputStream.java
8454
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Nam Nguyen */ package com.caucho.quercus.lib.zlib; import com.caucho.util.IoUtil; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.zip.CRC32; import java.util.zip.DataFormatException; import java.util.zip.Inflater; /** * Similar to GZIPInputStream but with ability to read appended gzip. */ public class GZInputStream extends InputStream { private PushbackInputStream _in; private Inflater _inflater; private CRC32 _crc; private boolean _eof; private boolean _isGzip; private byte[] _readBuffer; //raw input data buffer private byte[] _tbuffer; //temporary buffer private int _readBufferSize; //amount of raw data read into _readBuffer private int _inputSize; //decompressed bytes read so far // for the current 'append' stream private long _totalInputSize; //total decompressed bytes read public GZInputStream(InputStream in) throws IOException { this(in, 512); } public GZInputStream(InputStream in, int size) throws IOException { // Need to use same buffer size for pushback and _readBuffer // because will need to unread <= _readBuffer.length. _in = new PushbackInputStream(in, size); _inflater = new Inflater(true); _crc = new CRC32(); _eof = false; _readBuffer = new byte[size]; _tbuffer = new byte[128]; _totalInputSize = 0; init(); } /** * Returns 0 if gzip EOF has been reached, 1 otherwise */ public int available() throws IOException { if (!_isGzip) return _in.available(); if (_eof == true) return 0; return 1; } /** * mark() and reset() are not supported by this class. * @return false always */ public boolean markSupported() { return false; } /** * Returns the byte read, -1 if EOF * @return number of bytes read, or -1 if EOF */ public int read() throws IOException { byte[] b = new byte[1]; int n = read(b); if (n < 0) return -1; return b[0]; } /** * Reads from the compressed stream and * stores the resulting uncompressed data into the byte array. * @return number of bytes read, or -1 upon EOF */ public int read(byte[] b) throws IOException { return read(b, 0, b.length); } /** * Reads from the compressed stream and * stores the resulting uncompressed data into the byte array. * @return number of bytes read, or -1 upon EOF */ public int read(byte[] b, int off, int len) throws IOException { if (len <= 0 || off < 0 || off + len > b.length) return 0; if (_eof) return -1; // Read from uncompressed stream if (! _isGzip) return _in.read(b, off, len); try { int sublen; int length = 0; while (length < len) { if (_inflater.needsInput()) { _readBufferSize = _in.read(_readBuffer, 0, _readBuffer.length); if (_readBufferSize < 0) break; _inflater.setInput(_readBuffer, 0, _readBufferSize); } sublen = _inflater.inflate(b, off + length, len - length); _crc.update(b, off + length, sublen); _inputSize += sublen; _totalInputSize += sublen; length += sublen; // Unread gzip trailer and possibly beginning of appended gzip data. if (_inflater.finished()) { int remaining = _inflater.getRemaining(); _in.unread(_readBuffer, _readBufferSize - remaining, remaining); readTrailer(); int secondPart = read(b, off + length, len - length); return secondPart > 0 ? length + secondPart : length; } } return length; } catch (DataFormatException e) { throw new IOException(e); } } /** * Skips over and discards n bytes. * @param n number of bytes to skip * @return actual number of bytes skipped */ public long skip(long n) throws IOException { if (_eof || n <= 0) return 0; long remaining = n; while (remaining > 0) { int length = (int)Math.min(_tbuffer.length, remaining); int sublen = read(_tbuffer, 0, length); if (sublen < 0) break; remaining -= sublen; } return (n - remaining); } /** * Inits/resets this class to be ready to read the start of a gzip stream. */ private void init() throws IOException { _inflater.reset(); _crc.reset(); _inputSize = 0; _readBufferSize = 0; byte flg; int length = _in.read(_tbuffer, 0, 10); if (length < 0) { _isGzip = false; return; } else if (length != 10) { _isGzip = false; _in.unread(_tbuffer, 0, length); return; } if (_tbuffer[0] != (byte)0x1f || _tbuffer[1] != (byte)0x8b) { _isGzip = false; _in.unread(_tbuffer, 0, length); return; } flg = _tbuffer[3]; // Skip optional field if ((flg & (byte)0x04) > 0) { length = _in.read(_tbuffer, 0, 2); if (length != 2) throw new IOException("Bad GZIP (FEXTRA) header."); length = (((int)_tbuffer[1]) << 4) | _tbuffer[0]; _in.skip(length); } int c; // Skip optional field if ((flg & (byte)0x08) > 0) { c = _in.read(); while (c != 0) { if (c < 0) throw new IOException("Bad GZIP (FNAME) header."); c = _in.read(); } } // Skip optional field if ((flg & 0x10) > 0) { c = _in.read(); while (c != 0) { if (c < 0) throw new IOException("Bad GZIP (FCOMMENT) header."); c = _in.read(); } } // Skip optional field if ((flg & 0x02) > 0) { length = _in.read(_tbuffer, 0, 2); if (length != 2) throw new IOException("Bad GZIP (FHCRC) header."); } _isGzip = true; } /** * Reads the trailer and prepare this class for the possibility * of an appended gzip stream. */ private void readTrailer() throws IOException { int length = _in.read(_tbuffer, 0, 8); if (length != 8) throw new IOException("Bad GZIP trailer."); int refValue = _tbuffer[3] & 0xff; refValue <<= 8; refValue |= _tbuffer[2] & 0xff; refValue <<= 8; refValue |= _tbuffer[1] & 0xff; refValue <<= 8; refValue |= _tbuffer[0] & 0xff; int value = (int)_crc.getValue(); if (refValue != value) throw new IOException("Bad GZIP trailer (CRC32)."); refValue = _tbuffer[7] & 0xff; refValue <<= 8; refValue |= _tbuffer[6] & 0xff; refValue <<= 8; refValue |= _tbuffer[5] & 0xff; refValue <<= 8; refValue |= _tbuffer[4] & 0xff; if (refValue != _inputSize) throw new IOException("Bad GZIP trailer (LENGTH)."); // Check to see if this gzip stream is appended with a valid gzip stream. // If it is appended, then can continue reading from stream. int c = _in.read(); if (c < 0) _eof = true; else { _in.unread(c); init(); if (!_isGzip) _eof = true; } } /** * Returns true if stream is in gzip format. */ public boolean isGzip() { return _isGzip; } @Override public void close() { _eof = true; InputStream is = _in; _in = null; IoUtil.close(is); Inflater inflater = _inflater; _inflater = null; inflater.end(); } }
lgpl-3.0
smba/oak
quercus/src/main/java/com/caucho/quercus/lib/dom/DOMElement.java
6332
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Sam */ package com.caucho.quercus.lib.dom; import com.caucho.quercus.annotation.Optional; import com.caucho.quercus.env.Env; import org.w3c.dom.Element; public class DOMElement extends DOMNode<Element> { public static DOMElement __construct(Env env, String name, @Optional String textContent, @Optional String namespace) { DOMElement element; if (namespace != null && namespace.length() > 0) element = getImpl(env).createElement(name, namespace); else element = getImpl(env).createElement(name); if (textContent != null && textContent.length() > 0) element.setTextContent(textContent); return element; } DOMElement(DOMImplementation impl, Element node) { super(impl, node); } @Override public CharSequence getNodeValue(Env env) throws DOMException { // php/1zd1 return getTextContent(env); } public String getAttribute(String name) { return _delegate.getAttribute(name); } public String getAttributeNS(String namespaceURI, String localName) throws DOMException { try { return _delegate.getAttributeNS(namespaceURI, localName); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr getAttributeNode(String name) { return wrap(_delegate.getAttributeNode(name)); } public DOMAttr getAttributeNodeNS(String namespaceURI, String localName) throws DOMException { try { return wrap(_delegate.getAttributeNodeNS(namespaceURI, localName)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMNodeList getElementsByTagName(String name) { return wrap(_delegate.getElementsByTagName(name)); } public DOMNodeList getElementsByTagNameNS( String namespaceURI, String localName) throws DOMException { try { return wrap(_delegate.getElementsByTagNameNS(namespaceURI, localName)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMTypeInfo getSchemaTypeInfo() { return wrap(_delegate.getSchemaTypeInfo()); } public String getTagName() { return _delegate.getTagName(); } public boolean hasAttribute(String name) { return _delegate.hasAttribute(name); } public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException { try { return _delegate.hasAttributeNS(namespaceURI, localName); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void removeAttribute(String name) throws DOMException { try { _delegate.removeAttribute(name); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void removeAttributeNS(String namespaceURI, String localName) throws DOMException { try { _delegate.removeAttributeNS(namespaceURI, localName); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr removeAttributeNode(DOMAttr oldAttr) throws DOMException { try { return wrap(_delegate.removeAttributeNode(oldAttr._delegate)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setAttribute(String name, String value) throws DOMException { try { _delegate.setAttribute(name, value); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException { try { _delegate.setAttributeNS(namespaceURI, qualifiedName, value); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr setAttributeNode(DOMAttr newAttr) throws DOMException { try { return wrap(_delegate.setAttributeNode(newAttr._delegate)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public DOMAttr setAttributeNodeNS(DOMAttr newAttr) throws DOMException { try { return wrap(_delegate.setAttributeNodeNS(newAttr._delegate)); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setIdAttribute(String name, boolean isId) throws DOMException { try { _delegate.setIdAttribute(name, isId); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException { try { _delegate.setIdAttributeNS(namespaceURI, localName, isId); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setIdAttributeNode(DOMAttr idAttr, boolean isId) throws DOMException { try { _delegate.setIdAttributeNode(idAttr._delegate, isId); } catch (org.w3c.dom.DOMException ex) { throw wrap(ex); } } public void setNodeValue(String nodeValue) throws DOMException { // php/1zd1 if (nodeValue == null) nodeValue = ""; setTextContent(nodeValue); } }
lgpl-3.0
laetemn/SMSSync
smssync/src/main/java/org/addhen/smssync/presentation/view/ui/activity/AppCompatPreferenceActivity.java
3854
/* * Copyright (c) 2010 - 2015 Ushahidi Inc * All rights reserved * Contact: team@ushahidi.com * Website: http://www.ushahidi.com * GNU Lesser General Public License Usage * This file may be used under the terms of the GNU Lesser * General Public License version 3 as published by the Free Software * Foundation and appearing in the file LICENSE.LGPL included in the * packaging of this file. Please review the following information to * ensure the GNU Lesser General Public License version 3 requirements * will be met: http://www.gnu.org/licenses/lgpl.html. * * If you have questions regarding the use of this file, please contact * Ushahidi developers at team@ushahidi.com. */ package org.addhen.smssync.presentation.view.ui.activity; import android.content.res.Configuration; import android.os.Bundle; import android.preference.PreferenceActivity; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.Toolbar; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls * to be used with AppCompat. * * This technique can be used with an {@link android.app.Activity} class, not just * {@link android.preference.PreferenceActivity}. */ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { private AppCompatDelegate mDelegate; @Override protected void onCreate(Bundle savedInstanceState) { getDelegate().installViewFactory(); getDelegate().onCreate(savedInstanceState); super.onCreate(savedInstanceState); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getDelegate().onPostCreate(savedInstanceState); } public ActionBar getSupportActionBar() { return getDelegate().getSupportActionBar(); } public void setSupportActionBar(@Nullable Toolbar toolbar) { getDelegate().setSupportActionBar(toolbar); } @Override public MenuInflater getMenuInflater() { return getDelegate().getMenuInflater(); } @Override public void setContentView(@LayoutRes int layoutResID) { getDelegate().setContentView(layoutResID); } @Override public void setContentView(View view) { getDelegate().setContentView(view); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { getDelegate().setContentView(view, params); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { getDelegate().addContentView(view, params); } @Override protected void onPostResume() { super.onPostResume(); getDelegate().onPostResume(); } @Override protected void onTitleChanged(CharSequence title, int color) { super.onTitleChanged(title, color); getDelegate().setTitle(title); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); getDelegate().onConfigurationChanged(newConfig); } @Override protected void onStop() { super.onStop(); getDelegate().onStop(); } @Override protected void onDestroy() { super.onDestroy(); getDelegate().onDestroy(); } public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } private AppCompatDelegate getDelegate() { if (mDelegate == null) { mDelegate = AppCompatDelegate.create(this, null); } return mDelegate; } }
lgpl-3.0
McLeodMoores/starling
projects/component/src/main/java/com/opengamma/component/factory/engine/package-info.java
236
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ /** * Factories that help setup the engine. */ package com.opengamma.component.factory.engine;
apache-2.0
OpenCollabZA/sakai
webservices/cxf/src/test/java/org/sakaiproject/webservices/SakaiScriptFindSitesByTitleTest.java
2572
package org.sakaiproject.webservices; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import java.util.ArrayList; import org.apache.cxf.jaxrs.client.WebClient; import org.junit.Test; import org.sakaiproject.site.api.SiteService.SelectionType; import org.sakaiproject.site.api.SiteService.SortType; import org.sakaiproject.tool.api.Session; public class SakaiScriptFindSitesByTitleTest extends AbstractCXFTest { public static final String SESSION_ID = "***SESSION_HAS_BEEN_MOCKERIZED***"; public static final String NULL_SESSION = "***NULL_SESSION***"; private static final String SOAP_OPERATION = "findSitesByTitle"; @Override protected <T extends AbstractWebService> Class<T> getTestClass() { return (Class<T>) SakaiScript.class; } @Override protected String getOperation() { return SOAP_OPERATION; } private void addClientMocks(WebClient client) { addCXFClientMocks(client); } @Override protected void addServiceMocks(AbstractWebService service) { List<String> mockSiteIDs = new ArrayList<String>(); mockSiteIDs.add("validSiteIDs"); try { when(service.siteService.getSiteIds(SelectionType.ANY, null, "matchingCriteria", null, SortType.NONE, null)).thenReturn(mockSiteIDs); when(service.siteService.getSiteIds(SelectionType.ANY, null, "unmatchingCriteria", null, SortType.NONE, null)).thenReturn(null); } catch (Exception e) { } Session mockSession = mock(Session.class); when(service.sessionManager.getSession(SESSION_ID)).thenReturn(mockSession); when(service.sessionManager.getSession(NULL_SESSION)).thenReturn(null); } @Test public void testMatchingCriteria() { WebClient client = WebClient.create(getFullEndpointAddress()); addClientMocks(client); // client call client.accept("text/plain"); client.path("/" + getOperation()); client.query("sessionid", SESSION_ID); client.query("criteria", "matchingCriteria"); // client result String result = client.get(String.class); // test verifications assertNotNull(result); assertEquals("validSiteIDs", result); } @Test public void testUnmatchingCriteria() { WebClient client = WebClient.create(getFullEndpointAddress()); addClientMocks(client); // client call client.accept("text/plain"); client.path("/" + getOperation()); client.query("sessionid", SESSION_ID); client.query("criteria", "unmatchingCriteria"); // client result String result = client.get(String.class); // test verifications assertNotNull(result); assertEquals("", result); } }
apache-2.0
Distrotech/buck
src/com/facebook/buck/cxx/GnuArchiver.java
2215
/* * Copyright 2015-present Facebook, 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.facebook.buck.cxx; import com.facebook.buck.io.FileScrubber; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.RuleKeyBuilder; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.Tool; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; public class GnuArchiver implements Archiver { private static final byte[] EXPECTED_GLOBAL_HEADER = "!<arch>\n".getBytes(Charsets.US_ASCII); private final Tool tool; public GnuArchiver(Tool tool) { this.tool = tool; } @Override public ImmutableList<FileScrubber> getScrubbers() { return ImmutableList.of(ObjectFileScrubbers.createDateUidGidScrubber(EXPECTED_GLOBAL_HEADER)); } @Override public ImmutableCollection<BuildRule> getDeps(SourcePathResolver resolver) { return tool.getDeps(resolver); } @Override public ImmutableCollection<SourcePath> getInputs() { return tool.getInputs(); } @Override public ImmutableList<String> getCommandPrefix(SourcePathResolver resolver) { return tool.getCommandPrefix(resolver); } @Override public ImmutableMap<String, String> getEnvironment(SourcePathResolver resolver) { return tool.getEnvironment(resolver); } @Override public RuleKeyBuilder appendToRuleKey(RuleKeyBuilder builder) { return builder .setReflectively("tool", tool) .setReflectively("type", getClass().getSimpleName()); } }
apache-2.0
McLeodMoores/starling
projects/financial/src/test/java/com/opengamma/financial/conversion/ResultConverterCacheTest.java
1767
/** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.conversion; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import org.testng.annotations.Test; import com.opengamma.analytics.financial.model.interestrate.curve.DiscountCurve; import com.opengamma.analytics.math.curve.ConstantDoublesCurve; import com.opengamma.analytics.math.matrix.DoubleMatrix1D; import com.opengamma.analytics.math.matrix.DoubleMatrix2D; import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries; import com.opengamma.util.test.TestGroup; /** * Test. */ @Test(groups = TestGroup.UNIT) public class ResultConverterCacheTest { @Test public void get() { ResultConverterCache cache = new ResultConverterCache(); ResultConverter<?> converter = cache.getConverter(new Double(5.5)); assertNotNull(converter); assertTrue(converter instanceof DoubleConverter); converter = cache.getConverter(new DoubleMatrix1D(new double[0])); assertNotNull(converter); assertTrue(converter instanceof DoubleMatrix1DConverter); converter = cache.getConverter(new DoubleMatrix2D(new double[0][0])); assertNotNull(converter); assertTrue(converter instanceof DoubleMatrix2DConverter); converter = cache.getConverter(ImmutableLocalDateDoubleTimeSeries.EMPTY_SERIES); assertNotNull(converter); assertTrue(converter instanceof TimeSeriesConverter); converter = cache.getConverter(DiscountCurve.from(new ConstantDoublesCurve(2.5))); assertNotNull(converter); assertTrue(converter instanceof YieldAndDiscountCurveConverter); } }
apache-2.0
qqming113/bi-platform
designer/src/main/java/com/baidu/rigel/biplatform/ma/model/builder/impl/SchemaBuilder.java
1879
/** * Copyright (c) 2014 Baidu, 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.baidu.rigel.biplatform.ma.model.builder.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baidu.rigel.biplatform.ac.minicube.MiniCubeSchema; import com.baidu.rigel.biplatform.ac.model.Schema; import com.baidu.rigel.biplatform.ma.model.utils.UuidGeneratorUtils; /** * schema构建器 * * @author david.wang * */ class SchemaBuilder { /** * 日志记录管理工具 */ private Logger logger = LoggerFactory.getLogger(SchemaBuilder.class); /** * 构建schema对象 * * @param dsId * 数据源id * @return 转换成功的schema对象 */ public Schema buildSchema(String dsId) { logger.info("begin create schema process "); String id = UuidGeneratorUtils.generate(); logger.info("create schema with id " + id); MiniCubeSchema schema = new MiniCubeSchema("schema_" + id); schema.setId(id); schema.setVisible(true); schema.setCaption("schema_" + id); schema.setDatasource(dsId); // schema.setUniqueName(id); logger.info("create schema successfully : " + schema); return schema; } }
apache-2.0
q474818917/solr-5.2.0
solr/core/src/test/org/apache/solr/TestRandomDVFaceting.java
9038
/* * 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.solr; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.lucene.util.TestUtil; import org.apache.lucene.util.LuceneTestCase.Slow; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.schema.SchemaField; import org.junit.BeforeClass; import org.junit.Test; /** * This is like TestRandomFaceting, except it does a copyField on each * indexed field to field_dv, and compares the docvalues facet results * to the indexed facet results as if it were just another faceting method. */ @Slow public class TestRandomDVFaceting extends SolrTestCaseJ4 { @BeforeClass public static void beforeTests() throws Exception { initCore("solrconfig-basic.xml","schema-docValuesFaceting.xml"); } int indexSize; List<FldType> types; Map<Comparable, Doc> model = null; boolean validateResponses = true; void init() { Random rand = random(); clearIndex(); model = null; indexSize = rand.nextBoolean() ? (rand.nextInt(10) + 1) : (rand.nextInt(100) + 10); types = new ArrayList<>(); types.add(new FldType("id",ONE_ONE, new SVal('A','Z',4,4))); types.add(new FldType("score_f",ONE_ONE, new FVal(1,100))); types.add(new FldType("foo_i",ZERO_ONE, new IRange(0,indexSize))); types.add(new FldType("small_s",ZERO_ONE, new SVal('a',(char)('c'+indexSize/3),1,1))); types.add(new FldType("small2_s",ZERO_ONE, new SVal('a',(char)('c'+indexSize/3),1,1))); types.add(new FldType("small2_ss",ZERO_TWO, new SVal('a',(char)('c'+indexSize/3),1,1))); types.add(new FldType("small3_ss",new IRange(0,25), new SVal('A','z',1,1))); types.add(new FldType("small4_ss",ZERO_ONE, new SVal('a',(char)('c'+indexSize/3),1,1))); // to test specialization when a multi-valued field is actually single-valued types.add(new FldType("small_i",ZERO_ONE, new IRange(0,5+indexSize/3))); types.add(new FldType("small2_i",ZERO_ONE, new IRange(0,5+indexSize/3))); types.add(new FldType("small2_is",ZERO_TWO, new IRange(0,5+indexSize/3))); types.add(new FldType("small3_is",new IRange(0,25), new IRange(0,100))); types.add(new FldType("missing_i",new IRange(0,0), new IRange(0,100))); types.add(new FldType("missing_is",new IRange(0,0), new IRange(0,100))); types.add(new FldType("missing_s",new IRange(0,0), new SVal('a','b',1,1))); types.add(new FldType("missing_ss",new IRange(0,0), new SVal('a','b',1,1))); // TODO: doubles, multi-floats, ints with precisionStep>0, booleans } void addMoreDocs(int ndocs) throws Exception { model = indexDocs(types, model, ndocs); } void deleteSomeDocs() { Random rand = random(); int percent = rand.nextInt(100); if (model == null) return; ArrayList<String> ids = new ArrayList<>(model.size()); for (Comparable id : model.keySet()) { if (rand.nextInt(100) < percent) { ids.add(id.toString()); } } if (ids.size() == 0) return; StringBuilder sb = new StringBuilder("id:("); for (String id : ids) { sb.append(id).append(' '); model.remove(id); } sb.append(')'); assertU(delQ(sb.toString())); if (rand.nextInt(10)==0) { assertU(optimize()); } else { assertU(commit("softCommit",""+(rand.nextInt(10)!=0))); } } @Test public void testRandomFaceting() throws Exception { Random rand = random(); int iter = atLeast(100); init(); addMoreDocs(0); for (int i=0; i<iter; i++) { doFacetTests(); if (rand.nextInt(100) < 5) { init(); } addMoreDocs(rand.nextInt(indexSize) + 1); if (rand.nextInt(100) < 50) { deleteSomeDocs(); } } } void doFacetTests() throws Exception { for (FldType ftype : types) { doFacetTests(ftype); } } // NOTE: dv is not a "real" facet.method. when we see it, we facet on the dv field (*_dv) // but alias the result back as if we faceted on the regular indexed field for comparisons. List<String> multiValuedMethods = Arrays.asList(new String[]{"enum","fc","dv"}); List<String> singleValuedMethods = Arrays.asList(new String[]{"enum","fc","fcs","dv"}); void doFacetTests(FldType ftype) throws Exception { SolrQueryRequest req = req(); try { Random rand = random(); boolean validate = validateResponses; ModifiableSolrParams params = params("facet","true", "wt","json", "indent","true", "omitHeader","true"); params.add("q","*:*", "rows","0"); // TODO: select subsets params.add("rows","0"); SchemaField sf = req.getSchema().getField(ftype.fname); boolean multiValued = sf.getType().multiValuedFieldCache(); boolean indexed = sf.indexed(); boolean numeric = sf.getType().getNumericType() != null; int offset = 0; if (rand.nextInt(100) < 20) { if (rand.nextBoolean()) { offset = rand.nextInt(100) < 10 ? rand.nextInt(indexSize*2) : rand.nextInt(indexSize/3+1); } params.add("facet.offset", Integer.toString(offset)); } int limit = 100; if (rand.nextInt(100) < 20) { if (rand.nextBoolean()) { limit = rand.nextInt(100) < 10 ? rand.nextInt(indexSize/2+1) : rand.nextInt(indexSize*2); } params.add("facet.limit", Integer.toString(limit)); } // the following two situations cannot work for unindexed single-valued numerics: // (currently none of the dv fields in this test config) // facet.sort = index // facet.minCount = 0 if (!numeric || sf.multiValued()) { if (rand.nextBoolean()) { params.add("facet.sort", rand.nextBoolean() ? "index" : "count"); } if (rand.nextInt(100) < 10) { params.add("facet.mincount", Integer.toString(rand.nextInt(5))); } } else { params.add("facet.sort", "count"); params.add("facet.mincount", Integer.toString(1+rand.nextInt(5))); } if ((ftype.vals instanceof SVal) && rand.nextInt(100) < 20) { // validate = false; String prefix = ftype.createValue().toString(); if (rand.nextInt(100) < 5) prefix = TestUtil.randomUnicodeString(rand); else if (rand.nextInt(100) < 10) prefix = Character.toString((char)rand.nextInt(256)); else if (prefix.length() > 0) prefix = prefix.substring(0, rand.nextInt(prefix.length())); params.add("facet.prefix", prefix); } if (rand.nextInt(100) < 20) { params.add("facet.missing", "true"); } // TODO: randomly add other facet params String facet_field = ftype.fname; List<String> methods = multiValued ? multiValuedMethods : singleValuedMethods; List<String> responses = new ArrayList<>(methods.size()); for (String method : methods) { if (method.equals("dv")) { params.set("facet.field", "{!key="+facet_field+"}"+facet_field+"_dv"); params.set("facet.method",(String) null); } else { params.set("facet.field", facet_field); params.set("facet.method", method); } // if (random().nextBoolean()) params.set("facet.mincount", "1"); // uncomment to test that validation fails String strResponse = h.query(req(params)); // Object realResponse = ObjectBuilder.fromJSON(strResponse); // System.out.println(strResponse); responses.add(strResponse); } /** String strResponse = h.query(req(params)); Object realResponse = ObjectBuilder.fromJSON(strResponse); **/ if (validate) { for (int i=1; i<methods.size(); i++) { String err = JSONTestUtil.match("/", responses.get(i), responses.get(0), 0.0); if (err != null) { log.error("ERROR: mismatch facet response: " + err + "\n expected =" + responses.get(0) + "\n response = " + responses.get(i) + "\n request = " + params ); fail(err); } } } } finally { req.close(); } } }
apache-2.0
GabrielBrascher/cloudstack
utils/src/main/java/com/cloud/utils/concurrency/SynchronizationEvent.java
2603
// // 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 com.cloud.utils.concurrency; import org.apache.log4j.Logger; public class SynchronizationEvent { protected final static Logger s_logger = Logger.getLogger(SynchronizationEvent.class); private boolean signalled; public SynchronizationEvent() { signalled = false; } public SynchronizationEvent(boolean signalled) { this.signalled = signalled; } public void setEvent() { synchronized (this) { signalled = true; notifyAll(); } } public void resetEvent() { synchronized (this) { signalled = false; } } public boolean waitEvent() throws InterruptedException { synchronized (this) { if (signalled) return true; while (true) { try { wait(); assert (signalled); return signalled; } catch (InterruptedException e) { s_logger.debug("unexpected awaken signal in wait()"); throw e; } } } } public boolean waitEvent(long timeOutMiliseconds) throws InterruptedException { synchronized (this) { if (signalled) return true; try { wait(timeOutMiliseconds); return signalled; } catch (InterruptedException e) { // TODO, we don't honor time out semantics when the waiting thread is interrupted s_logger.debug("unexpected awaken signal in wait(...)"); throw e; } } } public boolean isSignalled() { synchronized (this) { return signalled; } } }
apache-2.0
Lekanich/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/GotoTargetHandler.java
13782
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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.intellij.codeInsight.navigation; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.hint.HintManager; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.find.FindUtil; import com.intellij.ide.util.EditSourceUtil; import com.intellij.ide.util.PsiElementListCellRenderer; import com.intellij.navigation.ItemPresentation; import com.intellij.navigation.NavigationItem; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.PopupChooserBuilder; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Ref; import com.intellij.pom.Navigatable; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiNamedElement; import com.intellij.ui.CollectionListModel; import com.intellij.ui.JBListWithHintProvider; import com.intellij.ui.popup.AbstractPopup; import com.intellij.ui.popup.HintUpdateSupply; import com.intellij.usages.UsageView; import com.intellij.util.ArrayUtil; import com.intellij.util.Function; import com.intellij.util.Processor; import com.intellij.util.containers.HashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.*; import java.util.List; public abstract class GotoTargetHandler implements CodeInsightActionHandler { private static final PsiElementListCellRenderer ourDefaultTargetElementRenderer = new DefaultPsiElementListCellRenderer(); private final DefaultListCellRenderer myActionElementRenderer = new ActionCellRenderer(); @Override public boolean startInWriteAction() { return false; } @Override public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { FeatureUsageTracker.getInstance().triggerFeatureUsed(getFeatureUsedKey()); try { GotoData gotoData = getSourceAndTargetElements(editor, file); if (gotoData != null && gotoData.source != null) { show(project, editor, file, gotoData); } } catch (IndexNotReadyException e) { DumbService.getInstance(project).showDumbModeNotification("Navigation is not available here during index update"); } } @NonNls protected abstract String getFeatureUsedKey(); @Nullable protected abstract GotoData getSourceAndTargetElements(Editor editor, PsiFile file); private void show(@NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file, @NotNull final GotoData gotoData) { final PsiElement[] targets = gotoData.targets; final List<AdditionalAction> additionalActions = gotoData.additionalActions; if (targets.length == 0 && additionalActions.isEmpty()) { HintManager.getInstance().showErrorHint(editor, getNotFoundMessage(project, editor, file)); return; } if (targets.length == 1 && additionalActions.isEmpty()) { Navigatable descriptor = targets[0] instanceof Navigatable ? (Navigatable)targets[0] : EditSourceUtil.getDescriptor(targets[0]); if (descriptor != null && descriptor.canNavigate()) { navigateToElement(descriptor); } return; } for (PsiElement eachTarget : targets) { gotoData.renderers.put(eachTarget, createRenderer(gotoData, eachTarget)); } final String name = ((PsiNamedElement)gotoData.source).getName(); final String title = getChooserTitle(gotoData.source, name, targets.length); if (shouldSortTargets()) { Arrays.sort(targets, createComparator(gotoData.renderers, gotoData)); } List<Object> allElements = new ArrayList<Object>(targets.length + additionalActions.size()); Collections.addAll(allElements, targets); allElements.addAll(additionalActions); final JBListWithHintProvider list = new JBListWithHintProvider(new CollectionListModel<Object>(allElements)) { @Override protected PsiElement getPsiElementForHint(final Object selectedValue) { return selectedValue instanceof PsiElement ? (PsiElement) selectedValue : null; } }; list.setCellRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (value == null) return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof AdditionalAction) { return myActionElementRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } PsiElementListCellRenderer renderer = getRenderer(value, gotoData.renderers, gotoData); return renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); } }); final Runnable runnable = new Runnable() { @Override public void run() { int[] ids = list.getSelectedIndices(); if (ids == null || ids.length == 0) return; Object[] selectedElements = list.getSelectedValues(); for (Object element : selectedElements) { if (element instanceof AdditionalAction) { ((AdditionalAction)element).execute(); } else { Navigatable nav = element instanceof Navigatable ? (Navigatable)element : EditSourceUtil.getDescriptor((PsiElement)element); try { if (nav != null && nav.canNavigate()) { navigateToElement(nav); } } catch (IndexNotReadyException e) { DumbService.getInstance(project).showDumbModeNotification("Navigation is not available while indexing"); } } } } }; final PopupChooserBuilder builder = new PopupChooserBuilder(list); builder.setFilteringEnabled(new Function<Object, String>() { @Override public String fun(Object o) { if (o instanceof AdditionalAction) { return ((AdditionalAction)o).getText(); } return getRenderer(o, gotoData.renderers, gotoData).getElementText((PsiElement)o); } }); final Ref<UsageView> usageView = new Ref<UsageView>(); final JBPopup popup = builder. setTitle(title). setItemChoosenCallback(runnable). setMovable(true). setCancelCallback(new Computable<Boolean>() { @Override public Boolean compute() { HintUpdateSupply.hideHint(list); return true; } }). setCouldPin(new Processor<JBPopup>() { @Override public boolean process(JBPopup popup) { usageView.set(FindUtil.showInUsageView(gotoData.source, gotoData.targets, getFindUsagesTitle(gotoData.source, name, gotoData.targets.length), project)); popup.cancel(); return false; } }). setAdText(getAdText(gotoData.source, targets.length)). createPopup(); if (gotoData.listUpdaterTask != null) { gotoData.listUpdaterTask.init((AbstractPopup)popup, list, usageView); ProgressManager.getInstance().run(gotoData.listUpdaterTask); } popup.showInBestPositionFor(editor); } private static PsiElementListCellRenderer getRenderer(Object value, Map<Object, PsiElementListCellRenderer> targetsWithRenderers, GotoData gotoData) { PsiElementListCellRenderer renderer = targetsWithRenderers.get(value); if (renderer == null) { renderer = gotoData.getRenderer(value); } if (renderer != null) { return renderer; } else { return ourDefaultTargetElementRenderer; } } protected static Comparator<PsiElement> createComparator(final Map<Object, PsiElementListCellRenderer> targetsWithRenderers, final GotoData gotoData) { return new Comparator<PsiElement>() { @Override public int compare(PsiElement o1, PsiElement o2) { return getComparingObject(o1).compareTo(getComparingObject(o2)); } private Comparable getComparingObject(PsiElement o1) { return getRenderer(o1, targetsWithRenderers, gotoData).getComparingObject(o1); } }; } protected static PsiElementListCellRenderer createRenderer(GotoData gotoData, PsiElement eachTarget) { PsiElementListCellRenderer renderer = null; for (GotoTargetRendererProvider eachProvider : Extensions.getExtensions(GotoTargetRendererProvider.EP_NAME)) { renderer = eachProvider.getRenderer(eachTarget, gotoData); if (renderer != null) break; } if (renderer == null) { renderer = ourDefaultTargetElementRenderer; } return renderer; } protected void navigateToElement(Navigatable descriptor) { descriptor.navigate(true); } protected boolean shouldSortTargets() { return true; } @NotNull protected abstract String getChooserTitle(PsiElement sourceElement, String name, int length); @NotNull protected String getFindUsagesTitle(PsiElement sourceElement, String name, int length) { return getChooserTitle(sourceElement, name, length); } @NotNull protected abstract String getNotFoundMessage(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file); @Nullable protected String getAdText(PsiElement source, int length) { return null; } public interface AdditionalAction { @NotNull String getText(); Icon getIcon(); void execute(); } public static class GotoData { @NotNull public final PsiElement source; public PsiElement[] targets; public final List<AdditionalAction> additionalActions; private boolean hasDifferentNames; public ListBackgroundUpdaterTask listUpdaterTask; protected final Set<String> myNames; public Map<Object, PsiElementListCellRenderer> renderers = new HashMap<Object, PsiElementListCellRenderer>(); public GotoData(@NotNull PsiElement source, @NotNull PsiElement[] targets, @NotNull List<AdditionalAction> additionalActions) { this.source = source; this.targets = targets; this.additionalActions = additionalActions; myNames = new HashSet<String>(); for (PsiElement target : targets) { if (target instanceof PsiNamedElement) { myNames.add(((PsiNamedElement)target).getName()); if (myNames.size() > 1) break; } } hasDifferentNames = myNames.size() > 1; } public boolean hasDifferentNames() { return hasDifferentNames; } public boolean addTarget(final PsiElement element) { if (ArrayUtil.find(targets, element) > -1) return false; targets = ArrayUtil.append(targets, element); renderers.put(element, createRenderer(this, element)); if (!hasDifferentNames && element instanceof PsiNamedElement) { final String name = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Override public String compute() { return ((PsiNamedElement)element).getName(); } }); myNames.add(name); hasDifferentNames = myNames.size() > 1; } return true; } public PsiElementListCellRenderer getRenderer(Object value) { return renderers.get(value); } } private static class DefaultPsiElementListCellRenderer extends PsiElementListCellRenderer { @Override public String getElementText(final PsiElement element) { if (element instanceof PsiNamedElement) { String name = ((PsiNamedElement)element).getName(); if (name != null) { return name; } } return element.getContainingFile().getName(); } @Override protected String getContainerText(final PsiElement element, final String name) { if (element instanceof NavigationItem) { final ItemPresentation presentation = ((NavigationItem)element).getPresentation(); return presentation != null ? presentation.getLocationString():null; } return null; } @Override protected int getIconFlags() { return 0; } } private static class ActionCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component result = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { AdditionalAction action = (AdditionalAction)value; setText(action.getText()); setIcon(action.getIcon()); } return result; } } }
apache-2.0
robin13/elasticsearch
x-pack/qa/rolling-upgrade/src/test/java/org/elasticsearch/upgrades/IndexingIT.java
5346
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.upgrades; import org.apache.http.util.EntityUtils; import org.elasticsearch.client.Request; import org.elasticsearch.client.Response; import org.elasticsearch.common.Booleans; import java.io.IOException; import java.nio.charset.StandardCharsets; import static org.elasticsearch.rest.action.search.RestSearchAction.TOTAL_HITS_AS_INT_PARAM; /** * Basic test that indexed documents survive the rolling restart. * <p> * This test is an almost exact copy of <code>IndexingIT</code> in the * oss rolling restart tests. We should work on a way to remove this * duplication but for now we have no real way to share code. */ public class IndexingIT extends AbstractUpgradeTestCase { public void testIndexing() throws IOException { switch (CLUSTER_TYPE) { case OLD: break; case MIXED: ensureHealth((request -> { request.addParameter("timeout", "70s"); request.addParameter("wait_for_nodes", "3"); request.addParameter("wait_for_status", "yellow"); })); break; case UPGRADED: ensureHealth("test_index,index_with_replicas,empty_index", (request -> { request.addParameter("wait_for_nodes", "3"); request.addParameter("wait_for_status", "green"); request.addParameter("timeout", "70s"); request.addParameter("level", "shards"); })); break; default: throw new UnsupportedOperationException("Unknown cluster type [" + CLUSTER_TYPE + "]"); } if (CLUSTER_TYPE == ClusterType.OLD) { Request createTestIndex = new Request("PUT", "/test_index"); createTestIndex.setJsonEntity("{\"settings\": {\"index.number_of_replicas\": 0}}"); client().performRequest(createTestIndex); String recoverQuickly = "{\"settings\": {\"index.unassigned.node_left.delayed_timeout\": \"100ms\"}}"; Request createIndexWithReplicas = new Request("PUT", "/index_with_replicas"); createIndexWithReplicas.setJsonEntity(recoverQuickly); client().performRequest(createIndexWithReplicas); Request createEmptyIndex = new Request("PUT", "/empty_index"); // Ask for recovery to be quick createEmptyIndex.setJsonEntity(recoverQuickly); client().performRequest(createEmptyIndex); bulk("test_index", "_OLD", 5); bulk("index_with_replicas", "_OLD", 5); } int expectedCount; switch (CLUSTER_TYPE) { case OLD: expectedCount = 5; break; case MIXED: if (Booleans.parseBoolean(System.getProperty("tests.first_round"))) { expectedCount = 5; } else { expectedCount = 10; } break; case UPGRADED: expectedCount = 15; break; default: throw new UnsupportedOperationException("Unknown cluster type [" + CLUSTER_TYPE + "]"); } assertCount("test_index", expectedCount); assertCount("index_with_replicas", 5); assertCount("empty_index", 0); if (CLUSTER_TYPE != ClusterType.OLD) { bulk("test_index", "_" + CLUSTER_TYPE, 5); Request toBeDeleted = new Request("PUT", "/test_index/_doc/to_be_deleted"); toBeDeleted.addParameter("refresh", "true"); toBeDeleted.setJsonEntity("{\"f1\": \"delete-me\"}"); client().performRequest(toBeDeleted); assertCount("test_index", expectedCount + 6); Request delete = new Request("DELETE", "/test_index/_doc/to_be_deleted"); delete.addParameter("refresh", "true"); client().performRequest(delete); assertCount("test_index", expectedCount + 5); } } private void bulk(String index, String valueSuffix, int count) throws IOException { StringBuilder b = new StringBuilder(); for (int i = 0; i < count; i++) { b.append("{\"index\": {\"_index\": \"").append(index).append("\"}}\n"); b.append("{\"f1\": \"v").append(i).append(valueSuffix).append("\", \"f2\": ").append(i).append("}\n"); } Request bulk = new Request("POST", "/_bulk"); bulk.addParameter("refresh", "true"); bulk.setJsonEntity(b.toString()); client().performRequest(bulk); } static void assertCount(String index, int count) throws IOException { Request searchTestIndexRequest = new Request("POST", "/" + index + "/_search"); searchTestIndexRequest.addParameter(TOTAL_HITS_AS_INT_PARAM, "true"); searchTestIndexRequest.addParameter("filter_path", "hits.total"); Response searchTestIndexResponse = client().performRequest(searchTestIndexRequest); assertEquals("{\"hits\":{\"total\":" + count + "}}", EntityUtils.toString(searchTestIndexResponse.getEntity(), StandardCharsets.UTF_8)); } }
apache-2.0
anuragphadke/Flume-Hive
src/java/com/cloudera/flume/agent/MemoryMonitor.java
4976
/** * Licensed to Cloudera, Inc. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Cloudera, Inc. 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 com.cloudera.flume.agent; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.MemoryNotificationInfo; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryType; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import javax.management.Notification; import javax.management.NotificationEmitter; import javax.management.NotificationListener; /** * This memory warning system will call the listeners when we exceed the * percentage of available memory specified. This is a singleton class. * * Based on code from: http://www.javaspecialists.co.za/archive/Issue092.html */ public class MemoryMonitor { static MemoryMonitor singleton = new MemoryMonitor(); private final Collection<Listener> listeners = Collections .synchronizedList(new ArrayList<Listener>()); public interface Listener { public void memoryUsageLow(long usedMemory, long maxMemory); } private MemoryMonitor() { final MemoryMXBean mbean = ManagementFactory.getMemoryMXBean(); NotificationEmitter emitter = (NotificationEmitter) mbean; emitter.addNotificationListener(new NotificationListener() { public void handleNotification(Notification n, Object hb) { if (n.getType() .equals(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED)) { long maxMemory = tenuredGenPool.getUsage().getMax(); long usedMemory = tenuredGenPool.getUsage().getUsed(); for (Listener listener : listeners) { listener.memoryUsageLow(usedMemory, maxMemory); } } } }, null, null); } public static MemoryMonitor getMemoryMonitor() { return singleton; } public boolean addListener(Listener listener) { return listeners.add(listener); } public boolean removeListener(Listener listener) { return listeners.remove(listener); } private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool(); public static void setPercentageUsageThreshold(double percentage) { if (percentage <= 0.0 || percentage > 1.0) { throw new IllegalArgumentException("Percentage not in range"); } long maxMemory = tenuredGenPool.getUsage().getMax(); long warningThreshold = (long) (maxMemory * percentage); tenuredGenPool.setUsageThreshold(warningThreshold); } public long getMemUsage() { return tenuredGenPool.getUsage().getUsed(); } public long getMemMax() { return tenuredGenPool.getUsage().getMax(); } /** * Tenured Space Pool can be determined by it being of type HEAP and by it * being possible to set the usage threshold. */ private static MemoryPoolMXBean findTenuredGenPool() { for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) { // I don't know whether this approach is better, or whether // we should rather check for the pool name "Tenured Gen"? if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) { return pool; } } throw new AssertionError("Could not find tenured space"); } /** * This sets up a trigger that hard exit's when a trigger happens and gc * doesn't relieve memory pressure * * @param threshold */ public static void setupHardExitMemMonitor(final double threshold) { MemoryMonitor.setPercentageUsageThreshold(threshold); final MemoryMonitor mem = MemoryMonitor.getMemoryMonitor(); Listener l = new Listener() { @Override public void memoryUsageLow(long usedMemory, long maxMemory) { System.gc(); // are we still using too much memory? long umem = mem.getMemUsage(); long mmem = mem.getMemMax(); double percent = (umem) / (double)mmem; if (percent > threshold) { System.err .printf( "%dMB/%dMB memory used (%.1f%%)\nExiting due to imminent OutOfMemoryError!\n", usedMemory / 1024 / 1024, maxMemory / 1024 / 1024, percent * 100.0); System.exit(-1); } } }; mem.addListener(l); } }
apache-2.0
axemblr/activiti-karaf
bpmn-webui-components/bpmn-webui-diagram-core/src/main/java/org/oryxeditor/server/diagram/label/Anchors.java
2750
package org.oryxeditor.server.diagram.label; import java.util.HashSet; import java.util.Set; /** * Wrapper class for a set of {@link Anchor} that can be used to define positioning policies of labels * @author philipp.maschke * */ public class Anchors { /** * Enumeration of anchor positions * @author philipp.maschke * */ public enum Anchor { BOTTOM("bottom"), TOP("top"), LEFT("left"), RIGHT("right"); /** * Returns the matching object for the given string * @param enumString * @throws IllegalArgumentException if no matching enumeration object was found * @return */ public static Anchor fromString(String enumString) { if (enumString == null) return null; for (Anchor attrEnum : values()) { if (attrEnum.label.equals(enumString) || attrEnum.name().equals(enumString)) return attrEnum; } throw new IllegalArgumentException("No matching enum constant found in '" + Anchor.class.getSimpleName() + "' for: " + enumString); } private String label; Anchor(String label) { this.label = label; } @Override public String toString() { return label; } } public static Anchors fromString(String anchorsString){ if (anchorsString == null) return null; anchorsString = anchorsString.trim(); if (anchorsString.equals("")) return null; Anchors result = new Anchors(); for (String anchorString: anchorsString.split(" ")){ result.addAnchor(Anchor.fromString(anchorString)); } return result; } private Set<Anchor> anchors = new HashSet<Anchor>(); public Anchors(Anchor...anchors){ for (Anchor anchor: anchors){ this.anchors.add(anchor); } } public void addAnchor(Anchor newAnchor){ anchors.add(newAnchor); } public String toString(){ StringBuffer buff = new StringBuffer(); for (Anchor anchor: anchors){ if (buff.length() > 0) buff.append(" "); buff.append(anchor.toString()); } return buff.toString(); } public int size(){ return anchors.size(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((anchors == null) ? 0 : anchors.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Anchors other = (Anchors) obj; if (anchors == null) { if (other.anchors != null) return false; } else if (!anchors.equals(other.anchors)) return false; return true; } public boolean contains(Anchor anchor){ return anchors.contains(anchor); } }
apache-2.0
eshen1991/optaplanner
optaplanner-core/src/main/java/org/optaplanner/core/api/domain/solution/cloner/package-info.java
689
/* * Copyright 2015 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. */ /** * Planning cloning support. */ package org.optaplanner.core.api.domain.solution.cloner;
apache-2.0
Vizaxo/Terasology
engine/src/main/java/org/terasology/config/RenderingDebugConfig.java
5874
/* * Copyright 2016 MovingBlocks * * 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.terasology.config; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.rendering.world.WorldRendererImpl; import org.terasology.utilities.subscribables.AbstractSubscribable; /** */ public class RenderingDebugConfig extends AbstractSubscribable implements PropertyChangeListener { public enum DebugRenderingStage { OPAQUE_COLOR(0, "DEBUG_STAGE_OPAQUE_COLOR"), TRANSPARENT_COLOR(1, "DEBUG_STAGE_TRANSPARENT_COLOR"), OPAQUE_NORMALS(2, "DEBUG_STAGE_OPAQUE_NORMALS"), OPAQUE_DEPTH(3, "DEBUG_STAGE_OPAQUE_DEPTH"), OPAQUE_SUNLIGHT(4, "DEBUG_STAGE_OPAQUE_SUNLIGHT"), BAKED_OCCLUSION(5, "DEBUG_STAGE_BAKED_OCCLUSION"), SSAO(6, "DEBUG_STAGE_SSAO"), OPAQUE_LIGHT_BUFFER(7, "DEBUG_STAGE_OPAQUE_LIGHT_BUFFER"), SHADOW_MAP(8, "DEBUG_STAGE_SHADOW_MAP"), SOBEL(9, "DEBUG_STAGE_SOBEL"), HIGH_PASS(10, "DEBUG_STAGE_HIGH_PASS"), BLOOM(11, "DEBUG_STAGE_BLOOM"), SKY_BAND(12, "DEBUG_STAGE_SKY_BAND"), LIGHT_SHAFTS(13, "DEBUG_STAGE_LIGHT_SHAFTS"), RECONSTRUCTED_POSITION(14, "DEBUG_STAGE_RECONSTRUCTED_POSITION"), VOLUMETRIC_LIGHTING(15, "DEBUG_STAGE_VOLUMETRIC_LIGHTING"); private int index; private String defineName; DebugRenderingStage(int index, String defineName) { this.index = index; this.defineName = defineName; } public int getIndex() { return index; } public String getDefineName() { return defineName; } } public static final String WIREFRAME = "wireframe"; public static final String ENABLED = "enabled"; public static final String STAGE = "stage"; public static final String FIRST_PERSON_ELEMENTS_HIDDEN = "FirstPersonElementsHidden"; public static final String HUD_HIDDEN = "hudHidden"; public static final String RENDER_CHUNK_BOUNDING_BOXES = "renderChunkBoundingBoxes"; public static final String RENDER_SKELETONS = "renderSkeletons"; private static final Logger logger = LoggerFactory.getLogger(WorldRendererImpl.class); private boolean enabled; private DebugRenderingStage stage; private boolean firstPersonElementsHidden; private boolean hudHidden; private boolean wireframe; private boolean renderChunkBoundingBoxes; private boolean renderSkeletons; public RenderingDebugConfig() { subscribe(this); } public boolean isWireframe() { return wireframe; } public void setWireframe(boolean wireframe) { boolean oldValue = this.wireframe; this.wireframe = wireframe; propertyChangeSupport.firePropertyChange(WIREFRAME, oldValue, this.wireframe); } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { boolean oldValue = this.enabled; this.enabled = enabled; propertyChangeSupport.firePropertyChange(ENABLED, oldValue, this.enabled); } public void cycleStage() { this.stage = DebugRenderingStage.values()[(stage.ordinal() + 1) % DebugRenderingStage.values().length]; } public DebugRenderingStage getStage() { return stage; } public void setStage(DebugRenderingStage stage) { DebugRenderingStage oldStage = this.stage; this.stage = stage; propertyChangeSupport.firePropertyChange(STAGE, oldStage, this.stage); } public boolean isFirstPersonElementsHidden() { return firstPersonElementsHidden; } public void setFirstPersonElementsHidden(boolean firstPersonElementsHidden) { boolean oldValue = this.firstPersonElementsHidden; this.firstPersonElementsHidden = firstPersonElementsHidden; propertyChangeSupport.firePropertyChange(FIRST_PERSON_ELEMENTS_HIDDEN, oldValue, this.firstPersonElementsHidden); } public boolean isHudHidden() { return hudHidden; } public void setHudHidden(boolean hudHidden) { boolean oldValue = this.hudHidden; this.hudHidden = hudHidden; propertyChangeSupport.firePropertyChange(HUD_HIDDEN, oldValue, this.hudHidden); } public boolean isRenderChunkBoundingBoxes() { return renderChunkBoundingBoxes; } public void setRenderChunkBoundingBoxes(boolean renderChunkBoundingBoxes) { boolean oldValue = this.renderChunkBoundingBoxes; this.renderChunkBoundingBoxes = renderChunkBoundingBoxes; propertyChangeSupport.firePropertyChange(RENDER_CHUNK_BOUNDING_BOXES, oldValue, this.renderChunkBoundingBoxes); } public boolean isRenderSkeletons() { return renderSkeletons; } public void setRenderSkeletons(boolean renderSkeletons) { boolean oldValue = this.renderSkeletons; this.renderSkeletons = renderSkeletons; propertyChangeSupport.firePropertyChange(RENDER_SKELETONS, oldValue, this.renderSkeletons); } @Override public void propertyChange(PropertyChangeEvent evt) { logger.info("Set {} property to {}. ", evt.getPropertyName().toUpperCase(), evt.getNewValue()); // for debugging purposes } }
apache-2.0
creamer/cas
support/cas-server-support-electrofence/src/main/java/org/apereo/cas/impl/plans/BlockAuthenticationContingencyPlan.java
1090
package org.apereo.cas.impl.plans; import org.apereo.cas.api.AuthenticationRiskContingencyResponse; import org.apereo.cas.api.AuthenticationRiskScore; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.services.RegisteredService; import org.springframework.webflow.execution.Event; import javax.servlet.http.HttpServletRequest; /** * This is {@link BlockAuthenticationContingencyPlan}. * * @author Misagh Moayyed * @since 5.1.0 */ public class BlockAuthenticationContingencyPlan extends BaseAuthenticationRiskContingencyPlan { /** Block authentication event. */ public static final String EVENT_ID_BLOCK_AUTHN = "blockedAuthentication"; @Override protected AuthenticationRiskContingencyResponse executeInternal(final Authentication authentication, final RegisteredService service, final AuthenticationRiskScore score, final HttpServletRequest request) { return new AuthenticationRiskContingencyResponse(new Event(this, EVENT_ID_BLOCK_AUTHN)); } }
apache-2.0
shun634501730/java_source_cn
src_en/javax/security/auth/login/CredentialException.java
974
/* * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.security.auth.login; /** * A generic credential exception. * * @since 1.5 */ public class CredentialException extends LoginException { private static final long serialVersionUID = -4772893876810601859L; /** * Constructs a CredentialException with no detail message. A detail * message is a String that describes this particular exception. */ public CredentialException() { super(); } /** * Constructs a CredentialException with the specified detail message. * A detail message is a String that describes this particular * exception. * * <p> * * @param msg the detail message. */ public CredentialException(String msg) { super(msg); } }
apache-2.0
strangelydim/Aeron
aeron-client/src/test/java/uk/co/real_logic/aeron/logbuffer/TermRebuilderTest.java
5137
/* * Copyright 2014 - 2015 Real Logic Ltd. * * 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 uk.co.real_logic.aeron.logbuffer; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import uk.co.real_logic.agrona.BitUtil; import uk.co.real_logic.agrona.concurrent.UnsafeBuffer; import java.nio.ByteBuffer; import static java.lang.Integer.valueOf; import static java.nio.ByteOrder.LITTLE_ENDIAN; import static org.mockito.Mockito.*; import static uk.co.real_logic.aeron.logbuffer.FrameDescriptor.*; public class TermRebuilderTest { private static final int TERM_BUFFER_CAPACITY = LogBufferDescriptor.TERM_MIN_LENGTH; private final UnsafeBuffer termBuffer = mock(UnsafeBuffer.class); @Before public void setUp() { when(valueOf(termBuffer.capacity())).thenReturn(valueOf(TERM_BUFFER_CAPACITY)); } @Test public void shouldInsertIntoEmptyBuffer() { final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocateDirect(256)); final int termOffset = 0; final int srcOffset = 0; final int length = 256; packet.putInt(srcOffset, length, LITTLE_ENDIAN); when(termBuffer.getInt(0, LITTLE_ENDIAN)).thenReturn(length); TermRebuilder.insert(termBuffer, termOffset, packet, length); final InOrder inOrder = inOrder(termBuffer); inOrder.verify(termBuffer).putBytes(termOffset, packet, srcOffset, length); inOrder.verify(termBuffer).putIntOrdered(termOffset, length); } @Test public void shouldInsertLastFrameIntoBuffer() { final int frameLength = BitUtil.align(256, FRAME_ALIGNMENT); final int srcOffset = 0; final int tail = TERM_BUFFER_CAPACITY - frameLength; final int termOffset = tail; final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocateDirect(frameLength)); packet.putShort(typeOffset(srcOffset), (short)PADDING_FRAME_TYPE, LITTLE_ENDIAN); packet.putInt(srcOffset, frameLength, LITTLE_ENDIAN); when(termBuffer.getInt(tail, LITTLE_ENDIAN)).thenReturn(frameLength); when(termBuffer.getShort(typeOffset(tail), LITTLE_ENDIAN)).thenReturn((short)PADDING_FRAME_TYPE); TermRebuilder.insert(termBuffer, termOffset, packet, frameLength); verify(termBuffer).putBytes(tail, packet, srcOffset, frameLength); } @Test public void shouldFillSingleGap() { final int frameLength = 50; final int alignedFrameLength = BitUtil.align(frameLength, FRAME_ALIGNMENT); final int srcOffset = 0; final int tail = alignedFrameLength; final int termOffset = tail; final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocateDirect(alignedFrameLength)); when(termBuffer.getInt(0)).thenReturn(frameLength); when(termBuffer.getInt(alignedFrameLength, LITTLE_ENDIAN)).thenReturn(frameLength); when(termBuffer.getInt(alignedFrameLength * 2, LITTLE_ENDIAN)).thenReturn(frameLength); TermRebuilder.insert(termBuffer, termOffset, packet, alignedFrameLength); verify(termBuffer).putBytes(tail, packet, srcOffset, alignedFrameLength); } @Test public void shouldFillAfterAGap() { final int frameLength = 50; final int alignedFrameLength = BitUtil.align(frameLength, FRAME_ALIGNMENT); final int srcOffset = 0; final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocateDirect(alignedFrameLength)); final int termOffset = alignedFrameLength * 2; when(termBuffer.getInt(0, LITTLE_ENDIAN)).thenReturn(0); when(termBuffer.getInt(alignedFrameLength, LITTLE_ENDIAN)).thenReturn(frameLength); TermRebuilder.insert(termBuffer, termOffset, packet, alignedFrameLength); verify(termBuffer).putBytes(alignedFrameLength * 2, packet, srcOffset, alignedFrameLength); } @Test public void shouldFillGapButNotMoveTailOrHwm() { final int frameLength = 50; final int alignedFrameLength = BitUtil.align(frameLength, FRAME_ALIGNMENT); final int srcOffset = 0; final UnsafeBuffer packet = new UnsafeBuffer(ByteBuffer.allocateDirect(alignedFrameLength)); final int termOffset = alignedFrameLength * 2; when(termBuffer.getInt(0, LITTLE_ENDIAN)).thenReturn(frameLength); when(termBuffer.getInt(alignedFrameLength, LITTLE_ENDIAN)).thenReturn(0); TermRebuilder.insert(termBuffer, termOffset, packet, alignedFrameLength); verify(termBuffer).putBytes(alignedFrameLength * 2, packet, srcOffset, alignedFrameLength); } }
apache-2.0
nikhilvibhav/camel
components/camel-salesforce/camel-salesforce-component/src/main/java/org/apache/camel/component/salesforce/internal/processor/AbstractSalesforceProcessor.java
9309
/* * 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.component.salesforce.internal.processor; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.camel.AsyncCallback; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.component.salesforce.SalesforceComponent; import org.apache.camel.component.salesforce.SalesforceEndpoint; import org.apache.camel.component.salesforce.SalesforceEndpointConfig; import org.apache.camel.component.salesforce.SalesforceHttpClient; import org.apache.camel.component.salesforce.SalesforceLoginConfig; import org.apache.camel.component.salesforce.api.SalesforceException; import org.apache.camel.component.salesforce.internal.OperationName; import org.apache.camel.component.salesforce.internal.SalesforceSession; import org.apache.camel.support.service.ServiceSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class AbstractSalesforceProcessor extends ServiceSupport implements SalesforceProcessor { protected static final boolean NOT_OPTIONAL = false; protected static final boolean IS_OPTIONAL = true; protected static final boolean USE_BODY = true; protected static final boolean IGNORE_BODY = false; protected final Logger log = LoggerFactory.getLogger(this.getClass()); protected final SalesforceEndpoint endpoint; protected final Map<String, Object> endpointConfigMap; protected final OperationName operationName; protected SalesforceSession session; protected SalesforceHttpClient httpClient; protected SalesforceLoginConfig loginConfig; protected Map<String, Class<?>> classMap; protected boolean rawPayload; public AbstractSalesforceProcessor(final SalesforceEndpoint endpoint) { this.endpoint = endpoint; this.operationName = endpoint.getOperationName(); this.endpointConfigMap = endpoint.getConfiguration().toValueMap(); } @Override protected void doStart() throws Exception { super.doStart(); SalesforceComponent component = endpoint.getComponent(); session = component.getSession(); loginConfig = component.getLoginConfig(); rawPayload = endpoint.getConfiguration().isRawPayload(); httpClient = endpoint.getConfiguration().getHttpClient(); if (httpClient == null) { httpClient = component.getHttpClient(); } if (classMap == null) { this.classMap = endpoint.getComponent().getClassMap(); } } @Override public abstract boolean process(Exchange exchange, AsyncCallback callback); /** * Gets String value for a parameter from header, endpoint config, or exchange body (optional). * * @param exchange exchange to inspect * @param convertInBody converts In body to String value if true * @param propName name of property * @param optional if {@code true} returns null, otherwise * throws RestException * @return value of property, or {@code null} for * optional parameters if not found. * @throws org.apache.camel.component.salesforce.api.SalesforceException if the property can't be found or on * conversion errors. */ protected final String getParameter( final String propName, final Exchange exchange, final boolean convertInBody, final boolean optional) throws SalesforceException { return getParameter(propName, exchange, convertInBody, optional, String.class); } /** * Gets value for a parameter from header, endpoint config, or exchange body (optional). * * @param exchange exchange to inspect * @param convertInBody converts In body to parameterClass value if * true * @param propName name of property * @param optional if {@code true} returns null, otherwise * throws RestException * @param parameterClass parameter type * @return value of property, or {@code null} for * optional parameters if not found. * @throws org.apache.camel.component.salesforce.api.SalesforceException if the property can't be found or on * conversion errors. */ protected final <T> T getParameter( final String propName, final Exchange exchange, final boolean convertInBody, final boolean optional, final Class<T> parameterClass) throws SalesforceException { final Message in = exchange.getIn(); T propValue = in.getHeader(propName, parameterClass); if (propValue == null) { // check if type conversion failed if (in.getHeader(propName) != null) { throw new IllegalArgumentException( "Header " + propName + " could not be converted to type " + parameterClass.getName()); } final Object value = endpointConfigMap.get(propName); if (value == null || parameterClass.isInstance(value)) { propValue = parameterClass.cast(value); } else { try { propValue = exchange.getContext().getTypeConverter().mandatoryConvertTo(parameterClass, value); } catch (final NoTypeConversionAvailableException e) { throw new SalesforceException(e); } } } propValue = propValue == null && convertInBody ? in.getBody(parameterClass) : propValue; // error if property was not set if (propValue == null && !optional) { final String msg = "Missing property " + propName + (convertInBody ? ", message body could not be converted to type " + parameterClass.getName() : ""); throw new SalesforceException(msg, null); } return propValue; } // Given a parameter value as List or a CSV String, will return a List<String> protected List<String> getListParameter( final String propName, final Exchange exchange, final boolean convertInBody, final boolean optional) throws SalesforceException { Object val = getParameter(propName, exchange, convertInBody, optional, Object.class); if (val instanceof String) { return Arrays.asList(((String) val).split(",")); } if (val instanceof List) { return (List<String>) val; } else { throw new SalesforceException("Expected " + propName + " parameter to be a List or CSV String.", 0); } } protected Class<?> getSObjectClass(String sObjectName, Exchange exchange) throws SalesforceException { Class<?> sObjectClass = null; if (sObjectName != null) { sObjectClass = classMap.get(sObjectName); } if (sObjectClass == null) { final String className = getParameter(SalesforceEndpointConfig.SOBJECT_CLASS, exchange, IGNORE_BODY, NOT_OPTIONAL); try { sObjectClass = endpoint.getComponent().getCamelContext().getClassResolver().resolveMandatoryClass(className); } catch (ClassNotFoundException e) { throw new SalesforceException( String.format("SObject class not found %s or by sObjectName %s", className, sObjectName), e); } } return sObjectClass; } }
apache-2.0
potatosalad/otp
lib/jinterface/java_src/com/ericsson/otp/erlang/OtpMsg.java
10524
/* * %CopyrightBegin% * * Copyright Ericsson AB 2000-2021. 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. * * %CopyrightEnd% */ package com.ericsson.otp.erlang; /** * <p> * Provides a carrier for Erlang messages. * </p> * * <p> * Instances of this class are created to package header and payload information * in received Erlang messages so that the recipient can obtain both parts with * a single call to {@link OtpMbox#receiveMsg receiveMsg()}. * </p> * * <p> * The header information that is available is as follows: * <ul> * <li>a tag indicating the type of message * <li>the intended recipient of the message, either as a {@link OtpErlangPid * pid} or as a String, but never both. * <li>(sometimes) the sender of the message. Due to some eccentric * characteristics of the Erlang distribution protocol, not all messages have * information about the sending process. In particular, only messages whose tag * is {@link OtpMsg#regSendTag regSendTag} contain sender information. * </ul> * * <p> * Message are sent using the Erlang external format (see separate * documentation). When a message is received and delivered to the recipient * {@link OtpMbox mailbox}, the body of the message is still in this external * representation until {@link #getMsg getMsg()} is called, at which point the * message is decoded. A copy of the decoded message is stored in the OtpMsg so * that subsequent calls to {@link #getMsg getMsg()} do not require that the * message be decoded a second time. * </p> */ public class OtpMsg { public static final int linkTag = 1; public static final int sendTag = 2; public static final int exitTag = 3; public static final int unlinkTag = 4; public static final int regSendTag = 6; /* public static final int groupLeaderTag = 7; */ public static final int exit2Tag = 8; protected int tag; // what type of message is this (send, link, exit etc) protected OtpInputStream paybuf; protected OtpErlangObject payload; protected OtpErlangPid from; protected OtpErlangPid to; protected String toName; protected long unlink_id; // send has receiver pid but no sender information OtpMsg(final OtpErlangPid to, final OtpInputStream paybuf) { tag = sendTag; from = null; this.to = to; toName = null; this.paybuf = paybuf; payload = null; this.unlink_id = 0; } // send has receiver pid but no sender information OtpMsg(final OtpErlangPid to, final OtpErlangObject payload) { tag = sendTag; from = null; this.to = to; toName = null; paybuf = null; this.payload = payload; this.unlink_id = 0; } // send_reg has sender pid and receiver name OtpMsg(final OtpErlangPid from, final String toName, final OtpInputStream paybuf) { tag = regSendTag; this.from = from; this.toName = toName; to = null; this.paybuf = paybuf; payload = null; this.unlink_id = 0; } // send_reg has sender pid and receiver name OtpMsg(final OtpErlangPid from, final String toName, final OtpErlangObject payload) { tag = regSendTag; this.from = from; this.toName = toName; to = null; paybuf = null; this.payload = payload; this.unlink_id = 0; } // exit (etc) has from, to, reason OtpMsg(final int tag, final OtpErlangPid from, final OtpErlangPid to, final OtpErlangObject reason) { this.tag = tag; this.from = from; this.to = to; this.unlink_id = 0; paybuf = null; payload = reason; this.unlink_id = 0; } // special case when reason is an atom (i.e. most of the time) OtpMsg(final int tag, final OtpErlangPid from, final OtpErlangPid to, final String reason) { this.tag = tag; this.from = from; this.to = to; paybuf = null; payload = new OtpErlangAtom(reason); this.unlink_id = 0; } // other message types (link and old unlink) OtpMsg(final int tag, final OtpErlangPid from, final OtpErlangPid to) { // convert TT-tags to equiv non-TT versions this.tag = drop_tt_tag(tag); this.from = from; this.to = to; this.unlink_id = 0; } // unlink OtpMsg(final int tag, final OtpErlangPid from, final OtpErlangPid to, final long unlink_id) { // convert TT-tags to equiv non-TT versions this.tag = drop_tt_tag(tag); this.from = from; this.to = to; this.unlink_id = unlink_id; } private int drop_tt_tag(final int tag) { switch (tag) { case AbstractConnection.sendTTTag: return OtpMsg.sendTag; case AbstractConnection.exitTTTag: return OtpMsg.exitTag; case AbstractConnection.regSendTTTag: return OtpMsg.regSendTag; case AbstractConnection.exit2TTTag: return OtpMsg.exit2Tag; default: return tag; } } /** * Get unlink identifier of an unlink or unlink acknowledgment * message. For package internal use only. * * @return the serialized Erlang term contained in this message. * */ long getUnlinkId() { return this.unlink_id; } /** * Get the payload from this message without deserializing it. * * @return the serialized Erlang term contained in this message. * */ OtpInputStream getMsgBuf() { return paybuf; } /** * <p> * Get the type marker from this message. The type marker identifies the * type of message. Valid values are the ``tag'' constants defined in this * class. * </p> * * <p> * The tab identifies not only the type of message but also the content of * the OtpMsg object, since different messages have different components, as * follows: * </p> * * <ul> * <li>sendTag identifies a "normal" message. The recipient is a * {@link OtpErlangPid Pid} and it is available through * {@link #getRecipientPid getRecipientPid()}. Sender information is not * available. The message body can be retrieved with {@link #getMsg * getMsg()}.</li> * * <li>regSendTag also identifies a "normal" message. The recipient here is * a String and it is available through {@link #getRecipientName * getRecipientName()}. Sender information is available through * #getSenderPid getSenderPid()}. The message body can be retrieved with * {@link #getMsg getMsg()}.</li> * * <li>linkTag identifies a link request. The Pid of the sender is * available, as well as the Pid to which the link should be made.</li> * * <li>exitTag and exit2Tag messages are sent as a result of broken links. * Both sender and recipient Pids and are available through the * corresponding methods, and the "reason" is available through * {@link #getMsg getMsg()}.</li> * </ul> */ public int type() { return tag; } /** * <p> * Deserialize and return a new copy of the message contained in this * OtpMsg. * </p> * * <p> * The first time this method is called the actual payload is deserialized * and the Erlang term is created. Calling this method subsequent times will * not cause the message to be deserialized additional times, instead the * same Erlang term object will be returned. * </p> * * @return an Erlang term. * * @exception OtpErlangDecodeException * if the byte stream could not be deserialized. * */ public OtpErlangObject getMsg() throws OtpErlangDecodeException { if (payload == null) { payload = paybuf.read_any(); } return payload; } /** * <p> * Get the name of the recipient for this message. * </p> * * <p> * Messages are sent to Pids or names. If this message was sent to a name * then the name is returned by this method. * </p> * * @return the name of the recipient, or null if the recipient was in fact a * Pid. */ public String getRecipientName() { return toName; } /** * <p> * Get the Pid of the recipient for this message, if it is a sendTag * message. * </p> * * <p> * Messages are sent to Pids or names. If this message was sent to a Pid * then the Pid is returned by this method. The recipient Pid is also * available for link, unlink and exit messages. * </p> * * @return the Pid of the recipient, or null if the recipient was in fact a * name. */ public OtpErlangPid getRecipientPid() { return to; } /** * <p> * Get the name of the recipient for this message, if it is a regSendTag * message. * </p> * * <p> * Messages are sent to Pids or names. If this message was sent to a name * then the name is returned by this method. * </p> * * @return the Pid of the recipient, or null if the recipient was in fact a * name. */ public Object getRecipient() { if (toName != null) { return toName; } return to; } /** * <p> * Get the Pid of the sender of this message. * </p> * * <p> * For messages sent to names, the Pid of the sender is included with the * message. The sender Pid is also available for link, unlink and exit * messages. It is not available for sendTag messages sent to Pids. * </p> * * @return the Pid of the sender, or null if it was not available. */ public OtpErlangPid getSenderPid() { return from; } }
apache-2.0
emag/codereading-undertow
websockets-jsr/src/test/java/io/undertow/websockets/jsr/test/autobahn/ProgramaticAutobahnServer.java
4770
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.websockets.jsr.test.autobahn; import io.undertow.server.protocol.http.HttpOpenListener; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.core.CompositeThreadSetupAction; import io.undertow.servlet.test.util.TestClassIntrospector; import io.undertow.websockets.jsr.JsrWebSocketFilter; import io.undertow.websockets.jsr.ServerEndpointConfigImpl; import io.undertow.websockets.jsr.ServerWebSocketContainer; import org.xnio.BufferAllocator; import org.xnio.ByteBufferSlicePool; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.OptionMap; import org.xnio.Options; import org.xnio.StreamConnection; import org.xnio.Xnio; import org.xnio.XnioWorker; import org.xnio.channels.AcceptingChannel; import javax.servlet.DispatcherType; import java.net.InetSocketAddress; import java.util.Collections; /** * @author <a href="mailto:nmaurer@redhat.com">Norman Maurer</a> */ public class ProgramaticAutobahnServer implements Runnable { private static ServerWebSocketContainer deployment; private final int port; public ProgramaticAutobahnServer(final int port) { this.port = port; } public void run() { Xnio xnio = Xnio.getInstance(); try { XnioWorker worker = xnio.createWorker(OptionMap.builder() .set(Options.WORKER_WRITE_THREADS, 4) .set(Options.WORKER_READ_THREADS, 4) .set(Options.CONNECTION_HIGH_WATER, 1000000) .set(Options.CONNECTION_LOW_WATER, 1000000) .set(Options.WORKER_TASK_CORE_THREADS, 10) .set(Options.WORKER_TASK_MAX_THREADS, 12) .set(Options.TCP_NODELAY, true) .set(Options.CORK, true) .getMap()); OptionMap serverOptions = OptionMap.builder() .set(Options.WORKER_ACCEPT_THREADS, 4) .set(Options.TCP_NODELAY, true) .set(Options.REUSE_ADDRESSES, true) .getMap(); HttpOpenListener openListener = new HttpOpenListener(new ByteBufferSlicePool(BufferAllocator.DIRECT_BYTE_BUFFER_ALLOCATOR, 8192, 8192 * 8192), 8192); ChannelListener acceptListener = ChannelListeners.openListenerAdapter(openListener); AcceptingChannel<StreamConnection> server = worker.createStreamConnectionServer(new InetSocketAddress(port), acceptListener, serverOptions); server.resumeAccepts(); final ServletContainer container = ServletContainer.Factory.newInstance(); ServerWebSocketContainer deployment = new ServerWebSocketContainer(TestClassIntrospector.INSTANCE, worker, new ByteBufferSlicePool(100, 1000),new CompositeThreadSetupAction(Collections.EMPTY_LIST), true, false); DeploymentInfo builder = new DeploymentInfo() .setClassLoader(ProgramaticAutobahnServer.class.getClassLoader()) .setContextPath("/") .setClassIntrospecter(TestClassIntrospector.INSTANCE) .setDeploymentName("servletContext.war") .addServletContextAttribute(javax.websocket.server.ServerContainer.class.getName(), deployment) .addFilter(new FilterInfo("filter", JsrWebSocketFilter.class)) .addFilterUrlMapping("filter", "/*", DispatcherType.REQUEST); deployment.addEndpoint(new ServerEndpointConfigImpl(ProgramaticAutobahnEndpoint.class, "/")); DeploymentManager manager = container.addDeployment(builder); manager.deploy(); openListener.setRootHandler(manager.start()); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { new ProgramaticAutobahnServer(7777).run(); } }
apache-2.0
psiinon/zaproxy
zap/src/main/java/org/zaproxy/zap/view/popup/ExtensionPopupMenuItemMessageContainer.java
2877
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2014 The ZAP Development 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 org.zaproxy.zap.view.popup; import java.awt.Component; import javax.swing.Action; import javax.swing.Icon; import org.parosproxy.paros.extension.ExtensionPopupMenuItem; import org.zaproxy.zap.view.messagecontainer.MessageContainer; /** * An {@code ExtensionPopupMenuItem} that, by default, is enable for all the {@code * MessageContainer} invokers and not enable for any {@code Component}. * * @since 2.3.0 */ public class ExtensionPopupMenuItemMessageContainer extends ExtensionPopupMenuItem { private static final long serialVersionUID = 5123729066062943072L; /** Constructs an {@code ExtensionPopupMenuItemMessageContainer} with no text nor icon. */ public ExtensionPopupMenuItemMessageContainer() { super(); } /** * Constructs an {@code ExtensionPopupMenuItemMessageContainer} with the given text and no icon. * * @param text the text of the menu item. */ public ExtensionPopupMenuItemMessageContainer(String text) { super(text); } /** * Constructs an {@code ExtensionPopupMenuItemMessageContainer} with the given text and icon. * * @param text the text of the menu item. * @param icon the icon of the menu item. * @since 2.7.0 */ public ExtensionPopupMenuItemMessageContainer(String text, Icon icon) { super(text, icon); } /** * Constructs an {@code ExtensionPopupMenuItemMessageContainer} with the given action. * * <p>The text and icon (if any) are obtained from the given action. * * @param action the action of the menu item. * @since 2.7.0 */ public ExtensionPopupMenuItemMessageContainer(Action action) { super(action); } /** By default, the pop up menu item is not enable for any invoker {@code Component}. */ @Override public boolean isEnableForComponent(Component invoker) { return false; } /** By default, the pop up menu item button is enabled and it is enable for all invokers. */ @Override public boolean isEnableForMessageContainer(MessageContainer<?> invoker) { return true; } }
apache-2.0
himanshug/druid
extensions-core/datasketches/src/main/java/org/apache/druid/query/aggregation/datasketches/theta/sql/ThetaSketchObjectSqlAggregator.java
2991
/* * 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.druid.query.aggregation.datasketches.theta.sql; import org.apache.calcite.sql.SqlAggFunction; import org.apache.calcite.sql.SqlFunctionCategory; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.type.InferTypes; import org.apache.calcite.sql.type.OperandTypes; import org.apache.calcite.sql.type.ReturnTypes; import org.apache.calcite.sql.type.SqlTypeFamily; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.druid.query.aggregation.AggregatorFactory; import org.apache.druid.segment.VirtualColumn; import org.apache.druid.sql.calcite.aggregation.Aggregation; import org.apache.druid.sql.calcite.aggregation.SqlAggregator; import java.util.Collections; import java.util.List; public class ThetaSketchObjectSqlAggregator extends ThetaSketchBaseSqlAggregator implements SqlAggregator { private static final SqlAggFunction FUNCTION_INSTANCE = new ThetaSketchObjectSqlAggFunction(); private static final String NAME = "DS_THETA"; @Override public SqlAggFunction calciteFunction() { return FUNCTION_INSTANCE; } @Override protected Aggregation toAggregation( String name, boolean finalizeAggregations, List<VirtualColumn> virtualColumns, AggregatorFactory aggregatorFactory ) { return Aggregation.create( virtualColumns, Collections.singletonList(aggregatorFactory), null ); } private static class ThetaSketchObjectSqlAggFunction extends SqlAggFunction { private static final String SIGNATURE = "'" + NAME + "(column, size)'\n"; ThetaSketchObjectSqlAggFunction() { super( NAME, null, SqlKind.OTHER_FUNCTION, ReturnTypes.explicit(SqlTypeName.OTHER), InferTypes.VARCHAR_1024, OperandTypes.or( OperandTypes.ANY, OperandTypes.and( OperandTypes.sequence(SIGNATURE, OperandTypes.ANY, OperandTypes.LITERAL), OperandTypes.family(SqlTypeFamily.ANY, SqlTypeFamily.NUMERIC) ) ), SqlFunctionCategory.USER_DEFINED_FUNCTION, false, false ); } } }
apache-2.0
smgoller/geode
geode-core/src/test/java/org/apache/geode/internal/util/concurrent/ReentrantSemaphoreJUnitTest.java
3965
/* * 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.geode.internal.util.concurrent; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; public class ReentrantSemaphoreJUnitTest { private static final long OPERATION_TIMEOUT_MILLIS = 10 * 1000; private CountDownLatch done; private CountDownLatch acquired; @Rule public Timeout timeout = new Timeout(30, TimeUnit.SECONDS); @Before public void setUp() throws Exception { done = new CountDownLatch(1); acquired = new CountDownLatch(2); } @After public void tearDown() throws Exception { acquired.countDown(); done.countDown(); } @Test public void testOneThread() throws Exception { final ReentrantSemaphore semaphore = new ReentrantSemaphore(2); semaphore.acquire(); semaphore.acquire(); assertEquals(1, semaphore.availablePermits()); semaphore.release(); semaphore.release(); assertEquals(2, semaphore.availablePermits()); } @Test public void testMultipleThreads() throws Exception { final ReentrantSemaphore sem = new ReentrantSemaphore(2); final AtomicReference<Throwable> failure = new AtomicReference<>(); Thread t1 = new Thread() { @Override public void run() { try { sem.acquire(); sem.acquire(); sem.acquire(); acquired.countDown(); assertTrue(done.await(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)); sem.release(); sem.release(); sem.release(); } catch (Exception e) { failure.compareAndSet(null, e); } } }; t1.start(); Thread t2 = new Thread() { @Override public void run() { try { sem.acquire(); sem.acquire(); sem.acquire(); acquired.countDown(); assertTrue(done.await(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)); sem.release(); sem.release(); sem.release(); } catch (Exception e) { failure.compareAndSet(null, e); } } }; t2.start(); Thread t3 = new Thread() { @Override public void run() { try { assertTrue(acquired.await(OPERATION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)); assertEquals(0, sem.availablePermits()); assertFalse(sem.tryAcquire(1, TimeUnit.SECONDS)); } catch (Exception e) { failure.compareAndSet(null, e); } } }; t3.start(); t3.join(OPERATION_TIMEOUT_MILLIS); assertFalse(t3.isAlive()); done.countDown(); t2.join(OPERATION_TIMEOUT_MILLIS); assertFalse(t3.isAlive()); t1.join(OPERATION_TIMEOUT_MILLIS); assertFalse(t1.isAlive()); if (failure.get() != null) { throw new AssertionError(failure.get()); } assertEquals(2, sem.availablePermits()); } }
apache-2.0
smartan/lucene
src/test/java/org/apache/lucene/index/TestStressNRT.java
17006
package org.apache.lucene.index; /* * 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. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.TestUtil; public class TestStressNRT extends LuceneTestCase { volatile DirectoryReader reader; final ConcurrentHashMap<Integer,Long> model = new ConcurrentHashMap<>(); Map<Integer,Long> committedModel = new HashMap<>(); long snapshotCount; long committedModelClock; volatile int lastId; final String field = "val_l"; Object[] syncArr; private void initModel(int ndocs) { snapshotCount = 0; committedModelClock = 0; lastId = 0; syncArr = new Object[ndocs]; for (int i=0; i<ndocs; i++) { model.put(i, -1L); syncArr[i] = new Object(); } committedModel.putAll(model); } public void test() throws Exception { // update variables final int commitPercent = random().nextInt(20); final int softCommitPercent = random().nextInt(100); // what percent of the commits are soft final int deletePercent = random().nextInt(50); final int deleteByQueryPercent = random().nextInt(25); final int ndocs = atLeast(50); final int nWriteThreads = TestUtil.nextInt(random(), 1, TEST_NIGHTLY ? 10 : 5); final int maxConcurrentCommits = TestUtil.nextInt(random(), 1, TEST_NIGHTLY ? 10 : 5); // number of committers at a time... needed if we want to avoid commit errors due to exceeding the max final boolean tombstones = random().nextBoolean(); // query variables final AtomicLong operations = new AtomicLong(atLeast(10000)); // number of query operations to perform in total final int nReadThreads = TestUtil.nextInt(random(), 1, TEST_NIGHTLY ? 10 : 5); initModel(ndocs); final FieldType storedOnlyType = new FieldType(); storedOnlyType.setStored(true); if (VERBOSE) { System.out.println("\n"); System.out.println("TEST: commitPercent=" + commitPercent); System.out.println("TEST: softCommitPercent=" + softCommitPercent); System.out.println("TEST: deletePercent=" + deletePercent); System.out.println("TEST: deleteByQueryPercent=" + deleteByQueryPercent); System.out.println("TEST: ndocs=" + ndocs); System.out.println("TEST: nWriteThreads=" + nWriteThreads); System.out.println("TEST: nReadThreads=" + nReadThreads); System.out.println("TEST: maxConcurrentCommits=" + maxConcurrentCommits); System.out.println("TEST: tombstones=" + tombstones); System.out.println("TEST: operations=" + operations); System.out.println("\n"); } final AtomicInteger numCommitting = new AtomicInteger(); List<Thread> threads = new ArrayList<>(); Directory dir = newDirectory(); final RandomIndexWriter writer = new RandomIndexWriter(random(), dir, newIndexWriterConfig(new MockAnalyzer(random()))); writer.setDoRandomForceMergeAssert(false); writer.commit(); reader = DirectoryReader.open(dir); for (int i=0; i<nWriteThreads; i++) { Thread thread = new Thread("WRITER"+i) { Random rand = new Random(random().nextInt()); @Override public void run() { try { while (operations.get() > 0) { int oper = rand.nextInt(100); if (oper < commitPercent) { if (numCommitting.incrementAndGet() <= maxConcurrentCommits) { Map<Integer,Long> newCommittedModel; long version; DirectoryReader oldReader; synchronized(TestStressNRT.this) { newCommittedModel = new HashMap<>(model); // take a snapshot version = snapshotCount++; oldReader = reader; oldReader.incRef(); // increment the reference since we will use this for reopening } DirectoryReader newReader; if (rand.nextInt(100) < softCommitPercent) { // assertU(h.commit("softCommit","true")); if (random().nextBoolean()) { if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": call writer.getReader"); } newReader = writer.getReader(true); } else { if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": reopen reader=" + oldReader + " version=" + version); } newReader = DirectoryReader.openIfChanged(oldReader, writer.w, true); } } else { // assertU(commit()); if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": commit+reopen reader=" + oldReader + " version=" + version); } writer.commit(); if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": now reopen after commit"); } newReader = DirectoryReader.openIfChanged(oldReader); } // Code below assumes newReader comes w/ // extra ref: if (newReader == null) { oldReader.incRef(); newReader = oldReader; } oldReader.decRef(); synchronized(TestStressNRT.this) { // install the new reader if it's newest (and check the current version since another reader may have already been installed) //System.out.println(Thread.currentThread().getName() + ": newVersion=" + newReader.getVersion()); assert newReader.getRefCount() > 0; assert reader.getRefCount() > 0; if (newReader.getVersion() > reader.getVersion()) { if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": install new reader=" + newReader); } reader.decRef(); reader = newReader; // Silly: forces fieldInfos to be // loaded so we don't hit IOE on later // reader.toString newReader.toString(); // install this snapshot only if it's newer than the current one if (version >= committedModelClock) { if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": install new model version=" + version); } committedModel = newCommittedModel; committedModelClock = version; } else { if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": skip install new model version=" + version); } } } else { // if the same reader, don't decRef. if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": skip install new reader=" + newReader); } newReader.decRef(); } } } numCommitting.decrementAndGet(); } else { int id = rand.nextInt(ndocs); Object sync = syncArr[id]; // set the lastId before we actually change it sometimes to try and // uncover more race conditions between writing and reading boolean before = random().nextBoolean(); if (before) { lastId = id; } // We can't concurrently update the same document and retain our invariants of increasing values // since we can't guarantee what order the updates will be executed. synchronized (sync) { Long val = model.get(id); long nextVal = Math.abs(val)+1; if (oper < commitPercent + deletePercent) { // assertU("<delete><id>" + id + "</id></delete>"); // add tombstone first if (tombstones) { Document d = new Document(); d.add(newStringField("id", "-"+Integer.toString(id), Field.Store.YES)); d.add(newField(field, Long.toString(nextVal), storedOnlyType)); writer.updateDocument(new Term("id", "-"+Integer.toString(id)), d); } if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": term delDocs id:" + id + " nextVal=" + nextVal); } writer.deleteDocuments(new Term("id",Integer.toString(id))); model.put(id, -nextVal); } else if (oper < commitPercent + deletePercent + deleteByQueryPercent) { //assertU("<delete><query>id:" + id + "</query></delete>"); // add tombstone first if (tombstones) { Document d = new Document(); d.add(newStringField("id", "-"+Integer.toString(id), Field.Store.YES)); d.add(newField(field, Long.toString(nextVal), storedOnlyType)); writer.updateDocument(new Term("id", "-"+Integer.toString(id)), d); } if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": query delDocs id:" + id + " nextVal=" + nextVal); } writer.deleteDocuments(new TermQuery(new Term("id", Integer.toString(id)))); model.put(id, -nextVal); } else { // assertU(adoc("id",Integer.toString(id), field, Long.toString(nextVal))); Document d = new Document(); d.add(newStringField("id", Integer.toString(id), Field.Store.YES)); d.add(newField(field, Long.toString(nextVal), storedOnlyType)); if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": u id:" + id + " val=" + nextVal); } writer.updateDocument(new Term("id", Integer.toString(id)), d); if (tombstones) { // remove tombstone after new addition (this should be optional?) writer.deleteDocuments(new Term("id","-"+Integer.toString(id))); } model.put(id, nextVal); } } if (!before) { lastId = id; } } } } catch (Throwable e) { System.out.println(Thread.currentThread().getName() + ": FAILED: unexpected exception"); e.printStackTrace(System.out); throw new RuntimeException(e); } } }; threads.add(thread); } for (int i=0; i<nReadThreads; i++) { Thread thread = new Thread("READER"+i) { Random rand = new Random(random().nextInt()); @Override public void run() { try { IndexReader lastReader = null; IndexSearcher lastSearcher = null; while (operations.decrementAndGet() >= 0) { // bias toward a recently changed doc int id = rand.nextInt(100) < 25 ? lastId : rand.nextInt(ndocs); // when indexing, we update the index, then the model // so when querying, we should first check the model, and then the index long val; DirectoryReader r; synchronized(TestStressNRT.this) { val = committedModel.get(id); r = reader; r.incRef(); } if (VERBOSE) { System.out.println("TEST: " + Thread.currentThread().getName() + ": s id=" + id + " val=" + val + " r=" + r.getVersion()); } // sreq = req("wt","json", "q","id:"+Integer.toString(id), "omitHeader","true"); IndexSearcher searcher; if (r == lastReader) { // Just re-use lastSearcher, else // newSearcher may create too many thread // pools (ExecutorService): searcher = lastSearcher; } else { searcher = newSearcher(r); lastReader = r; lastSearcher = searcher; } Query q = new TermQuery(new Term("id",Integer.toString(id))); TopDocs results = searcher.search(q, 10); if (results.totalHits == 0 && tombstones) { // if we couldn't find the doc, look for its tombstone q = new TermQuery(new Term("id","-"+Integer.toString(id))); results = searcher.search(q, 1); if (results.totalHits == 0) { if (val == -1L) { // expected... no doc was added yet r.decRef(); continue; } fail("No documents or tombstones found for id " + id + ", expected at least " + val + " reader=" + r); } } if (results.totalHits == 0 && !tombstones) { // nothing to do - we can't tell anything from a deleted doc without tombstones } else { // we should have found the document, or its tombstone if (results.totalHits != 1) { System.out.println("FAIL: hits id:" + id + " val=" + val); for(ScoreDoc sd : results.scoreDocs) { final Document doc = r.document(sd.doc); System.out.println(" docID=" + sd.doc + " id:" + doc.get("id") + " foundVal=" + doc.get(field)); } fail("id=" + id + " reader=" + r + " totalHits=" + results.totalHits); } Document doc = searcher.doc(results.scoreDocs[0].doc); long foundVal = Long.parseLong(doc.get(field)); if (foundVal < Math.abs(val)) { fail("foundVal=" + foundVal + " val=" + val + " id=" + id + " reader=" + r); } } r.decRef(); } } catch (Throwable e) { operations.set(-1L); System.out.println(Thread.currentThread().getName() + ": FAILED: unexpected exception"); e.printStackTrace(System.out); throw new RuntimeException(e); } } }; threads.add(thread); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } writer.close(); if (VERBOSE) { System.out.println("TEST: close reader=" + reader); } reader.close(); dir.close(); } }
apache-2.0
psiinon/zaproxy
zap/src/main/java/org/zaproxy/zap/view/popup/PopupMenuItemContextDataDriven.java
3126
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2015 The ZAP Development 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 org.zaproxy.zap.view.popup; import java.util.ArrayList; import java.util.List; import javax.swing.JMenuItem; import org.parosproxy.paros.Constant; import org.parosproxy.paros.extension.ExtensionPopupMenuItem; import org.parosproxy.paros.model.Model; import org.parosproxy.paros.model.Session; import org.parosproxy.paros.model.SiteNode; import org.parosproxy.paros.view.View; import org.zaproxy.zap.model.Context; /** @since 2.4.3 */ public class PopupMenuItemContextDataDriven extends PopupMenuItemSiteNodeContainer { private static final long serialVersionUID = 3790264690466717219L; private List<ExtensionPopupMenuItem> subMenus = new ArrayList<>(); /** This method initializes */ public PopupMenuItemContextDataDriven() { super("DataDrivenNodeX", true); } @Override public String getParentMenuName() { return Constant.messages.getString("context.flag.popup"); } @Override public boolean isSubMenu() { return true; } @Override public boolean isDummyItem() { return true; } @Override public void performAction(SiteNode sn) { // Do nothing } @Override public boolean isButtonEnabledForSiteNode(SiteNode sn) { reCreateSubMenu(sn); return false; } protected void reCreateSubMenu(SiteNode sn) { final List<JMenuItem> mainPopupMenuItems = View.getSingleton().getPopupList(); for (ExtensionPopupMenuItem menu : subMenus) { mainPopupMenuItems.remove(menu); } subMenus.clear(); Session session = Model.getSingleton().getSession(); List<Context> contexts = session.getContexts(); for (Context context : contexts) { if (context.isIncluded(sn)) { ExtensionPopupMenuItem piicm = createPopupDataDrivenNodeMenu(context); piicm.setMenuIndex(this.getMenuIndex()); mainPopupMenuItems.add(piicm); this.subMenus.add(piicm); } } } protected ExtensionPopupMenuItem createPopupDataDrivenNodeMenu(Context context) { return new PopupMenuItemContextDataDrivenNode( context, Constant.messages.getString("context.flag.popup.datadriven", context.getName())); } @Override public boolean isSafe() { return true; } }
apache-2.0
zlamalp/perun
perun-core/src/main/java/cz/metacentrum/perun/core/provisioning/GenDataProvider.java
3738
package cz.metacentrum.perun.core.provisioning; import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.Service; import cz.metacentrum.perun.core.impl.PerunSessionImpl; import java.util.List; import java.util.Map; /** * This component is used to efficiently load required attributes. * * Attributes, that can be hashed, must be loaded first via load* methods. * E.g.: to be able to call getResourceAttributesHashes, one must first call * loadResourceSpecificAttributes. * * IMPORTANT: this components has a STATE! The order of load methods is important. * E.g.: loadResourceSpecificAttributes will overwrite data for previously loaded resource. * * @author Vojtech Sassmann <vojtech.sassmann@gmail.com> */ public interface GenDataProvider { /** * Return all hashes for facility attributes. * * @return list of hashes */ List<String> getFacilityAttributesHashes(); /** * Return all hashes for given resource attributes. * If addVoAttributes is true, also adds a hash for resource's vo attributes, * if they are not empty. * * @param resource resource * @param addVoAttributes if true, add also vo attributes hash, if not empty * @return list of hashes */ List<String> getResourceAttributesHashes(Resource resource, boolean addVoAttributes); /** * Return all hashes relevant for given member. * Member, User, Member-Resource, User-Facility. * * @param resource resource used to get member-resource attributes hash * @param member given member * @return list of hashes */ List<String> getMemberAttributesHashes(Resource resource, Member member); /** * Return all hashes relevant for given member. * Member, User, Member-Resource, User-Facility and Member-Group. * * @param resource resource used to get member-resource attributes hash * @param member given member * @param group group used to get member-group attributes * @return list of hashes */ List<String> getMemberAttributesHashes(Resource resource, Member member, Group group); /** * Returns all hashes relevant for given group. * Group and Group-Resource attributes. * * @param resource resource used to get Group-Resource attributes. * @param group group * @return list of hashes */ List<String> getGroupAttributesHashes(Resource resource, Group group); /** * Loads Facility attributes. */ void loadFacilityAttributes(); /** * Loads Resource and Member specific attributes. * Resouce, Member, User, User-Facility (if not already loaded). * Resource-Member (always) * Vo - if specified by loadVoAttributes * * @param resource resource * @param members members * @param loadVoAttributes specifies, if the voAttributesShould be loaded as well. */ void loadResourceAttributes(Resource resource, List<Member> members, boolean loadVoAttributes); /** * Loads Group and Group-Resource attributes. * Group attributes are loaded only for groups that has not been already loaded. * * @param resource resource * @param groups groups */ void loadGroupsAttributes(Resource resource, List<Group> groups); /** * Loads Member-Group attributes. * * @param group groups * @param members members */ void loadMemberGroupAttributes(Group group, List<Member> members); /** * Returns map of all loaded attributes grouped by their hashes. * Returns only non-empty lists, and only lists, for which their hashes has been returned, * by some get.*attributesHashes method. * * @return map of hashes attributes */ Map<String, Map<String, Object>> getAllFetchedAttributes(); }
bsd-2-clause
lukeweber/webrtc-jingle-client
android/voice-client-core/src/main/java/com/tuenti/voice/core/XmppPresenceAvailable.java
492
package com.tuenti.voice.core; public enum XmppPresenceAvailable { XMPP_PRESENCE_UNAVAILABLE, XMPP_PRESENCE_AVAILABLE, XMPP_PRESENCE_ERROR; // ------------------------------ FIELDS ------------------------------ private static final XmppPresenceAvailable[] values = XmppPresenceAvailable.values(); // -------------------------- STATIC METHODS -------------------------- public static XmppPresenceAvailable fromInteger( int i ) { return values[i]; } }
bsd-3-clause
martacou/exercises-java-lang
java-concurrency-threads/src/main/java/edu/upc/eetac/dsa/exercises/java/lang/RunnableClass.java
1970
/* * * The MIT License (MIT) * * Copyright (c) 2015 Sergio Machado * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package edu.upc.eetac.dsa.exercises.java.lang; /** * Created by Sergio Machado on 4/02/15. */ public class RunnableClass implements Runnable { long lastExecution = 0; int counter = 0; @Override public void run() { for (int i = 0; i < 10; i++) { long currentExecution = System.currentTimeMillis(); long elapsed = (lastExecution == 0) ? 0 : currentExecution - lastExecution; lastExecution = currentExecution; System.out.println(Thread.currentThread().getName() + " elapsed = " + elapsed + " ms. [" + (++counter)+"]"); long sleep = (long) (Math.random() * 2000); try { Thread.sleep(sleep); } catch (InterruptedException e) { e.printStackTrace(); } } } }
mit
chauhansaurabhb/Android-End-User-Interaction-Request-Response-Command-Notify-
CodeForDeployment/JavaSED8/src/logic/LogicBadgeReader.java
1676
package logic; import iotsuite.pubsubmiddleware.*; import iotsuite.common.GlobalVariable; import android.content.Context; import iotsuite.semanticmodel.*; import android.app.Activity; import framework.*; import factory.*; public class LogicBadgeReader extends BadgeReader { IBadgeReader objBadgeReader; Activity ui; public LogicBadgeReader obj = this; Device deviceInfo; public String deviceType; public LogicBadgeReader(PubSubMiddleware pubSubM, final Device deviceInfo, final Object ui, Context myContext) { super(pubSubM, deviceInfo); deviceType = deviceInfo.getType(); if (deviceType.equals(GlobalVariable.deviceJAVASEType)) { IBadgeReader objBadgeReader = BadgeReaderFactory.getBadgeReader( myDeviceInfo.getType(), null, null); if (objBadgeReader.isEventDriven()) { objBadgeReader.getbadgeDisappeared(badgeDisappearedEvent); objBadgeReader.getbadgeDetected(badgeDetectedEvent); } else { objBadgeReader.getbadgeDisappeared(badgeDisappearedEvent); objBadgeReader.getbadgeDetected(badgeDetectedEvent); } } } ListenerbadgeDisappeared badgeDisappearedEvent = new ListenerbadgeDisappeared() { @Override public void onNewbadgeDisappeared(BadgeStruct response) { BadgeStruct sBadgeStruct = new BadgeStruct(response.getbadgeID(), response.getbadgeEvent()); setBadgeDisappeared(sBadgeStruct); } }; ListenerbadgeDetected badgeDetectedEvent = new ListenerbadgeDetected() { @Override public void onNewbadgeDetected(BadgeStruct response) { BadgeStruct sBadgeStruct = new BadgeStruct(response.getbadgeID(), response.getbadgeEvent()); setBadgeDetected(sBadgeStruct); } }; }
gpl-2.0
google/error-prone-javac
src/jdk.compiler/share/classes/module-info.java
5319
/* * Copyright (c) 2014, 2017, 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. */ /** * Defines the implementation of the * {@linkplain javax.tools.ToolProvider#getSystemJavaCompiler system Java compiler} * and its command line equivalent, <em>{@index javac javac tool}</em>, * as well as <em>{@index javah javah tool}</em>. * * <h2 style="font-family:'DejaVu Sans Mono', monospace; font-style:italic">javac</h2> * * <p> * This module provides the equivalent of command-line access to <em>javac</em> * via the {@link java.util.spi.ToolProvider ToolProvider} and * {@link javax.tools.Tool} service provider interfaces (SPIs), * and more flexible access via the {@link javax.tools.JavaCompiler JavaCompiler} * SPI.</p> * * <p> Instances of the tools can be obtained by calling * {@link java.util.spi.ToolProvider#findFirst ToolProvider.findFirst} * or the {@linkplain java.util.ServiceLoader service loader} with the name * {@code "javac"}. * * <p> * In addition, instances of {@link javax.tools.JavaCompiler.CompilationTask} * obtained from {@linkplain javax.tools.JavaCompiler JavaCompiler} can be * downcast to {@link com.sun.source.util.JavacTask JavacTask} for access to * lower level aspects of <em>javac</em>, such as the * {@link com.sun.source.tree Abstract Syntax Tree} (AST).</p> * * <p>This module uses the {@link java.nio.file.spi.FileSystemProvider * FileSystemProvider} API to locate file system providers. In particular, * this means that a jar file system provider, such as that in the * {@code jdk.zipfs} module, must be available if the compiler is to be able * to read JAR files. * * <h2 style="font-family:'DejaVu Sans Mono', monospace; font-style:italic">javah</h2> * * <p> * <em>javah</em> only exists as a command line tool, and does not provide any * direct API. As of JDK 9, it has been deprecated. * Use the {@code -h} option in <em>javac</em> instead.</p> * * <dl style="font-family:'DejaVu Sans', Arial, Helvetica, sans serif"> * <dt class="simpleTagLabel">Tool Guides: * <dd>{@extLink javac_tool_reference javac}, * {@extLink javah_tool_reference javah} * </dl> * * @provides java.util.spi.ToolProvider * @provides com.sun.tools.javac.platform.PlatformProvider * @provides javax.tools.JavaCompiler * @provides javax.tools.Tool * * @uses javax.annotation.processing.Processor * @uses com.sun.source.util.Plugin * @uses com.sun.tools.javac.platform.PlatformProvider * * @moduleGraph * @since 9 */ module jdk.compiler { requires transitive java.compiler; exports com.sun.source.doctree; exports com.sun.source.tree; exports com.sun.source.util; exports com.sun.tools.javac; exports com.sun.tools.doclint to jdk.javadoc; exports com.sun.tools.javac.api to jdk.javadoc, jdk.jshell; exports com.sun.tools.javac.code to jdk.javadoc, jdk.jshell; exports com.sun.tools.javac.comp to jdk.javadoc, jdk.jshell; exports com.sun.tools.javac.file to jdk.jdeps, jdk.javadoc; exports com.sun.tools.javac.jvm to jdk.javadoc; exports com.sun.tools.javac.main to jdk.javadoc; exports com.sun.tools.javac.model to jdk.javadoc; exports com.sun.tools.javac.parser to jdk.jshell; exports com.sun.tools.javac.platform to jdk.javadoc; exports com.sun.tools.javac.tree to jdk.javadoc, jdk.jshell; exports com.sun.tools.javac.util to jdk.jdeps, jdk.javadoc, jdk.jshell; exports jdk.internal.shellsupport.doc to jdk.jshell, jdk.scripting.nashorn.shell; uses javax.annotation.processing.Processor; uses com.sun.source.util.Plugin; uses com.sun.tools.javac.platform.PlatformProvider; provides java.util.spi.ToolProvider with com.sun.tools.javac.main.JavacToolProvider; provides com.sun.tools.javac.platform.PlatformProvider with com.sun.tools.javac.platform.JDKPlatformProvider; provides javax.tools.JavaCompiler with com.sun.tools.javac.api.JavacTool; provides javax.tools.Tool with com.sun.tools.javac.api.JavacTool; }
gpl-2.0
JoeHsiao/bioformats
components/forks/jai/src/jj2000/j2k/codestream/reader/PktDecoder.java
56980
/* * #%L * Fork of JAI Image I/O Tools. * %% * Copyright (C) 2008 - 2015 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ /* * $RCSfile: PktDecoder.java,v $ * $Revision: 1.1 $ * $Date: 2005/02/11 05:02:01 $ * $State: Exp $ * * Class: PktDecoder * * Description: Reads packets heads and keeps location of * code-blocks' codewords * * * COPYRIGHT: * * This software module was originally developed by Raphaël Grosbois and * Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel * Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David * Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research * Centre France S.A) in the course of development of the JPEG2000 * standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This * software module is an implementation of a part of the JPEG 2000 * Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio * Systems AB and Canon Research Centre France S.A (collectively JJ2000 * Partners) agree not to assert against ISO/IEC and users of the JPEG * 2000 Standard (Users) any of their rights under the copyright, not * including other intellectual property rights, for this software module * with respect to the usage by ISO/IEC and Users of this software module * or modifications thereof for use in hardware or software products * claiming conformance to the JPEG 2000 Standard. Those intending to use * this software module in hardware or software products are advised that * their use may infringe existing patents. The original developers of * this software module, JJ2000 Partners and ISO/IEC assume no liability * for use of this software module or modifications thereof. No license * or right to this software module is granted for non JPEG 2000 Standard * conforming products. JJ2000 Partners have full right to use this * software module for his/her own purpose, assign or donate this * software module to any third party and to inhibit third parties from * using this software module for non JPEG 2000 Standard conforming * products. This copyright notice must be included in all copies or * derivative works of this software module. * * Copyright (c) 1999/2000 JJ2000 Partners. * */ package jj2000.j2k.codestream.reader; import java.awt.Point; import jj2000.j2k.wavelet.synthesis.*; import jj2000.j2k.codestream.*; import jj2000.j2k.entropy.*; import jj2000.j2k.wavelet.*; import jj2000.j2k.decoder.*; import jj2000.j2k.image.*; import jj2000.j2k.util.*; import jj2000.j2k.io.*; import java.util.*; import java.io.*; /** * This class is used to read packet's head and body. All the members must be * re-initialized at the beginning of each tile thanks to the restart() * method. * */ public class PktDecoder implements StdEntropyCoderOptions{ /** Reference to the codestream reader agent */ private BitstreamReaderAgent src; /** Flag indicating whether packed packet header was used for this tile*/ private boolean pph=false; /** The packed packet header if it was used */ private ByteArrayInputStream pphbais; /** Reference to decoder specifications */ private DecoderSpecs decSpec; /** Reference to the HeaderDecoder */ private HeaderDecoder hd; /** Initial value of the state variable associated with code-block * length. */ private final int INIT_LBLOCK = 3; /** The wrapper to read bits for the packet heads */ private PktHeaderBitReader bin; /** Reference to the stream where to read from */ private RandomAccessIO ehs; /** * Maximum number of precincts : * * <ul> * <li> 1st dim: component index.</li> * <li> 2nd dim: resolution level index.</li> * </ul> * */ private Point[][] numPrec; /** Index of the current tile */ private int tIdx; /** * Array containing the coordinates, width, height, indexes, ... of the * precincts in the current tile: * * <ul> * <li> 1st dim: component index.</li> * <li> 2nd dim: resolution level index.</li> * <li> 3rd dim: precinct index.</li> * </ul> * */ private PrecInfo[][][] ppinfo; /** * Lblock value used to read code size information in each packet head: * * <ul> * <li> 1st dim: component index.</li> * <li> 2nd dim: resolution level index.</li> * <li> 3rd dim: subband index.</li> * <li> 4th/5th dim: code-block index (vert. and horiz.).</li> * </ul> * */ private int[][][][][] lblock; /** * Tag tree used to read inclusion informations in packet's head: * * <ul> * <li> 1st dim: component index.</li> * <li> 2nd dim: resolution level index.</li> * <li> 3rd dim: precinct index.</li> * <li> 4th dim: subband index.</li> * */ private TagTreeDecoder[][][][] ttIncl; /** * Tag tree used to read bit-depth information in packet's head: * * <ul> * <li> 1st dim: component index.</li> * <li> 2nd dim: resolution level index.</li> * <li> 3rd dim: precinct index.</li> * <li> 4th dim: subband index.</li> * </ul> * */ private TagTreeDecoder[][][][] ttMaxBP; /** Number of layers in t he current tile */ private int nl = 0; /** The number of components */ private int nc; /** Whether or not SOP marker segment are used */ private boolean sopUsed = false; /** Whether or not EPH marker are used */ private boolean ephUsed = false; /** Index of the current packet in the tile. Used with SOP marker segment*/ private int pktIdx; /** List of code-blocks found in last read packet head (one list * per subband) */ private Vector[] cblks; /** Number of codeblocks encountered. used for ncb quit condition*/ private int ncb; /** Maximum number of codeblocks to read before ncb quit condition is * reached */ private int maxCB; /** Flag indicating whether ncb quit condition has been reached */ private boolean ncbQuit; /** The tile in which the ncb quit condition was reached */ private int tQuit; /** The component in which the ncb quit condition was reached */ private int cQuit; /** The subband in which the ncb quit condition was reached */ private int sQuit; /** The resolution in which the ncb quit condition was reached */ private int rQuit; /** The x position of the last code block before ncb quit reached */ private int xQuit; /** The y position of the last code block before ncb quit reached */ private int yQuit; /** True if truncation mode is used. False if it is parsing mode */ private boolean isTruncMode; /** * Creates an empty PktDecoder object associated with given decoder * specifications and HeaderDecoder. This object must be initialized * thanks to the restart method before being used. * * @param decSpec The decoder specifications. * * @param hd The HeaderDecoder instance. * * @param ehs The stream where to read data from. * * @param src The bit stream reader agent. * * @param isTruncMode Whether or not truncation mode is required. * * @param maxCB The maximum number of code-blocks to read before ncbquit * * */ public PktDecoder(DecoderSpecs decSpec,HeaderDecoder hd, RandomAccessIO ehs,BitstreamReaderAgent src, boolean isTruncMode, int maxCB) { this.decSpec = decSpec; this.hd = hd; this.ehs = ehs; this.isTruncMode = isTruncMode; bin = new PktHeaderBitReader(ehs); this.src = src; ncb = 0; ncbQuit = false; this.maxCB = maxCB; } /** * Re-initialize the PktDecoder instance at the beginning of a new tile. * * @param nc The number of components in this tile * * @param mdl The maximum number of decomposition level in each component * of this tile * * @param nl The number of layers in this tile * * @param cbI The code-blocks array * * @param pph Flag indicating whether packed packet headers was used * * @param pphbais Stream containing the packed packet headers * */ public CBlkInfo[][][][][] restart(int nc,int[] mdl,int nl, CBlkInfo[][][][][] cbI, boolean pph, ByteArrayInputStream pphbais) { this.nc = nc; this.nl = nl; this.tIdx = src.getTileIdx(); this.pph = pph; this.pphbais = pphbais; sopUsed = ((Boolean)decSpec.sops.getTileDef(tIdx)).booleanValue(); pktIdx = 0; ephUsed = ((Boolean)decSpec.ephs.getTileDef(tIdx)).booleanValue(); cbI = new CBlkInfo[nc][][][][]; lblock = new int[nc][][][][]; ttIncl = new TagTreeDecoder[nc][][][]; ttMaxBP = new TagTreeDecoder[nc][][][]; numPrec = new Point[nc][]; ppinfo = new PrecInfo[nc][][]; // Used to compute the maximum number of precincts for each resolution // level int tcx0, tcy0, tcx1, tcy1; // Current tile position in the domain of // the image component int trx0, try0, trx1, try1; // Current tile position in the reduced // resolution image domain int xrsiz, yrsiz; // Component sub-sampling factors SubbandSyn root,sb; int mins,maxs; Point nBlk = null; int cb0x = src.getCbULX(); int cb0y = src.getCbULY(); for(int c=0; c<nc; c++) { cbI[c] = new CBlkInfo[mdl[c]+1][][][]; lblock[c] = new int[mdl[c]+1][][][]; ttIncl[c] = new TagTreeDecoder[mdl[c]+1][][]; ttMaxBP[c] = new TagTreeDecoder[mdl[c]+1][][]; numPrec[c] = new Point[mdl[c]+1]; ppinfo[c] = new PrecInfo[mdl[c]+1][]; // Get the tile-component coordinates on the reference grid tcx0 = src.getResULX(c,mdl[c]); tcy0 = src.getResULY(c,mdl[c]); tcx1 = tcx0 + src.getTileCompWidth(tIdx,c,mdl[c]); tcy1 = tcy0 + src.getTileCompHeight(tIdx,c,mdl[c]); for(int r=0; r<=mdl[c]; r++) { // Tile's coordinates in the reduced resolution image domain trx0 = (int)Math.ceil(tcx0/(double)(1<<(mdl[c]-r))); try0 = (int)Math.ceil(tcy0/(double)(1<<(mdl[c]-r))); trx1 = (int)Math.ceil(tcx1/(double)(1<<(mdl[c]-r))); try1 = (int)Math.ceil(tcy1/(double)(1<<(mdl[c]-r))); // Calculate the maximum number of precincts for each // resolution level taking into account tile specific options. double twoppx = (double)getPPX(tIdx,c,r); double twoppy = (double)getPPY(tIdx,c,r); numPrec[c][r] = new Point(); if (trx1>trx0) { numPrec[c][r].x = (int)Math.ceil((trx1-cb0x)/twoppx) - (int)Math.floor((trx0-cb0x)/twoppx); } else { numPrec[c][r].x = 0; } if (try1>try0) { numPrec[c][r].y = (int)Math.ceil((try1-cb0y)/twoppy) - (int)Math.floor((try0-cb0y)/twoppy); } else { numPrec[c][r].y = 0; } // First and last subbands indexes mins = (r==0) ? 0 : 1; maxs = (r==0) ? 1 : 4; int maxPrec = numPrec[c][r].x * numPrec[c][r].y; ttIncl[c][r] = new TagTreeDecoder[maxPrec][maxs+1]; ttMaxBP[c][r] = new TagTreeDecoder[maxPrec][maxs+1]; cbI[c][r] = new CBlkInfo[maxs+1][][]; lblock[c][r] = new int[maxs+1][][]; ppinfo[c][r] = new PrecInfo[maxPrec]; fillPrecInfo(c,r,mdl[c]); root = (SubbandSyn)src.getSynSubbandTree(tIdx,c); for(int s=mins; s<maxs; s++){ sb = (SubbandSyn)root.getSubbandByIdx(r,s); nBlk = sb.numCb; cbI[c][r][s] = new CBlkInfo[nBlk.y][nBlk.x]; lblock[c][r][s] = new int[nBlk.y][nBlk.x]; for(int i=nBlk.y-1;i>=0;i--) { ArrayUtil.intArraySet(lblock[c][r][s][i],INIT_LBLOCK); } } // loop on subbands } // End loop on resolution levels } // End loop on components return cbI; } /** * Retrives precincts and code-blocks coordinates in the given resolution, * level and component. Finishes TagTreeEncoder initialization as well. * * @param c Component index. * * @param r Resolution level index. * * @param mdl Number of decomposition level in component <tt>c</tt>. * */ private void fillPrecInfo(int c,int r,int mdl) { if(ppinfo[c][r].length==0) return; // No precinct in this // resolution level Point tileI = src.getTile(null); Point nTiles = src.getNumTiles(null); int xsiz,ysiz,x0siz,y0siz; int xt0siz,yt0siz; int xtsiz,ytsiz; xt0siz = src.getTilePartULX(); yt0siz = src.getTilePartULY(); xtsiz = src.getNomTileWidth(); ytsiz = src.getNomTileHeight(); x0siz = hd.getImgULX(); y0siz = hd.getImgULY(); xsiz = hd.getImgWidth(); ysiz = hd.getImgHeight(); int tx0 = (tileI.x==0) ? x0siz : xt0siz+tileI.x*xtsiz; int ty0 = (tileI.y==0) ? y0siz : yt0siz+tileI.y*ytsiz; int tx1 = (tileI.x!=nTiles.x-1) ? xt0siz+(tileI.x+1)*xtsiz : xsiz; int ty1 = (tileI.y!=nTiles.y-1) ? yt0siz+(tileI.y+1)*ytsiz : ysiz; int xrsiz = hd.getCompSubsX(c); int yrsiz = hd.getCompSubsY(c); int tcx0 = src.getResULX(c,mdl); int tcy0 = src.getResULY(c,mdl); int tcx1 = tcx0 + src.getTileCompWidth(tIdx,c,mdl); int tcy1 = tcy0 + src.getTileCompHeight(tIdx,c,mdl); int ndl = mdl-r; int trx0 = (int)Math.ceil(tcx0/(double)(1<<ndl)); int try0 = (int)Math.ceil(tcy0/(double)(1<<ndl)); int trx1 = (int)Math.ceil(tcx1/(double)(1<<ndl)); int try1 = (int)Math.ceil(tcy1/(double)(1<<ndl)); int cb0x = src.getCbULX(); int cb0y = src.getCbULY(); double twoppx = (double)getPPX(tIdx,c,r); double twoppy = (double)getPPY(tIdx,c,r); int twoppx2 = (int)(twoppx/2); int twoppy2 = (int)(twoppy/2); // Precincts are located at (cb0x+i*twoppx,cb0y+j*twoppy) // Valid precincts are those which intersect with the current // resolution level int maxPrec = ppinfo[c][r].length; int nPrec = 0; int istart = (int)Math.floor((try0-cb0y)/twoppy); int iend = (int)Math.floor((try1-1-cb0y)/twoppy); int jstart = (int)Math.floor((trx0-cb0x)/twoppx); int jend = (int)Math.floor((trx1-1-cb0x)/twoppx); int acb0x,acb0y; SubbandSyn root = src.getSynSubbandTree(tIdx,c); SubbandSyn sb = null; int p0x,p0y,p1x,p1y; // Precinct projection in subband int s0x,s0y,s1x,s1y; // Active subband portion int cw,ch; int kstart,kend,lstart,lend,k0,l0; int prg_ulx,prg_uly; int prg_w = (int)twoppx<<ndl; int prg_h = (int)twoppy<<ndl; int tmp1,tmp2; CBlkCoordInfo cb; for(int i=istart; i<=iend; i++) { // Vertical precincts for(int j=jstart; j<=jend; j++,nPrec++) { // Horizontal precincts if(j==jstart && (trx0-cb0x)%(xrsiz*((int)twoppx))!=0) { prg_ulx = tx0; } else { prg_ulx = cb0x+j*xrsiz*((int)twoppx<<ndl); } if(i==istart && (try0-cb0y)%(yrsiz*((int)twoppy))!=0) { prg_uly = ty0; } else { prg_uly = cb0y+i*yrsiz*((int)twoppy<<ndl); } ppinfo[c][r][nPrec] = new PrecInfo(r,(int)(cb0x+j*twoppx),(int)(cb0y+i*twoppy), (int)twoppx,(int)twoppy, prg_ulx,prg_uly,prg_w,prg_h); if(r==0) { // LL subband acb0x = cb0x; acb0y = cb0y; p0x = acb0x+j*(int)twoppx; p1x = p0x + (int)twoppx; p0y = acb0y+i*(int)twoppy; p1y = p0y + (int)twoppy; sb = (SubbandSyn)root.getSubbandByIdx(0,0); s0x = (p0x<sb.ulcx) ? sb.ulcx : p0x; s1x = (p1x>sb.ulcx+sb.w) ? sb.ulcx+sb.w : p1x; s0y = (p0y<sb.ulcy) ? sb.ulcy : p0y; s1y = (p1y>sb.ulcy+sb.h) ? sb.ulcy+sb.h : p1y; // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) cw = sb.nomCBlkW; ch = sb.nomCBlkH; k0 = (int)Math.floor((sb.ulcy-acb0y)/(double)ch); kstart = (int)Math.floor((s0y-acb0y)/(double)ch); kend = (int)Math.floor((s1y-1-acb0y)/(double)ch); l0 = (int)Math.floor((sb.ulcx-acb0x)/(double)cw); lstart = (int)Math.floor((s0x-acb0x)/(double)cw); lend = (int)Math.floor((s1x-1-acb0x)/(double)cw); if(s1x-s0x<=0 || s1y-s0y<=0) { ppinfo[c][r][nPrec].nblk[0] = 0; ttIncl[c][r][nPrec][0] = new TagTreeDecoder(0,0); ttMaxBP[c][r][nPrec][0] = new TagTreeDecoder(0,0); } else { ttIncl[c][r][nPrec][0] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ttMaxBP[c][r][nPrec][0] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ppinfo[c][r][nPrec].cblk[0] = new CBlkCoordInfo[kend-kstart+1][lend-lstart+1]; ppinfo[c][r][nPrec]. nblk[0] = (kend-kstart+1)*(lend-lstart+1); for(int k=kstart; k<=kend; k++) { // Vertical cblks for(int l=lstart; l<=lend; l++) { // Horiz. cblks cb = new CBlkCoordInfo(k-k0,l-l0); if(l==l0) { cb.ulx = sb.ulx; } else { cb.ulx = sb.ulx+l*cw-(sb.ulcx-acb0x); } if(k==k0) { cb.uly = sb.uly; } else { cb.uly = sb.uly+k*ch-(sb.ulcy-acb0y); } tmp1 = acb0x+l*cw; tmp1 = (tmp1>sb.ulcx) ? tmp1 : sb.ulcx; tmp2 = acb0x+(l+1)*cw; tmp2 = (tmp2>sb.ulcx+sb.w) ? sb.ulcx+sb.w : tmp2; cb.w = tmp2-tmp1; tmp1 = acb0y+k*ch; tmp1 = (tmp1>sb.ulcy) ? tmp1 : sb.ulcy; tmp2 = acb0y+(k+1)*ch; tmp2 = (tmp2>sb.ulcy+sb.h) ? sb.ulcy+sb.h : tmp2; cb.h = tmp2-tmp1; ppinfo[c][r][nPrec]. cblk[0][k-kstart][l-lstart] = cb; } // Horizontal code-blocks } // Vertical code-blocks } } else { // HL, LH and HH subbands // HL subband acb0x = 0; acb0y = cb0y; p0x = acb0x+j*twoppx2; p1x = p0x + twoppx2; p0y = acb0y+i*twoppy2; p1y = p0y + twoppy2; sb = (SubbandSyn)root.getSubbandByIdx(r,1); s0x = (p0x<sb.ulcx) ? sb.ulcx : p0x; s1x = (p1x>sb.ulcx+sb.w) ? sb.ulcx+sb.w : p1x; s0y = (p0y<sb.ulcy) ? sb.ulcy : p0y; s1y = (p1y>sb.ulcy+sb.h) ? sb.ulcy+sb.h : p1y; // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) cw = sb.nomCBlkW; ch = sb.nomCBlkH; k0 = (int)Math.floor((sb.ulcy-acb0y)/(double)ch); kstart = (int)Math.floor((s0y-acb0y)/(double)ch); kend = (int)Math.floor((s1y-1-acb0y)/(double)ch); l0 = (int)Math.floor((sb.ulcx-acb0x)/(double)cw); lstart = (int)Math.floor((s0x-acb0x)/(double)cw); lend = (int)Math.floor((s1x-1-acb0x)/(double)cw); if(s1x-s0x<=0 || s1y-s0y<=0) { ppinfo[c][r][nPrec].nblk[1] = 0; ttIncl[c][r][nPrec][1] = new TagTreeDecoder(0,0); ttMaxBP[c][r][nPrec][1] = new TagTreeDecoder(0,0); } else { ttIncl[c][r][nPrec][1] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ttMaxBP[c][r][nPrec][1] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ppinfo[c][r][nPrec].cblk[1] = new CBlkCoordInfo[kend-kstart+1][lend-lstart+1]; ppinfo[c][r][nPrec]. nblk[1] = (kend-kstart+1)*(lend-lstart+1); for(int k=kstart; k<=kend; k++) { // Vertical cblks for(int l=lstart; l<=lend; l++) { // Horiz. cblks cb = new CBlkCoordInfo(k-k0,l-l0); if(l==l0) { cb.ulx = sb.ulx; } else { cb.ulx = sb.ulx+l*cw-(sb.ulcx-acb0x); } if(k==k0) { cb.uly = sb.uly; } else { cb.uly = sb.uly+k*ch-(sb.ulcy-acb0y); } tmp1 = acb0x+l*cw; tmp1 = (tmp1>sb.ulcx) ? tmp1 : sb.ulcx; tmp2 = acb0x+(l+1)*cw; tmp2 = (tmp2>sb.ulcx+sb.w) ? sb.ulcx+sb.w : tmp2; cb.w = tmp2-tmp1; tmp1 = acb0y+k*ch; tmp1 = (tmp1>sb.ulcy) ? tmp1 : sb.ulcy; tmp2 = acb0y+(k+1)*ch; tmp2 = (tmp2>sb.ulcy+sb.h) ? sb.ulcy+sb.h : tmp2; cb.h = tmp2-tmp1; ppinfo[c][r][nPrec]. cblk[1][k-kstart][l-lstart] = cb; } // Horizontal code-blocks } // Vertical code-blocks } // LH subband acb0x = cb0x; acb0y = 0; p0x = acb0x+j*twoppx2; p1x = p0x + twoppx2; p0y = acb0y+i*twoppy2; p1y = p0y + twoppy2; sb = (SubbandSyn)root.getSubbandByIdx(r,2); s0x = (p0x<sb.ulcx) ? sb.ulcx : p0x; s1x = (p1x>sb.ulcx+sb.w) ? sb.ulcx+sb.w : p1x; s0y = (p0y<sb.ulcy) ? sb.ulcy : p0y; s1y = (p1y>sb.ulcy+sb.h) ? sb.ulcy+sb.h : p1y; // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) cw = sb.nomCBlkW; ch = sb.nomCBlkH; k0 = (int)Math.floor((sb.ulcy-acb0y)/(double)ch); kstart = (int)Math.floor((s0y-acb0y)/(double)ch); kend = (int)Math.floor((s1y-1-acb0y)/(double)ch); l0 = (int)Math.floor((sb.ulcx-acb0x)/(double)cw); lstart = (int)Math.floor((s0x-acb0x)/(double)cw); lend = (int)Math.floor((s1x-1-acb0x)/(double)cw); if(s1x-s0x<=0 || s1y-s0y<=0) { ppinfo[c][r][nPrec].nblk[2] = 0; ttIncl[c][r][nPrec][2] = new TagTreeDecoder(0,0); ttMaxBP[c][r][nPrec][2] = new TagTreeDecoder(0,0); } else { ttIncl[c][r][nPrec][2] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ttMaxBP[c][r][nPrec][2] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ppinfo[c][r][nPrec].cblk[2] = new CBlkCoordInfo[kend-kstart+1][lend-lstart+1]; ppinfo[c][r][nPrec]. nblk[2] = (kend-kstart+1)*(lend-lstart+1); for(int k=kstart; k<=kend; k++) { // Vertical cblks for(int l=lstart; l<=lend; l++) { // Horiz cblks cb = new CBlkCoordInfo(k-k0,l-l0); if(l==l0) { cb.ulx = sb.ulx; } else { cb.ulx = sb.ulx+l*cw-(sb.ulcx-acb0x); } if(k==k0) { cb.uly = sb.uly; } else { cb.uly = sb.uly+k*ch-(sb.ulcy-acb0y); } tmp1 = acb0x+l*cw; tmp1 = (tmp1>sb.ulcx) ? tmp1 : sb.ulcx; tmp2 = acb0x+(l+1)*cw; tmp2 = (tmp2>sb.ulcx+sb.w) ? sb.ulcx+sb.w : tmp2; cb.w = tmp2-tmp1; tmp1 = acb0y+k*ch; tmp1 = (tmp1>sb.ulcy) ? tmp1 : sb.ulcy; tmp2 = acb0y+(k+1)*ch; tmp2 = (tmp2>sb.ulcy+sb.h) ? sb.ulcy+sb.h : tmp2; cb.h = tmp2-tmp1; ppinfo[c][r][nPrec]. cblk[2][k-kstart][l-lstart] = cb; } // Horizontal code-blocks } // Vertical code-blocks } // HH subband acb0x = 0; acb0y = 0; p0x = acb0x+j*twoppx2; p1x = p0x + twoppx2; p0y = acb0y+i*twoppy2; p1y = p0y + twoppy2; sb = (SubbandSyn)root.getSubbandByIdx(r,3); s0x = (p0x<sb.ulcx) ? sb.ulcx : p0x; s1x = (p1x>sb.ulcx+sb.w) ? sb.ulcx+sb.w : p1x; s0y = (p0y<sb.ulcy) ? sb.ulcy : p0y; s1y = (p1y>sb.ulcy+sb.h) ? sb.ulcy+sb.h : p1y; // Code-blocks are located at (acb0x+k*cw,acb0y+l*ch) cw = sb.nomCBlkW; ch = sb.nomCBlkH; k0 = (int)Math.floor((sb.ulcy-acb0y)/(double)ch); kstart = (int)Math.floor((s0y-acb0y)/(double)ch); kend = (int)Math.floor((s1y-1-acb0y)/(double)ch); l0 = (int)Math.floor((sb.ulcx-acb0x)/(double)cw); lstart = (int)Math.floor((s0x-acb0x)/(double)cw); lend = (int)Math.floor((s1x-1-acb0x)/(double)cw); if(s1x-s0x<=0 || s1y-s0y<=0) { ppinfo[c][r][nPrec].nblk[3] = 0; ttIncl[c][r][nPrec][3] = new TagTreeDecoder(0,0); ttMaxBP[c][r][nPrec][3] = new TagTreeDecoder(0,0); } else { ttIncl[c][r][nPrec][3] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ttMaxBP[c][r][nPrec][3] = new TagTreeDecoder(kend-kstart+1,lend-lstart+1); ppinfo[c][r][nPrec].cblk[3] = new CBlkCoordInfo[kend-kstart+1][lend-lstart+1]; ppinfo[c][r][nPrec]. nblk[3] = (kend-kstart+1)*(lend-lstart+1); for(int k=kstart; k<=kend; k++) { // Vertical cblks for(int l=lstart; l<=lend; l++) { // Horiz cblks cb = new CBlkCoordInfo(k-k0,l-l0); if(l==l0) { cb.ulx = sb.ulx; } else { cb.ulx = sb.ulx+l*cw-(sb.ulcx-acb0x); } if(k==k0) { cb.uly = sb.uly; } else { cb.uly = sb.uly+k*ch-(sb.ulcy-acb0y); } tmp1 = acb0x+l*cw; tmp1 = (tmp1>sb.ulcx) ? tmp1 : sb.ulcx; tmp2 = acb0x+(l+1)*cw; tmp2 = (tmp2>sb.ulcx+sb.w) ? sb.ulcx+sb.w : tmp2; cb.w = tmp2-tmp1; tmp1 = acb0y+k*ch; tmp1 = (tmp1>sb.ulcy) ? tmp1 : sb.ulcy; tmp2 = acb0y+(k+1)*ch; tmp2 = (tmp2>sb.ulcy+sb.h) ? sb.ulcy+sb.h : tmp2; cb.h = tmp2-tmp1; ppinfo[c][r][nPrec]. cblk[3][k-kstart][l-lstart] = cb; } // Horizontal code-blocks } // Vertical code-blocks } } } // Horizontal precincts } // Vertical precincts } /** * Gets the number of precincts in a given component and resolution level. * * @param c Component index * * @param r Resolution index * */ public int getNumPrecinct(int c,int r) { return numPrec[c][r].x*numPrec[c][r].y; } /** * Read specified packet head and found length of each code-block's piece * of codewords as well as number of skipped most significant bit-planes. * * @param l layer index * * @param r Resolution level index * * @param c Component index * * @param p Precinct index * * @param cbI CBlkInfo array of relevant component and resolution * level. * * @param nb The number of bytes to read in each tile before reaching * output rate (used by truncation mode) * * @return True if specified output rate or EOF is reached. * */ public boolean readPktHead(int l,int r,int c,int p,CBlkInfo[][][] cbI, int[] nb) throws IOException { CBlkInfo ccb; int nSeg; // number of segment to read int cbLen; // Length of cblk's code-words int ltp; // last truncation point index int passtype; // coding pass type TagTreeDecoder tdIncl,tdBD; int tmp,tmp2,totnewtp,lblockCur,tpidx; int sumtotnewtp = 0; Point cbc; int startPktHead = ehs.getPos(); if(startPktHead>=ehs.length()) { // EOF reached at the beginning of this packet head return true; } int tIdx = src.getTileIdx(); PktHeaderBitReader bin; int mend,nend; int b; SubbandSyn sb; SubbandSyn root = src.getSynSubbandTree(tIdx,c); // If packed packet headers was used, use separate stream for reading // of packet headers if(pph) { bin = new PktHeaderBitReader(pphbais); } else { bin = this.bin; } int mins = (r==0) ? 0 : 1; int maxs = (r==0) ? 1 : 4; boolean precFound = false; for(int s=mins; s<maxs; s++) { if(p<ppinfo[c][r].length) { precFound = true; } } if(!precFound) { return false; } PrecInfo prec = ppinfo[c][r][p]; // Synchronize for bit reading bin.sync(); // If packet is empty there is no info in it (i.e. no code-blocks) if(bin.readBit()==0) { // No code-block is included cblks = new Vector[maxs+1]; for(int s=mins; s<maxs; s++){ cblks[s] = new Vector(); } pktIdx++; // If truncation mode, checks if output rate is reached // unless ncb quit condition is used in which case headers // are not counted if(isTruncMode && maxCB == -1) { tmp = ehs.getPos()-startPktHead; if(tmp>nb[tIdx]) { nb[tIdx] = 0; return true; } else { nb[tIdx] -= tmp; } } // Read EPH marker if needed if(ephUsed) { readEPHMarker(bin); } return false; } // Packet is not empty => decode info // Loop on each subband in this resolution level if(cblks==null || cblks.length<maxs+1) { cblks = new Vector[maxs+1]; } for(int s=mins; s<maxs; s++) { if(cblks[s]==null) { cblks[s] = new Vector(); } else { cblks[s].removeAllElements(); } sb = (SubbandSyn)root.getSubbandByIdx(r,s); // No code-block in this precinct if(prec.nblk[s]==0) { // Go to next subband continue; } tdIncl = ttIncl[c][r][p][s]; tdBD = ttMaxBP[c][r][p][s]; mend = (prec.cblk[s]==null) ? 0 : prec.cblk[s].length; for(int m=0; m<mend; m++) { // Vertical code-blocks nend = (prec.cblk[s][m]==null) ? 0 : prec.cblk[s][m].length; for (int n=0; n<nend; n++) { // Horizontal code-blocks cbc = prec.cblk[s][m][n].idx; b = cbc.x+cbc.y*sb.numCb.x; ccb = cbI[s][cbc.y][cbc.x]; try { // If code-block not included in previous layer(s) if(ccb==null || ccb.ctp==0) { if(ccb==null) { ccb = cbI[s][cbc.y][cbc.x] = new CBlkInfo(prec.cblk[s][m][n].ulx, prec.cblk[s][m][n].uly, prec.cblk[s][m][n].w, prec.cblk[s][m][n].h,nl); } ccb.pktIdx[l] = pktIdx; // Read inclusion using tag-tree tmp = tdIncl.update(m,n,l+1,bin); if(tmp>l) { // Not included continue; } // Read bitdepth using tag-tree tmp = 1;// initialization for(tmp2=1; tmp>=tmp2; tmp2++) { tmp = tdBD.update(m,n,tmp2,bin); } ccb.msbSkipped = tmp2-2; // New code-block => at least one truncation point totnewtp = 1; ccb.addNTP(l,0); // Check whether ncb quit condition is reached ncb++; if(maxCB != -1 && !ncbQuit && ncb == maxCB){ // ncb quit contidion reached ncbQuit = true; tQuit = tIdx; cQuit = c; sQuit = s; rQuit = r; xQuit = cbc.x; yQuit = cbc.y; } } else { // If code-block already included in one of // the previous layers. ccb.pktIdx[l] = pktIdx; // If not inclused if(bin.readBit()!=1) { continue; } // At least 1 more truncation point than // prev. packet totnewtp = 1; } // Read new truncation points if(bin.readBit()==1) {// if bit is 1 totnewtp++; // if next bit is 0 do nothing if(bin.readBit()==1) {//if is 1 totnewtp++; tmp = bin.readBits(2); totnewtp += tmp; // If next 2 bits are not 11 do nothing if(tmp==0x3) { //if 11 tmp = bin.readBits(5); totnewtp += tmp; // If next 5 bits are not 11111 do nothing if(tmp==0x1F) { //if 11111 totnewtp += bin.readBits(7); } } } } ccb.addNTP(l,totnewtp); sumtotnewtp += totnewtp; cblks[s].addElement(prec.cblk[s][m][n]); // Code-block length // -- Compute the number of bit to read to obtain // code-block length. // numBits = betaLamda + log2(totnewtp); // The length is signalled for each segment in // addition to the final one. The total length is the // sum of all segment lengths. // If regular termination in use, then there is one // segment per truncation point present. Otherwise, if // selective arithmetic bypass coding mode is present, // then there is one termination per bypass/MQ and // MQ/bypass transition. Otherwise the only // termination is at the end of the code-block. int options = ((Integer)decSpec.ecopts.getTileCompVal(tIdx,c)). intValue(); if( (options&OPT_TERM_PASS) != 0) { // Regular termination in use, one segment per new // pass (i.e. truncation point) nSeg = totnewtp; } else if( (options&OPT_BYPASS) != 0) { // Selective arithmetic coding bypass coding mode // in use, but no regular termination 1 segment up // to the end of the last pass of the 4th most // significant bit-plane, and, in each following // bit-plane, one segment upto the end of the 2nd // pass and one upto the end of the 3rd pass. if(ccb.ctp<=FIRST_BYPASS_PASS_IDX) { nSeg = 1; } else { nSeg = 1; // One at least for last pass // And one for each other terminated pass for(tpidx = ccb.ctp-totnewtp; tpidx < ccb.ctp-1; tpidx++) { if(tpidx >= FIRST_BYPASS_PASS_IDX-1) { passtype = (tpidx+NUM_EMPTY_PASSES_IN_MS_BP)% NUM_PASSES; if (passtype==1 || passtype==2) { // bypass coding just before MQ // pass or MQ pass just before // bypass coding => terminated nSeg++; } } } } } else { // Nothing special in use, just one segment nSeg = 1; } // Reads lblock increment (common to all segments) while(bin.readBit()!=0) { lblock[c][r][s][cbc.y][cbc.x]++; } if(nSeg==1) { // Only one segment in packet cbLen = bin.readBits(lblock[c][r][s][cbc.y][cbc.x]+ MathUtil.log2(totnewtp)); } else { // We must read one length per segment ccb.segLen[l] = new int[nSeg]; cbLen = 0; int j; if((options&OPT_TERM_PASS) != 0) { // Regular termination: each pass is terminated for(tpidx=ccb.ctp-totnewtp,j=0; tpidx<ccb.ctp;tpidx++,j++) { lblockCur = lblock[c][r][s][cbc.y][cbc.x]; tmp = bin.readBits(lblockCur); ccb.segLen[l][j] = tmp; cbLen += tmp; } } else { // Bypass coding: only some passes are // terminated ltp = ccb.ctp-totnewtp-1; for(tpidx = ccb.ctp-totnewtp, j=0; tpidx<ccb.ctp-1;tpidx++) { if(tpidx >= FIRST_BYPASS_PASS_IDX-1) { passtype = (tpidx+NUM_EMPTY_PASSES_IN_MS_BP)% NUM_PASSES; if (passtype==0) continue; lblockCur = lblock[c][r][s][cbc.y][cbc.x]; tmp = bin. readBits(lblockCur+ MathUtil.log2(tpidx-ltp)); ccb.segLen[l][j] = tmp; cbLen += tmp; ltp = tpidx; j++; } } // Last pass has always the length sent lblockCur = lblock[c][r][s][cbc.y][cbc.x]; tmp = bin.readBits(lblockCur+ MathUtil.log2(tpidx-ltp)); cbLen += tmp; ccb.segLen[l][j] = tmp; } } ccb.len[l] = cbLen; // If truncation mode, checks if output rate is reached // unless ncb and lbody quit contitions used. if(isTruncMode && maxCB==-1) { tmp = ehs.getPos()-startPktHead; if(tmp>nb[tIdx]) { nb[tIdx] = 0; // Remove found information in this code-block if(l==0) { cbI[s][cbc.y][cbc.x] = null; } else { ccb.off[l]=ccb.len[l]=0; ccb.ctp -= ccb.ntp[l]; ccb.ntp[l] = 0; ccb.pktIdx[l] = -1; } return true; } } } catch(EOFException e) { // Remove found information in this code-block if(l==0) { cbI[s][cbc.y][cbc.x] = null; } else { ccb.off[l]=ccb.len[l]=0; ccb.ctp -= ccb.ntp[l]; ccb.ntp[l] = 0; ccb.pktIdx[l] = -1; } // throw new EOFException(); return true; } } // End loop on horizontal code-blocks } // End loop on vertical code-blocks } // End loop on subbands // Read EPH marker if needed if(ephUsed) { readEPHMarker(bin); } pktIdx++; // If truncation mode, checks if output rate is reached if(isTruncMode && maxCB == -1) { tmp = ehs.getPos()-startPktHead; if(tmp>nb[tIdx]) { nb[tIdx] = 0; return true; } else { nb[tIdx] -= tmp; } } return false; } /** * Reads specificied packet body in order to find offset of each * code-block's piece of codeword. This use the list of found code-blocks * in previous red packet head. * * @param l layer index * * @param r Resolution level index * * @param c Component index * * @param p Precinct index * * @param cbI CBlkInfo array of relevant component and resolution * level. * * @param nb The remainding number of bytes to read from the bit stream in * each tile before reaching the decoding rate (in truncation mode) * * @return True if decoding rate is reached * */ public boolean readPktBody(int l,int r,int c,int p,CBlkInfo[][][] cbI, int[] nb) throws IOException { int curOff = ehs.getPos(); Point curCB; CBlkInfo ccb; boolean stopRead = false; int tIdx = src.getTileIdx(); Point cbc; boolean precFound = false; int mins = (r==0) ? 0 : 1; int maxs = (r==0) ? 1 : 4; for(int s=mins; s<maxs; s++) { if(p<ppinfo[c][r].length) { precFound = true; } } if(!precFound) { return false; } for(int s=mins; s<maxs; s++) { for(int numCB=0; numCB<cblks[s].size(); numCB++) { cbc = ((CBlkCoordInfo)cblks[s].elementAt(numCB)).idx; ccb = cbI[s][cbc.y][cbc.x]; ccb.off[l] = curOff; curOff += ccb.len[l]; try { ehs.seek(curOff); } catch(EOFException e) { if(l==0) { cbI[s][cbc.y][cbc.x] = null; } else { ccb.off[l] = ccb.len[l]=0; ccb.ctp -= ccb.ntp[l]; ccb.ntp[l] = 0; ccb.pktIdx[l] = -1; } throw new EOFException(); } // If truncation mode if(isTruncMode) { if(stopRead || ccb.len[l]>nb[tIdx]) { // Remove found information in this code-block if(l==0) { cbI[s][cbc.y][cbc.x] = null; } else { ccb.off[l] = ccb.len[l] = 0; ccb.ctp -= ccb.ntp[l]; ccb.ntp[l] = 0; ccb.pktIdx[l] = -1; } stopRead = true; } if(!stopRead) { nb[tIdx] -= ccb.len[l]; } } // If ncb quit condition reached if(ncbQuit && r == rQuit && s == sQuit && cbc.x == xQuit && cbc.y == yQuit && tIdx == tQuit && c == cQuit) { cbI[s][cbc.y][cbc.x] = null; stopRead = true; } } // Loop on code-blocks } // End loop on subbands // Seek to the end of the packet ehs.seek(curOff); if(stopRead) { return true; } else { return false; } } /** * Returns the precinct partition width for the specified component, * resolution level and tile. * * @param t the tile index * * @param c The index of the component (between 0 and C-1) * * @param r The resolution level, from 0 to L. * * @return the precinct partition width for the specified component, * resolution level and tile. * */ public final int getPPX(int t,int c,int r){ return decSpec.pss.getPPX(t,c,r); } /** * Returns the precinct partition height for the specified component, * resolution level and tile. * * @param t the tile index * * @param c The index of the component (between 0 and C-1) * * @param rl The resolution level, from 0 to L. * * @return the precinct partition height in the specified component, for * the specified resolution level, for the current tile. * */ public final int getPPY(int t,int c,int rl) { return decSpec.pss.getPPY(t,c,rl); } /** * Try to read a SOP marker and check that its sequence number if not out * of sequence. If so, an error is thrown. * * @param nBytes The number of bytes left to read from each tile * * @param p Precinct index * * @param r Resolution level index * * @param c Component index * */ public boolean readSOPMarker(int[] nBytes,int p,int c,int r) throws IOException { int val; byte sopArray[] = new byte[6]; int tIdx = src.getTileIdx(); int mins = (r==0) ? 0 : 1; int maxs = (r==0) ? 1 : 4; boolean precFound = false; for(int s=mins; s<maxs; s++) { if(p<ppinfo[c][r].length) { precFound = true; } } if(!precFound) { return false; } // If SOP markers are not used, return if(!sopUsed) { return false; } // Check if SOP is used for this packet int pos = ehs.getPos(); if( (short)((ehs.read()<<8) | ehs.read()) != Markers.SOP ) { ehs.seek(pos); return false; } ehs.seek(pos); // If length of SOP marker greater than remaining bytes to read for // this tile return true if(nBytes[tIdx]<6) { return true; } nBytes[tIdx] -= 6; // Read marker into array 'sopArray' ehs.readFully(sopArray,0,Markers.SOP_LENGTH); // Check if this is the correct marker val = sopArray[0]; val <<= 8; val |= sopArray[1]; if(val!=Markers.SOP) { throw new Error("Corrupted Bitstream: Could not parse SOP "+ "marker !"); } // Check if length is correct val = (sopArray[2]&0xff); val <<= 8; val |= (sopArray[3]&0xff); if(val!=4) { throw new Error("Corrupted Bitstream: Corrupted SOP marker !"); } // Check if sequence number if ok val = (sopArray[4]&0xff); val <<= 8; val |= (sopArray[5]&0xff); if(!pph && val!=pktIdx) { throw new Error("Corrupted Bitstream: SOP marker out of " +"sequence !"); } if(pph && val!=pktIdx-1) { // if packed packet headers are used, packet header was read // before SOP marker segment throw new Error("Corrupted Bitstream: SOP marker out of " +"sequence !"); } return false; } /** * Try to read an EPH marker. If it is not possible then an Error is * thrown. * * @param bin The packet header reader to read the EPH marker from * */ public void readEPHMarker(PktHeaderBitReader bin) throws IOException { int val; byte ephArray[] = new byte[2]; if(bin.usebais) { bin.bais.read(ephArray,0,Markers.EPH_LENGTH); } else { bin.in.readFully(ephArray,0,Markers.EPH_LENGTH); } // Check if this is the correct marker val = ephArray[0]; val <<= 8; val |= ephArray[1]; if (val!=Markers.EPH) { throw new Error("Corrupted Bitstream: Could not parse EPH " +"marker ! "); } } /** * Get PrecInfo instance of the specified resolution level, component and * precinct. * * @param c Component index. * * @param r Resolution level index. * * @param p Precinct index. * */ public PrecInfo getPrecInfo(int c,int r,int p) { return ppinfo[c][r][p]; } }
gpl-2.0
litchie/exult-ios
ios/SDL2/android-project/app/src/main/java/org/libsdl/app/SDLActivity.java
84067
package org.libsdl.app; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Hashtable; import java.lang.reflect.Method; import java.lang.Math; import android.app.*; import android.content.*; import android.content.res.Configuration; import android.text.InputType; import android.view.*; import android.view.inputmethod.BaseInputConnection; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.RelativeLayout; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.os.*; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.graphics.*; import android.graphics.drawable.Drawable; import android.hardware.*; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ApplicationInfo; /** SDL Activity */ public class SDLActivity extends Activity implements View.OnSystemUiVisibilityChangeListener { private static final String TAG = "SDL"; public static boolean mIsResumedCalled, mHasFocus; public static final boolean mHasMultiWindow = (Build.VERSION.SDK_INT >= 24); // Cursor types private static final int SDL_SYSTEM_CURSOR_NONE = -1; private static final int SDL_SYSTEM_CURSOR_ARROW = 0; private static final int SDL_SYSTEM_CURSOR_IBEAM = 1; private static final int SDL_SYSTEM_CURSOR_WAIT = 2; private static final int SDL_SYSTEM_CURSOR_CROSSHAIR = 3; private static final int SDL_SYSTEM_CURSOR_WAITARROW = 4; private static final int SDL_SYSTEM_CURSOR_SIZENWSE = 5; private static final int SDL_SYSTEM_CURSOR_SIZENESW = 6; private static final int SDL_SYSTEM_CURSOR_SIZEWE = 7; private static final int SDL_SYSTEM_CURSOR_SIZENS = 8; private static final int SDL_SYSTEM_CURSOR_SIZEALL = 9; private static final int SDL_SYSTEM_CURSOR_NO = 10; private static final int SDL_SYSTEM_CURSOR_HAND = 11; protected static final int SDL_ORIENTATION_UNKNOWN = 0; protected static final int SDL_ORIENTATION_LANDSCAPE = 1; protected static final int SDL_ORIENTATION_LANDSCAPE_FLIPPED = 2; protected static final int SDL_ORIENTATION_PORTRAIT = 3; protected static final int SDL_ORIENTATION_PORTRAIT_FLIPPED = 4; protected static int mCurrentOrientation; // Handle the state of the native layer public enum NativeState { INIT, RESUMED, PAUSED } public static NativeState mNextNativeState; public static NativeState mCurrentNativeState; /** If shared libraries (e.g. SDL or the native application) could not be loaded. */ public static boolean mBrokenLibraries; // Main components protected static SDLActivity mSingleton; protected static SDLSurface mSurface; protected static View mTextEdit; protected static boolean mScreenKeyboardShown; protected static ViewGroup mLayout; protected static SDLClipboardHandler mClipboardHandler; protected static Hashtable<Integer, PointerIcon> mCursors; protected static int mLastCursorID; protected static SDLGenericMotionListener_API12 mMotionListener; protected static HIDDeviceManager mHIDDeviceManager; // This is what SDL runs in. It invokes SDL_main(), eventually protected static Thread mSDLThread; protected static SDLGenericMotionListener_API12 getMotionListener() { if (mMotionListener == null) { if (Build.VERSION.SDK_INT >= 26) { mMotionListener = new SDLGenericMotionListener_API26(); } else if (Build.VERSION.SDK_INT >= 24) { mMotionListener = new SDLGenericMotionListener_API24(); } else { mMotionListener = new SDLGenericMotionListener_API12(); } } return mMotionListener; } /** * This method returns the name of the shared object with the application entry point * It can be overridden by derived classes. */ protected String getMainSharedObject() { String library; String[] libraries = SDLActivity.mSingleton.getLibraries(); if (libraries.length > 0) { library = "lib" + libraries[libraries.length - 1] + ".so"; } else { library = "libmain.so"; } return getContext().getApplicationInfo().nativeLibraryDir + "/" + library; } /** * This method returns the name of the application entry point * It can be overridden by derived classes. */ protected String getMainFunction() { return "SDL_main"; } /** * This method is called by SDL before loading the native shared libraries. * It can be overridden to provide names of shared libraries to be loaded. * The default implementation returns the defaults. It never returns null. * An array returned by a new implementation must at least contain "SDL2". * Also keep in mind that the order the libraries are loaded may matter. * @return names of shared libraries to be loaded (e.g. "SDL2", "main"). */ protected String[] getLibraries() { return new String[] { "hidapi", "SDL2", // "SDL2_image", // "SDL2_mixer", // "SDL2_net", // "SDL2_ttf", "main" }; } // Load the .so public void loadLibraries() { for (String lib : getLibraries()) { SDL.loadLibrary(lib); } } /** * This method is called by SDL before starting the native application thread. * It can be overridden to provide the arguments after the application name. * The default implementation returns an empty array. It never returns null. * @return arguments for the native application. */ protected String[] getArguments() { return new String[0]; } public static void initialize() { // The static nature of the singleton and Android quirkyness force us to initialize everything here // Otherwise, when exiting the app and returning to it, these variables *keep* their pre exit values mSingleton = null; mSurface = null; mTextEdit = null; mLayout = null; mClipboardHandler = null; mCursors = new Hashtable<Integer, PointerIcon>(); mLastCursorID = 0; mSDLThread = null; mBrokenLibraries = false; mIsResumedCalled = false; mHasFocus = true; mNextNativeState = NativeState.INIT; mCurrentNativeState = NativeState.INIT; } // Setup @Override protected void onCreate(Bundle savedInstanceState) { Log.v(TAG, "Device: " + Build.DEVICE); Log.v(TAG, "Model: " + Build.MODEL); Log.v(TAG, "onCreate()"); super.onCreate(savedInstanceState); try { Thread.currentThread().setName("SDLActivity"); } catch (Exception e) { Log.v(TAG, "modify thread properties failed " + e.toString()); } // Load shared libraries String errorMsgBrokenLib = ""; try { loadLibraries(); } catch(UnsatisfiedLinkError e) { System.err.println(e.getMessage()); mBrokenLibraries = true; errorMsgBrokenLib = e.getMessage(); } catch(Exception e) { System.err.println(e.getMessage()); mBrokenLibraries = true; errorMsgBrokenLib = e.getMessage(); } if (mBrokenLibraries) { mSingleton = this; AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this); dlgAlert.setMessage("An error occurred while trying to start the application. Please try again and/or reinstall." + System.getProperty("line.separator") + System.getProperty("line.separator") + "Error: " + errorMsgBrokenLib); dlgAlert.setTitle("SDL Error"); dlgAlert.setPositiveButton("Exit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog,int id) { // if this button is clicked, close current activity SDLActivity.mSingleton.finish(); } }); dlgAlert.setCancelable(false); dlgAlert.create().show(); return; } // Set up JNI SDL.setupJNI(); // Initialize state SDL.initialize(); // So we can call stuff from static callbacks mSingleton = this; SDL.setContext(this); mClipboardHandler = new SDLClipboardHandler_API11(); mHIDDeviceManager = HIDDeviceManager.acquire(this); // Set up the surface mSurface = new SDLSurface(getApplication()); mLayout = new RelativeLayout(this); mLayout.addView(mSurface); // Get our current screen orientation and pass it down. mCurrentOrientation = SDLActivity.getCurrentOrientation(); // Only record current orientation SDLActivity.onNativeOrientationChanged(mCurrentOrientation); setContentView(mLayout); setWindowStyle(false); getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(this); // Get filename from "Open with" of another application Intent intent = getIntent(); if (intent != null && intent.getData() != null) { String filename = intent.getData().getPath(); if (filename != null) { Log.v(TAG, "Got filename: " + filename); SDLActivity.onNativeDropFile(filename); } } } protected void pauseNativeThread() { mNextNativeState = NativeState.PAUSED; mIsResumedCalled = false; if (SDLActivity.mBrokenLibraries) { return; } SDLActivity.handleNativeState(); } protected void resumeNativeThread() { mNextNativeState = NativeState.RESUMED; mIsResumedCalled = true; if (SDLActivity.mBrokenLibraries) { return; } SDLActivity.handleNativeState(); } // Events @Override protected void onPause() { Log.v(TAG, "onPause()"); super.onPause(); if (mHIDDeviceManager != null) { mHIDDeviceManager.setFrozen(true); } if (!mHasMultiWindow) { pauseNativeThread(); } } @Override protected void onResume() { Log.v(TAG, "onResume()"); super.onResume(); if (mHIDDeviceManager != null) { mHIDDeviceManager.setFrozen(false); } if (!mHasMultiWindow) { resumeNativeThread(); } } @Override protected void onStop() { Log.v(TAG, "onStop()"); super.onStop(); if (mHasMultiWindow) { pauseNativeThread(); } } @Override protected void onStart() { Log.v(TAG, "onStart()"); super.onStart(); if (mHasMultiWindow) { resumeNativeThread(); } } public static int getCurrentOrientation() { final Context context = SDLActivity.getContext(); final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int result = SDL_ORIENTATION_UNKNOWN; switch (display.getRotation()) { case Surface.ROTATION_0: result = SDL_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_90: result = SDL_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_180: result = SDL_ORIENTATION_PORTRAIT_FLIPPED; break; case Surface.ROTATION_270: result = SDL_ORIENTATION_LANDSCAPE_FLIPPED; break; } return result; } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); Log.v(TAG, "onWindowFocusChanged(): " + hasFocus); if (SDLActivity.mBrokenLibraries) { return; } mHasFocus = hasFocus; if (hasFocus) { mNextNativeState = NativeState.RESUMED; SDLActivity.getMotionListener().reclaimRelativeMouseModeIfNeeded(); SDLActivity.handleNativeState(); nativeFocusChanged(true); } else { nativeFocusChanged(false); if (!mHasMultiWindow) { mNextNativeState = NativeState.PAUSED; SDLActivity.handleNativeState(); } } } @Override public void onLowMemory() { Log.v(TAG, "onLowMemory()"); super.onLowMemory(); if (SDLActivity.mBrokenLibraries) { return; } SDLActivity.nativeLowMemory(); } @Override protected void onDestroy() { Log.v(TAG, "onDestroy()"); if (mHIDDeviceManager != null) { HIDDeviceManager.release(mHIDDeviceManager); mHIDDeviceManager = null; } if (SDLActivity.mBrokenLibraries) { super.onDestroy(); return; } if (SDLActivity.mSDLThread != null) { // Send Quit event to "SDLThread" thread SDLActivity.nativeSendQuit(); // Wait for "SDLThread" thread to end try { SDLActivity.mSDLThread.join(); } catch(Exception e) { Log.v(TAG, "Problem stopping SDLThread: " + e); } } SDLActivity.nativeQuit(); super.onDestroy(); } @Override public void onBackPressed() { // Check if we want to block the back button in case of mouse right click. // // If we do, the normal hardware back button will no longer work and people have to use home, // but the mouse right click will work. // String trapBack = SDLActivity.nativeGetHint("SDL_ANDROID_TRAP_BACK_BUTTON"); if ((trapBack != null) && trapBack.equals("1")) { // Exit and let the mouse handler handle this button (if appropriate) return; } // Default system back button behavior. if (!isFinishing()) { super.onBackPressed(); } } // Called by JNI from SDL. public static void manualBackButton() { mSingleton.pressBackButton(); } // Used to get us onto the activity's main thread public void pressBackButton() { runOnUiThread(new Runnable() { @Override public void run() { if (!SDLActivity.this.isFinishing()) { SDLActivity.this.superOnBackPressed(); } } }); } // Used to access the system back behavior. public void superOnBackPressed() { super.onBackPressed(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (SDLActivity.mBrokenLibraries) { return false; } int keyCode = event.getKeyCode(); // Ignore certain special keys so they're handled by Android if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_CAMERA || keyCode == KeyEvent.KEYCODE_ZOOM_IN || /* API 11 */ keyCode == KeyEvent.KEYCODE_ZOOM_OUT /* API 11 */ ) { return false; } return super.dispatchKeyEvent(event); } /* Transition to next state */ public static void handleNativeState() { if (mNextNativeState == mCurrentNativeState) { // Already in same state, discard. return; } // Try a transition to init state if (mNextNativeState == NativeState.INIT) { mCurrentNativeState = mNextNativeState; return; } // Try a transition to paused state if (mNextNativeState == NativeState.PAUSED) { if (mSDLThread != null) { nativePause(); } if (mSurface != null) { mSurface.handlePause(); } mCurrentNativeState = mNextNativeState; return; } // Try a transition to resumed state if (mNextNativeState == NativeState.RESUMED) { if (mSurface.mIsSurfaceReady && mHasFocus && mIsResumedCalled) { if (mSDLThread == null) { // This is the entry point to the C app. // Start up the C app thread and enable sensor input for the first time // FIXME: Why aren't we enabling sensor input at start? mSDLThread = new Thread(new SDLMain(), "SDLThread"); mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, true); mSDLThread.start(); // No nativeResume(), don't signal Android_ResumeSem mSurface.handleResume(); } else { nativeResume(); mSurface.handleResume(); } mCurrentNativeState = mNextNativeState; } } } // Messages from the SDLMain thread static final int COMMAND_CHANGE_TITLE = 1; static final int COMMAND_CHANGE_WINDOW_STYLE = 2; static final int COMMAND_TEXTEDIT_HIDE = 3; static final int COMMAND_CHANGE_SURFACEVIEW_FORMAT = 4; static final int COMMAND_SET_KEEP_SCREEN_ON = 5; protected static final int COMMAND_USER = 0x8000; protected static boolean mFullscreenModeActive; /** * This method is called by SDL if SDL did not handle a message itself. * This happens if a received message contains an unsupported command. * Method can be overwritten to handle Messages in a different class. * @param command the command of the message. * @param param the parameter of the message. May be null. * @return if the message was handled in overridden method. */ protected boolean onUnhandledMessage(int command, Object param) { return false; } /** * A Handler class for Messages from native SDL applications. * It uses current Activities as target (e.g. for the title). * static to prevent implicit references to enclosing object. */ protected static class SDLCommandHandler extends Handler { @Override public void handleMessage(Message msg) { Context context = SDL.getContext(); if (context == null) { Log.e(TAG, "error handling message, getContext() returned null"); return; } switch (msg.arg1) { case COMMAND_CHANGE_TITLE: if (context instanceof Activity) { ((Activity) context).setTitle((String)msg.obj); } else { Log.e(TAG, "error handling message, getContext() returned no Activity"); } break; case COMMAND_CHANGE_WINDOW_STYLE: if (Build.VERSION.SDK_INT < 19) { // This version of Android doesn't support the immersive fullscreen mode break; } if (context instanceof Activity) { Window window = ((Activity) context).getWindow(); if (window != null) { if ((msg.obj instanceof Integer) && (((Integer) msg.obj).intValue() != 0)) { int flags = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.INVISIBLE; window.getDecorView().setSystemUiVisibility(flags); window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); SDLActivity.mFullscreenModeActive = true; } else { int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_VISIBLE; window.getDecorView().setSystemUiVisibility(flags); window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); SDLActivity.mFullscreenModeActive = false; } } } else { Log.e(TAG, "error handling message, getContext() returned no Activity"); } break; case COMMAND_TEXTEDIT_HIDE: if (mTextEdit != null) { // Note: On some devices setting view to GONE creates a flicker in landscape. // Setting the View's sizes to 0 is similar to GONE but without the flicker. // The sizes will be set to useful values when the keyboard is shown again. mTextEdit.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0); mScreenKeyboardShown = false; mSurface.requestFocus(); } break; case COMMAND_SET_KEEP_SCREEN_ON: { if (context instanceof Activity) { Window window = ((Activity) context).getWindow(); if (window != null) { if ((msg.obj instanceof Integer) && (((Integer) msg.obj).intValue() != 0)) { window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } } } break; } case COMMAND_CHANGE_SURFACEVIEW_FORMAT: { int format = (Integer) msg.obj; int pf; if (SDLActivity.mSurface == null) { return; } SurfaceHolder holder = SDLActivity.mSurface.getHolder(); if (holder == null) { return; } if (format == 1) { pf = PixelFormat.RGBA_8888; } else if (format == 2) { pf = PixelFormat.RGBX_8888; } else { pf = PixelFormat.RGB_565; } holder.setFormat(pf); break; } default: if ((context instanceof SDLActivity) && !((SDLActivity) context).onUnhandledMessage(msg.arg1, msg.obj)) { Log.e(TAG, "error handling message, command is " + msg.arg1); } } } } // Handler for the messages Handler commandHandler = new SDLCommandHandler(); // Send a message from the SDLMain thread boolean sendCommand(int command, Object data) { Message msg = commandHandler.obtainMessage(); msg.arg1 = command; msg.obj = data; boolean result = commandHandler.sendMessage(msg); if ((Build.VERSION.SDK_INT >= 19) && (command == COMMAND_CHANGE_WINDOW_STYLE)) { // Ensure we don't return until the resize has actually happened, // or 500ms have passed. boolean bShouldWait = false; if (data instanceof Integer) { // Let's figure out if we're already laid out fullscreen or not. Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); android.util.DisplayMetrics realMetrics = new android.util.DisplayMetrics(); display.getRealMetrics( realMetrics ); boolean bFullscreenLayout = ((realMetrics.widthPixels == mSurface.getWidth()) && (realMetrics.heightPixels == mSurface.getHeight())); if (((Integer)data).intValue() == 1) { // If we aren't laid out fullscreen or actively in fullscreen mode already, we're going // to change size and should wait for surfaceChanged() before we return, so the size // is right back in native code. If we're already laid out fullscreen, though, we're // not going to change size even if we change decor modes, so we shouldn't wait for // surfaceChanged() -- which may not even happen -- and should return immediately. bShouldWait = !bFullscreenLayout; } else { // If we're laid out fullscreen (even if the status bar and nav bar are present), // or are actively in fullscreen, we're going to change size and should wait for // surfaceChanged before we return, so the size is right back in native code. bShouldWait = bFullscreenLayout; } } if (bShouldWait && (SDLActivity.getContext() != null)) { // We'll wait for the surfaceChanged() method, which will notify us // when called. That way, we know our current size is really the // size we need, instead of grabbing a size that's still got // the navigation and/or status bars before they're hidden. // // We'll wait for up to half a second, because some devices // take a surprisingly long time for the surface resize, but // then we'll just give up and return. // synchronized(SDLActivity.getContext()) { try { SDLActivity.getContext().wait(500); } catch (InterruptedException ie) { ie.printStackTrace(); } } } } return result; } // C functions we call public static native int nativeSetupJNI(); public static native int nativeRunMain(String library, String function, Object arguments); public static native void nativeLowMemory(); public static native void nativeSendQuit(); public static native void nativeQuit(); public static native void nativePause(); public static native void nativeResume(); public static native void nativeFocusChanged(boolean hasFocus); public static native void onNativeDropFile(String filename); public static native void nativeSetScreenResolution(int surfaceWidth, int surfaceHeight, int deviceWidth, int deviceHeight, int format, float rate); public static native void onNativeResize(); public static native void onNativeKeyDown(int keycode); public static native void onNativeKeyUp(int keycode); public static native boolean onNativeSoftReturnKey(); public static native void onNativeKeyboardFocusLost(); public static native void onNativeMouse(int button, int action, float x, float y, boolean relative); public static native void onNativeTouch(int touchDevId, int pointerFingerId, int action, float x, float y, float p); public static native void onNativeAccel(float x, float y, float z); public static native void onNativeClipboardChanged(); public static native void onNativeSurfaceCreated(); public static native void onNativeSurfaceChanged(); public static native void onNativeSurfaceDestroyed(); public static native String nativeGetHint(String name); public static native void nativeSetenv(String name, String value); public static native void onNativeOrientationChanged(int orientation); public static native void nativeAddTouch(int touchId, String name); public static native void nativePermissionResult(int requestCode, boolean result); /** * This method is called by SDL using JNI. */ public static boolean setActivityTitle(String title) { // Called from SDLMain() thread and can't directly affect the view return mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title); } /** * This method is called by SDL using JNI. */ public static void setWindowStyle(boolean fullscreen) { // Called from SDLMain() thread and can't directly affect the view mSingleton.sendCommand(COMMAND_CHANGE_WINDOW_STYLE, fullscreen ? 1 : 0); } /** * This method is called by SDL using JNI. * This is a static method for JNI convenience, it calls a non-static method * so that is can be overridden */ public static void setOrientation(int w, int h, boolean resizable, String hint) { if (mSingleton != null) { mSingleton.setOrientationBis(w, h, resizable, hint); } } /** * This can be overridden */ public void setOrientationBis(int w, int h, boolean resizable, String hint) { int orientation_landscape = -1; int orientation_portrait = -1; /* If set, hint "explicitly controls which UI orientations are allowed". */ if (hint.contains("LandscapeRight") && hint.contains("LandscapeLeft")) { orientation_landscape = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE; } else if (hint.contains("LandscapeRight")) { orientation_landscape = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; } else if (hint.contains("LandscapeLeft")) { orientation_landscape = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; } if (hint.contains("Portrait") && hint.contains("PortraitUpsideDown")) { orientation_portrait = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT; } else if (hint.contains("Portrait")) { orientation_portrait = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } else if (hint.contains("PortraitUpsideDown")) { orientation_portrait = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; } boolean is_landscape_allowed = (orientation_landscape == -1 ? false : true); boolean is_portrait_allowed = (orientation_portrait == -1 ? false : true); int req = -1; /* Requested orientation */ /* No valid hint, nothing is explicitly allowed */ if (!is_portrait_allowed && !is_landscape_allowed) { if (resizable) { /* All orientations are allowed */ req = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR; } else { /* Fixed window and nothing specified. Get orientation from w/h of created window */ req = (w > h ? ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } } else { /* At least one orientation is allowed */ if (resizable) { if (is_portrait_allowed && is_landscape_allowed) { /* hint allows both landscape and portrait, promote to full sensor */ req = ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR; } else { /* Use the only one allowed "orientation" */ req = (is_landscape_allowed ? orientation_landscape : orientation_portrait); } } else { /* Fixed window and both orientations are allowed. Choose one. */ if (is_portrait_allowed && is_landscape_allowed) { req = (w > h ? orientation_landscape : orientation_portrait); } else { /* Use the only one allowed "orientation" */ req = (is_landscape_allowed ? orientation_landscape : orientation_portrait); } } } Log.v("SDL", "setOrientation() requestedOrientation=" + req + " width=" + w +" height="+ h +" resizable=" + resizable + " hint=" + hint); mSingleton.setRequestedOrientation(req); } /** * This method is called by SDL using JNI. */ public static void minimizeWindow() { if (mSingleton == null) { return; } Intent startMain = new Intent(Intent.ACTION_MAIN); startMain.addCategory(Intent.CATEGORY_HOME); startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mSingleton.startActivity(startMain); } /** * This method is called by SDL using JNI. */ public static boolean shouldMinimizeOnFocusLoss() { /* if (Build.VERSION.SDK_INT >= 24) { if (mSingleton == null) { return true; } if (mSingleton.isInMultiWindowMode()) { return false; } if (mSingleton.isInPictureInPictureMode()) { return false; } } return true; */ return false; } /** * This method is called by SDL using JNI. */ public static boolean isScreenKeyboardShown() { if (mTextEdit == null) { return false; } if (!mScreenKeyboardShown) { return false; } InputMethodManager imm = (InputMethodManager) SDL.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); return imm.isAcceptingText(); } /** * This method is called by SDL using JNI. */ public static boolean supportsRelativeMouse() { // ChromeOS doesn't provide relative mouse motion via the Android 7 APIs if (isChromebook()) { return false; } // DeX mode in Samsung Experience 9.0 and earlier doesn't support relative mice properly under // Android 7 APIs, and simply returns no data under Android 8 APIs. // // This is fixed in Samsung Experience 9.5, which corresponds to Android 8.1.0, and // thus SDK version 27. If we are in DeX mode and not API 27 or higher, as a result, // we should stick to relative mode. // if ((Build.VERSION.SDK_INT < 27) && isDeXMode()) { return false; } return SDLActivity.getMotionListener().supportsRelativeMouse(); } /** * This method is called by SDL using JNI. */ public static boolean setRelativeMouseEnabled(boolean enabled) { if (enabled && !supportsRelativeMouse()) { return false; } return SDLActivity.getMotionListener().setRelativeMouseEnabled(enabled); } /** * This method is called by SDL using JNI. */ public static boolean sendMessage(int command, int param) { if (mSingleton == null) { return false; } return mSingleton.sendCommand(command, Integer.valueOf(param)); } /** * This method is called by SDL using JNI. */ public static Context getContext() { return SDL.getContext(); } /** * This method is called by SDL using JNI. */ public static boolean isAndroidTV() { UiModeManager uiModeManager = (UiModeManager) getContext().getSystemService(UI_MODE_SERVICE); if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) { return true; } if (Build.MANUFACTURER.equals("MINIX") && Build.MODEL.equals("NEO-U1")) { return true; } if (Build.MANUFACTURER.equals("Amlogic") && Build.MODEL.equals("X96-W")) { return true; } if (Build.MANUFACTURER.equals("Amlogic") && Build.MODEL.startsWith("TV")) { return true; } return false; } /** * This method is called by SDL using JNI. */ public static boolean isTablet() { DisplayMetrics metrics = new DisplayMetrics(); Activity activity = (Activity)getContext(); if (activity == null) { return false; } activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); double dWidthInches = metrics.widthPixels / (double)metrics.xdpi; double dHeightInches = metrics.heightPixels / (double)metrics.ydpi; double dDiagonal = Math.sqrt((dWidthInches * dWidthInches) + (dHeightInches * dHeightInches)); // If our diagonal size is seven inches or greater, we consider ourselves a tablet. return (dDiagonal >= 7.0); } /** * This method is called by SDL using JNI. */ public static boolean isChromebook() { if (getContext() == null) { return false; } return getContext().getPackageManager().hasSystemFeature("org.chromium.arc.device_management"); } /** * This method is called by SDL using JNI. */ public static boolean isDeXMode() { if (Build.VERSION.SDK_INT < 24) { return false; } try { final Configuration config = getContext().getResources().getConfiguration(); final Class configClass = config.getClass(); return configClass.getField("SEM_DESKTOP_MODE_ENABLED").getInt(configClass) == configClass.getField("semDesktopModeEnabled").getInt(config); } catch(Exception ignored) { return false; } } /** * This method is called by SDL using JNI. */ public static DisplayMetrics getDisplayDPI() { return getContext().getResources().getDisplayMetrics(); } /** * This method is called by SDL using JNI. */ public static boolean getManifestEnvironmentVariables() { try { ApplicationInfo applicationInfo = getContext().getPackageManager().getApplicationInfo(getContext().getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = applicationInfo.metaData; if (bundle == null) { return false; } String prefix = "SDL_ENV."; final int trimLength = prefix.length(); for (String key : bundle.keySet()) { if (key.startsWith(prefix)) { String name = key.substring(trimLength); String value = bundle.get(key).toString(); nativeSetenv(name, value); } } /* environment variables set! */ return true; } catch (Exception e) { Log.v("SDL", "exception " + e.toString()); } return false; } // This method is called by SDLControllerManager's API 26 Generic Motion Handler. public static View getContentView() { return mSingleton.mLayout; } static class ShowTextInputTask implements Runnable { /* * This is used to regulate the pan&scan method to have some offset from * the bottom edge of the input region and the top edge of an input * method (soft keyboard) */ static final int HEIGHT_PADDING = 15; public int x, y, w, h; public ShowTextInputTask(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; /* Minimum size of 1 pixel, so it takes focus. */ if (this.w <= 0) { this.w = 1; } if (this.h + HEIGHT_PADDING <= 0) { this.h = 1 - HEIGHT_PADDING; } } @Override public void run() { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h + HEIGHT_PADDING); params.leftMargin = x; params.topMargin = y; if (mTextEdit == null) { mTextEdit = new DummyEdit(SDL.getContext()); mLayout.addView(mTextEdit, params); } else { mTextEdit.setLayoutParams(params); } mTextEdit.setVisibility(View.VISIBLE); mTextEdit.requestFocus(); InputMethodManager imm = (InputMethodManager) SDL.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mTextEdit, 0); mScreenKeyboardShown = true; } } /** * This method is called by SDL using JNI. */ public static boolean showTextInput(int x, int y, int w, int h) { // Transfer the task to the main thread as a Runnable return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h)); } public static boolean isTextInputEvent(KeyEvent event) { // Key pressed with Ctrl should be sent as SDL_KEYDOWN/SDL_KEYUP and not SDL_TEXTINPUT if (event.isCtrlPressed()) { return false; } return event.isPrintingKey() || event.getKeyCode() == KeyEvent.KEYCODE_SPACE; } /** * This method is called by SDL using JNI. */ public static Surface getNativeSurface() { if (SDLActivity.mSurface == null) { return null; } return SDLActivity.mSurface.getNativeSurface(); } /** * This method is called by SDL using JNI. */ public static void setSurfaceViewFormat(int format) { mSingleton.sendCommand(COMMAND_CHANGE_SURFACEVIEW_FORMAT, format); return; } // Input /** * This method is called by SDL using JNI. */ public static void initTouch() { int[] ids = InputDevice.getDeviceIds(); for (int i = 0; i < ids.length; ++i) { InputDevice device = InputDevice.getDevice(ids[i]); if (device != null && (device.getSources() & InputDevice.SOURCE_TOUCHSCREEN) != 0) { nativeAddTouch(device.getId(), device.getName()); } } } // APK expansion files support /** com.android.vending.expansion.zipfile.ZipResourceFile object or null. */ private static Object expansionFile; /** com.android.vending.expansion.zipfile.ZipResourceFile's getInputStream() or null. */ private static Method expansionFileMethod; /** * This method is called by SDL using JNI. * @return an InputStream on success or null if no expansion file was used. * @throws IOException on errors. Message is set for the SDL error message. */ public static InputStream openAPKExpansionInputStream(String fileName) throws IOException { // Get a ZipResourceFile representing a merger of both the main and patch files if (expansionFile == null) { String mainHint = nativeGetHint("SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"); if (mainHint == null) { return null; // no expansion use if no main version was set } String patchHint = nativeGetHint("SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"); if (patchHint == null) { return null; // no expansion use if no patch version was set } Integer mainVersion; Integer patchVersion; try { mainVersion = Integer.valueOf(mainHint); patchVersion = Integer.valueOf(patchHint); } catch (NumberFormatException ex) { ex.printStackTrace(); throw new IOException("No valid file versions set for APK expansion files", ex); } try { // To avoid direct dependency on Google APK expansion library that is // not a part of Android SDK we access it using reflection expansionFile = Class.forName("com.android.vending.expansion.zipfile.APKExpansionSupport") .getMethod("getAPKExpansionZipFile", Context.class, int.class, int.class) .invoke(null, SDL.getContext(), mainVersion, patchVersion); expansionFileMethod = expansionFile.getClass() .getMethod("getInputStream", String.class); } catch (Exception ex) { ex.printStackTrace(); expansionFile = null; expansionFileMethod = null; throw new IOException("Could not access APK expansion support library", ex); } } // Get an input stream for a known file inside the expansion file ZIPs InputStream fileStream; try { fileStream = (InputStream)expansionFileMethod.invoke(expansionFile, fileName); } catch (Exception ex) { // calling "getInputStream" failed ex.printStackTrace(); throw new IOException("Could not open stream from APK expansion file", ex); } if (fileStream == null) { // calling "getInputStream" was successful but null was returned throw new IOException("Could not find path in APK expansion file"); } return fileStream; } // Messagebox /** Result of current messagebox. Also used for blocking the calling thread. */ protected final int[] messageboxSelection = new int[1]; /** Id of current dialog. */ protected int dialogs = 0; /** * This method is called by SDL using JNI. * Shows the messagebox from UI thread and block calling thread. * buttonFlags, buttonIds and buttonTexts must have same length. * @param buttonFlags array containing flags for every button. * @param buttonIds array containing id for every button. * @param buttonTexts array containing text for every button. * @param colors null for default or array of length 5 containing colors. * @return button id or -1. */ public int messageboxShowMessageBox( final int flags, final String title, final String message, final int[] buttonFlags, final int[] buttonIds, final String[] buttonTexts, final int[] colors) { messageboxSelection[0] = -1; // sanity checks if ((buttonFlags.length != buttonIds.length) && (buttonIds.length != buttonTexts.length)) { return -1; // implementation broken } // collect arguments for Dialog final Bundle args = new Bundle(); args.putInt("flags", flags); args.putString("title", title); args.putString("message", message); args.putIntArray("buttonFlags", buttonFlags); args.putIntArray("buttonIds", buttonIds); args.putStringArray("buttonTexts", buttonTexts); args.putIntArray("colors", colors); // trigger Dialog creation on UI thread runOnUiThread(new Runnable() { @Override public void run() { showDialog(dialogs++, args); } }); // block the calling thread synchronized (messageboxSelection) { try { messageboxSelection.wait(); } catch (InterruptedException ex) { ex.printStackTrace(); return -1; } } // return selected value return messageboxSelection[0]; } @Override protected Dialog onCreateDialog(int ignore, Bundle args) { // TODO set values from "flags" to messagebox dialog // get colors int[] colors = args.getIntArray("colors"); int backgroundColor; int textColor; int buttonBorderColor; int buttonBackgroundColor; int buttonSelectedColor; if (colors != null) { int i = -1; backgroundColor = colors[++i]; textColor = colors[++i]; buttonBorderColor = colors[++i]; buttonBackgroundColor = colors[++i]; buttonSelectedColor = colors[++i]; } else { backgroundColor = Color.TRANSPARENT; textColor = Color.TRANSPARENT; buttonBorderColor = Color.TRANSPARENT; buttonBackgroundColor = Color.TRANSPARENT; buttonSelectedColor = Color.TRANSPARENT; } // create dialog with title and a listener to wake up calling thread final Dialog dialog = new Dialog(this); dialog.setTitle(args.getString("title")); dialog.setCancelable(false); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface unused) { synchronized (messageboxSelection) { messageboxSelection.notify(); } } }); // create text TextView message = new TextView(this); message.setGravity(Gravity.CENTER); message.setText(args.getString("message")); if (textColor != Color.TRANSPARENT) { message.setTextColor(textColor); } // create buttons int[] buttonFlags = args.getIntArray("buttonFlags"); int[] buttonIds = args.getIntArray("buttonIds"); String[] buttonTexts = args.getStringArray("buttonTexts"); final SparseArray<Button> mapping = new SparseArray<Button>(); LinearLayout buttons = new LinearLayout(this); buttons.setOrientation(LinearLayout.HORIZONTAL); buttons.setGravity(Gravity.CENTER); for (int i = 0; i < buttonTexts.length; ++i) { Button button = new Button(this); final int id = buttonIds[i]; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { messageboxSelection[0] = id; dialog.dismiss(); } }); if (buttonFlags[i] != 0) { // see SDL_messagebox.h if ((buttonFlags[i] & 0x00000001) != 0) { mapping.put(KeyEvent.KEYCODE_ENTER, button); } if ((buttonFlags[i] & 0x00000002) != 0) { mapping.put(KeyEvent.KEYCODE_ESCAPE, button); /* API 11 */ } } button.setText(buttonTexts[i]); if (textColor != Color.TRANSPARENT) { button.setTextColor(textColor); } if (buttonBorderColor != Color.TRANSPARENT) { // TODO set color for border of messagebox button } if (buttonBackgroundColor != Color.TRANSPARENT) { Drawable drawable = button.getBackground(); if (drawable == null) { // setting the color this way removes the style button.setBackgroundColor(buttonBackgroundColor); } else { // setting the color this way keeps the style (gradient, padding, etc.) drawable.setColorFilter(buttonBackgroundColor, PorterDuff.Mode.MULTIPLY); } } if (buttonSelectedColor != Color.TRANSPARENT) { // TODO set color for selected messagebox button } buttons.addView(button); } // create content LinearLayout content = new LinearLayout(this); content.setOrientation(LinearLayout.VERTICAL); content.addView(message); content.addView(buttons); if (backgroundColor != Color.TRANSPARENT) { content.setBackgroundColor(backgroundColor); } // add content to dialog and return dialog.setContentView(content); dialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) { Button button = mapping.get(keyCode); if (button != null) { if (event.getAction() == KeyEvent.ACTION_UP) { button.performClick(); } return true; // also for ignored actions } return false; } }); return dialog; } private final Runnable rehideSystemUi = new Runnable() { @Override public void run() { int flags = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.INVISIBLE; SDLActivity.this.getWindow().getDecorView().setSystemUiVisibility(flags); } }; public void onSystemUiVisibilityChange(int visibility) { if (SDLActivity.mFullscreenModeActive && ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0 || (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0)) { Handler handler = getWindow().getDecorView().getHandler(); if (handler != null) { handler.removeCallbacks(rehideSystemUi); // Prevent a hide loop. handler.postDelayed(rehideSystemUi, 2000); } } } /** * This method is called by SDL using JNI. */ public static boolean clipboardHasText() { return mClipboardHandler.clipboardHasText(); } /** * This method is called by SDL using JNI. */ public static String clipboardGetText() { return mClipboardHandler.clipboardGetText(); } /** * This method is called by SDL using JNI. */ public static void clipboardSetText(String string) { mClipboardHandler.clipboardSetText(string); } /** * This method is called by SDL using JNI. */ public static int createCustomCursor(int[] colors, int width, int height, int hotSpotX, int hotSpotY) { Bitmap bitmap = Bitmap.createBitmap(colors, width, height, Bitmap.Config.ARGB_8888); ++mLastCursorID; if (Build.VERSION.SDK_INT >= 24) { try { mCursors.put(mLastCursorID, PointerIcon.create(bitmap, hotSpotX, hotSpotY)); } catch (Exception e) { return 0; } } else { return 0; } return mLastCursorID; } /** * This method is called by SDL using JNI. */ public static boolean setCustomCursor(int cursorID) { if (Build.VERSION.SDK_INT >= 24) { try { mSurface.setPointerIcon(mCursors.get(cursorID)); } catch (Exception e) { return false; } } else { return false; } return true; } /** * This method is called by SDL using JNI. */ public static boolean setSystemCursor(int cursorID) { int cursor_type = 0; //PointerIcon.TYPE_NULL; switch (cursorID) { case SDL_SYSTEM_CURSOR_ARROW: cursor_type = 1000; //PointerIcon.TYPE_ARROW; break; case SDL_SYSTEM_CURSOR_IBEAM: cursor_type = 1008; //PointerIcon.TYPE_TEXT; break; case SDL_SYSTEM_CURSOR_WAIT: cursor_type = 1004; //PointerIcon.TYPE_WAIT; break; case SDL_SYSTEM_CURSOR_CROSSHAIR: cursor_type = 1007; //PointerIcon.TYPE_CROSSHAIR; break; case SDL_SYSTEM_CURSOR_WAITARROW: cursor_type = 1004; //PointerIcon.TYPE_WAIT; break; case SDL_SYSTEM_CURSOR_SIZENWSE: cursor_type = 1017; //PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW; break; case SDL_SYSTEM_CURSOR_SIZENESW: cursor_type = 1016; //PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW; break; case SDL_SYSTEM_CURSOR_SIZEWE: cursor_type = 1014; //PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW; break; case SDL_SYSTEM_CURSOR_SIZENS: cursor_type = 1015; //PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW; break; case SDL_SYSTEM_CURSOR_SIZEALL: cursor_type = 1020; //PointerIcon.TYPE_GRAB; break; case SDL_SYSTEM_CURSOR_NO: cursor_type = 1012; //PointerIcon.TYPE_NO_DROP; break; case SDL_SYSTEM_CURSOR_HAND: cursor_type = 1002; //PointerIcon.TYPE_HAND; break; } if (Build.VERSION.SDK_INT >= 24) { try { mSurface.setPointerIcon(PointerIcon.getSystemIcon(SDL.getContext(), cursor_type)); } catch (Exception e) { return false; } } return true; } /** * This method is called by SDL using JNI. */ public static void requestPermission(String permission, int requestCode) { if (Build.VERSION.SDK_INT < 23) { nativePermissionResult(requestCode, true); return; } Activity activity = (Activity)getContext(); if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { activity.requestPermissions(new String[]{permission}, requestCode); } else { nativePermissionResult(requestCode, true); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { nativePermissionResult(requestCode, true); } else { nativePermissionResult(requestCode, false); } } } /** Simple runnable to start the SDL application */ class SDLMain implements Runnable { @Override public void run() { // Runs SDL_main() String library = SDLActivity.mSingleton.getMainSharedObject(); String function = SDLActivity.mSingleton.getMainFunction(); String[] arguments = SDLActivity.mSingleton.getArguments(); try { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_DISPLAY); } catch (Exception e) { Log.v("SDL", "modify thread properties failed " + e.toString()); } Log.v("SDL", "Running main function " + function + " from library " + library); SDLActivity.nativeRunMain(library, function, arguments); Log.v("SDL", "Finished main function"); if (SDLActivity.mSingleton == null || SDLActivity.mSingleton.isFinishing()) { // Activity is already being destroyed } else { // Let's finish the Activity SDLActivity.mSDLThread = null; SDLActivity.mSingleton.finish(); } } } /** SDLSurface. This is what we draw on, so we need to know when it's created in order to do anything useful. Because of this, that's where we set up the SDL thread */ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnKeyListener, View.OnTouchListener, SensorEventListener { // Sensors protected SensorManager mSensorManager; protected Display mDisplay; // Keep track of the surface size to normalize touch events protected float mWidth, mHeight; // Is SurfaceView ready for rendering public boolean mIsSurfaceReady; // Startup public SDLSurface(Context context) { super(context); getHolder().addCallback(this); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); setOnKeyListener(this); setOnTouchListener(this); mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE); setOnGenericMotionListener(SDLActivity.getMotionListener()); // Some arbitrary defaults to avoid a potential division by zero mWidth = 1.0f; mHeight = 1.0f; mIsSurfaceReady = false; } public void handlePause() { enableSensor(Sensor.TYPE_ACCELEROMETER, false); } public void handleResume() { setFocusable(true); setFocusableInTouchMode(true); requestFocus(); setOnKeyListener(this); setOnTouchListener(this); enableSensor(Sensor.TYPE_ACCELEROMETER, true); } public Surface getNativeSurface() { return getHolder().getSurface(); } // Called when we have a valid drawing surface @Override public void surfaceCreated(SurfaceHolder holder) { Log.v("SDL", "surfaceCreated()"); SDLActivity.onNativeSurfaceCreated(); } // Called when we lose the surface @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.v("SDL", "surfaceDestroyed()"); // Transition to pause, if needed SDLActivity.mNextNativeState = SDLActivity.NativeState.PAUSED; SDLActivity.handleNativeState(); mIsSurfaceReady = false; SDLActivity.onNativeSurfaceDestroyed(); } // Called when the surface is resized @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.v("SDL", "surfaceChanged()"); if (SDLActivity.mSingleton == null) { return; } int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default switch (format) { case PixelFormat.RGBA_8888: Log.v("SDL", "pixel format RGBA_8888"); sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888 break; case PixelFormat.RGBX_8888: Log.v("SDL", "pixel format RGBX_8888"); sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888 break; case PixelFormat.RGB_565: Log.v("SDL", "pixel format RGB_565"); sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 break; case PixelFormat.RGB_888: Log.v("SDL", "pixel format RGB_888"); // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888 break; default: Log.v("SDL", "pixel format unknown " + format); break; } mWidth = width; mHeight = height; int nDeviceWidth = width; int nDeviceHeight = height; try { if (Build.VERSION.SDK_INT >= 17) { android.util.DisplayMetrics realMetrics = new android.util.DisplayMetrics(); mDisplay.getRealMetrics( realMetrics ); nDeviceWidth = realMetrics.widthPixels; nDeviceHeight = realMetrics.heightPixels; } } catch ( java.lang.Throwable throwable ) {} synchronized(SDLActivity.getContext()) { // In case we're waiting on a size change after going fullscreen, send a notification. SDLActivity.getContext().notifyAll(); } Log.v("SDL", "Window size: " + width + "x" + height); Log.v("SDL", "Device size: " + nDeviceWidth + "x" + nDeviceHeight); SDLActivity.nativeSetScreenResolution(width, height, nDeviceWidth, nDeviceHeight, sdlFormat, mDisplay.getRefreshRate()); SDLActivity.onNativeResize(); // Prevent a screen distortion glitch, // for instance when the device is in Landscape and a Portrait App is resumed. boolean skip = false; int requestedOrientation = SDLActivity.mSingleton.getRequestedOrientation(); if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) { // Accept any } else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT) { if (mWidth > mHeight) { skip = true; } } else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) { if (mWidth < mHeight) { skip = true; } } // Special Patch for Square Resolution: Black Berry Passport if (skip) { double min = Math.min(mWidth, mHeight); double max = Math.max(mWidth, mHeight); if (max / min < 1.20) { Log.v("SDL", "Don't skip on such aspect-ratio. Could be a square resolution."); skip = false; } } // Don't skip in MultiWindow. if (skip) { if (Build.VERSION.SDK_INT >= 24) { if (SDLActivity.mSingleton.isInMultiWindowMode()) { Log.v("SDL", "Don't skip in Multi-Window"); skip = false; } } } if (skip) { Log.v("SDL", "Skip .. Surface is not ready."); mIsSurfaceReady = false; return; } /* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */ SDLActivity.onNativeSurfaceChanged(); /* Surface is ready */ mIsSurfaceReady = true; SDLActivity.mNextNativeState = SDLActivity.NativeState.RESUMED; SDLActivity.handleNativeState(); } // Key events @Override public boolean onKey(View v, int keyCode, KeyEvent event) { int deviceId = event.getDeviceId(); int source = event.getSource(); // Dispatch the different events depending on where they come from // Some SOURCE_JOYSTICK, SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD // So, we try to process them as JOYSTICK/DPAD/GAMEPAD events first, if that fails we try them as KEYBOARD // // Furthermore, it's possible a game controller has SOURCE_KEYBOARD and // SOURCE_JOYSTICK, while its key events arrive from the keyboard source // So, retrieve the device itself and check all of its sources if (SDLControllerManager.isDeviceSDLJoystick(deviceId)) { // Note that we process events with specific key codes here if (event.getAction() == KeyEvent.ACTION_DOWN) { if (SDLControllerManager.onNativePadDown(deviceId, keyCode) == 0) { return true; } } else if (event.getAction() == KeyEvent.ACTION_UP) { if (SDLControllerManager.onNativePadUp(deviceId, keyCode) == 0) { return true; } } } if (source == InputDevice.SOURCE_UNKNOWN) { InputDevice device = InputDevice.getDevice(deviceId); if (device != null) { source = device.getSources(); } } if ((source & InputDevice.SOURCE_KEYBOARD) != 0) { if (event.getAction() == KeyEvent.ACTION_DOWN) { //Log.v("SDL", "key down: " + keyCode); if (SDLActivity.isTextInputEvent(event)) { SDLInputConnection.nativeCommitText(String.valueOf((char) event.getUnicodeChar()), 1); } SDLActivity.onNativeKeyDown(keyCode); return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { //Log.v("SDL", "key up: " + keyCode); SDLActivity.onNativeKeyUp(keyCode); return true; } } if ((source & InputDevice.SOURCE_MOUSE) != 0) { // on some devices key events are sent for mouse BUTTON_BACK/FORWARD presses // they are ignored here because sending them as mouse input to SDL is messy if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_FORWARD)) { switch (event.getAction()) { case KeyEvent.ACTION_DOWN: case KeyEvent.ACTION_UP: // mark the event as handled or it will be handled by system // handling KEYCODE_BACK by system will call onBackPressed() return true; } } } return false; } // Touch events @Override public boolean onTouch(View v, MotionEvent event) { /* Ref: http://developer.android.com/training/gestures/multi.html */ final int touchDevId = event.getDeviceId(); final int pointerCount = event.getPointerCount(); int action = event.getActionMasked(); int pointerFingerId; int mouseButton; int i = -1; float x,y,p; // 12290 = Samsung DeX mode desktop mouse // 12290 = 0x3002 = 0x2002 | 0x1002 = SOURCE_MOUSE | SOURCE_TOUCHSCREEN // 0x2 = SOURCE_CLASS_POINTER if (event.getSource() == InputDevice.SOURCE_MOUSE || event.getSource() == (InputDevice.SOURCE_MOUSE | InputDevice.SOURCE_TOUCHSCREEN)) { try { mouseButton = (Integer) event.getClass().getMethod("getButtonState").invoke(event); } catch(Exception e) { mouseButton = 1; // oh well. } // We need to check if we're in relative mouse mode and get the axis offset rather than the x/y values // if we are. We'll leverage our existing mouse motion listener SDLGenericMotionListener_API12 motionListener = SDLActivity.getMotionListener(); x = motionListener.getEventX(event); y = motionListener.getEventY(event); SDLActivity.onNativeMouse(mouseButton, action, x, y, motionListener.inRelativeMode()); } else { switch(action) { case MotionEvent.ACTION_MOVE: for (i = 0; i < pointerCount; i++) { pointerFingerId = event.getPointerId(i); x = event.getX(i) / mWidth; y = event.getY(i) / mHeight; p = event.getPressure(i); if (p > 1.0f) { // may be larger than 1.0f on some devices // see the documentation of getPressure(i) p = 1.0f; } SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_DOWN: // Primary pointer up/down, the index is always zero i = 0; case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_POINTER_DOWN: // Non primary pointer up/down if (i == -1) { i = event.getActionIndex(); } pointerFingerId = event.getPointerId(i); x = event.getX(i) / mWidth; y = event.getY(i) / mHeight; p = event.getPressure(i); if (p > 1.0f) { // may be larger than 1.0f on some devices // see the documentation of getPressure(i) p = 1.0f; } SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p); break; case MotionEvent.ACTION_CANCEL: for (i = 0; i < pointerCount; i++) { pointerFingerId = event.getPointerId(i); x = event.getX(i) / mWidth; y = event.getY(i) / mHeight; p = event.getPressure(i); if (p > 1.0f) { // may be larger than 1.0f on some devices // see the documentation of getPressure(i) p = 1.0f; } SDLActivity.onNativeTouch(touchDevId, pointerFingerId, MotionEvent.ACTION_UP, x, y, p); } break; default: break; } } return true; } // Sensor events public void enableSensor(int sensortype, boolean enabled) { // TODO: This uses getDefaultSensor - what if we have >1 accels? if (enabled) { mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(sensortype), SensorManager.SENSOR_DELAY_GAME, null); } else { mSensorManager.unregisterListener(this, mSensorManager.getDefaultSensor(sensortype)); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO } @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { // Since we may have an orientation set, we won't receive onConfigurationChanged events. // We thus should check here. int newOrientation = SDLActivity.SDL_ORIENTATION_UNKNOWN; float x, y; switch (mDisplay.getRotation()) { case Surface.ROTATION_90: x = -event.values[1]; y = event.values[0]; newOrientation = SDLActivity.SDL_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_270: x = event.values[1]; y = -event.values[0]; newOrientation = SDLActivity.SDL_ORIENTATION_LANDSCAPE_FLIPPED; break; case Surface.ROTATION_180: x = -event.values[0]; y = -event.values[1]; newOrientation = SDLActivity.SDL_ORIENTATION_PORTRAIT_FLIPPED; break; default: x = event.values[0]; y = event.values[1]; newOrientation = SDLActivity.SDL_ORIENTATION_PORTRAIT; break; } if (newOrientation != SDLActivity.mCurrentOrientation) { SDLActivity.mCurrentOrientation = newOrientation; SDLActivity.onNativeOrientationChanged(newOrientation); } SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH, y / SensorManager.GRAVITY_EARTH, event.values[2] / SensorManager.GRAVITY_EARTH); } } // Captured pointer events for API 26. public boolean onCapturedPointerEvent(MotionEvent event) { int action = event.getActionMasked(); float x, y; switch (action) { case MotionEvent.ACTION_SCROLL: x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0); y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0); SDLActivity.onNativeMouse(0, action, x, y, false); return true; case MotionEvent.ACTION_HOVER_MOVE: case MotionEvent.ACTION_MOVE: x = event.getX(0); y = event.getY(0); SDLActivity.onNativeMouse(0, action, x, y, true); return true; case MotionEvent.ACTION_BUTTON_PRESS: case MotionEvent.ACTION_BUTTON_RELEASE: // Change our action value to what SDL's code expects. if (action == MotionEvent.ACTION_BUTTON_PRESS) { action = MotionEvent.ACTION_DOWN; } else if (action == MotionEvent.ACTION_BUTTON_RELEASE) { action = MotionEvent.ACTION_UP; } x = event.getX(0); y = event.getY(0); int button = event.getButtonState(); SDLActivity.onNativeMouse(button, action, x, y, true); return true; } return false; } } /* This is a fake invisible editor view that receives the input and defines the * pan&scan region */ class DummyEdit extends View implements View.OnKeyListener { InputConnection ic; public DummyEdit(Context context) { super(context); setFocusableInTouchMode(true); setFocusable(true); setOnKeyListener(this); } @Override public boolean onCheckIsTextEditor() { return true; } @Override public boolean onKey(View v, int keyCode, KeyEvent event) { /* * This handles the hardware keyboard input */ if (event.getAction() == KeyEvent.ACTION_DOWN) { if (SDLActivity.isTextInputEvent(event)) { ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1); return true; } SDLActivity.onNativeKeyDown(keyCode); return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { SDLActivity.onNativeKeyUp(keyCode); return true; } return false; } // @Override public boolean onKeyPreIme (int keyCode, KeyEvent event) { // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639 // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not // FIXME: A more effective solution would be to assume our Layout to be RelativeLayout or LinearLayout // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :) if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) { SDLActivity.onNativeKeyboardFocusLost(); } } return super.onKeyPreIme(keyCode, event); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { ic = new SDLInputConnection(this, true); outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD; outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI | EditorInfo.IME_FLAG_NO_FULLSCREEN /* API 11 */; return ic; } } class SDLInputConnection extends BaseInputConnection { public SDLInputConnection(View targetView, boolean fullEditor) { super(targetView, fullEditor); } @Override public boolean sendKeyEvent(KeyEvent event) { /* * This used to handle the keycodes from soft keyboard (and IME-translated input from hardkeyboard) * However, as of Ice Cream Sandwich and later, almost all soft keyboard doesn't generate key presses * and so we need to generate them ourselves in commitText. To avoid duplicates on the handful of keys * that still do, we empty this out. */ /* * Return DOES still generate a key event, however. So rather than using it as the 'click a button' key * as we do with physical keyboards, let's just use it to hide the keyboard. */ if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { if (SDLActivity.onNativeSoftReturnKey()) { return true; } } return super.sendKeyEvent(event); } @Override public boolean commitText(CharSequence text, int newCursorPosition) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (c == '\n') { if (SDLActivity.onNativeSoftReturnKey()) { return true; } } nativeGenerateScancodeForUnichar(c); } SDLInputConnection.nativeCommitText(text.toString(), newCursorPosition); return super.commitText(text, newCursorPosition); } @Override public boolean setComposingText(CharSequence text, int newCursorPosition) { nativeSetComposingText(text.toString(), newCursorPosition); return super.setComposingText(text, newCursorPosition); } public static native void nativeCommitText(String text, int newCursorPosition); public native void nativeGenerateScancodeForUnichar(char c); public native void nativeSetComposingText(String text, int newCursorPosition); @Override public boolean deleteSurroundingText(int beforeLength, int afterLength) { // Workaround to capture backspace key. Ref: http://stackoverflow.com/questions/14560344/android-backspace-in-webview-baseinputconnection // and https://bugzilla.libsdl.org/show_bug.cgi?id=2265 if (beforeLength > 0 && afterLength == 0) { boolean ret = true; // backspace(s) while (beforeLength-- > 0) { boolean ret_key = sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL)); ret = ret && ret_key; } return ret; } return super.deleteSurroundingText(beforeLength, afterLength); } } interface SDLClipboardHandler { public boolean clipboardHasText(); public String clipboardGetText(); public void clipboardSetText(String string); } class SDLClipboardHandler_API11 implements SDLClipboardHandler, android.content.ClipboardManager.OnPrimaryClipChangedListener { protected android.content.ClipboardManager mClipMgr; SDLClipboardHandler_API11() { mClipMgr = (android.content.ClipboardManager) SDL.getContext().getSystemService(Context.CLIPBOARD_SERVICE); mClipMgr.addPrimaryClipChangedListener(this); } @Override public boolean clipboardHasText() { return mClipMgr.hasText(); } @Override public String clipboardGetText() { CharSequence text; text = mClipMgr.getText(); if (text != null) { return text.toString(); } return null; } @Override public void clipboardSetText(String string) { mClipMgr.removePrimaryClipChangedListener(this); mClipMgr.setText(string); mClipMgr.addPrimaryClipChangedListener(this); } @Override public void onPrimaryClipChanged() { SDLActivity.onNativeClipboardChanged(); } }
gpl-2.0
freenet/fred
src/freenet/node/NewPacketFormatKeyContext.java
9909
package freenet.node; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; import freenet.io.xfer.PacketThrottle; import freenet.node.NewPacketFormat.SentPacket; import freenet.support.LogThresholdCallback; import freenet.support.Logger; import freenet.support.SentTimeCache; import freenet.support.Logger.LogLevel; /** NewPacketFormat's context for each SessionKey. Specifically, packet numbers are unique * to a SessionKey, because the packet number is used in encrypting the packet. Hence this * class has everything to do with packet numbers - which to use next, which we've sent * packets on and are waiting for acks, which we've received and should ack etc. * @author toad */ public class NewPacketFormatKeyContext { public int firstSeqNumUsed = -1; public int nextSeqNum; public int highestReceivedSeqNum; public byte[][] seqNumWatchList = null; /** Index of the packet with the lowest sequence number */ public int watchListPointer = 0; public int watchListOffset = 0; private final TreeMap<Integer, Long> acks = new TreeMap<Integer, Long>(); private final HashMap<Integer, SentPacket> sentPackets = new HashMap<Integer, SentPacket>(); /** Keep this many sent times for lost packets, so we can compute an accurate round trip time if * they are acked after we had decided they were lost. */ private static final int MAX_LOST_SENT_TIMES = 128; /** We add all lost packets sequence numbers and the corresponding sent time to this cache. */ private final SentTimeCache lostSentTimes = new SentTimeCache(MAX_LOST_SENT_TIMES); private final Object sequenceNumberLock = new Object(); private static final int REKEY_THRESHOLD = 100; /** All acks must be sent within 200ms */ static final int MAX_ACK_DELAY = 200; /** Minimum RTT for purposes of calculating whether to retransmit. * Must be greater than MAX_ACK_DELAY */ private static final int MIN_RTT_FOR_RETRANSMIT = 250; private int maxSeenInFlight; private static volatile boolean logMINOR; private static volatile boolean logDEBUG; static { Logger.registerLogThresholdCallback(new LogThresholdCallback(){ @Override public void shouldUpdate(){ logMINOR = Logger.shouldLog(LogLevel.MINOR, this); logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this); } }); } NewPacketFormatKeyContext(int ourFirstSeqNum, int theirFirstSeqNum) { ourFirstSeqNum &= 0x7FFFFFFF; theirFirstSeqNum &= 0x7FFFFFFF; this.nextSeqNum = ourFirstSeqNum; this.watchListOffset = theirFirstSeqNum; this.highestReceivedSeqNum = theirFirstSeqNum - 1; if(this.highestReceivedSeqNum == -1) this.highestReceivedSeqNum = Integer.MAX_VALUE; } boolean canAllocateSeqNum() { synchronized(sequenceNumberLock) { return nextSeqNum != firstSeqNumUsed; } } int allocateSequenceNumber(BasePeerNode pn) { synchronized(sequenceNumberLock) { if(firstSeqNumUsed == -1) { firstSeqNumUsed = nextSeqNum; if(logMINOR) Logger.minor(this, "First seqnum used for " + this + " is " + firstSeqNumUsed); } else { if(nextSeqNum == firstSeqNumUsed) { Logger.error(this, "Blocked because we haven't rekeyed yet"); pn.startRekeying(); return -1; } if(firstSeqNumUsed > nextSeqNum) { if(firstSeqNumUsed - nextSeqNum < REKEY_THRESHOLD) pn.startRekeying(); } else { if((NewPacketFormat.NUM_SEQNUMS - nextSeqNum) + firstSeqNumUsed < REKEY_THRESHOLD) pn.startRekeying(); } } int seqNum = nextSeqNum++; if(nextSeqNum < 0) { nextSeqNum = 0; } return seqNum; } } /** One of our outgoing packets has been acknowledged. */ public void ack(int ack, BasePeerNode pn, SessionKey key) { long rtt; int maxSize; boolean validAck = false; long ackReceived = System.currentTimeMillis(); if(logDEBUG) Logger.debug(this, "Acknowledging packet "+ack+" from "+pn); SentPacket sent; synchronized(sentPackets) { sent = sentPackets.remove(ack); maxSize = (maxSeenInFlight * 2) + 10; } if(sent != null) { rtt = sent.acked(key); validAck = true; } else { if(logDEBUG) Logger.debug(this, "Already acked or lost "+ack); long packetSent = lostSentTimes.queryAndRemove(ack); if(packetSent < 0) { if(logDEBUG) Logger.debug(this, "No time for "+ack+" - maybe acked twice?"); return; } rtt = ackReceived - packetSent; } if(pn == null) return; int rt = (int) Math.min(rtt, Integer.MAX_VALUE); pn.reportPing(rt); if(validAck) pn.receivedAck(ackReceived); PacketThrottle throttle = pn.getThrottle(); if(throttle == null) return; throttle.setRoundTripTime(rt); if(validAck) throttle.notifyOfPacketAcknowledged(maxSize); } /** Queue an ack. * @return -1 If the ack was already queued, or the total number queued. */ public int queueAck(int seqno) { synchronized(acks) { if(!acks.containsKey(seqno)) { acks.put(seqno, System.currentTimeMillis()); return acks.size(); } else return -1; } } public void sent(int sequenceNumber, int length) { synchronized(sentPackets) { SentPacket sentPacket = sentPackets.get(sequenceNumber); if(sentPacket != null) sentPacket.sent(length); } } class AddedAcks { /** Are there any urgent acks? */ final boolean anyUrgentAcks; private final HashMap<Integer, Long> moved; public AddedAcks(boolean mustSend, HashMap<Integer, Long> moved) { this.anyUrgentAcks = mustSend; this.moved = moved; } public void abort() { synchronized(acks) { acks.putAll(moved); } } } /** Add as many acks as possible to the packet. * @return True if there are any old acks i.e. acks that will force us to send a packet * even if there isn't anything else in it. */ public AddedAcks addAcks(NPFPacket packet, int maxPacketSize, long now) { boolean mustSend = false; HashMap<Integer, Long> moved = null; int numAcks = 0; synchronized(acks) { Iterator<Map.Entry<Integer, Long>> it = acks.entrySet().iterator(); while (it.hasNext() && packet.getLength() < maxPacketSize) { Map.Entry<Integer, Long> entry = it.next(); int ack = entry.getKey(); // All acks must be sent within 200ms. if(logDEBUG) Logger.debug(this, "Trying to ack "+ack); if(!packet.addAck(ack, maxPacketSize)) { if(logDEBUG) Logger.debug(this, "Can't add ack "+ack); break; } if(entry.getValue() + MAX_ACK_DELAY < now) mustSend = true; if(moved == null) { // FIXME some more memory efficient representation, since this will normally be very small? moved = new HashMap<Integer, Long>(); } moved.put(ack, entry.getValue()); ++numAcks; it.remove(); } } if(numAcks == 0) return null; return new AddedAcks(mustSend, moved); } public int countSentPackets() { synchronized(sentPackets) { return sentPackets.size(); } } public void sent(SentPacket sentPacket, int seqNum, int length) { sentPacket.sent(length); synchronized(sentPackets) { sentPackets.put(seqNum, sentPacket); int inFlight = sentPackets.size(); if(inFlight > maxSeenInFlight) { maxSeenInFlight = inFlight; if (logDEBUG) { Logger.debug(this, "Max seen in flight new record: " + maxSeenInFlight + " for " + this); } } } } public long timeCheckForLostPackets(double averageRTT) { long timeCheck = Long.MAX_VALUE; // Because MIN_RTT_FOR_RETRANSMIT > MAX_ACK_DELAY, and because averageRTT() includes the // actual ack delay, we don't need to add it on here. double avgRtt = Math.max(MIN_RTT_FOR_RETRANSMIT, averageRTT); long maxDelay = (long)(avgRtt + MAX_ACK_DELAY * 1.1); synchronized(sentPackets) { for (SentPacket s : sentPackets.values()) { long t = s.getSentTime() + maxDelay; if (t < timeCheck) { timeCheck = t; } } } return timeCheck; } public void checkForLostPackets(double averageRTT, long curTime, BasePeerNode pn) { //Mark packets as lost int bigLostCount = 0; int count = 0; // Because MIN_RTT_FOR_RETRANSMIT > MAX_ACK_DELAY, and because averageRTT() includes the // actual ack delay, we don't need to add it on here. double avgRtt = Math.max(MIN_RTT_FOR_RETRANSMIT, averageRTT); long maxDelay = (long)(avgRtt + MAX_ACK_DELAY * 1.1); long threshold = curTime - maxDelay; synchronized(sentPackets) { Iterator<Map.Entry<Integer, SentPacket>> it = sentPackets.entrySet().iterator(); while(it.hasNext()) { Map.Entry<Integer, SentPacket> e = it.next(); SentPacket s = e.getValue(); if (s.getSentTime() < threshold) { if (logMINOR) { Logger.minor(this, "Assuming packet " + e.getKey() + " has been lost. " + "Delay " + (curTime - s.getSentTime()) + "ms, " + "threshold " + threshold + "ms"); } // Store the packet sentTime in our lost sent times cache, so we can calculate // RTT if an ack may surface later on. if(!s.messages.isEmpty()) { lostSentTimes.report(e.getKey(), s.getSentTime()); } // Mark the packet as lost and remove it from our active packets. s.lost(); it.remove(); bigLostCount++; } else { count++; } } } if(count > 0 && logMINOR) Logger.minor(this, "" + count + " packets in flight with threshold " + maxDelay + "ms"); if(bigLostCount != 0 && pn != null) { PacketThrottle throttle = pn.getThrottle(); if(throttle != null) { throttle.notifyOfPacketsLost(bigLostCount); } pn.backoffOnResend(); } } public long timeCheckForAcks() { long ret = Long.MAX_VALUE; synchronized(acks) { for(Long l : acks.values()) { long timeout = l + MAX_ACK_DELAY; if(ret > timeout) ret = timeout; } } return ret; } public void disconnected() { synchronized(sentPackets) { for (SentPacket s: sentPackets.values()) { s.lost(); } sentPackets.clear(); } } }
gpl-2.0
robertoandrade/cyclos
src/nl/strohalm/cyclos/webservices/PrincipalParameters.java
1728
/* This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos 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. Cyclos 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 Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.webservices; import java.io.Serializable; /** * Parameters used to search for a member by one of it's principals * * @author luis */ public class PrincipalParameters implements Serializable { private static final long serialVersionUID = 7870025837827799653L; private String principalType; private String principal; public String getPrincipal() { return principal; } public String getPrincipalType() { return principalType; } public void setPrincipal(final String principal) { this.principal = principal; } public void setPrincipalType(final String principalType) { this.principalType = principalType; } @Override public String toString() { return "PrincipalParameters [principal=" + principal + ", principalType=" + principalType + "]"; } }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jdi/ObjectReference/invokeMethod/invokemethod007/TestDescription.java
2369
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * @test * * @summary converted from VM Testbase nsk/jdi/ObjectReference/invokeMethod/invokemethod007. * VM Testbase keywords: [quick, jpda, jdi] * VM Testbase readme: * DESCRIPTION * This test checks that the JDI method * com.sun.jdi.ObjectReference.invokeMethod() properly throws * InvalidTypeException when a debugger part of the test * invokes several debuggee methods with different kinds of * arguments which are not assignment compatible with the argument * type and not convertible without loss of information as well. * COMMENTS * * @library /vmTestbase * /test/lib * @run driver jdk.test.lib.FileInstaller . . * @build nsk.jdi.ObjectReference.invokeMethod.invokemethod007 * nsk.jdi.ObjectReference.invokeMethod.invokemethod007t * * @comment make sure invokemethod007t is compiled with full debug info * @clean nsk.jdi.ObjectReference.invokeMethod.invokemethod007t * @compile -g:lines,source,vars ../invokemethod007t.java * * @run main/othervm PropertyResolvingWrapper * nsk.jdi.ObjectReference.invokeMethod.invokemethod007 * -verbose * -arch=${os.family}-${os.simpleArch} * -waittime=5 * -debugee.vmkind=java * -transport.address=dynamic * "-debugee.vmkeys=${test.vm.opts} ${test.java.opts}" */
gpl-2.0
xucp/mpc_hc
src/thirdparty/LAVFilters/src/libbluray/src/libbluray/bdj/java/org/bluray/ui/event/HRcEvent.java
1437
/* * This file is part of libbluray * Copyright (C) 2010 William Hahne * * 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, see * <http://www.gnu.org/licenses/>. */ package org.bluray.ui.event; import java.awt.Component; public abstract class HRcEvent extends org.havi.ui.event.HRcEvent { public HRcEvent(Component source, int id, long when, int modifiers, int keyCode, char keyChar) { super(source, id, when, modifiers, keyCode, keyChar); } public static final int VK_PG_TEXTST_ENABLE_DISABLE = 465; public static final int VK_POPUP_MENU = 461; public static final int VK_SECONDARY_AUDIO_ENABLE_DISABLE = 463; public static final int VK_SECONDARY_VIDEO_ENABLE_DISABLE = 464; public static final int VK_STILL_OFF = 462; private static final long serialVersionUID = 3477897216005481682L; }
gpl-3.0
jtux270/translate
ovirt/backend/manager/modules/compat/src/test/java/org/ovirt/engine/core/compat/RegexTest.java
1413
package org.ovirt.engine.core.compat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class RegexTest { @Test public void testSimpleMatches() { Regex regex = new Regex("[0-9]"); assertTrue("A number should match", regex.IsMatch("1")); assertFalse("A letter should not match", regex.IsMatch("a")); } @Test public void testIsMatch() { assertTrue("A number should match", Regex.IsMatch("1", "[0-9]")); assertFalse("A letter should not match", Regex.IsMatch("a", "[0-9]")); } @Test public void testIgnoreCaseOff() { Regex regex = new Regex("[A-Z]"); assertTrue("A cap should match", regex.IsMatch("K")); assertFalse("A lowercase should not match", regex.IsMatch("k")); } @Test public void testIgnoreCaseOn() { Regex regex = new Regex("[A-Z]", RegexOptions.IgnoreCase); assertTrue("A cap should match", regex.IsMatch("K")); assertTrue("A lowercase should match", regex.IsMatch("k")); } @Test public void testGroups() { Match match = Regex.Match("ABC,123", "([A-Z]+),([0-9]+)"); assertEquals("First Group", "ABC", match.groups().get(0).getValue()); assertEquals("Second Group", "123", match.groups().get(1).getValue()); } }
gpl-3.0
moliva/proactive
src/Examples/org/objectweb/proactive/examples/robustarith/Int.java
3485
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero 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 * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.examples.robustarith; import java.math.BigInteger; /** * @author The ProActive Team * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Int { public static final BigInteger MINUS_ONE = BigInteger.ONE.negate(); private static final int MAGNITUDE = 6553600; private static final BigInteger MAX = BigInteger.ONE.shiftLeft(MAGNITUDE); private static final BigInteger MIN = MAX.negate(); public static BigInteger pow2(int e) throws OverflowException { BigInteger val = BigInteger.ONE.shiftLeft(e); if (val.compareTo(MAX) > 0) { throw new OverflowException("pow", new BigInteger("2"), new BigInteger("" + e)); } return val; } public static BigInteger add(BigInteger a, BigInteger b) throws OverflowException { if ((a.signum() > 0) && (b.signum() > 0)) { if (MAX.subtract(a).compareTo(b) < 0) { throw new OverflowException("add", a, b); } } else if ((a.signum() < 0) && (b.signum() < 0)) { if (a.subtract(MIN).compareTo(b.negate()) < 0) { throw new OverflowException("add", a, b); } } return a.add(b); } public static BigInteger sub(BigInteger a, BigInteger b) throws OverflowException { try { return add(a, b.negate()); } catch (OverflowException oe) { throw new OverflowException("sub", a, b); } } public static BigInteger mul(BigInteger a, BigInteger b) throws OverflowException { BigInteger m = a.multiply(b); if (m.compareTo(MAX) > 0) { throw new OverflowException("mul", a, b); } return m; } public static BigInteger div(BigInteger a, BigInteger b) throws OverflowException { if (b.signum() == 0) { throw new OverflowException("div", a, b); } return a.divide(b); } }
agpl-3.0
jamezp/wildfly-core
testsuite/standalone/src/test/java/org/jboss/as/test/integration/logging/profiles/AbstractLoggingProfilesTestCase.java
15700
/* * JBoss, Home of Professional Open Source. * Copyright 2015, 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.jboss.as.test.integration.logging.profiles; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.http.HttpStatus; import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.client.helpers.Operations.CompositeOperationBuilder; import org.jboss.as.test.integration.logging.AbstractLoggingTestCase; import org.jboss.as.test.integration.logging.LoggingServiceActivator; import org.jboss.as.test.integration.management.util.ServerReload; import org.jboss.dmr.ModelNode; import org.jboss.msc.service.ServiceActivator; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Assert; import org.junit.Test; import org.wildfly.core.testrunner.ManagementClient; /** * @author Petr Křemenský <pkremens@redhat.com> */ abstract class AbstractLoggingProfilesTestCase extends AbstractLoggingTestCase { private static final String PROFILE1 = "dummy-profile1"; private static final String PROFILE2 = "dummy-profile2"; private static final String RUNTIME_NAME1 = "logging1.jar"; private static final String RUNTIME_NAME2 = "logging2.jar"; private static final String LOG_FILE_NAME = "profiles-test.log"; private static final String PROFILE1_LOG_NAME = "dummy-profile1.log"; private static final String PROFILE2_LOG_NAME = "dummy-profile2.log"; private static final String CHANGED_LOG_NAME = "dummy-profile1-changed.log"; private static final String LOG_DIR = resolveRelativePath("jboss.server.log.dir"); private static final Path logFile = Paths.get(LOG_DIR, LOG_FILE_NAME); private static final Path dummyLog1 = Paths.get(LOG_DIR, PROFILE1_LOG_NAME); private static final Path dummyLog2 = Paths.get(LOG_DIR, PROFILE2_LOG_NAME); private static final Path dummyLog1Changed = Paths.get(LOG_DIR, CHANGED_LOG_NAME); private final Class<? extends ServiceActivator> serviceActivator; private final int profile1LogCount; protected AbstractLoggingProfilesTestCase(final Class<? extends ServiceActivator> serviceActivator, final int profile1LogCount) { this.serviceActivator = serviceActivator; this.profile1LogCount = profile1LogCount; } static class LoggingProfilesTestCaseSetup extends ServerReload.SetupTask { @Override public void setup(ManagementClient managementClient) throws Exception { final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); ModelNode op = Operations.createAddOperation(createAddress("periodic-rotating-file-handler", "LOGGING_TEST")); op.get("append").set("true"); op.get("suffix").set(".yyyy-MM-dd"); ModelNode file = new ModelNode(); file.get("relative-to").set("jboss.server.log.dir"); file.get("path").set(LOG_FILE_NAME); op.get("file").set(file); op.get("formatter").set("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"); builder.addStep(op); op = Operations.createOperation("add-handler", createAddress("root-logger", "ROOT")); op.get("name").set("LOGGING_TEST"); builder.addStep(op); // create dummy-profile1 builder.addStep(Operations.createAddOperation(createAddress("logging-profile", "dummy-profile1"))); // add file handler op = Operations.createAddOperation(createAddress("logging-profile", "dummy-profile1", "periodic-rotating-file-handler", "DUMMY1")); op.get("level").set("ERROR"); op.get("append").set("true"); op.get("suffix").set(".yyyy-MM-dd"); file = new ModelNode(); file.get("relative-to").set("jboss.server.log.dir"); file.get("path").set(PROFILE1_LOG_NAME); op.get("file").set(file); op.get("formatter").set("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"); builder.addStep(op); // add root logger op = Operations.createAddOperation(createAddress("logging-profile", "dummy-profile1", "root-logger", "ROOT")); op.get("level").set("INFO"); ModelNode handlers = op.get("handlers"); handlers.add("DUMMY1"); op.get("handlers").set(handlers); builder.addStep(op); // create dummy-profile2 builder.addStep(Operations.createAddOperation(createAddress("logging-profile", "dummy-profile2"))); // add file handler op = Operations.createAddOperation(createAddress("logging-profile", "dummy-profile2", "periodic-rotating-file-handler", "DUMMY2")); op.get("level").set("INFO"); op.get("append").set("true"); op.get("suffix").set(".yyyy-MM-dd"); file = new ModelNode(); file.get("relative-to").set("jboss.server.log.dir"); file.get("path").set(PROFILE2_LOG_NAME); op.get("file").set(file); op.get("formatter").set("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"); builder.addStep(op); // add root logger op = Operations.createAddOperation(createAddress("logging-profile", "dummy-profile2", "root-logger", "ROOT")); op.get("level").set("INFO"); handlers = op.get("handlers"); handlers.add("DUMMY2"); op.get("handlers").set(handlers); builder.addStep(op); executeOperation(builder.build()); } @Override public void tearDown(ManagementClient managementClient) throws Exception { final CompositeOperationBuilder builder = CompositeOperationBuilder.create(); // remove LOGGING_TEST from root-logger ModelNode op = Operations.createOperation("remove-handler", createAddress("root-logger", "ROOT")); op.get("name").set("LOGGING_TEST"); builder.addStep(op); // remove custom file handler builder.addStep(Operations.createRemoveOperation(createAddress("periodic-rotating-file-handler", "LOGGING_TEST"))); // remove dummy-profile1 builder.addStep(Operations.createRemoveOperation(createAddress("logging-profile", "dummy-profile1"))); // remove dummy-profile2 builder.addStep(Operations.createRemoveOperation(createAddress("logging-profile", "dummy-profile2"))); executeOperation(builder.build()); // delete log files only if this did not fail Files.deleteIfExists(logFile); Files.deleteIfExists(dummyLog1); Files.deleteIfExists(dummyLog2); Files.deleteIfExists(dummyLog1Changed); super.tearDown(client); } } @Test public void noWarningTest() throws Exception { try { deploy(RUNTIME_NAME1, PROFILE1, false); deploy(RUNTIME_NAME2, PROFILE2, false); try (final BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) { String line; while ((line = reader.readLine()) != null) { // Look for message id in order to support all languages. if (line.contains(PROFILE1) || line.contains(PROFILE2)) { Assert.fail("Every deployment should have defined its own logging profile. But found this line in logs: " + line); } } } } finally { undeploy(RUNTIME_NAME1, RUNTIME_NAME2); } } @Test public void testProfiles() throws Exception { // Test the first profile try { deploy(RUNTIME_NAME1, PROFILE1); // make some logs int statusCode = getResponse("DummyProfile1: Test log message from 1"); assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); } finally { undeploy(RUNTIME_NAME1); } // Test the next profile try { deploy(RUNTIME_NAME2, PROFILE2); // make some logs int statusCode = getResponse("DummyProfile2: Test log message from 2"); assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); } finally { undeploy(RUNTIME_NAME2); } // Check that only one log record is in the first file Assert.assertTrue("dummy-profile1.log was not created", Files.exists(dummyLog1)); try (final BufferedReader reader = Files.newBufferedReader(dummyLog1, StandardCharsets.UTF_8)) { String line = reader.readLine(); Assert.assertNotNull("Log file dummy-profile1.log is empty and should not be.", line); Assert.assertTrue( "\"LoggingServlet is logging error message\" should be presented in dummy-profile1.log", line.contains("DummyProfile1: Test log message from 1")); // Read lines until we expect no more for (int i = 1; i < profile1LogCount; i++) { Assert.assertNotNull(String.format("Expected %d log records but only got %d", profile1LogCount, i) , reader.readLine()); } Assert.assertTrue("Only " + profile1LogCount + " log should be found in dummy-profile1.log", reader.readLine() == null); } // Check that only one log record is in the second file Assert.assertTrue("dummy-profile2.log was not created", Files.exists(dummyLog2)); try (final BufferedReader reader = Files.newBufferedReader(dummyLog2, StandardCharsets.UTF_8)) { String line; while ((line = reader.readLine()) != null) { // The UndertowService also logs one line, this line should be ignored if (line.contains("UndertowService")) continue; if (!line.contains("DummyProfile2: Test log message from 2")) { Assert.fail("dummy-profile2 should not contains this line: " + line); } } } // Check a file that should not have been written to try (final BufferedReader reader = Files.newBufferedReader(logFile, StandardCharsets.UTF_8)) { String line; while ((line = reader.readLine()) != null) { if (line.contains("Test log message from")) { Assert.fail("LoggingServlet messages should be presented only in files specified in profiles, but found: " + line); } } } // Change the file for the first profile try { deploy(RUNTIME_NAME1, PROFILE1); // Change logging level of file handler on dummy-profile1 from ERROR to // INFO final ModelNode address = createAddress("logging-profile", PROFILE1, "periodic-rotating-file-handler", "DUMMY1"); final ModelNode file = new ModelNode(); file.get("relative-to").set("jboss.server.log.dir"); file.get("path").set(CHANGED_LOG_NAME); ModelNode op = Operations.createWriteAttributeOperation(address, "file", file); executeOperation(op); // make some logs int statusCode = getResponse("DummyProfile1: Changed test message 1"); assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK); // check logs, after logging level change we should see also INFO and // ... messages try (final BufferedReader reader = Files.newBufferedReader(dummyLog1Changed, StandardCharsets.UTF_8)) { String line = reader.readLine(); Assert.assertNotNull("Log file " + CHANGED_LOG_NAME + " is empty and should not be.", line); Assert.assertTrue( "\"LoggingServlet is logging error message\" should be presented in " + CHANGED_LOG_NAME, line.contains("DummyProfile1: Changed test message 1")); // Read lines until we expect no more for (int i = 1; i < profile1LogCount; i++) { Assert.assertNotNull(String.format("Expected %d log records but only got %d", profile1LogCount, i) , reader.readLine()); } Assert.assertNull("Only " + profile1LogCount + " log should be found in " + CHANGED_LOG_NAME, reader.readLine()); } } finally { undeploy(RUNTIME_NAME1); } } @Test public void testDeploymentConfigurationResource() throws Exception { try { deploy(RUNTIME_NAME1, PROFILE1); // Get the resulting model final ModelNode loggingConfiguration = readDeploymentResource(RUNTIME_NAME1, "profile-" + PROFILE1); Assert.assertTrue("No logging subsystem resource found on the deployment", loggingConfiguration.isDefined()); // Check the handler exists on the configuration final ModelNode handler = loggingConfiguration.get("handler", "DUMMY1"); Assert.assertTrue("The DUMMY1 handler was not found effective configuration", handler.isDefined()); Assert.assertEquals("The level should be ERROR", "ERROR", handler.get("level").asString()); } finally { undeploy(RUNTIME_NAME1); } } protected void processDeployment(final JavaArchive deployment) { addPermissions(deployment); } private void deploy(final String name, final String profileName) throws IOException { deploy(name, profileName, true); } private void deploy(final String name, final String profileName, final boolean useServiceActivator) throws IOException { final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, name); if (useServiceActivator) { archive.addClasses(LoggingServiceActivator.DEPENDENCIES); archive.addAsServiceProviderAndClasses(ServiceActivator.class, serviceActivator); } archive.addAsResource(new StringAsset("Dependencies: io.undertow.core\nLogging-Profile: " + profileName), "META-INF/MANIFEST.MF"); processDeployment(archive); deploy(archive, name); } }
lgpl-2.1
52nlp/thebeast
src/thebeast/nodmem/expression/MemIntAdd.java
868
package thebeast.nodmem.expression; import thebeast.nod.expression.ExpressionVisitor; import thebeast.nod.expression.IntAdd; import thebeast.nod.expression.IntExpression; import thebeast.nod.type.IntType; /** * Created by IntelliJ IDEA. User: s0349492 Date: 30-Jan-2007 Time: 20:31:49 */ public class MemIntAdd extends AbstractMemExpression<IntType> implements IntAdd { private IntExpression leftHandSide, rightHandSide; public MemIntAdd(IntType type, IntExpression leftHandSide, IntExpression rightHandSide) { super(type); this.leftHandSide = leftHandSide; this.rightHandSide = rightHandSide; } public void acceptExpressionVisitor(ExpressionVisitor visitor) { visitor.visitIntAdd(this); } public IntExpression leftHandSide() { return leftHandSide; } public IntExpression rightHandSide() { return rightHandSide; } }
lgpl-3.0
Teino1978-Corp/Teino1978-Corp-helix
helix-core/src/main/java/org/apache/helix/controller/stages/ExternalViewComputeStage.java
12880
package org.apache.helix.controller.stages; /* * 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. */ import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixDefinedState; import org.apache.helix.HelixManager; import org.apache.helix.PropertyKey; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.ZNRecord; import org.apache.helix.ZNRecordDelta; import org.apache.helix.ZNRecordDelta.MergeOperation; import org.apache.helix.api.Cluster; import org.apache.helix.api.State; import org.apache.helix.api.config.ResourceConfig; import org.apache.helix.api.config.SchedulerTaskConfig; import org.apache.helix.api.id.ParticipantId; import org.apache.helix.api.id.PartitionId; import org.apache.helix.api.id.ResourceId; import org.apache.helix.api.id.StateModelDefId; import org.apache.helix.controller.pipeline.AbstractBaseStage; import org.apache.helix.controller.pipeline.StageException; import org.apache.helix.manager.zk.DefaultSchedulerMessageHandlerFactory; import org.apache.helix.model.ExternalView; import org.apache.helix.model.IdealState; import org.apache.helix.model.Message; import org.apache.helix.model.Message.MessageType; import org.apache.helix.model.StateModelDefinition; import org.apache.helix.model.StatusUpdate; import org.apache.helix.monitoring.mbeans.ClusterStatusMonitor; import org.apache.log4j.Logger; public class ExternalViewComputeStage extends AbstractBaseStage { private static Logger LOG = Logger.getLogger(ExternalViewComputeStage.class); @Override public void process(ClusterEvent event) throws Exception { long startTime = System.currentTimeMillis(); LOG.info("START ExternalViewComputeStage.process()"); HelixManager manager = event.getAttribute("helixmanager"); Map<ResourceId, ResourceConfig> resourceMap = event.getAttribute(AttributeName.RESOURCES.toString()); Cluster cluster = event.getAttribute("Cluster"); ClusterDataCache cache = event.getAttribute("ClusterDataCache"); if (manager == null || resourceMap == null || cluster == null || cache == null) { throw new StageException("Missing attributes in event:" + event + ". Requires ClusterManager|RESOURCES|Cluster|ClusterDataCache"); } HelixDataAccessor dataAccessor = manager.getHelixDataAccessor(); PropertyKey.Builder keyBuilder = dataAccessor.keyBuilder(); ResourceCurrentState currentStateOutput = event.getAttribute(AttributeName.CURRENT_STATE.toString()); List<ExternalView> newExtViews = new ArrayList<ExternalView>(); List<PropertyKey> keys = new ArrayList<PropertyKey>(); // TODO use external-view accessor Map<String, ExternalView> curExtViews = dataAccessor.getChildValuesMap(keyBuilder.externalViews()); for (ResourceId resourceId : resourceMap.keySet()) { ExternalView view = new ExternalView(resourceId.stringify()); // view.setBucketSize(currentStateOutput.getBucketSize(resourceName)); // if resource ideal state has bucket size, set it // otherwise resource has been dropped, use bucket size from current state instead ResourceConfig resource = resourceMap.get(resourceId); SchedulerTaskConfig schedulerTaskConfig = resource.getSchedulerTaskConfig(); if (resource.getIdealState().getBucketSize() > 0) { view.setBucketSize(resource.getIdealState().getBucketSize()); } else { view.setBucketSize(currentStateOutput.getBucketSize(resourceId)); } for (PartitionId partitionId : resource.getSubUnitSet()) { Map<ParticipantId, State> currentStateMap = currentStateOutput.getCurrentStateMap(resourceId, partitionId); if (currentStateMap != null && currentStateMap.size() > 0) { // Set<String> disabledInstances // = cache.getDisabledInstancesForResource(resource.toString()); for (ParticipantId participantId : currentStateMap.keySet()) { // if (!disabledInstances.contains(instance)) // { view.setState(partitionId.stringify(), participantId.stringify(), currentStateMap.get(participantId).toString()); // } } } } // Update cluster status monitor mbean ClusterStatusMonitor clusterStatusMonitor = (ClusterStatusMonitor) event.getAttribute("clusterStatusMonitor"); IdealState idealState = cache._idealStateMap.get(view.getResourceName()); if (idealState != null) { if (clusterStatusMonitor != null && !idealState.getStateModelDefRef().equalsIgnoreCase( DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE)) { StateModelDefinition stateModelDef = cache.getStateModelDef(idealState.getStateModelDefRef()); clusterStatusMonitor.setResourceStatus(view, cache._idealStateMap.get(view.getResourceName()), stateModelDef); } } else { // Drop the metrics for the dropped resource clusterStatusMonitor.unregisterResource(view.getResourceName()); } // compare the new external view with current one, set only on different ExternalView curExtView = curExtViews.get(resourceId.stringify()); if (curExtView == null || !curExtView.getRecord().equals(view.getRecord())) { keys.add(keyBuilder.externalView(resourceId.stringify())); newExtViews.add(view); // For SCHEDULER_TASK_RESOURCE resource group (helix task queue), we need to find out which // task // partitions are finished (COMPLETED or ERROR), update the status update of the original // scheduler // message, and then remove the partitions from the ideal state if (idealState != null && idealState.getStateModelDefId() != null && idealState.getStateModelDefId().equalsIgnoreCase(StateModelDefId.SchedulerTaskQueue)) { updateScheduledTaskStatus(resourceId, view, manager, schedulerTaskConfig); } } } // TODO: consider not setting the externalview of SCHEDULER_TASK_QUEUE at all. // Are there any entity that will be interested in its change? // add/update external-views if (newExtViews.size() > 0) { dataAccessor.setChildren(keys, newExtViews); } // remove dead external-views for (String resourceName : curExtViews.keySet()) { if (!resourceMap.containsKey(ResourceId.from(resourceName))) { LOG.info("Remove externalView for resource: " + resourceName); dataAccessor.removeProperty(keyBuilder.externalView(resourceName)); } } long endTime = System.currentTimeMillis(); LOG.info("END ExternalViewComputeStage.process(). took: " + (endTime - startTime) + " ms"); } // TODO fix it private void updateScheduledTaskStatus(ResourceId resourceId, ExternalView ev, HelixManager manager, SchedulerTaskConfig schedulerTaskConfig) { HelixDataAccessor accessor = manager.getHelixDataAccessor(); Builder keyBuilder = accessor.keyBuilder(); ZNRecord finishedTasks = new ZNRecord(ev.getResourceName()); // Place holder for finished partitions Map<String, String> emptyMap = new HashMap<String, String>(); List<String> emptyList = new LinkedList<String>(); Map<String, Integer> controllerMsgIdCountMap = new HashMap<String, Integer>(); Map<String, Map<String, String>> controllerMsgUpdates = new HashMap<String, Map<String, String>>(); for (String taskPartitionName : ev.getPartitionSet()) { for (String taskState : ev.getStateMap(taskPartitionName).values()) { if (taskState.equalsIgnoreCase(HelixDefinedState.ERROR.toString()) || taskState.equalsIgnoreCase("COMPLETED")) { LOG.info(taskPartitionName + " finished as " + taskState); finishedTasks.setListField(taskPartitionName, emptyList); finishedTasks.setMapField(taskPartitionName, emptyMap); // Update original scheduler message status update Message innerMessage = schedulerTaskConfig.getInnerMessage(PartitionId.from(taskPartitionName)); if (innerMessage != null) { String controllerMsgId = innerMessage.getControllerMessageId(); if (controllerMsgId != null) { LOG.info(taskPartitionName + " finished with controllerMsg " + controllerMsgId); if (!controllerMsgUpdates.containsKey(controllerMsgId)) { controllerMsgUpdates.put(controllerMsgId, new HashMap<String, String>()); } controllerMsgUpdates.get(controllerMsgId).put(taskPartitionName, taskState); } } } } } // fill the controllerMsgIdCountMap for (PartitionId taskId : schedulerTaskConfig.getPartitionSet()) { Message innerMessage = schedulerTaskConfig.getInnerMessage(taskId); String controllerMsgId = innerMessage.getControllerMessageId(); if (controllerMsgId != null) { Integer curCnt = controllerMsgIdCountMap.get(controllerMsgId); if (curCnt == null) { curCnt = 0; } controllerMsgIdCountMap.put(controllerMsgId, curCnt + 1); } } if (controllerMsgUpdates.size() > 0) { for (String controllerMsgId : controllerMsgUpdates.keySet()) { PropertyKey controllerStatusUpdateKey = keyBuilder.controllerTaskStatus(MessageType.SCHEDULER_MSG.toString(), controllerMsgId); StatusUpdate controllerStatusUpdate = accessor.getProperty(controllerStatusUpdateKey); for (String taskPartitionName : controllerMsgUpdates.get(controllerMsgId).keySet()) { Message innerMessage = schedulerTaskConfig.getInnerMessage(PartitionId.from(taskPartitionName)); Map<String, String> result = new HashMap<String, String>(); result.put("Result", controllerMsgUpdates.get(controllerMsgId).get(taskPartitionName)); controllerStatusUpdate.getRecord().setMapField( "MessageResult " + innerMessage.getTgtName() + " " + taskPartitionName + " " + innerMessage.getMessageId(), result); } // All done for the scheduled tasks that came from controllerMsgId, add summary for it if (controllerMsgUpdates.get(controllerMsgId).size() == controllerMsgIdCountMap.get( controllerMsgId).intValue()) { int finishedTasksNum = 0; int completedTasksNum = 0; for (String key : controllerStatusUpdate.getRecord().getMapFields().keySet()) { if (key.startsWith("MessageResult ")) { finishedTasksNum++; } if (controllerStatusUpdate.getRecord().getMapField(key).get("Result") != null) { if (controllerStatusUpdate.getRecord().getMapField(key).get("Result") .equalsIgnoreCase("COMPLETED")) { completedTasksNum++; } } } Map<String, String> summary = new TreeMap<String, String>(); summary.put("TotalMessages:", "" + finishedTasksNum); summary.put("CompletedMessages", "" + completedTasksNum); controllerStatusUpdate.getRecord().setMapField("Summary", summary); } // Update the statusUpdate of controllerMsgId accessor.updateProperty(controllerStatusUpdateKey, controllerStatusUpdate); } } if (finishedTasks.getListFields().size() > 0) { ZNRecordDelta znDelta = new ZNRecordDelta(finishedTasks, MergeOperation.SUBTRACT); List<ZNRecordDelta> deltaList = new LinkedList<ZNRecordDelta>(); deltaList.add(znDelta); IdealState delta = new IdealState(resourceId); delta.setDeltaList(deltaList); // Remove the finished (COMPLETED or ERROR) tasks from the SCHEDULER_TASK_RESOURCE idealstate keyBuilder = accessor.keyBuilder(); accessor.updateProperty(keyBuilder.idealStates(resourceId.stringify()), delta); } } }
apache-2.0
immortius/Terasology
engine-tests/src/test/java/org/terasology/entitySystem/metadata/ComponentMetadataTest.java
2759
/* * Copyright 2013 MovingBlocks * * 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.terasology.entitySystem.metadata; import org.junit.Before; import org.junit.Test; import org.terasology.context.Context; import org.terasology.context.internal.ContextImpl; import org.terasology.engine.SimpleUri; import org.terasology.entitySystem.stubs.OwnerComponent; import org.terasology.entitySystem.stubs.StringComponent; import org.terasology.persistence.typeHandling.TypeSerializationLibrary; import org.terasology.reflection.copy.CopyStrategyLibrary; import org.terasology.reflection.reflect.ReflectFactory; import org.terasology.reflection.reflect.ReflectionReflectFactory; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * @author Immortius */ public class ComponentMetadataTest { private Context context; private ReflectFactory reflectFactory = new ReflectionReflectFactory(); private CopyStrategyLibrary copyStrategies = new CopyStrategyLibrary(reflectFactory); @Before public void prepare() { context = new ContextImpl(); context.put(ReflectFactory.class, reflectFactory); context.put(CopyStrategyLibrary.class, copyStrategies); } @Test public void staticFieldsIgnored() { EntitySystemLibrary entitySystemLibrary = new EntitySystemLibrary(context, new TypeSerializationLibrary(reflectFactory, copyStrategies)); ComponentLibrary lib = entitySystemLibrary.getComponentLibrary(); lib.register(new SimpleUri("unittest:string"), StringComponent.class); ComponentMetadata<StringComponent> metadata = lib.getMetadata(StringComponent.class); assertNull(metadata.getField("STATIC_VALUE")); } @Test public void ownsReferencesPopulated() { EntitySystemLibrary entitySystemLibrary = new EntitySystemLibrary(context, new TypeSerializationLibrary(reflectFactory, copyStrategies)); ComponentLibrary lib = entitySystemLibrary.getComponentLibrary(); lib.register(new SimpleUri("unittest:owner"), OwnerComponent.class); ComponentMetadata<OwnerComponent> metadata = lib.getMetadata(OwnerComponent.class); assertTrue(metadata.isReferenceOwner()); } }
apache-2.0
codescale/logging-log4j2
log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/IfEnabledTagTest.java
3740
/* * 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.logging.log4j.taglib; import javax.servlet.jsp.tagext.Tag; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.junit.LoggerContextRule; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.springframework.mock.web.MockPageContext; import static org.junit.Assert.*; /** * */ public class IfEnabledTagTest { private static final String CONFIG = "log4j-test1.xml"; @ClassRule public static LoggerContextRule context = new LoggerContextRule(CONFIG); private final Logger logger = context.getLogger("IfEnabledTagTest"); private IfEnabledTag tag; @Before public void setUp() { this.tag = new IfEnabledTag(); this.tag.setPageContext(new MockPageContext()); this.tag.setLogger(this.logger); } @Test public void testDoStartTagEnabledString() throws Exception { this.tag.setLevel("warn"); assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag()); } @Test public void testDoStartTagEnabledLevel() throws Exception { this.tag.setLevel(Level.WARN); assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag()); } @Test public void testDoStartTagEnabledStringMarker() throws Exception { this.tag.setMarker(MarkerManager.getMarker("E01")); this.tag.setLevel("error"); assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag()); } @Test public void testDoStartTagEnabledLevelMarker() throws Exception { this.tag.setMarker(MarkerManager.getMarker("F02")); this.tag.setLevel(Level.ERROR); assertEquals("The return value is not correct.", Tag.EVAL_BODY_INCLUDE, this.tag.doStartTag()); } @Test public void testDoStartTagDisabledString() throws Exception { this.tag.setLevel("info"); assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag()); } @Test public void testDoStartTagDisabledLevel() throws Exception { this.tag.setLevel(Level.INFO); assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag()); } @Test public void testDoStartTagDisabledStringMarker() throws Exception { this.tag.setMarker(MarkerManager.getMarker("E01")); this.tag.setLevel("trace"); assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag()); } @Test public void testDoStartTagDisabledLevelMarker() throws Exception { this.tag.setMarker(MarkerManager.getMarker("F02")); this.tag.setLevel(Level.TRACE); assertEquals("The return value is not correct.", Tag.SKIP_BODY, this.tag.doStartTag()); } }
apache-2.0
kokareff/live-chat-engine
common/util/src/och/util/StringUtil.java
6039
/* * Copyright 2015 Evgeny Dolganov (evgenij.dolganov@gmail.com). * * 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 och.util; import static och.util.Util.*; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import java.util.StringTokenizer; import och.util.model.HasIntCode; import och.util.model.JsonConvertible; public class StringUtil { public static final String DEFAULT_ST_SEPARATORS = " \t\n\r\f"; public static String removeAll(String str, String invalidChars){ return replaceAll(str, invalidChars, null); } public static String replaceAll(String str, String invalidChars, String replacement){ if(str == null) return null; char ch; boolean invalid; StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.length(); i++) { ch = str.charAt(i); invalid = false; for (int j = 0; j < invalidChars.length(); j++) { if(ch == invalidChars.charAt(j)){ invalid = true; break; } } if( ! invalid) sb.append(ch); else if(replacement != null )sb.append(replacement); } return sb.toString(); } public static String cropWithDots(String str, int maxLenght){ return crop(str, maxLenght, true); } public static String crop(String str, int maxLenght, boolean useDots){ if(Util.isEmpty(str)){ return str; } if(str.length() <= maxLenght){ return str; } String out = str.substring(0, maxLenght); if(useDots){ out += "..."; } return out; } public static String createStr(char c, int length){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(c); } return sb.toString(); } public static String randomStr(int length){ int beginCode = 'a'; int endCode = 'z'; int delta = endCode - beginCode; Random r = new Random(); char nextCh; StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { nextCh = (char)(r.nextInt(delta+1) + beginCode); sb.append(nextCh); } return sb.toString(); } public static boolean containsAny(String source, String... subs){ if(source == null) return false; if(isEmpty(subs)) return true; for (String str : subs) { if(source.contains(str)){ return true; } } return false; } public static byte[] getBytesUTF8(String str){ try { return str.getBytes(UTF8); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("can't get utf8 Encoding", e); } } public static String getStrUTF8(byte[] bytes){ try { return new String(bytes, UTF8); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("can't get utf8 Encoding", e); } } public static String collectionToStr(Collection<?> collection){ return collectionToStr(collection, null, null, null, true); } public static String collectionToStr(Collection<?> collection, Object separator){ return collectionToStr(collection, separator, null, null, true); } public static String collectionToStr(Collection<?> collection, Object beginBlock, Object endBlock){ return collectionToStr(collection, null, beginBlock, endBlock, true); } public static String collectionToStr(Collection<?> collection, Object separator, Object beginBlock, Object endBlock){ return collectionToStr(collection, separator, beginBlock, endBlock, true); } public static String collectionToStr(Collection<?> collection, Object separator, Object beginBlock, Object endBlock, boolean useConvert){ if(collection == null) return null; if(separator == null) separator = ','; StringBuilder sb = new StringBuilder(); if(beginBlock != null) sb.append(beginBlock); boolean first = true; for(Object ob : collection){ if(!first) sb.append(separator); first = false; if(!useConvert) sb.append(ob); else if(ob instanceof HasIntCode) sb.append(((HasIntCode)ob).getCode()); else if(ob instanceof JsonConvertible) sb.append(((JsonConvertible)ob).toJson()); else sb.append(ob); } if(endBlock != null) sb.append(endBlock); return sb.toString(); } public static List<String> strToList(String val){ return strToList(val, ",", null, null); } public static List<String> strToListWithDefaultSeps(String val){ return strToList(val, DEFAULT_ST_SEPARATORS, null, null); } public static List<String> strToList(String val, String separators){ return strToList(val, separators, null, null); } public static List<String> strToList(String val, Character separator, Character beginBlock, Character endBlock){ return strToList(val, separator == null? null : separator.toString(), beginBlock, endBlock); } public static List<String> strToList(String val, String separators, Character beginBlock, Character endBlock){ if(val == null) return null; if(separators == null) separators = ","; if(beginBlock != null && val.indexOf(beginBlock) == 0){ val = val.substring(1); } if(endBlock != null && val.lastIndexOf(endBlock) == val.length()-1){ val = val.substring(0, val.length()-1); } ArrayList<String> out = new ArrayList<>(); StringTokenizer st = new StringTokenizer(val, separators); while(st.hasMoreTokens()){ String token = st.nextToken(); if( ! isEmpty(token)) out.add(token); } return out; } /** removes all whitespaces and non visible characters such as tab, \n */ public static String removeSpaceSeparators(String s){ if(s == null) return s; return s.replaceAll("\\s+",""); } }
apache-2.0
cshannon/activemq-artemis
artemis-protocols/artemis-stomp-protocol/src/main/java/org/apache/activemq/artemis/core/protocol/stomp/v11/StompFrameHandlerV11.java
25002
/* * 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.artemis.core.protocol.stomp.v11; import javax.security.cert.X509Certificate; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompException; import org.apache.activemq.artemis.core.protocol.stomp.FrameEventListener; import org.apache.activemq.artemis.core.protocol.stomp.SimpleBytes; import org.apache.activemq.artemis.core.protocol.stomp.Stomp; import org.apache.activemq.artemis.core.protocol.stomp.StompConnection; import org.apache.activemq.artemis.core.protocol.stomp.StompDecoder; import org.apache.activemq.artemis.core.protocol.stomp.StompFrame; import org.apache.activemq.artemis.core.protocol.stomp.VersionedStompFrameHandler; import org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnection; import org.apache.activemq.artemis.core.remoting.impl.netty.TransportConstants; import org.apache.activemq.artemis.core.remoting.server.impl.RemotingServiceImpl; import org.apache.activemq.artemis.core.server.ActiveMQScheduledComponent; import org.apache.activemq.artemis.core.server.ActiveMQServerLogger; import org.apache.activemq.artemis.spi.core.protocol.ConnectionEntry; import org.apache.activemq.artemis.utils.CertificateUtil; import org.apache.activemq.artemis.utils.ExecutorFactory; import static org.apache.activemq.artemis.core.protocol.stomp.ActiveMQStompProtocolMessageBundle.BUNDLE; public class StompFrameHandlerV11 extends VersionedStompFrameHandler implements FrameEventListener { protected static final char ESC_CHAR = '\\'; private HeartBeater heartBeater; public StompFrameHandlerV11(StompConnection connection, ScheduledExecutorService scheduledExecutorService, ExecutorFactory executorFactory) { super(connection, scheduledExecutorService, executorFactory); connection.addStompEventListener(this); decoder = new StompDecoderV11(this); decoder.init(); } public ActiveMQScheduledComponent getHeartBeater() { return heartBeater; } @Override public StompFrame onConnect(StompFrame frame) { StompFrame response = null; Map<String, String> headers = frame.getHeadersMap(); String login = headers.get(Stomp.Headers.Connect.LOGIN); String passcode = headers.get(Stomp.Headers.Connect.PASSCODE); String clientID = headers.get(Stomp.Headers.Connect.CLIENT_ID); String requestID = headers.get(Stomp.Headers.Connect.REQUEST_ID); X509Certificate[] certificates = null; if (connection.getTransportConnection() instanceof NettyConnection) { certificates = CertificateUtil.getCertsFromChannel(((NettyConnection) connection.getTransportConnection()).getChannel()); } try { if (connection.validateUser(login, passcode, certificates)) { connection.setClientID(clientID); connection.setValid(true); response = this.createStompFrame(Stomp.Responses.CONNECTED); // version response.addHeader(Stomp.Headers.Connected.VERSION, connection.getVersion()); // session response.addHeader(Stomp.Headers.Connected.SESSION, connection.getID().toString()); // server response.addHeader(Stomp.Headers.Connected.SERVER, connection.getActiveMQServerName()); if (requestID != null) { response.addHeader(Stomp.Headers.Connected.RESPONSE_ID, requestID); } // heart-beat. We need to start after connected frame has been sent. // otherwise the client may receive heart-beat before it receives // connected frame. String heartBeat = headers.get(Stomp.Headers.Connect.HEART_BEAT); if (heartBeat != null) { handleHeartBeat(heartBeat); if (heartBeater == null) { response.addHeader(Stomp.Headers.Connected.HEART_BEAT, "0,0"); } else { response.addHeader(Stomp.Headers.Connected.HEART_BEAT, heartBeater.serverPingPeriod + "," + heartBeater.clientPingResponse); } } } else { // not valid response = createStompFrame(Stomp.Responses.ERROR); response.setNeedsDisconnect(true); response.addHeader(Stomp.Headers.CONTENT_TYPE, "text/plain"); String responseText = "Security Error occurred: User name [" + login + "] or password is invalid"; response.setBody(responseText); response.addHeader(Stomp.Headers.Error.MESSAGE, responseText); } } catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } private void handleHeartBeat(String heartBeatHeader) throws ActiveMQStompException { String[] params = heartBeatHeader.split(","); if (params.length != 2) { throw new ActiveMQStompException(connection, "Incorrect heartbeat header " + heartBeatHeader); } //client ping long minPingInterval = Long.valueOf(params[0]); //client receive ping long minAcceptInterval = Long.valueOf(params[1]); if (heartBeater == null) { heartBeater = new HeartBeater(scheduledExecutorService, executorFactory.getExecutor(), minPingInterval, minAcceptInterval); } } @Override public StompFrame onDisconnect(StompFrame frame) { disconnect(); return null; } @Override protected void disconnect() { if (this.heartBeater != null) { heartBeater.shutdown(); } } @Override public StompFrame onUnsubscribe(StompFrame request) { StompFrame response = null; //unsubscribe in 1.1 only needs id header String id = request.getHeader(Stomp.Headers.Unsubscribe.ID); String durableSubscriptionName = request.getHeader(Stomp.Headers.Unsubscribe.DURABLE_SUBSCRIBER_NAME); if (durableSubscriptionName == null) { durableSubscriptionName = request.getHeader(Stomp.Headers.Unsubscribe.DURABLE_SUBSCRIPTION_NAME); } String subscriptionID = null; if (id != null) { subscriptionID = id; } else if (durableSubscriptionName == null) { response = BUNDLE.needSubscriptionID().setHandler(this).getFrame(); return response; } try { connection.unsubscribe(subscriptionID, durableSubscriptionName); } catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } @Override public StompFrame onAck(StompFrame request) { StompFrame response = null; String messageID = request.getHeader(Stomp.Headers.Ack.MESSAGE_ID); String txID = request.getHeader(Stomp.Headers.TRANSACTION); String subscriptionID = request.getHeader(Stomp.Headers.Ack.SUBSCRIPTION); if (txID != null) { ActiveMQServerLogger.LOGGER.stompTXAckNorSupported(); } if (subscriptionID == null) { response = BUNDLE.needSubscriptionID().setHandler(this).getFrame(); return response; } try { connection.acknowledge(messageID, subscriptionID); } catch (ActiveMQStompException e) { response = e.getFrame(); } return response; } @Override public StompFrame onStomp(StompFrame request) { if (!connection.isValid()) { return onConnect(request); } return null; } @Override public StompFrame onNack(StompFrame request) { //this eventually means discard the message (it never be redelivered again). //we can consider supporting redeliver to a different sub. return onAck(request); } @Override public void replySent(StompFrame reply) { if (reply.getCommand().equals(Stomp.Responses.CONNECTED)) { //kick off the pinger startHeartBeat(); } if (reply.needsDisconnect()) { connection.disconnect(false); } else { //update ping if (heartBeater != null) { heartBeater.pinged(); } } } private void startHeartBeat() { if (heartBeater != null && heartBeater.serverPingPeriod != 0) { heartBeater.start(); } } public StompFrame createPingFrame() { StompFrame frame = createStompFrame(Stomp.Commands.STOMP); frame.setPing(true); return frame; } /* * HeartBeater functions: * (a) server ping: if server hasn't sent any frame within serverPingPeriod interval, send a ping * (b) configure connection ttl so that org.apache.activemq.artemis.core.remoting.server.impl.RemotingServiceImpl.FailureCheckAndFlushThread * can deal with closing connections which go stale */ private class HeartBeater extends ActiveMQScheduledComponent { private static final int MIN_SERVER_PING = 500; long serverPingPeriod = 0; long clientPingResponse; volatile boolean shutdown = false; AtomicLong lastPingTimestamp = new AtomicLong(0); ConnectionEntry connectionEntry; private HeartBeater(ScheduledExecutorService scheduledExecutorService, Executor executor, final long clientPing, final long clientAcceptPing) { super(scheduledExecutorService, executor, clientAcceptPing > MIN_SERVER_PING ? clientAcceptPing : MIN_SERVER_PING, TimeUnit.MILLISECONDS, false); if (clientAcceptPing != 0) { serverPingPeriod = super.getPeriod(); } connectionEntry = ((RemotingServiceImpl) connection.getManager().getServer().getRemotingService()).getConnectionEntry(connection.getID()); if (connectionEntry != null) { String heartBeatToTtlModifierStr = (String) connection.getAcceptorUsed().getConfiguration().get(TransportConstants.HEART_BEAT_TO_CONNECTION_TTL_MODIFIER); double heartBeatToTtlModifier = heartBeatToTtlModifierStr == null ? 2 : Double.valueOf(heartBeatToTtlModifierStr); // the default response to the client clientPingResponse = (long) (connectionEntry.ttl / heartBeatToTtlModifier); if (clientPing != 0) { clientPingResponse = clientPing; String ttlMaxStr = (String) connection.getAcceptorUsed().getConfiguration().get(TransportConstants.CONNECTION_TTL_MAX); long ttlMax = ttlMaxStr == null ? Long.MAX_VALUE : Long.valueOf(ttlMaxStr); String ttlMinStr = (String) connection.getAcceptorUsed().getConfiguration().get(TransportConstants.CONNECTION_TTL_MIN); long ttlMin = ttlMinStr == null ? 1000 : Long.valueOf(ttlMinStr); /* The connection's TTL should be one of the following: * 1) clientPing * heartBeatToTtlModifier * 2) ttlMin * 3) ttlMax */ long connectionTtl = (long) (clientPing * heartBeatToTtlModifier); if (connectionTtl < ttlMin) { connectionTtl = ttlMin; clientPingResponse = (long) (ttlMin / heartBeatToTtlModifier); } else if (connectionTtl > ttlMax) { connectionTtl = ttlMax; clientPingResponse = (long) (ttlMax / heartBeatToTtlModifier); } if (ActiveMQServerLogger.LOGGER.isDebugEnabled()) { ActiveMQServerLogger.LOGGER.debug("Setting STOMP client TTL to: " + connectionTtl); } connectionEntry.ttl = connectionTtl; } } } public void shutdown() { this.stop(); } public void pinged() { lastPingTimestamp.set(System.currentTimeMillis()); } @Override public void run() { lastPingTimestamp.set(System.currentTimeMillis()); connection.ping(createPingFrame()); } } @Override public void requestAccepted(StompFrame request) { } @Override public StompFrame createStompFrame(String command) { return new StompFrameV11(command); } @Override public void initDecoder(VersionedStompFrameHandler existingHandler) { decoder.init(existingHandler.getDecoder()); } protected class StompDecoderV11 extends StompDecoder { protected boolean isEscaping = false; protected SimpleBytes holder = new SimpleBytes(1024); public StompDecoderV11(StompFrameHandlerV11 handler) { super(handler); } @Override public void init(StompDecoder decoder) { this.data = decoder.data; this.workingBuffer = decoder.workingBuffer; this.pos = decoder.pos; this.command = decoder.command; } @Override public void init() { super.init(); isEscaping = false; holder.reset(); } @Override protected boolean parseCommand() throws ActiveMQStompException { int offset = 0; boolean nextChar = false; //check for ping // Some badly behaved STOMP clients add a \n *after* the terminating NUL char at the end of the // STOMP frame this can manifest as an extra \n at the beginning when the // next STOMP frame is read - we need to deal with this. // Besides, Stomp 1.2 allows for extra EOLs after NULL (i.e. // either "[\r]\n"s or "\n"s) while (true) { if (workingBuffer[offset] == NEW_LINE) { //client ping nextChar = false; } else if (workingBuffer[offset] == CR) { if (nextChar) throw BUNDLE.invalidTwoCRs().setHandler(handler); nextChar = true; } else { break; } offset++; if (offset == data) return false; //no more bytes } if (nextChar) { throw BUNDLE.badCRs().setHandler(handler); } //if some EOLs have been processed, drop those bytes before parsing command if (offset > 0) { System.arraycopy(workingBuffer, offset, workingBuffer, 0, data - offset); data = data - offset; offset = 0; } if (data < 4) { // Need at least four bytes to identify the command // - up to 3 bytes for the command name + potentially another byte for a leading \n return false; } byte b = workingBuffer[offset]; switch (b) { case A: { if (workingBuffer[offset + 1] == StompDecoder.B) { if (!tryIncrement(offset + COMMAND_ABORT_LENGTH + eolLen)) { return false; } // ABORT command = COMMAND_ABORT; } else { if (!tryIncrement(offset + COMMAND_ACK_LENGTH + eolLen)) { return false; } // ACK command = COMMAND_ACK; } break; } case B: { if (!tryIncrement(offset + COMMAND_BEGIN_LENGTH + eolLen)) { return false; } // BEGIN command = COMMAND_BEGIN; break; } case C: { if (workingBuffer[offset + 2] == M) { if (!tryIncrement(offset + COMMAND_COMMIT_LENGTH + eolLen)) { return false; } // COMMIT command = COMMAND_COMMIT; } else if (workingBuffer[offset + 7] == E) { if (!tryIncrement(offset + COMMAND_CONNECTED_LENGTH + eolLen)) { return false; } // CONNECTED command = COMMAND_CONNECTED; } else { if (!tryIncrement(offset + COMMAND_CONNECT_LENGTH + eolLen)) { return false; } // CONNECT command = COMMAND_CONNECT; } break; } case D: { if (!tryIncrement(offset + COMMAND_DISCONNECT_LENGTH + eolLen)) { return false; } // DISCONNECT command = COMMAND_DISCONNECT; break; } case R: { if (!tryIncrement(offset + COMMAND_RECEIPT_LENGTH + eolLen)) { return false; } // RECEIPT command = COMMAND_RECEIPT; break; } /**** added by meddy, 27 april 2011, handle header parser for reply to websocket protocol ****/ case E: { if (!tryIncrement(offset + COMMAND_ERROR_LENGTH + eolLen)) { return false; } // ERROR command = COMMAND_ERROR; break; } case M: { if (!tryIncrement(offset + COMMAND_MESSAGE_LENGTH + eolLen)) { return false; } // MESSAGE command = COMMAND_MESSAGE; break; } /**** end ****/ case S: { if (workingBuffer[offset + 1] == E) { if (!tryIncrement(offset + COMMAND_SEND_LENGTH + eolLen)) { return false; } // SEND command = COMMAND_SEND; } else if (workingBuffer[offset + 1] == U) { if (!tryIncrement(offset + COMMAND_SUBSCRIBE_LENGTH + eolLen)) { return false; } // SUBSCRIBE command = COMMAND_SUBSCRIBE; } else { if (!tryIncrement(offset + StompDecoder.COMMAND_STOMP_LENGTH + eolLen)) { return false; } // SUBSCRIBE command = COMMAND_STOMP; } break; } case U: { if (!tryIncrement(offset + COMMAND_UNSUBSCRIBE_LENGTH + eolLen)) { return false; } // UNSUBSCRIBE command = COMMAND_UNSUBSCRIBE; break; } case N: { if (!tryIncrement(offset + COMMAND_NACK_LENGTH + eolLen)) { return false; } //NACK command = COMMAND_NACK; break; } default: { throwInvalid(); } } checkEol(); return true; } protected void checkEol() throws ActiveMQStompException { if (workingBuffer[pos - 1] != NEW_LINE) { throwInvalid(); } } protected void throwUndefinedEscape(byte b) throws ActiveMQStompException { ActiveMQStompException error = BUNDLE.undefinedEscapeSequence(new String(new char[]{ESC_CHAR, (char) b})).setHandler(handler); error.setCode(ActiveMQStompException.UNDEFINED_ESCAPE); throw error; } @Override protected boolean parseHeaders() throws ActiveMQStompException { outer: while (true) { byte b = workingBuffer[pos++]; switch (b) { //escaping case ESC_CHAR: { if (isEscaping) { //this is a backslash holder.append(b); isEscaping = false; } else { //begin escaping isEscaping = true; } break; } case HEADER_SEPARATOR: { if (inHeaderName) { headerName = holder.getString(); holder.reset(); inHeaderName = false; headerValueWhitespace = true; } whiteSpaceOnly = false; break; } case StompDecoder.LN: { if (isEscaping) { holder.append(StompDecoder.NEW_LINE); isEscaping = false; } else { holder.append(b); } break; } case StompDecoder.c: { if (isEscaping) { holder.append(StompDecoder.HEADER_SEPARATOR); isEscaping = false; } else { holder.append(b); } break; } case StompDecoder.NEW_LINE: { if (whiteSpaceOnly) { // Headers are terminated by a blank line readingHeaders = false; break outer; } String headerValue = holder.getString(); holder.reset(); headers.put(headerName, headerValue); if (headerName.equals(Stomp.Headers.CONTENT_LENGTH)) { contentLength = Integer.parseInt(headerValue); } if (headerName.equals(Stomp.Headers.CONTENT_TYPE)) { contentType = headerValue; } whiteSpaceOnly = true; inHeaderName = true; headerValueWhitespace = false; break; } default: { whiteSpaceOnly = false; headerValueWhitespace = false; if (isEscaping) { throwUndefinedEscape(b); } holder.append(b); } } if (pos == data) { // Run out of data return false; } } return true; } @Override protected StompFrame parseBody() throws ActiveMQStompException { byte[] content = null; if (contentLength != -1) { if (pos + contentLength + 1 > data) { // Need more bytes } else { content = new byte[contentLength]; System.arraycopy(workingBuffer, pos, content, 0, contentLength); pos += contentLength; //drain all the rest if (bodyStart == -1) { bodyStart = pos; } while (pos < data) { if (workingBuffer[pos++] == 0) { break; } } } } else { // Need to scan for terminating NUL if (bodyStart == -1) { bodyStart = pos; } while (pos < data) { if (workingBuffer[pos++] == 0) { content = new byte[pos - bodyStart - 1]; System.arraycopy(workingBuffer, bodyStart, content, 0, content.length); break; } } } if (content != null) { if (data > pos) { if (workingBuffer[pos] == NEW_LINE) pos++; if (data > pos) // More data still in the buffer from the next packet System.arraycopy(workingBuffer, pos, workingBuffer, 0, data - pos); } data = data - pos; // reset StompFrame ret = new StompFrameV11(command, headers, content); init(); return ret; } else { return null; } } } }
apache-2.0
balazs-zsoldos/querydsl
querydsl-sql/src/test/java/com/querydsl/sql/MultikeyTest.java
1905
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/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.querydsl.sql; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import org.junit.Test; public class MultikeyTest { Multikey multiKey1 = new Multikey(); Multikey multiKey2 = new Multikey(); @Test public void hashCode_() { int hashCode = multiKey1.hashCode(); multiKey1.setId(1); assertEquals(hashCode, multiKey1.hashCode()); multiKey1.setId2("2"); multiKey1.setId3(3); multiKey2.setId(1); multiKey2.setId2("2"); multiKey2.setId3(3); assertEquals(multiKey1.hashCode(), multiKey2.hashCode()); } @Test public void equals() { multiKey1.setId(1); multiKey1.setId2("2"); multiKey1.setId3(3); assertFalse(multiKey1.equals(multiKey2)); multiKey2.setId(1); assertFalse(multiKey1.equals(multiKey2)); multiKey2.setId2("2"); multiKey2.setId3(3); assertEquals(multiKey1, multiKey2); } @Test public void toString_() { assertEquals("Multikey#null;null;null", multiKey1.toString()); multiKey1.setId(1); multiKey1.setId2("2"); multiKey1.setId3(3); assertEquals("Multikey#1;2;3", multiKey1.toString()); } }
apache-2.0
TatsianaKasiankova/pentaho-kettle
plugins/repositories/core/src/main/java/org/pentaho/di/ui/repo/model/RepositoryModel.java
2685
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.ui.repo.model; /** * Created by bmorrise on 10/24/16. */ public class RepositoryModel { private String id; private String displayName; private String url; private String description; private String location; private Boolean isDefault = false; private Boolean doNotModify = false; private Boolean showHiddenFolders = false; private String databaseConnection; public String getId() { return id; } public void setId( String id ) { this.id = id; } public String getDisplayName() { return displayName; } public void setDisplayName( String displayName ) { this.displayName = displayName; } public String getUrl() { return url; } public void setUrl( String url ) { this.url = url; } public String getDescription() { return description; } public void setDescription( String description ) { this.description = description; } public Boolean getIsDefault() { return isDefault; } public void setIsDefault( Boolean isDefault ) { this.isDefault = isDefault; } public String getLocation() { return location; } public void setLocation( String location ) { this.location = location; } public Boolean getDoNotModify() { return doNotModify; } public void setDoNotModify( Boolean doNotModify ) { this.doNotModify = doNotModify; } public Boolean getShowHiddenFolders() { return showHiddenFolders; } public void setShowHiddenFolders( Boolean showHiddenFolders ) { this.showHiddenFolders = showHiddenFolders; } public String getDatabaseConnection() { return databaseConnection; } public void setDatabaseConnection( String databaseConnection ) { this.databaseConnection = databaseConnection; } }
apache-2.0
wso2/siddhi
modules/siddhi-core/src/test/java/io/siddhi/core/query/table/DefineTableTestCase.java
17493
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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 io.siddhi.core.query.table; import io.siddhi.core.SiddhiAppRuntime; import io.siddhi.core.SiddhiManager; import io.siddhi.core.exception.SiddhiAppCreationException; import io.siddhi.core.query.table.util.TestStore; import io.siddhi.core.util.config.InMemoryConfigManager; import io.siddhi.query.api.SiddhiApp; import io.siddhi.query.api.definition.Attribute; import io.siddhi.query.api.definition.TableDefinition; import io.siddhi.query.api.exception.DuplicateDefinitionException; import io.siddhi.query.compiler.exception.SiddhiParserException; import org.apache.log4j.Logger; import org.testng.AssertJUnit; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; /** * Created on 1/17/15. */ public class DefineTableTestCase { private static final Logger log = Logger.getLogger(DefineTableTestCase.class); @Test public void testQuery1() throws InterruptedException { log.info("testTableDefinition1 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); TableDefinition tableDefinition = TableDefinition.id("cseEventStream").attribute("symbol", Attribute.Type .STRING).attribute("price", Attribute.Type.INT); SiddhiApp siddhiApp = new SiddhiApp("ep1"); siddhiApp.defineTable(tableDefinition); SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test public void testQuery2() throws InterruptedException { log.info("testTableDefinition2 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String tables = "define table Table(symbol string, price int, volume float) "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(tables); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery3() throws InterruptedException { log.info("testTableDefinition3 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String tables = "define table TestTable(symbol string, price int, volume float); " + "define table TestTable(symbols string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(tables); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery4() throws InterruptedException { log.info("testTableDefinition4 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String tables = "define table TestTable(symbol string, volume float); " + "define table TestTable(symbols string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(tables); siddhiAppRuntime.shutdown(); } @Test public void testQuery5() throws InterruptedException { log.info("testTableDefinition5 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String tables = "define table TestTable(symbol string, price int, volume float); " + "define table TestTable(symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(tables); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery6() throws InterruptedException { log.info("testTableDefinition6 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String definitions = "define stream TestTable(symbol string, price int, volume float); " + "define table TestTable(symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(definitions); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery7() throws InterruptedException { log.info("testTableDefinition7 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String definitions = "define table TestTable(symbol string, price int, volume float); " + "define stream TestTable(symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(definitions); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = SiddhiParserException.class) public void testQuery8() throws InterruptedException { log.info("testTableDefinition8 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "" + "from StockStream " + "select symbol, price, volume " + "insert into OutputStream;" + "" + "define table OutputStream (symbol string, price float, volume long); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery9() throws InterruptedException { log.info("testTableDefinition9 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "define table OutputStream (symbol string, price float, volume long); " + "" + "from StockStream " + "select symbol, price, volume " + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery10() throws InterruptedException { log.info("testTableDefinition10 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float); " + "define table OutputStream (symbol string, price float, volume long);" + "" + "from StockStream " + "select symbol, price " + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test public void testQuery11() throws InterruptedException { log.info("testTableDefinition11 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "define table OutputStream (symbol string, price int, volume float); " + "" + "from StockStream " + "select symbol, price, volume " + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test public void testQuery12() throws InterruptedException { log.info("testTableDefinition12 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "define table OutputStream (symbol string, price int, volume float); " + "" + "from StockStream " + "select * " + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery13() throws InterruptedException { log.info("testTableDefinition13 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "define table OutputStream (symbol string, price int, volume float, time long); " + "" + "from StockStream " + "select * " + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = DuplicateDefinitionException.class) public void testQuery14() throws InterruptedException { log.info("testTableDefinition14 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "define table OutputStream (symbol string, price int, volume int); " + "" + "from StockStream " + "select * " + "insert into OutputStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = SiddhiAppCreationException.class) public void testQuery15() throws InterruptedException { log.info("testTableDefinition15 - OUT 0"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "define table OutputStream (symbol string, price int, volume float); " + "" + "from OutputStream " + "select symbol, price, volume " + "insert into StockStream;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test public void testQuery16() { log.info("testTableDefinition16 - Table w/ ref"); Map<String, String> systemConfigs = new HashMap<>(); systemConfigs.put("test1.type", "test"); systemConfigs.put("test1.uri", "http://localhost"); InMemoryConfigManager inMemoryConfigManager = new InMemoryConfigManager(null, systemConfigs); inMemoryConfigManager.extractSystemConfigs("test1"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setConfigManager(inMemoryConfigManager); siddhiManager.setExtension("store:test", TestStore.class); String siddhiApp = "" + "@store(ref='test1')" + "define table testTable (symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); Map<String, String> expectedSystemConfigs = new HashMap<>(); expectedSystemConfigs.put("type", "test"); expectedSystemConfigs.put("uri", "http://localhost"); AssertJUnit.assertEquals("Test store initialization failure", expectedSystemConfigs, TestStore.systemConfigs); } @Test public void testQuery17() throws InterruptedException { log.info("testTableDefinition17 - Table w/o ref"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream StockStream(symbol string, price int, volume float);" + "@store(type='test', uri='http://localhost:8080')" + "define table testStore (symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); Map<String, String> expectedSystemConfigs = new HashMap<>(); expectedSystemConfigs.put("type", "test"); expectedSystemConfigs.put("uri", "http://localhost:8080"); AssertJUnit.assertEquals("Test store initialization failure", expectedSystemConfigs, TestStore.systemConfigs); } @Test public void testQuery18() { log.info("testTableDefinition18 - Table w/ ref and additional properties"); Map<String, String> systemConfigs = new HashMap<>(); systemConfigs.put("test1.type", "test"); systemConfigs.put("test1.uri", "http://localhost"); InMemoryConfigManager inMemoryConfigManager = new InMemoryConfigManager(null, systemConfigs); inMemoryConfigManager.extractSystemConfigs("test1"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setConfigManager(inMemoryConfigManager); siddhiManager.setExtension("store:test", TestStore.class); String siddhiApp = "" + "@store(ref='test1', uri='http://localhost:8080', table.name ='Foo')" + "define table testTable (symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); Map<String, String> expectedSystemConfigs = new HashMap<>(); expectedSystemConfigs.put("type", "test"); expectedSystemConfigs.put("uri", "http://localhost:8080"); expectedSystemConfigs.put("table.name", "Foo"); AssertJUnit.assertEquals("Test store initialization failure", expectedSystemConfigs, TestStore.systemConfigs); } @Test(expectedExceptions = SiddhiAppCreationException.class) public void testQuery19() { log.info("testTableDefinition19 - Table w/ ref w/o type"); Map<String, String> systemConfigs = new HashMap<>(); systemConfigs.put("test1.uri", "http://localhost"); InMemoryConfigManager inMemoryConfigManager = new InMemoryConfigManager(null, systemConfigs); inMemoryConfigManager.extractSystemConfigs("test1"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setConfigManager(inMemoryConfigManager); siddhiManager.setExtension("store:test", TestStore.class); String siddhiApp = "" + "@store(ref='test1', uri='http://localhost:8080', table.name ='Foo')" + "define table testTable (symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = SiddhiAppCreationException.class) public void testQuery20() { log.info("testTableDefinition20 - Table w/ ref to an undefined store"); Map<String, String> systemConfigs = new HashMap<>(); systemConfigs.put("test1.uri", "http://localhost"); InMemoryConfigManager inMemoryConfigManager = new InMemoryConfigManager(null, systemConfigs); inMemoryConfigManager.extractSystemConfigs("test2"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setConfigManager(inMemoryConfigManager); siddhiManager.setExtension("store:test", TestStore.class); String siddhiApp = "" + "@store(ref='test2', uri='http://localhost:8080', table.name ='Foo')" + "define table testTable (symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } @Test(expectedExceptions = SiddhiAppCreationException.class) public void testQuery21() { log.info("testTableDefinition21 - Table w/ ref to an undefined store type"); Map<String, String> systemConfigs = new HashMap<>(); systemConfigs.put("test1.type", "testdb"); systemConfigs.put("test1.uri", "http://localhost"); InMemoryConfigManager inMemoryConfigManager = new InMemoryConfigManager(null, systemConfigs); inMemoryConfigManager.extractSystemConfigs("test2"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.setConfigManager(inMemoryConfigManager); siddhiManager.setExtension("store:test", TestStore.class); String siddhiApp = "" + "@store(ref='test2', uri='http://localhost:8080', table.name ='Foo')" + "define table testTable (symbol string, price int, volume float); "; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.shutdown(); } }
apache-2.0
smmribeiro/intellij-community
plugins/InspectionGadgets/testsrc/com/siyeh/ig/jdk/ForwardCompatibilityInspectionTest.java
2006
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.siyeh.ig.jdk; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.openapi.module.LanguageLevelUtil; import com.intellij.openapi.module.Module; import com.intellij.pom.java.LanguageLevel; import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.LightProjectDescriptor; import com.siyeh.ig.LightJavaInspectionTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ForwardCompatibilityInspectionTest extends LightJavaInspectionTestCase { @Override protected String getBasePath() { return LightJavaInspectionTestCase.INSPECTION_GADGETS_TEST_DATA_PATH + "com/siyeh/igtest/jdk/forward_compatibility"; } @Nullable @Override protected InspectionProfileEntry getInspection() { return new ForwardCompatibilityInspection(); } @NotNull @Override protected LightProjectDescriptor getProjectDescriptor() { return JAVA_8; } public void testAssert() { withLevel(LanguageLevel.JDK_1_3, this::doTest); } public void testEnum() { withLevel(LanguageLevel.JDK_1_3, this::doTest); } public void testUnqualifiedYield() { doTest(); } public void testUnderscore() { doTest(); } public void testRestrictedKeywordWarning() { doTest(); } public void testModuleInfoWarning() { withLevel(LanguageLevel.JDK_1_9, () -> { myFixture.configureByFile("module-info.java"); myFixture.testHighlighting(true, false, false); }); } public void withLevel(LanguageLevel languageLevel, Runnable runnable) { Module module = getModule(); LanguageLevel prev = LanguageLevelUtil.getCustomLanguageLevel(module); IdeaTestUtil.setModuleLanguageLevel(module, languageLevel); try { runnable.run(); } finally { IdeaTestUtil.setModuleLanguageLevel(module, prev); } } }
apache-2.0
tkafalas/pentaho-kettle
core/src/main/java/org/pentaho/di/core/row/SpeedTest.java
8136
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2020 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.core.row; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.value.ValueMetaBoolean; import org.pentaho.di.core.row.value.ValueMetaDate; import org.pentaho.di.core.row.value.ValueMetaInteger; import org.pentaho.di.core.row.value.ValueMetaNumber; import org.pentaho.di.core.row.value.ValueMetaString; import org.pentaho.di.core.util.StringUtil; public class SpeedTest { private static final Log log = LogFactory.getLog( SpeedTest.class ); private Object[] rowString10; private Object[] rowString100; private Object[] rowString1000; private Object[] rowMixed10; private Object[] rowMixed100; private Object[] rowMixed1000; private RowMetaInterface metaString10; private RowMetaInterface metaMixed10; private RowMetaInterface metaString100; private RowMetaInterface metaMixed100; private RowMetaInterface metaString1000; private RowMetaInterface metaMixed1000; public SpeedTest() { rowString10 = new Object[10]; rowString100 = new Object[100]; rowString1000 = new Object[1000]; rowMixed10 = new Object[50]; rowMixed100 = new Object[500]; rowMixed1000 = new Object[5000]; metaString10 = new RowMeta(); metaMixed10 = new RowMeta(); metaString100 = new RowMeta(); metaMixed100 = new RowMeta(); metaString1000 = new RowMeta(); metaMixed1000 = new RowMeta(); for ( int i = 0; i < 10; i++ ) { populateMetaAndData( i, rowString10, metaString10, rowMixed10, metaMixed10 ); } for ( int i = 0; i < 100; i++ ) { populateMetaAndData( i, rowString100, metaString100, rowMixed100, metaMixed100 ); } for ( int i = 0; i < 1000; i++ ) { populateMetaAndData( i, rowString1000, metaString1000, rowMixed1000, metaMixed1000 ); } } private static void populateMetaAndData( int i, Object[] rowString10, RowMetaInterface metaString10, Object[] rowMixed10, RowMetaInterface metaMixed10 ) { String strNamePrefix = "String"; rowString10[i] = StringUtil.generateRandomString( 20, "", "", false ); ValueMetaInterface meta = new ValueMetaString( strNamePrefix + ( i + 1 ), 20, 0 ); metaString10.addValueMeta( meta ); rowMixed10[i * 5 + 0] = StringUtil.generateRandomString( 20, "", "", false ); ValueMetaInterface meta0 = new ValueMetaString( strNamePrefix + ( i * 5 + 1 ), 20, 0 ); metaMixed10.addValueMeta( meta0 ); rowMixed10[i * 5 + 1] = new Date(); ValueMetaInterface meta1 = new ValueMetaDate( strNamePrefix + ( i * 5 + 1 ) ); metaMixed10.addValueMeta( meta1 ); rowMixed10[i * 5 + 2] = Double.valueOf( Math.random() * 1000000 ); ValueMetaInterface meta2 = new ValueMetaNumber( strNamePrefix + ( i * 5 + 1 ), 12, 4 ); metaMixed10.addValueMeta( meta2 ); rowMixed10[i * 5 + 3] = Long.valueOf( (long) ( Math.random() * 1000000 ) ); ValueMetaInterface meta3 = new ValueMetaInteger( strNamePrefix + ( i * 5 + 1 ), 8, 0 ); metaMixed10.addValueMeta( meta3 ); rowMixed10[i * 5 + 4] = Boolean.valueOf( Math.random() > 0.5 ); ValueMetaInterface meta4 = new ValueMetaBoolean( strNamePrefix + ( i * 5 + 1 ) ); metaMixed10.addValueMeta( meta4 ); } public long runTestStrings10( int iterations ) throws KettleValueException { long startTime = System.currentTimeMillis(); for ( int i = 0; i < iterations; i++ ) { metaString10.cloneRow( rowString10 ); } long stopTime = System.currentTimeMillis(); return stopTime - startTime; } public long runTestMixed10( int iterations ) throws KettleValueException { long startTime = System.currentTimeMillis(); for ( int i = 0; i < iterations; i++ ) { metaMixed10.cloneRow( rowMixed10 ); } long stopTime = System.currentTimeMillis(); return stopTime - startTime; } public long runTestStrings100( int iterations ) throws KettleValueException { long startTime = System.currentTimeMillis(); for ( int i = 0; i < iterations; i++ ) { metaString100.cloneRow( rowString100 ); } long stopTime = System.currentTimeMillis(); return stopTime - startTime; } public long runTestMixed100( int iterations ) throws KettleValueException { long startTime = System.currentTimeMillis(); for ( int i = 0; i < iterations; i++ ) { metaMixed100.cloneRow( rowMixed100 ); } long stopTime = System.currentTimeMillis(); return stopTime - startTime; } public long runTestStrings1000( int iterations ) throws KettleValueException { long startTime = System.currentTimeMillis(); for ( int i = 0; i < iterations; i++ ) { metaString1000.cloneRow( rowString1000 ); } long stopTime = System.currentTimeMillis(); return stopTime - startTime; } public long runTestMixed1000( int iterations ) throws KettleValueException { long startTime = System.currentTimeMillis(); for ( int i = 0; i < iterations; i++ ) { metaMixed1000.cloneRow( rowMixed1000 ); } long stopTime = System.currentTimeMillis(); return stopTime - startTime; } public static final int ITERATIONS = 1000000; public static void main( String[] args ) throws KettleValueException { SpeedTest speedTest = new SpeedTest(); String strTimesPrefix = " times : "; String strMsPrefix = " ms ("; String strRowPerSec = " r/s)\n"; // Found a speed boost in adding to a string builder, then logging rather than logging each time. StringBuilder runtimeTestMessage = new StringBuilder(); long timeString10 = speedTest.runTestStrings10( ITERATIONS ); runtimeTestMessage.append( "\nTime to run 'String10' test " + ITERATIONS + strTimesPrefix + timeString10 + strMsPrefix + ( 1000 * ITERATIONS / timeString10 ) + strRowPerSec ); long timeMixed10 = speedTest.runTestMixed10( ITERATIONS ); runtimeTestMessage.append( "Time to run 'Mixed10' test " + ITERATIONS + strTimesPrefix + timeMixed10 + strMsPrefix + ( 1000 * ITERATIONS / timeMixed10 ) + strRowPerSec ); long timeString100 = speedTest.runTestStrings100( ITERATIONS ); runtimeTestMessage.append( "Time to run 'String100' test " + ITERATIONS + strTimesPrefix + timeString100 + strMsPrefix + ( 1000 * ITERATIONS / timeString100 ) + strRowPerSec ); long timeMixed100 = speedTest.runTestMixed100( ITERATIONS ); runtimeTestMessage.append( "Time to run 'Mixed100' test " + ITERATIONS + strTimesPrefix + timeMixed100 + strMsPrefix + ( 1000 * ITERATIONS / timeMixed100 ) + strRowPerSec ); long timeString1000 = speedTest.runTestStrings1000( ITERATIONS ); runtimeTestMessage.append( "Time to run 'String1000' test " + ITERATIONS + strTimesPrefix + timeString1000 + strMsPrefix + ( 1000 * ITERATIONS / timeString1000 ) + strRowPerSec ); long timeMixed1000 = speedTest.runTestMixed1000( ITERATIONS ); runtimeTestMessage.append( "Time to run 'Mixed1000' test " + ITERATIONS + strTimesPrefix + timeMixed1000 + strMsPrefix + ( 1000 * ITERATIONS / timeMixed1000 ) + strRowPerSec ); log.info( runtimeTestMessage ); } }
apache-2.0
meiercaleb/incubator-rya
extras/rya.giraph/src/main/java/org/apache/rya/giraph/format/RyaEdgeInputFormat.java
2409
package org.apache.rya.giraph.format; /* * 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. */ import java.io.IOException; import java.util.List; import org.apache.giraph.io.EdgeInputFormat; import org.apache.giraph.io.EdgeReader; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.Text; import org.apache.rya.accumulo.mr.RyaInputFormat; import org.apache.rya.accumulo.mr.RyaInputFormat.RyaStatementRecordReader; import org.apache.rya.accumulo.mr.RyaStatementWritable; import org.apache.rya.api.RdfCloudTripleStoreConstants.TABLE_LAYOUT; import org.apache.rya.api.resolver.RyaTripleContext; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.TaskAttemptContext; public class RyaEdgeInputFormat extends EdgeInputFormat<Text, RyaStatementWritable> { private RyaInputFormat ryaInputFormat = new RyaInputFormat(); private TABLE_LAYOUT rdfTableLayout; private RyaTripleContext tripleContext; @Override public EdgeReader<Text, RyaStatementWritable> createEdgeReader(InputSplit split, TaskAttemptContext context) throws IOException { return new RyaEdgeReader((RyaStatementRecordReader) ryaInputFormat.createRecordReader(split, context), rdfTableLayout, tripleContext, context.getConfiguration()); } @Override public void checkInputSpecs(Configuration arg0) { // nothing to do } @Override public List<InputSplit> getSplits(JobContext context, int arg1) throws IOException, InterruptedException { return ryaInputFormat.getSplits(context); } }
apache-2.0
senorcris/Atlas-Android
layer-atlas-messenger/src/main/java/com/layer/atlas/messenger/AtlasMessagesScreen.java
24874
/* * Copyright (c) 2015 Layer. 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.layer.atlas.messenger; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Locale; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.layer.atlas.Atlas; import com.layer.atlas.Atlas.Participant; import com.layer.atlas.Atlas.Tools; import com.layer.atlas.AtlasMessageComposer; import com.layer.atlas.AtlasMessagesList; import com.layer.atlas.AtlasMessagesList.Cell; import com.layer.atlas.AtlasMessagesList.ItemClickListener; import com.layer.atlas.AtlasParticipantPicker; import com.layer.atlas.AtlasTypingIndicator; import com.layer.atlas.cells.ImageCell; import com.layer.atlas.messenger.MessengerApp.keys; import com.layer.sdk.LayerClient; import com.layer.sdk.changes.LayerChangeEvent; import com.layer.sdk.listeners.LayerChangeEventListener; import com.layer.sdk.messaging.Conversation; import com.layer.sdk.messaging.ConversationOptions; import com.layer.sdk.messaging.Message; import com.layer.sdk.messaging.MessagePart; import com.layer.sdk.query.Predicate; import com.layer.sdk.query.Query; import com.layer.sdk.query.SortDescriptor; /** * @author Oleg Orlov * @since 14 Apr 2015 */ public class AtlasMessagesScreen extends Activity { private static final String TAG = AtlasMessagesScreen.class.getSimpleName(); private static final boolean debug = false; public static final String EXTRA_CONVERSATION_IS_NEW = "conversation.new"; public static final String EXTRA_CONVERSATION_URI = keys.CONVERSATION_URI; public static final int REQUEST_CODE_SETTINGS = 101; public static final int REQUEST_CODE_GALLERY = 111; public static final int REQUEST_CODE_CAMERA = 112; /** Switch it to <code>true</code> to see {@link #AtlasMessagesScreen()} Query support in action */ private static final boolean USE_QUERY = false; private volatile Conversation conv; private LocationManager locationManager; private Location lastKnownLocation; private Handler uiHandler; private AtlasMessagesList messagesList; private AtlasMessageComposer messageComposer; private AtlasParticipantPicker participantsPicker; private AtlasTypingIndicator typingIndicator; private MessengerApp app; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.uiHandler = new Handler(); this.app = (MessengerApp) getApplication(); setContentView(R.layout.atlas_screen_messages); boolean convIsNew = getIntent().getBooleanExtra(EXTRA_CONVERSATION_IS_NEW, false); String convUri = getIntent().getStringExtra(EXTRA_CONVERSATION_URI); if (convUri != null) { Uri uri = Uri.parse(convUri); conv = app.getLayerClient().getConversation(uri); ((NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE)).cancel(convUri.hashCode()); // Clear notifications for this Conversation } participantsPicker = (AtlasParticipantPicker) findViewById(R.id.atlas_screen_messages_participants_picker); participantsPicker.init(new String[]{app.getLayerClient().getAuthenticatedUserId()}, app.getParticipantProvider()); if (convIsNew) { participantsPicker.setVisibility(View.VISIBLE); } messageComposer = (AtlasMessageComposer) findViewById(R.id.atlas_screen_messages_message_composer); messageComposer.init(app.getLayerClient(), conv); messageComposer.setListener(new AtlasMessageComposer.Listener() { public boolean beforeSend(Message message) { boolean conversationReady = ensureConversationReady(); if (!conversationReady) return false; // push preparePushMetadata(message); return true; } }); messageComposer.registerMenuItem("Photo", new OnClickListener() { public void onClick(View v) { if (!ensureConversationReady()) return; Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); String fileName = "cameraOutput" + System.currentTimeMillis() + ".jpg"; photoFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName); final Uri outputUri = Uri.fromFile(photoFile); cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri); if (debug) Log.w(TAG, "onClick() requesting photo to file: " + fileName + ", uri: " + outputUri); startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA); } }); messageComposer.registerMenuItem("Image", new OnClickListener() { public void onClick(View v) { if (!ensureConversationReady()) return; // in onCreate or any event where your want the user to select a file Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_CODE_GALLERY); } }); messageComposer.registerMenuItem("Location", new OnClickListener() { public void onClick(View v) { if (!ensureConversationReady()) return; if (lastKnownLocation == null) { Toast.makeText(v.getContext(), "Inserting Location: Location is unknown yet", Toast.LENGTH_SHORT).show(); return; } String locationString = "{\"lat\":" + lastKnownLocation.getLatitude() + ", \"lon\":" + lastKnownLocation.getLongitude() + "}"; MessagePart part = app.getLayerClient().newMessagePart(Atlas.MIME_TYPE_ATLAS_LOCATION, locationString.getBytes()); Message message = app.getLayerClient().newMessage(Arrays.asList(part)); preparePushMetadata(message); conv.send(message); if (debug) Log.w(TAG, "onSendLocation() loc: " + locationString); } }); messagesList = (AtlasMessagesList) findViewById(R.id.atlas_screen_messages_messages_list); messagesList.init(app.getLayerClient(), app.getParticipantProvider()); if (USE_QUERY) { Query<Message> query = Query.builder(Message.class) .predicate(new Predicate(Message.Property.CONVERSATION, Predicate.Operator.EQUAL_TO, conv)) .sortDescriptor(new SortDescriptor(Message.Property.POSITION, SortDescriptor.Order.ASCENDING)) .build(); messagesList.setQuery(query); } else { messagesList.setConversation(conv); } messagesList.setItemClickListener(new ItemClickListener() { public void onItemClick(Cell cell) { if (Atlas.MIME_TYPE_ATLAS_LOCATION.equals(cell.messagePart.getMimeType())) { String jsonLonLat = new String(cell.messagePart.getData()); JSONObject json; try { json = new JSONObject(jsonLonLat); double lon = json.getDouble("lon"); double lat = json.getDouble("lat"); Intent openMapIntent = new Intent(Intent.ACTION_VIEW); String uriString = String.format(Locale.ENGLISH, "geo:%f,%f?z=%d&q=%f,%f", lat, lon, 18, lat, lon); final Uri geoUri = Uri.parse(uriString); openMapIntent.setData(geoUri); if (openMapIntent.resolveActivity(getPackageManager()) != null) { startActivity(openMapIntent); if (debug) Log.w(TAG, "onItemClick() starting Map: " + uriString); } else { if (debug) Log.w(TAG, "onItemClick() No Activity to start Map: " + geoUri); } } catch (JSONException ignored) { } } else if (cell instanceof ImageCell) { Intent intent = new Intent(AtlasMessagesScreen.this.getApplicationContext(), AtlasImageViewScreen.class); app.setParam(intent, cell); startActivity(intent); } } }); typingIndicator = (AtlasTypingIndicator)findViewById(R.id.atlas_screen_messages_typing_indicator); typingIndicator.init(conv, new AtlasTypingIndicator.DefaultTypingIndicatorCallback(app.getParticipantProvider())); // location manager for inserting locations: this.locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); prepareActionBar(); } private void updateValues() { if (conv == null) { Log.e(TAG, "updateValues() no conversation set"); return; } TextView titleText = (TextView) findViewById(R.id.atlas_actionbar_title_text); titleText.setText(Atlas.getTitle(conv, app.getParticipantProvider(), app.getLayerClient().getAuthenticatedUserId())); } private boolean ensureConversationReady() { if (conv != null) return true; // create new one String[] userIds = participantsPicker.getSelectedUserIds(); // no people, no conversation if (userIds.length == 0) { Toast.makeText(this, "Conversation cannot be created without participants", Toast.LENGTH_SHORT).show(); return false; } conv = app.getLayerClient().newConversation(new ConversationOptions().distinct(false), userIds); participantsPicker.setVisibility(View.GONE); messageComposer.setConversation(conv); messagesList.setConversation(conv); typingIndicator.setConversation(conv); updateValues(); return true; } private void preparePushMetadata(Message message) { Participant me = app.getParticipantProvider().getParticipant(app.getLayerClient().getAuthenticatedUserId()); String senderName = Atlas.getFullName(me); String text = Atlas.Tools.toString(message); if (!text.isEmpty()) { if (senderName != null && !senderName.isEmpty()) { message.getOptions().pushNotificationMessage(senderName + ": " + text); } else { message.getOptions().pushNotificationMessage(text); } } } /** used to take photos from camera */ private File photoFile = null; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (debug) Log.w(TAG, "onActivityResult() requestCode: " + requestCode + ", resultCode: " + resultCode + ", uri: " + (data == null ? "" : data.getData()) + ", data: " + (data == null ? "" : MessengerApp.toString(data.getExtras())) ); if (resultCode != Activity.RESULT_OK) return; final LayerClient layerClient = ((MessengerApp) getApplication()).getLayerClient(); switch (requestCode) { case REQUEST_CODE_CAMERA : if (photoFile == null) { if (debug) Log.w(TAG, "onActivityResult() taking photo, but output is undefined... "); return; } if (!photoFile.exists()) { if (debug) Log.w(TAG, "onActivityResult() taking photo, but photo file doesn't exist: " + photoFile.getPath()); return; } if (photoFile.length() == 0) { if (debug) Log.w(TAG, "onActivityResult() taking photo, but photo file is empty: " + photoFile.getPath()); return; } try { // prepare original final File originalFile = photoFile; FileInputStream fisOriginal = new FileInputStream(originalFile) { public void close() throws IOException { super.close(); boolean deleted = originalFile.delete(); if (debug) Log.w(TAG, "close() original file is" + (!deleted ? " not" : "") + " removed: " + originalFile.getName()); photoFile = null; } }; final MessagePart originalPart = layerClient.newMessagePart(Atlas.MIME_TYPE_IMAGE_JPEG, fisOriginal, originalFile.length()); File tempDir = getCacheDir(); MessagePart[] previewAndSize = Atlas.buildPreviewAndSize(originalFile, layerClient, tempDir); if (previewAndSize == null) { Log.e(TAG, "onActivityResult() cannot build preview, cancel send..."); return; } Message msg = layerClient.newMessage(originalPart, previewAndSize[0], previewAndSize[1]); if (debug) Log.w(TAG, "onActivityResult() sending photo... "); preparePushMetadata(msg); conv.send(msg); } catch (Exception e) { Log.e(TAG, "onActivityResult() cannot insert photo" + e); } break; case REQUEST_CODE_GALLERY : if (data == null) { if (debug) Log.w(TAG, "onActivityResult() insert from gallery: no data... :( "); return; } // first check media gallery Uri selectedImageUri = data.getData(); // TODO: Mi4 requires READ_EXTERNAL_STORAGE permission for such operation String selectedImagePath = getGalleryImagePath(selectedImageUri); String resultFileName = selectedImagePath; if (selectedImagePath != null) { if (debug) Log.w(TAG, "onActivityResult() image from gallery selected: " + selectedImagePath); } else if (selectedImageUri.getPath() != null) { if (debug) Log.w(TAG, "onActivityResult() image from file picker appears... " + selectedImageUri.getPath()); resultFileName = selectedImageUri.getPath(); } if (resultFileName != null) { String mimeType = Atlas.MIME_TYPE_IMAGE_JPEG; if (resultFileName.endsWith(".png")) mimeType = Atlas.MIME_TYPE_IMAGE_PNG; if (resultFileName.endsWith(".gif")) mimeType = Atlas.MIME_TYPE_IMAGE_GIF; // test file copy locally try { // create message and upload content InputStream fis = null; File fileToUpload = new File(resultFileName); if (fileToUpload.exists()) { fis = new FileInputStream(fileToUpload); } else { if (debug) Log.w(TAG, "onActivityResult() file to upload doesn't exist, path: " + resultFileName + ", trying ContentResolver"); fis = getContentResolver().openInputStream(data.getData()); if (fis == null) { if (debug) Log.w(TAG, "onActivityResult() cannot open stream with ContentResolver, uri: " + data.getData()); } } String fileName = "galleryFile" + System.currentTimeMillis() + ".jpg"; final File originalFile = new File(getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES), fileName); OutputStream fos = new FileOutputStream(originalFile); int totalBytes = Tools.streamCopyAndClose(fis, fos); if (debug) Log.w(TAG, "onActivityResult() copied " + totalBytes + " to file: " + originalFile.getName()); FileInputStream fisOriginal = new FileInputStream(originalFile) { public void close() throws IOException { super.close(); boolean deleted = originalFile.delete(); if (debug) Log.w(TAG, "close() original file is" + (!deleted ? " not" : "") + " removed: " + originalFile.getName()); } }; final MessagePart originalPart = layerClient.newMessagePart(mimeType, fisOriginal, originalFile.length()); File tempDir = getCacheDir(); MessagePart[] previewAndSize = Atlas.buildPreviewAndSize(originalFile, layerClient, tempDir); if (previewAndSize == null) { Log.e(TAG, "onActivityResult() cannot build preview, cancel send..."); return; } Message msg = layerClient.newMessage(originalPart, previewAndSize[0], previewAndSize[1]); if (debug) Log.w(TAG, "onActivityResult() uploaded " + originalFile.length() + " bytes"); preparePushMetadata(msg); conv.send(msg); } catch (Exception e) { Log.e(TAG, "onActivityResult() cannot upload file: " + resultFileName, e); return; } } break; default : break; } } /** * pick file name from content provider with Gallery-flavor format */ public String getGalleryImagePath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor == null) { return null; // uri could be not suitable for ContentProviders, i.e. points to file } int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } @Override protected void onResume() { super.onResume(); updateValues(); messagesList.jumpToLastMessage(); // restore location tracking int requestLocationTimeout = 1 * 1000; // every second int distance = 100; Location loc = null; if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) { loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (debug) Log.w(TAG, "onResume() location from gps: " + loc); } if (loc == null && locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) { loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (debug) Log.w(TAG, "onResume() location from network: " + loc); } if (loc != null && loc.getTime() < System.currentTimeMillis() + LOCATION_EXPIRATION_TIME) { locationTracker.onLocationChanged(loc); } if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, requestLocationTimeout, distance, locationTracker); } if (locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null) { locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, requestLocationTimeout, distance, locationTracker); } app.getLayerClient().registerEventListener(messagesList); app.getLayerClient().registerTypingIndicator(typingIndicator.clear()); // when something changed app.getLayerClient().registerEventListener(new LayerChangeEventListener.MainThread() { public void onEventMainThread(LayerChangeEvent event) { updateValues(); } }); } private static final int LOCATION_EXPIRATION_TIME = 60 * 1000; // 1 minute LocationListener locationTracker = new LocationListener() { @Override public void onLocationChanged(final Location location) { uiHandler.post(new Runnable() { @Override public void run() { lastKnownLocation = location; if (debug) Log.d(TAG, "onLocationChanged() location: " + location); } }); } public void onStatusChanged(String provider, int status, Bundle extras) {} public void onProviderEnabled(String provider) {} public void onProviderDisabled(String provider) {} }; @Override protected void onPause() { super.onPause(); locationManager.removeUpdates(locationTracker); app.getLayerClient().unregisterEventListener(messagesList); app.getLayerClient().unregisterTypingIndicator(typingIndicator.clear()); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (debug) Log.w(TAG, "onConfigurationChanged() newConfig: " + newConfig); updateValues(); messagesList.jumpToLastMessage(); } private void prepareActionBar() { ImageView menuBtn = (ImageView) findViewById(R.id.atlas_actionbar_left_btn); menuBtn.setImageResource(R.drawable.atlas_ctl_btn_back); menuBtn.setVisibility(View.VISIBLE); menuBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); ((TextView)findViewById(R.id.atlas_actionbar_title_text)).setText("Messages"); ((TextView)findViewById(R.id.atlas_actionbar_title_text)).setOnClickListener(new OnClickListener() { public void onClick(View v) { messagesList.requestRefreshValues(true, false); } }); ImageView settingsBtn = (ImageView) findViewById(R.id.atlas_actionbar_right_btn); settingsBtn.setImageResource(R.drawable.atlas_ctl_btn_detail); settingsBtn.setVisibility(View.VISIBLE); settingsBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (conv == null) return; AtlasConversationSettingsScreen.conv = conv; Intent intent = new Intent(v.getContext(), AtlasConversationSettingsScreen.class); startActivityForResult(intent, REQUEST_CODE_SETTINGS); } }); Tools.setStatusBarColor(getWindow(), getResources().getColor(R.color.atlas_background_blue_dark)); } }
apache-2.0
floodlight/ubuntu-packaging-floodlight
src/main/java/net/floodlightcontroller/flowcache/IFlowReconcileService.java
2383
/** * Provides Flow Reconcile service to other modules that need to reconcile * flows. */ package net.floodlightcontroller.flowcache; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.devicemanager.IDevice; import net.floodlightcontroller.flowcache.IFlowCacheService.FCQueryEvType; public interface IFlowReconcileService extends IFloodlightService { /** * Add a flow reconcile listener * @param listener The module that can reconcile flows */ public void addFlowReconcileListener(IFlowReconcileListener listener); /** * Remove a flow reconcile listener * @param listener The module that no longer reconcile flows */ public void removeFlowReconcileListener(IFlowReconcileListener listener); /** * Remove all flow reconcile listeners */ public void clearFlowReconcileListeners(); /** * Reconcile flow. Returns false if no modified flow-mod need to be * programmed if cluster ID is providced then pnly flows in the given * cluster are reprogrammed * * @param ofmRcIn the ofm rc in */ public void reconcileFlow(OFMatchReconcile ofmRcIn); /** * Updates the flows to a device after the device moved to a new location * <p> * Queries the flow-cache to get all the flows destined to the given device. * Reconciles each of these flows by potentially reprogramming them to its * new attachment point * * @param device device that has moved * @param fcEvType Event type that triggered the update * */ public void updateFlowForDestinationDevice(IDevice device, FCQueryEvType fcEvType); /** * Updates the flows from a device * <p> * Queries the flow-cache to get all the flows source from the given device. * Reconciles each of these flows by potentially reprogramming them to its * new attachment point * * @param device device where the flow originates * @param fcEvType Event type that triggered the update * */ public void updateFlowForSourceDevice(IDevice device, FCQueryEvType fcEvType); /** * Generic flow query handler to insert FlowMods into the reconcile pipeline. * @param flowResp */ public void flowQueryGenericHandler(FlowCacheQueryResp flowResp); }
apache-2.0
sardine/mina-ja
src/mina-core/src/main/java/org/apache/mina/transport/vmpipe/VmPipeAcceptor.java
5889
/* * 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.mina.transport.vmpipe; import java.io.IOException; import java.net.SocketAddress; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import org.apache.mina.core.future.IoFuture; import org.apache.mina.core.service.AbstractIoAcceptor; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.service.TransportMetadata; import org.apache.mina.core.session.IdleStatusChecker; import org.apache.mina.core.session.IoSession; /** * Binds the specified {@link IoHandler} to the specified * {@link VmPipeAddress}. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ public final class VmPipeAcceptor extends AbstractIoAcceptor { // object used for checking session idle private IdleStatusChecker idleChecker; static final Map<VmPipeAddress, VmPipe> boundHandlers = new HashMap<VmPipeAddress, VmPipe>(); /** * Creates a new instance. */ public VmPipeAcceptor() { this(null); } /** * Creates a new instance. */ public VmPipeAcceptor(Executor executor) { super(new DefaultVmPipeSessionConfig(), executor); idleChecker = new IdleStatusChecker(); // we schedule the idle status checking task in this service exceutor // it will be woke up every seconds executeWorker(idleChecker.getNotifyingTask(), "idleStatusChecker"); } public TransportMetadata getTransportMetadata() { return VmPipeSession.METADATA; } @Override public VmPipeSessionConfig getSessionConfig() { return (VmPipeSessionConfig) super.getSessionConfig(); } @Override public VmPipeAddress getLocalAddress() { return (VmPipeAddress) super.getLocalAddress(); } @Override public VmPipeAddress getDefaultLocalAddress() { return (VmPipeAddress) super.getDefaultLocalAddress(); } // This method is overriden to work around a problem with // bean property access mechanism. public void setDefaultLocalAddress(VmPipeAddress localAddress) { super.setDefaultLocalAddress(localAddress); } @Override protected IoFuture dispose0() throws Exception { // stop the idle checking task idleChecker.getNotifyingTask().cancel(); unbind(); return null; } @Override protected Set<SocketAddress> bindInternal(List<? extends SocketAddress> localAddresses) throws IOException { Set<SocketAddress> newLocalAddresses = new HashSet<SocketAddress>(); synchronized (boundHandlers) { for (SocketAddress a: localAddresses) { VmPipeAddress localAddress = (VmPipeAddress) a; if (localAddress == null || localAddress.getPort() == 0) { localAddress = null; for (int i = 10000; i < Integer.MAX_VALUE; i++) { VmPipeAddress newLocalAddress = new VmPipeAddress(i); if (!boundHandlers.containsKey(newLocalAddress) && !newLocalAddresses.contains(newLocalAddress)) { localAddress = newLocalAddress; break; } } if (localAddress == null) { throw new IOException("No port available."); } } else if (localAddress.getPort() < 0) { throw new IOException("Bind port number must be 0 or above."); } else if (boundHandlers.containsKey(localAddress)) { throw new IOException("Address already bound: " + localAddress); } newLocalAddresses.add(localAddress); } for (SocketAddress a: newLocalAddresses) { VmPipeAddress localAddress = (VmPipeAddress) a; if (!boundHandlers.containsKey(localAddress)) { boundHandlers.put(localAddress, new VmPipe(this, localAddress, getHandler(), getListeners())); } else { for (SocketAddress a2: newLocalAddresses) { boundHandlers.remove(a2); } throw new IOException("Duplicate local address: " + a); } } } return newLocalAddresses; } @Override protected void unbind0(List<? extends SocketAddress> localAddresses) { synchronized (boundHandlers) { for (SocketAddress a: localAddresses) { boundHandlers.remove(a); } } } public IoSession newSession(SocketAddress remoteAddress, SocketAddress localAddress) { throw new UnsupportedOperationException(); } void doFinishSessionInitialization(IoSession session, IoFuture future) { initSession(session, future, null); } }
apache-2.0
irudyak/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/GridCacheTransactionalAbstractMetricsSelfTest.java
12545
/* * 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.ignite.internal.processors.cache; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteTransactions; import org.apache.ignite.cache.CacheMetrics; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.GridTestUtils; import org.apache.ignite.transactions.Transaction; import org.apache.ignite.transactions.TransactionConcurrency; import org.apache.ignite.transactions.TransactionIsolation; import org.apache.ignite.transactions.TransactionMetrics; import static org.apache.ignite.transactions.TransactionConcurrency.OPTIMISTIC; import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC; import static org.apache.ignite.transactions.TransactionIsolation.READ_COMMITTED; import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ; import static org.apache.ignite.transactions.TransactionIsolation.SERIALIZABLE; import static org.apache.ignite.transactions.TransactionState.ROLLED_BACK; /** * Transactional cache metrics test. */ public abstract class GridCacheTransactionalAbstractMetricsSelfTest extends GridCacheAbstractMetricsSelfTest { /** */ private static final int TX_CNT = 3; /** Transaction timeout. */ private static final long TX_TIMEOUT = 500L; /** * @throws Exception If failed. */ public void testOptimisticReadCommittedCommits() throws Exception { testCommits(OPTIMISTIC, READ_COMMITTED, true); } /** * @throws Exception If failed. */ public void testOptimisticReadCommittedCommitsNoData() throws Exception { testCommits(OPTIMISTIC, READ_COMMITTED, false); } /** * @throws Exception If failed. */ public void testOptimisticRepeatableReadCommits() throws Exception { testCommits(OPTIMISTIC, REPEATABLE_READ, true); } /** * @throws Exception If failed. */ public void testOptimisticRepeatableReadCommitsNoData() throws Exception { testCommits(OPTIMISTIC, REPEATABLE_READ, false); } /** * @throws Exception If failed. */ public void testOptimisticSerializableCommits() throws Exception { testCommits(OPTIMISTIC, SERIALIZABLE, true); } /** * @throws Exception If failed. */ public void testOptimisticSerializableCommitsNoData() throws Exception { testCommits(OPTIMISTIC, SERIALIZABLE, false); } /** * @throws Exception If failed. */ public void testPessimisticReadCommittedCommits() throws Exception { testCommits(PESSIMISTIC, READ_COMMITTED, true); } /** * @throws Exception If failed. */ public void testPessimisticReadCommittedCommitsNoData() throws Exception { testCommits(PESSIMISTIC, READ_COMMITTED, false); } /** * @throws Exception If failed. */ public void testPessimisticRepeatableReadCommits() throws Exception { testCommits(PESSIMISTIC, REPEATABLE_READ, true); } /** * @throws Exception If failed. */ public void testPessimisticRepeatableReadCommitsNoData() throws Exception { testCommits(PESSIMISTIC, REPEATABLE_READ, false); } /** * @throws Exception If failed. */ public void testPessimisticSerializableCommits() throws Exception { testCommits(PESSIMISTIC, SERIALIZABLE, true); } /** * @throws Exception If failed. */ public void testPessimisticSerializableCommitsNoData() throws Exception { testCommits(PESSIMISTIC, SERIALIZABLE, false); } /** * @throws Exception If failed. */ public void testOptimisticReadCommittedRollbacks() throws Exception { testRollbacks(OPTIMISTIC, READ_COMMITTED, true); } /** * @throws Exception If failed. */ public void testOptimisticReadCommittedRollbacksNoData() throws Exception { testRollbacks(OPTIMISTIC, READ_COMMITTED, false); } /** * @throws Exception If failed. */ public void testOptimisticRepeatableReadRollbacks() throws Exception { testRollbacks(OPTIMISTIC, REPEATABLE_READ, true); } /** * @throws Exception If failed. */ public void testOptimisticRepeatableReadRollbacksNoData() throws Exception { testRollbacks(OPTIMISTIC, REPEATABLE_READ, false); } /** * @throws Exception If failed. */ public void testOptimisticSerializableRollbacks() throws Exception { testRollbacks(OPTIMISTIC, SERIALIZABLE, true); } /** * @throws Exception If failed. */ public void testOptimisticSerializableRollbacksNoData() throws Exception { testRollbacks(OPTIMISTIC, SERIALIZABLE, false); } /** * @throws Exception If failed. */ public void testPessimisticReadCommittedRollbacks() throws Exception { testRollbacks(PESSIMISTIC, READ_COMMITTED, true); } /** * @throws Exception If failed. */ public void testPessimisticReadCommittedRollbacksNoData() throws Exception { testRollbacks(PESSIMISTIC, READ_COMMITTED, false); } /** * @throws Exception If failed. */ public void testPessimisticRepeatableReadRollbacks() throws Exception { testRollbacks(PESSIMISTIC, REPEATABLE_READ, true); } /** * @throws Exception If failed. */ public void testPessimisticRepeatableReadRollbacksNoData() throws Exception { testRollbacks(PESSIMISTIC, REPEATABLE_READ, false); } /** * @throws Exception If failed. */ public void testPessimisticSerializableRollbacks() throws Exception { testRollbacks(PESSIMISTIC, SERIALIZABLE, true); } /** * @throws Exception If failed. */ public void testPessimisticSerializableRollbacksNoData() throws Exception { testRollbacks(PESSIMISTIC, SERIALIZABLE, false); } /** * @throws Exception If failed. */ public void testOptimisticSuspendedReadCommittedTxTimeoutRollbacks() throws Exception { doTestSuspendedTxTimeoutRollbacks(OPTIMISTIC, READ_COMMITTED); } /** * @throws Exception If failed. */ public void testOptimisticSuspendedRepeatableReadTxTimeoutRollbacks() throws Exception { doTestSuspendedTxTimeoutRollbacks(OPTIMISTIC, REPEATABLE_READ); } /** * @throws Exception If failed. */ public void testOptimisticSuspendedSerializableTxTimeoutRollbacks() throws Exception { doTestSuspendedTxTimeoutRollbacks(OPTIMISTIC, SERIALIZABLE); } /** * @param concurrency Concurrency control. * @param isolation Isolation level. * @param put Put some data if {@code true}. * @throws Exception If failed. */ private void testCommits(TransactionConcurrency concurrency, TransactionIsolation isolation, boolean put) throws Exception { IgniteCache<Integer, Integer> cache = grid(0).cache(DEFAULT_CACHE_NAME); for (int i = 0; i < TX_CNT; i++) { Transaction tx = grid(0).transactions().txStart(concurrency, isolation); if (put) for (int j = 0; j < keyCount(); j++) cache.put(j, j); // Waiting 30 ms for metrics. U.currentTimeMillis() method has 10 ms discretization. U.sleep(30); tx.commit(); } for (int i = 0; i < gridCount(); i++) { TransactionMetrics metrics = grid(i).transactions().metrics(); CacheMetrics cacheMetrics = grid(i).cache(DEFAULT_CACHE_NAME).localMetrics(); if (i == 0) { assertEquals(TX_CNT, metrics.txCommits()); if (put) { assertEquals(TX_CNT, cacheMetrics.getCacheTxCommits()); // Expected metric value should be in microseconds. assert cacheMetrics.getAverageTxCommitTime() > 1000 : cacheMetrics.getAverageTxCommitTime(); } } else { assertEquals(0, metrics.txCommits()); assertEquals(0, cacheMetrics.getCacheTxCommits()); } assertEquals(0, metrics.txRollbacks()); assertEquals(0, cacheMetrics.getCacheTxRollbacks()); } } /** * @param concurrency Concurrency control. * @param isolation Isolation level. * @param put Put some data if {@code true}. * @throws Exception If failed. */ private void testRollbacks(TransactionConcurrency concurrency, TransactionIsolation isolation, boolean put) throws Exception { IgniteCache<Integer, Integer> cache = grid(0).cache(DEFAULT_CACHE_NAME); for (int i = 0; i < TX_CNT; i++) { Transaction tx = grid(0).transactions().txStart(concurrency, isolation); if (put) for (int j = 0; j < keyCount(); j++) cache.put(j, j); // Waiting 30 ms for metrics. U.currentTimeMillis() method has 10 ms discretization. U.sleep(30); tx.rollback(); } for (int i = 0; i < gridCount(); i++) { TransactionMetrics metrics = grid(i).transactions().metrics(); CacheMetrics cacheMetrics = grid(i).cache(DEFAULT_CACHE_NAME).localMetrics(); assertEquals(0, metrics.txCommits()); assertEquals(0, cacheMetrics.getCacheTxCommits()); if (i == 0) { assertEquals(TX_CNT, metrics.txRollbacks()); if (put) { assertEquals(TX_CNT, cacheMetrics.getCacheTxRollbacks()); // Expected metric value should be in microseconds. assert cacheMetrics.getAverageTxRollbackTime() > 1000 : cacheMetrics.getAverageTxRollbackTime(); } } else { assertEquals(0, metrics.txRollbacks()); assertEquals(0, cacheMetrics.getCacheTxRollbacks()); } } } /** * Metrics test for transaction timeout rollback. * * @param concurrency Concurrency control. * @param isolation Isolation level. * @throws Exception If failed. */ private void doTestSuspendedTxTimeoutRollbacks(TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception { IgniteCache<Integer, Integer> cache = grid(0).cache(DEFAULT_CACHE_NAME); IgniteTransactions transactions = grid(0).transactions(); for (int i = 0; i < TX_CNT; i++) { Transaction tx = transactions.txStart(concurrency, isolation, TX_TIMEOUT, 0); cache.put(1, 1); tx.suspend(); boolean res = GridTestUtils.waitForCondition(() -> tx.state() == ROLLED_BACK, TX_TIMEOUT * 10); assertTrue(res); tx.close(); } TransactionMetrics txMetrics = transactions.metrics(); CacheMetrics cacheMetrics = cache.localMetrics(); assertEquals(0, txMetrics.txCommits()); assertEquals(0, cacheMetrics.getCacheTxCommits()); assertEquals(TX_CNT, txMetrics.txRollbacks()); assertEquals(TX_CNT, cacheMetrics.getCacheTxRollbacks()); assertTrue(cacheMetrics.getAverageTxRollbackTime() > 0); for (int i = 1; i < gridCount(); i++) { txMetrics = grid(i).transactions().metrics(); cacheMetrics = grid(i).cache(DEFAULT_CACHE_NAME).localMetrics(); assertEquals(0, txMetrics.txCommits()); assertEquals(0, cacheMetrics.getCacheTxCommits()); assertEquals(0, txMetrics.txRollbacks()); assertEquals(0, cacheMetrics.getCacheTxRollbacks()); } } }
apache-2.0
jomarko/kie-wb-common
kie-wb-common-dmn/kie-wb-common-dmn-client/src/main/java/org/kie/workbench/common/dmn/client/widgets/grid/handlers/EditableHeaderGridWidgetEditCellMouseEventHandler.java
4278
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * 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.kie.workbench.common.dmn.client.widgets.grid.handlers; import java.util.List; import java.util.Objects; import java.util.Optional; import com.ait.lienzo.client.core.event.AbstractNodeMouseEvent; import com.ait.lienzo.client.core.types.Point2D; import org.kie.workbench.common.dmn.client.editors.expressions.util.DynamicReadOnlyUtils; import org.kie.workbench.common.dmn.client.widgets.grid.columns.EditableHeaderMetaData; import org.kie.workbench.common.dmn.client.widgets.grid.columns.EditableHeaderUtilities; import org.uberfire.ext.wires.core.grids.client.model.GridCellEditAction; import org.uberfire.ext.wires.core.grids.client.model.GridColumn; import org.uberfire.ext.wires.core.grids.client.util.CellContextUtilities; import org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget; import org.uberfire.ext.wires.core.grids.client.widget.grid.impl.DefaultGridWidgetEditCellMouseEventHandler; public class EditableHeaderGridWidgetEditCellMouseEventHandler extends DefaultGridWidgetEditCellMouseEventHandler { @Override public boolean onNodeMouseEvent(final GridWidget gridWidget, final Point2D relativeLocation, final Optional<Integer> uiHeaderRowIndex, final Optional<Integer> uiHeaderColumnIndex, final Optional<Integer> uiRowIndex, final Optional<Integer> uiColumnIndex, final AbstractNodeMouseEvent event) { if (DynamicReadOnlyUtils.isOnlyVisualChangeAllowed(gridWidget)) { return false; } return super.onNodeMouseEvent(gridWidget, relativeLocation, uiHeaderRowIndex, uiHeaderColumnIndex, uiRowIndex, uiColumnIndex, event); } @Override public boolean handleHeaderCell(final GridWidget gridWidget, final Point2D relativeLocation, final int uiHeaderRowIndex, final int uiHeaderColumnIndex, final AbstractNodeMouseEvent event) { final List<GridColumn<?>> gridColumns = gridWidget.getModel().getColumns(); final GridColumn<?> gridColumn = gridColumns.get(uiHeaderColumnIndex); final List<GridColumn.HeaderMetaData> gridColumnHeaderMetaData = gridColumn.getHeaderMetaData(); if (Objects.isNull(gridColumnHeaderMetaData) || gridColumnHeaderMetaData.isEmpty()) { return false; } if (!EditableHeaderUtilities.hasEditableHeader(gridColumn)) { return false; } if (!EditableHeaderUtilities.isEditableHeader(gridColumn, uiHeaderRowIndex)) { return false; } final EditableHeaderMetaData editableHeaderMetaData = (EditableHeaderMetaData) gridColumn.getHeaderMetaData().get(uiHeaderRowIndex); if (Objects.equals(editableHeaderMetaData.getSupportedEditAction(), GridCellEditAction.getSupportedEditAction(event))) { final Point2D gridWidgetComputedLocation = gridWidget.getComputedLocation(); CellContextUtilities.editSelectedCell(gridWidget, relativeLocation.add(gridWidgetComputedLocation)); return true; } return false; } }
apache-2.0
smanvi-pivotal/geode
geode-core/src/main/java/org/apache/geode/distributed/internal/WanLocatorDiscoverer.java
1355
/* * 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.geode.distributed.internal; import org.apache.geode.cache.client.internal.locator.wan.LocatorMembershipListener; public interface WanLocatorDiscoverer { int WAN_LOCATOR_CONNECTION_TIMEOUT = Integer.getInteger("WANLocator.CONNECTION_TIMEOUT", 50000).intValue(); /** * For WAN 70 Exchange the locator information within the distributed system */ void discover(int port, DistributionConfigImpl config, LocatorMembershipListener locatorListener, final String hostnameForClients); void stop(); boolean isStopped(); }
apache-2.0
adrian-galbenus/gateway
transport/nio/src/main/java/org/kaazing/gateway/transport/nio/internal/socket/TcpExtensionFactory.java
2135
/** * Copyright 2007-2016, Kaazing Corporation. 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 org.kaazing.gateway.transport.nio.internal.socket; import static java.util.ServiceLoader.load; import java.util.Collection; import java.util.List; import java.util.ServiceLoader; import org.kaazing.gateway.resource.address.ResourceAddress; import org.kaazing.gateway.transport.nio.TcpExtension; import org.kaazing.gateway.transport.nio.TcpExtensionFactorySpi; public interface TcpExtensionFactory { List<TcpExtension> bind(ResourceAddress address); Collection<TcpExtensionFactorySpi> availableExtensions(); /** * Creates a new instance of WebSocketExtensionFactory. It uses the specified {@link ClassLoader} to load * {@link WebSocketExtensionFactorySpi} objects that are registered using META-INF/services. * * @return WebSocketExtensionFactory */ static TcpExtensionFactory newInstance(ClassLoader cl) { ServiceLoader<TcpExtensionFactorySpi> services = load(TcpExtensionFactorySpi.class, cl); return TcpExtensionFactoryImpl.newInstance(services); } /** * Creates a new instance of WebSocketExtensionFactory. It uses the default {@link ClassLoader} to load * {@link WebSocketExtensionFactorySpi} objects that are registered using META-INF/services. * * @return WebSocketExtensionFactory */ static TcpExtensionFactory newInstance() { ServiceLoader<TcpExtensionFactorySpi> services = load(TcpExtensionFactorySpi.class); return TcpExtensionFactoryImpl.newInstance(services); } }
apache-2.0
asedunov/intellij-community
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexScanRunnableCollectorImpl.java
5969
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.util.indexing; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; public class FileBasedIndexScanRunnableCollectorImpl extends FileBasedIndexScanRunnableCollector { private final Project myProject; private final ProjectFileIndex myProjectFileIndex; private final FileTypeManager myFileTypeManager; public FileBasedIndexScanRunnableCollectorImpl(@NotNull Project project) { this.myProject = project; this.myProjectFileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); this.myFileTypeManager = FileTypeManager.getInstance(); } @Override public boolean shouldCollect(@NotNull VirtualFile file) { if (myProjectFileIndex.isInContent(file) || myProjectFileIndex.isInLibraryClasses(file) || myProjectFileIndex.isInLibrarySource(file)) { return !myFileTypeManager.isFileIgnored(file); } return false; } @Override public List<Runnable> collectScanRootRunnables(@NotNull ContentIterator processor, ProgressIndicator indicator) { try (AccessToken ignore = ReadAction.start()) { if (myProject.isDisposed()) { return Collections.emptyList(); } List<Runnable> tasks = new ArrayList<>(); final Set<VirtualFile> visitedRoots = ContainerUtil.newConcurrentSet(); tasks.add(() -> myProjectFileIndex.iterateContent(processor, file -> !file.isDirectory() || visitedRoots.add(file))); /* Module[] modules = ModuleManager.getInstance(project).getModules(); for(final Module module: modules) { tasks.add(new Runnable() { @Override public void run() { if (module.isDisposed()) return; ModuleRootManager.getInstance(module).getFileIndex().iterateContent(processor); } }); }*/ JBIterable<VirtualFile> contributedRoots = JBIterable.empty(); for (IndexableSetContributor contributor : Extensions.getExtensions(IndexableSetContributor.EP_NAME)) { //important not to depend on project here, to support per-project background reindex // each client gives a project to FileBasedIndex if (myProject.isDisposed()) { return tasks; } contributedRoots = contributedRoots.append(IndexableSetContributor.getRootsToIndex(contributor)); contributedRoots = contributedRoots.append(IndexableSetContributor.getProjectRootsToIndex(contributor, myProject)); } for (VirtualFile root : contributedRoots) { if (visitedRoots.add(root)) { tasks.add(() -> { if (myProject.isDisposed() || !root.isValid()) return; FileBasedIndex.iterateRecursively(root, processor, indicator, visitedRoots, null); }); } } // iterate synthetic project libraries for (AdditionalLibraryRootsProvider provider : Extensions.getExtensions(AdditionalLibraryRootsProvider.EP_NAME)) { if (myProject.isDisposed()) { return tasks; } for (SyntheticLibrary library : provider.getAdditionalProjectLibraries(myProject)) { for (VirtualFile root : library.getSourceRoots()) { if (visitedRoots.add(root)) { tasks.add(() -> { if (myProject.isDisposed() || !root.isValid()) return; FileBasedIndex.iterateRecursively(root, processor, indicator, visitedRoots, myProjectFileIndex); }); } } } } // iterate associated libraries for (final Module module : ModuleManager.getInstance(myProject).getModules()) { OrderEntry[] orderEntries = ModuleRootManager.getInstance(module).getOrderEntries(); for (OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrSdkOrderEntry) { if (orderEntry.isValid()) { final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry)orderEntry; final VirtualFile[] libSources = entry.getRootFiles(OrderRootType.SOURCES); final VirtualFile[] libClasses = entry.getRootFiles(OrderRootType.CLASSES); for (VirtualFile[] roots : new VirtualFile[][]{libSources, libClasses}) { for (final VirtualFile root : roots) { if (visitedRoots.add(root)) { tasks.add(() -> { if (myProject.isDisposed() || module.isDisposed() || !root.isValid()) return; FileBasedIndex.iterateRecursively(root, processor, indicator, visitedRoots, myProjectFileIndex); }); } } } } } } } return tasks; } } }
apache-2.0
blackberry/WebWorks-Community-APIs
Smartphone/Barcode/webworks/media/barcode/BarcodeNamespace.java
1433
/* * Copyright 2011 Research In Motion Limited. * * 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 webworks.media.barcode; import net.rim.device.api.script.Scriptable; public class BarcodeNamespace extends Scriptable { public static final String FEATURE_NAME = "webworks.media.barcode"; private static class BarcodeNamespaceHolder{ private static final BarcodeNamespace INSTANCE = new BarcodeNamespace(); } public static final BarcodeNamespace getInstance() { return BarcodeNamespaceHolder.INSTANCE; } private BarcodeNamespace(){ } public Object getField(final String name) throws Exception { //Functions if (name.equals(ScanBarcodeAction.NAME)) { return new ScanBarcodeAction(); } else if (name.equals(GenerateBarcodeAction.NAME)){ return new GenerateBarcodeAction(); } return super.getField(name); } }
apache-2.0
acq/AirMapView
library/src/test/java/com/airbnb/android/airmapview/NativeAirMapViewBuilderTest.java
657
package com.airbnb.android.airmapview; import android.os.Bundle; import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class NativeAirMapViewBuilderTest { @Test public void shouldBuildNativeAirMapView() { NativeAirMapViewBuilder builder = new NativeAirMapViewBuilder(); AirGoogleMapOptions options = mock(AirGoogleMapOptions.class); when(options.toBundle()).thenReturn(new Bundle()); assertThat(builder.withOptions(options).build(), instanceOf(NativeGoogleMapFragment.class)); } }
apache-2.0
duzhen1996/SSM
smart-hadoop-support/smart-erasurecodec/src/test/java/org/smartdata/erasurecode/coder/TestXORCoder.java
2120
/** * 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.smartdata.erasurecode.coder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; /** * Test XOR encoding and decoding. */ public class TestXORCoder extends TestErasureCoderBase { @Rule public Timeout globalTimeout = new Timeout(300000); @Before public void setup() { this.encoderClass = XORErasureEncoder.class; this.decoderClass = XORErasureDecoder.class; this.numDataUnits = 10; this.numParityUnits = 1; this.numChunksInBlock = 10; } @Test public void testCodingNoDirectBuffer_erasing_p0() { prepare(null, 10, 1, new int[0], new int[] {0}); /** * Doing twice to test if the coders can be repeatedly reused. This matters * as the underlying coding buffers are shared, which may have bugs. */ testCoding(false); testCoding(false); } @Test public void testCodingBothBuffers_erasing_d5() { prepare(null, 10, 1, new int[]{5}, new int[0]); /** * Doing in mixed buffer usage model to test if the coders can be repeatedly * reused with different buffer usage model. This matters as the underlying * coding buffers are shared, which may have bugs. */ testCoding(true); testCoding(false); testCoding(true); testCoding(false); } }
apache-2.0
siosio/intellij-community
platform/util/collections/src/com/intellij/util/containers/ConcurrentWeakKeyWeakValueHashMap.java
2632
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.containers; import com.intellij.util.ObjectUtilsRt; import org.jetbrains.annotations.NotNull; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; /** * Concurrent map with weak keys and weak values. * Null keys are NOT allowed * Null values are NOT allowed * Use {@link ContainerUtil#createConcurrentWeakKeyWeakValueMap()} to create this */ final class ConcurrentWeakKeyWeakValueHashMap<K, V> extends ConcurrentWeakKeySoftValueHashMap<K,V> { ConcurrentWeakKeyWeakValueHashMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull HashingStrategy<? super K> hashingStrategy) { super(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy); } private static final class WeakValue<K, V> extends WeakReference<V> implements ValueReference<K,V> { @NotNull private volatile KeyReference<K, V> myKeyReference; // can't make it final because of circular dependency of KeyReference to ValueReference private WeakValue(@NotNull V value, @NotNull ReferenceQueue<? super V> queue) { super(value, queue); } // When referent is collected, equality should be identity-based (for the processQueues() remove this very same SoftValue) // otherwise it's just canonical equals on referents for replace(K,V,V) to work @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null) return false; V v = get(); //noinspection unchecked V thatV = ((ValueReference<K, V>)o).get(); return v != null && v.equals(thatV); } @NotNull @Override public KeyReference<K, V> getKeyReference() { return myKeyReference; } } @Override @NotNull KeyReference<K,V> createKeyReference(@NotNull K k, @NotNull final V v) { ValueReference<K, V> valueReference = createValueReference(v, myValueQueue); WeakKey<K, V> keyReference = new WeakKey<>(k, valueReference, myHashingStrategy, myKeyQueue); if (valueReference instanceof WeakValue) { ((WeakValue<K, V>)valueReference).myKeyReference = keyReference; } ObjectUtilsRt.reachabilityFence(k); return keyReference; } @Override @NotNull protected ValueReference<K, V> createValueReference(@NotNull V value, @NotNull ReferenceQueue<? super V> queue) { return new WeakValue<>(value, queue); } }
apache-2.0
MicheleGuerriero/SeaCloudsPlatform
deployer/src/main/java/org/apache/brooklyn/entity/openshift/webapp/OpenShiftWebApp.java
2747
/* * 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.brooklyn.entity.openshift.webapp; import com.google.common.collect.ImmutableMap; import org.apache.brooklyn.api.entity.ImplementedBy; import org.apache.brooklyn.api.sensor.AttributeSensor; import org.apache.brooklyn.config.ConfigKey; import org.apache.brooklyn.core.config.ConfigKeys; import org.apache.brooklyn.core.config.MapConfigKey; import org.apache.brooklyn.core.sensor.Sensors; import org.apache.brooklyn.entity.openshift.OpenShiftEntity; import org.apache.brooklyn.util.core.flags.SetFromFlag; import org.apache.brooklyn.util.text.Identifiers; @ImplementedBy(OpenShiftWebAppImpl.class) public interface OpenShiftWebApp extends OpenShiftEntity { @SetFromFlag("application-name") ConfigKey<String> APPLICATION_NAME = ConfigKeys.newStringConfigKey( "openshiftWebApp.application.name", "Name of the application" , "os-app-" + Identifiers.makeRandomId(8)); @SetFromFlag("git-url-repo") ConfigKey<String> GIT_REPOSITORY_URL = ConfigKeys.newStringConfigKey( "openshiftWebApp.application.git.url", "URL of repository which contains the application"); //TODO, should it be moved to Location config? @SetFromFlag("application-domain") ConfigKey<String> DOMAIN = ConfigKeys.newStringConfigKey( "openshiftWebApp.application.domain", "Application domain used by the user", "brooklyndomain"); @SetFromFlag("env") public static final MapConfigKey<String> ENV = new MapConfigKey<String>(String.class, "openshift.webapp.env", "List of user-defined environment variables", ImmutableMap.<String, String>of()); AttributeSensor<String> ROOT_URL = Sensors.newStringSensor("webapp.url", "URL of the application"); /** * @return URL of the OpenShift Cartridge needed for building the application */ public String getCartridge(); }
apache-2.0
mtolan/ec2-plugin
src/main/java/hudson/plugins/ec2/EC2RetentionStrategy.java
6093
/* * The MIT License * * Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.plugins.ec2; import hudson.model.Descriptor; import hudson.slaves.RetentionStrategy; import hudson.util.TimeUnit2; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import org.kohsuke.stapler.DataBoundConstructor; /** * {@link RetentionStrategy} for EC2. * * @author Kohsuke Kawaguchi */ public class EC2RetentionStrategy extends RetentionStrategy<EC2Computer> { /** * Number of minutes of idleness before an instance should be terminated. A value of zero indicates that the * instance should never be automatically terminated. Negative values are times in remaining minutes before end of * billing period. */ public final int idleTerminationMinutes; private transient ReentrantLock checkLock; @DataBoundConstructor public EC2RetentionStrategy(String idleTerminationMinutes) { readResolve(); if (idleTerminationMinutes == null || idleTerminationMinutes.trim() == "") { this.idleTerminationMinutes = 0; } else { int value = 30; try { value = Integer.parseInt(idleTerminationMinutes); } catch (NumberFormatException nfe) { LOGGER.info("Malformed default idleTermination value: " + idleTerminationMinutes); } this.idleTerminationMinutes = value; } } @Override public long check(EC2Computer c) { if (!checkLock.tryLock()) { return 1; } else { try { return _check(c); } finally { checkLock.unlock(); } } } private long _check(EC2Computer c) { /* If we've been told never to terminate, then we're done. */ if (idleTerminationMinutes == 0) { return 1; } /* * Don't idle-out instances that're offline, per JENKINS-23792. This prevents a node from being idled down while * it's still starting up. */ if (c.isOffline()) { return 1; } if (c.isIdle() && !disabled) { final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds(); if (idleTerminationMinutes > 0) { // TODO: really think about the right strategy here, see // JENKINS-23792 if (idleMilliseconds > TimeUnit2.MINUTES.toMillis(idleTerminationMinutes)) { LOGGER.info("Idle timeout of " + c.getName() + " after " + TimeUnit2.MILLISECONDS.toMinutes(idleMilliseconds) + " idle minutes"); c.getNode().idleTimeout(); } } else { final long uptime; try { uptime = c.getUptime(); } catch (InterruptedException e) { // We'll just retry next time we test for idleness. LOGGER.fine("Interrupted while checking host uptime for " + c.getName() + ", will retry next check. Interrupted by: " + e); return 1; } final int freeSecondsLeft = (60 * 60) - (int) (TimeUnit2.SECONDS.convert(uptime, TimeUnit2.MILLISECONDS) % (60 * 60)); // if we have less "free" (aka already paid for) time left than // our idle time, stop/terminate the instance // See JENKINS-23821 if (freeSecondsLeft <= (Math.abs(idleTerminationMinutes * 60))) { LOGGER.info("Idle timeout of " + c.getName() + " after " + TimeUnit2.MILLISECONDS.toMinutes(idleMilliseconds) + " idle minutes, with " + TimeUnit2.MILLISECONDS.toMinutes(freeSecondsLeft) + " minutes remaining in billing period"); c.getNode().idleTimeout(); } } } return 1; } /** * Try to connect to it ASAP. */ @Override public void start(EC2Computer c) { LOGGER.info("Start requested for " + c.getName()); c.connect(false); } // no registration since this retention strategy is used only for EC2 nodes // that we provision automatically. // @Extension public static class DescriptorImpl extends Descriptor<RetentionStrategy<?>> { @Override public String getDisplayName() { return "EC2"; } } protected Object readResolve() { checkLock = new ReentrantLock(false); return this; } private static final Logger LOGGER = Logger.getLogger(EC2RetentionStrategy.class.getName()); public static boolean disabled = Boolean.getBoolean(EC2RetentionStrategy.class.getName() + ".disabled"); }
mit
kashike/SpongeAPI
src/main/java/org/spongepowered/api/data/manipulator/immutable/entity/ImmutableStuckArrowsData.java
2019
/* * This file is part of SpongeAPI, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.data.manipulator.immutable.entity; import org.spongepowered.api.data.manipulator.ImmutableDataManipulator; import org.spongepowered.api.data.manipulator.mutable.entity.StuckArrowsData; import org.spongepowered.api.data.value.immutable.ImmutableBoundedValue; import org.spongepowered.api.entity.living.Living; /** * An {@link ImmutableDataManipulator} for the number of "stuck arrows" in * {@link Living} entities. */ public interface ImmutableStuckArrowsData extends ImmutableDataManipulator<ImmutableStuckArrowsData, StuckArrowsData> { /** * Gets the {@link ImmutableBoundedValue} for the stuck arrows. * * @return The immutable value of stuck arrows */ ImmutableBoundedValue<Integer> stuckArrows(); }
mit
jaypatil/hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timeline-pluginstorage/src/test/java/org/apache/hadoop/yarn/server/timeline/TestLogInfo.java
11023
/** * 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 * <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 org.apache.hadoop.yarn.server.timeline; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.FileContextTestHelper; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.yarn.api.records.timeline.TimelineDomain; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntities; import org.apache.hadoop.yarn.api.records.timeline.TimelineEntity; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.util.MinimalPrettyPrinter; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.charset.Charset; import java.util.EnumSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class TestLogInfo { private static final Path TEST_ROOT_DIR = new Path( System.getProperty("test.build.data", System.getProperty("java.io.tmpdir")), TestLogInfo.class.getSimpleName()); private static final String TEST_ATTEMPT_DIR_NAME = "test_app"; private static final String TEST_ENTITY_FILE_NAME = "test_entity"; private static final String TEST_DOMAIN_FILE_NAME = "test_domain"; private static final String TEST_BROKEN_FILE_NAME = "test_broken"; private Configuration config = new YarnConfiguration(); private MiniDFSCluster hdfsCluster; private FileSystem fs; private FileContext fc; private FileContextTestHelper fileContextTestHelper = new FileContextTestHelper("/tmp/TestLogInfo"); private ObjectMapper objMapper; private JsonFactory jsonFactory = new JsonFactory(); private JsonGenerator jsonGenerator; private FSDataOutputStream outStream = null; private FSDataOutputStream outStreamDomain = null; private TimelineDomain testDomain; private static final short FILE_LOG_DIR_PERMISSIONS = 0770; @Before public void setup() throws Exception { config.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, TEST_ROOT_DIR.toString()); HdfsConfiguration hdfsConfig = new HdfsConfiguration(); hdfsCluster = new MiniDFSCluster.Builder(hdfsConfig).numDataNodes(1).build(); fs = hdfsCluster.getFileSystem(); fc = FileContext.getFileContext(hdfsCluster.getURI(0), config); Path testAppDirPath = getTestRootPath(TEST_ATTEMPT_DIR_NAME); fs.mkdirs(testAppDirPath, new FsPermission(FILE_LOG_DIR_PERMISSIONS)); objMapper = PluginStoreTestUtils.createObjectMapper(); TimelineEntities testEntities = PluginStoreTestUtils.generateTestEntities(); writeEntitiesLeaveOpen(testEntities, new Path(testAppDirPath, TEST_ENTITY_FILE_NAME)); testDomain = new TimelineDomain(); testDomain.setId("domain_1"); testDomain.setReaders(UserGroupInformation.getLoginUser().getUserName()); testDomain.setOwner(UserGroupInformation.getLoginUser().getUserName()); testDomain.setDescription("description"); writeDomainLeaveOpen(testDomain, new Path(testAppDirPath, TEST_DOMAIN_FILE_NAME)); writeBrokenFile(new Path(testAppDirPath, TEST_BROKEN_FILE_NAME)); } @After public void tearDown() throws Exception { jsonGenerator.close(); outStream.close(); outStreamDomain.close(); hdfsCluster.shutdown(); } @Test public void testMatchesGroupId() throws Exception { String testGroupId = "app1_group1"; // Match EntityLogInfo testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app1_group1", UserGroupInformation.getLoginUser().getUserName()); assertTrue(testLogInfo.matchesGroupId(testGroupId)); testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "test_app1_group1", UserGroupInformation.getLoginUser().getUserName()); assertTrue(testLogInfo.matchesGroupId(testGroupId)); // Unmatch testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app2_group1", UserGroupInformation.getLoginUser().getUserName()); assertFalse(testLogInfo.matchesGroupId(testGroupId)); testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app1_group2", UserGroupInformation.getLoginUser().getUserName()); assertFalse(testLogInfo.matchesGroupId(testGroupId)); testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app1_group12", UserGroupInformation.getLoginUser().getUserName()); assertFalse(testLogInfo.matchesGroupId(testGroupId)); // Check delimiters testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app1_group1_2", UserGroupInformation.getLoginUser().getUserName()); assertTrue(testLogInfo.matchesGroupId(testGroupId)); testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app1_group1.dat", UserGroupInformation.getLoginUser().getUserName()); assertTrue(testLogInfo.matchesGroupId(testGroupId)); // Check file names shorter than group id testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, "app2", UserGroupInformation.getLoginUser().getUserName()); assertFalse(testLogInfo.matchesGroupId(testGroupId)); } @Test public void testParseEntity() throws Exception { // Load test data TimelineDataManager tdm = PluginStoreTestUtils.getTdmWithMemStore(config); EntityLogInfo testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_ENTITY_FILE_NAME, UserGroupInformation.getLoginUser().getUserName()); testLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); // Verify for the first batch PluginStoreTestUtils.verifyTestEntities(tdm); // Load new data TimelineEntity entityNew = PluginStoreTestUtils .createEntity("id_3", "type_3", 789l, null, null, null, null, "domain_id_1"); TimelineEntities entityList = new TimelineEntities(); entityList.addEntity(entityNew); writeEntitiesLeaveOpen(entityList, new Path(getTestRootPath(TEST_ATTEMPT_DIR_NAME), TEST_ENTITY_FILE_NAME)); testLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); // Verify the newly added data TimelineEntity entity3 = tdm.getEntity(entityNew.getEntityType(), entityNew.getEntityId(), EnumSet.allOf(TimelineReader.Field.class), UserGroupInformation.getLoginUser()); assertNotNull(entity3); assertEquals("Failed to read out entity new", entityNew.getStartTime(), entity3.getStartTime()); tdm.close(); } @Test public void testParseBrokenEntity() throws Exception { // Load test data TimelineDataManager tdm = PluginStoreTestUtils.getTdmWithMemStore(config); EntityLogInfo testLogInfo = new EntityLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_BROKEN_FILE_NAME, UserGroupInformation.getLoginUser().getUserName()); DomainLogInfo domainLogInfo = new DomainLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_BROKEN_FILE_NAME, UserGroupInformation.getLoginUser().getUserName()); // Try parse, should not fail testLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); domainLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); tdm.close(); } @Test public void testParseDomain() throws Exception { // Load test data TimelineDataManager tdm = PluginStoreTestUtils.getTdmWithMemStore(config); DomainLogInfo domainLogInfo = new DomainLogInfo(TEST_ATTEMPT_DIR_NAME, TEST_DOMAIN_FILE_NAME, UserGroupInformation.getLoginUser().getUserName()); domainLogInfo.parseForStore(tdm, getTestRootPath(), true, jsonFactory, objMapper, fs); // Verify domain data TimelineDomain resultDomain = tdm.getDomain("domain_1", UserGroupInformation.getLoginUser()); assertNotNull(resultDomain); assertEquals(testDomain.getReaders(), resultDomain.getReaders()); assertEquals(testDomain.getOwner(), resultDomain.getOwner()); assertEquals(testDomain.getDescription(), resultDomain.getDescription()); } private void writeBrokenFile(Path logPath) throws IOException { FSDataOutputStream out = null; try { String broken = "{ broken { [[]} broken"; out = PluginStoreTestUtils.createLogFile(logPath, fs); out.write(broken.getBytes(Charset.forName("UTF-8"))); out.close(); out = null; } finally { if (out != null) { out.close(); } } } // TestLogInfo needs to maintain opened hdfs files so we have to build our own // write methods private void writeEntitiesLeaveOpen(TimelineEntities entities, Path logPath) throws IOException { if (outStream == null) { outStream = PluginStoreTestUtils.createLogFile(logPath, fs); jsonGenerator = (new JsonFactory()).createJsonGenerator(outStream); jsonGenerator.setPrettyPrinter(new MinimalPrettyPrinter("\n")); } for (TimelineEntity entity : entities.getEntities()) { objMapper.writeValue(jsonGenerator, entity); } outStream.hflush(); } private void writeDomainLeaveOpen(TimelineDomain domain, Path logPath) throws IOException { if (outStreamDomain == null) { outStreamDomain = PluginStoreTestUtils.createLogFile(logPath, fs); } // Write domain uses its own json generator to isolate from entity writers JsonGenerator jsonGeneratorLocal = (new JsonFactory()).createJsonGenerator(outStreamDomain); jsonGeneratorLocal.setPrettyPrinter(new MinimalPrettyPrinter("\n")); objMapper.writeValue(jsonGeneratorLocal, domain); outStreamDomain.hflush(); } private Path getTestRootPath() { return fileContextTestHelper.getTestRootPath(fc); } private Path getTestRootPath(String pathString) { return fileContextTestHelper.getTestRootPath(fc, pathString); } }
gpl-3.0
jaechoon2/droidar
droidar/src/v2/simpleUi/M_Caption.java
2122
package v2.simpleUi; import v2.simpleUi.uiDecoration.UiDecoratable; import v2.simpleUi.uiDecoration.UiDecorator; import android.content.Context; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; public class M_Caption implements ModifierInterface, UiDecoratable { private String myText; private float mySizeFactor = 1.1f; private UiDecorator myDecorator; private OnClickListener myOnClickListener; private LinearLayout container; public M_Caption(String text) { myText = text; } /** * @param text * @param sizeFactor * default is 1.1f (of normal size) */ public M_Caption(String text, float sizeFactor) { this(text); mySizeFactor = sizeFactor; } public void setMyText(String myText) { this.myText = myText; } public void setOnClickListener(OnClickListener onClickListener) { this.myOnClickListener = onClickListener; } @Override public View getView(Context context) { int bottomAndTopPadding = 4; int textPadding = 7; container = new LinearLayout(context); container.setGravity(Gravity.CENTER); container.setPadding(0, bottomAndTopPadding, 0, bottomAndTopPadding); TextView t = new TextView(context); t.setText(myText); t.setPadding(textPadding, textPadding, textPadding, textPadding); t.setGravity(Gravity.CENTER_HORIZONTAL); if (myOnClickListener != null) { t.setOnClickListener(myOnClickListener); } container.addView(t); if (mySizeFactor != 1) { t.setTextSize(t.getTextSize() * mySizeFactor); } if (myDecorator != null) { int level = myDecorator.getCurrentLevel(); myDecorator.decorate(context, container, level + 1, UiDecorator.TYPE_CONTAINER); myDecorator.decorate(context, t, level + 1, UiDecorator.TYPE_CAPTION); } return container; } @Override public boolean assignNewDecorator(UiDecorator decorator) { myDecorator = decorator; return true; } @Override public boolean save() { return true; } public int getHeightInPixels() { return container.getHeight(); } }
gpl-3.0
thialfihar/apg
OpenKeychain/src/main/java/org/sufficientlysecure/keychain/operations/results/GetKeyResult.java
2254
/* * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de> * Copyright (C) 2014 Vincent Breitmoser <v.breitmoser@mugenguild.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sufficientlysecure.keychain.operations.results; import android.os.Parcel; public class GetKeyResult extends OperationResult { public int mNonPgpPartsCount; public int getNonPgpPartsCount() { return mNonPgpPartsCount; } public void setNonPgpPartsCount(int nonPgpPartsCount) { mNonPgpPartsCount = nonPgpPartsCount; } public GetKeyResult(int result, OperationLog log) { super(result, log); } public static final int RESULT_ERROR_NO_VALID_KEYS = RESULT_ERROR + 8; public static final int RESULT_ERROR_NO_PGP_PARTS = RESULT_ERROR + 16; public static final int RESULT_ERROR_QUERY_TOO_SHORT = RESULT_ERROR + 32; public static final int RESULT_ERROR_TOO_MANY_RESPONSES = RESULT_ERROR + 64; public static final int RESULT_ERROR_TOO_SHORT_OR_TOO_MANY_RESPONSES = RESULT_ERROR + 128; public static final int RESULT_ERROR_QUERY_FAILED = RESULT_ERROR + 256; public GetKeyResult(Parcel source) { super(source); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); } public static Creator<GetKeyResult> CREATOR = new Creator<GetKeyResult>() { public GetKeyResult createFromParcel(final Parcel source) { return new GetKeyResult(source); } public GetKeyResult[] newArray(final int size) { return new GetKeyResult[size]; } }; }
gpl-3.0