code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* 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.isis.core.unittestsupport.files;
import java.io.File;
import java.io.IOException;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.jmock.Expectations;
import org.jmock.auto.Mock;
import org.junit.Rule;
import org.junit.Test;
import org.apache.isis.core.unittestsupport.files.Files.Deleter;
import org.apache.isis.core.unittestsupport.files.Files.Recursion;
import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2;
import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2.Mode;
public class FilesTest_deleteFiles {
@Rule
public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(Mode.INTERFACES_AND_CLASSES);
@Mock
private Deleter deleter;
@Test
public void test() throws IOException {
final File cusIdxFile = new File("xml/objects/CUS.xml");
final File cus1File = new File("xml/objects/CUS/1.xml");
final File cus2File = new File("xml/objects/CUS/2.xml");
context.checking(new Expectations() {
{
one(deleter).deleteFile(with(equalsFile(cusIdxFile)));
one(deleter).deleteFile(with(equalsFile(cus1File)));
one(deleter).deleteFile(with(equalsFile(cus2File)));
}
});
Files.deleteFiles(new File("xml/objects"), Files.filterFileNameExtension(".xml"), Recursion.DO_RECURSE, deleter);
}
private static Matcher<File> equalsFile(final File file) throws IOException {
final String canonicalPath = file.getCanonicalPath();
return new TypeSafeMatcher<File>() {
@Override
public void describeTo(Description arg0) {
arg0.appendText("file '" + canonicalPath + "'");
}
@Override
public boolean matchesSafely(File arg0) {
try {
return arg0.getCanonicalPath().equals(canonicalPath);
} catch (IOException e) {
return false;
}
}
};
}
}
| howepeng/isis | core/unittestsupport/src/test/java/org/apache/isis/core/unittestsupport/files/FilesTest_deleteFiles.java | Java | apache-2.0 | 2,945 |
/*
* Copyright (C) 2007 The Guava 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 com.google.common.base;
import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;
import static com.google.common.base.Throwables.getStackTraceAsString;
import static com.google.common.base.Throwables.lazyStackTrace;
import static com.google.common.base.Throwables.lazyStackTraceIsLazy;
import static com.google.common.base.Throwables.throwIfInstanceOf;
import static com.google.common.base.Throwables.throwIfUnchecked;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Arrays.asList;
import static java.util.regex.Pattern.quote;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import com.google.common.testing.NullPointerTester;
import java.util.List;
import junit.framework.TestCase;
/**
* Unit test for {@link Throwables}.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(emulated = true)
public class ThrowablesTest extends TestCase {
public void testThrowIfUnchecked_Unchecked() {
try {
throwIfUnchecked(new SomeUncheckedException());
fail();
} catch (SomeUncheckedException expected) {
}
}
public void testThrowIfUnchecked_Error() {
try {
throwIfUnchecked(new SomeError());
fail();
} catch (SomeError expected) {
}
}
@SuppressWarnings("ThrowIfUncheckedKnownChecked")
public void testThrowIfUnchecked_Checked() {
throwIfUnchecked(new SomeCheckedException());
}
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_NoneThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatDoesntThrowAnything();
} catch (Throwable t) {
Throwables.propagateIfPossible(t);
throw new SomeChainingException(t);
}
}
};
// Expect no exception to be thrown
sample.noneDeclared();
}
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_UncheckedThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatThrowsUnchecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(t);
throw new SomeChainingException(t);
}
}
};
// Expect the unchecked exception to propagate as-is
try {
sample.noneDeclared();
fail();
} catch (SomeUncheckedException expected) {
}
}
@GwtIncompatible // propagateIfPossible
public void testPropagateIfPossible_NoneDeclared_UndeclaredThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatThrowsUndeclaredChecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(t);
throw new SomeChainingException(t);
}
}
};
// Expect the undeclared exception to have been chained inside another
try {
sample.noneDeclared();
fail();
} catch (SomeChainingException expected) {
}
}
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_NoneThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatDoesntThrowAnything();
} catch (Throwable t) {
// yes, this block is never reached, but for purposes of illustration
// we're keeping it the same in each test
Throwables.propagateIfPossible(t, SomeCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect no exception to be thrown
sample.oneDeclared();
}
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_UncheckedThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatThrowsUnchecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(t, SomeCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect the unchecked exception to propagate as-is
try {
sample.oneDeclared();
fail();
} catch (SomeUncheckedException expected) {
}
}
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_CheckedThrown() {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatThrowsChecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(t, SomeCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect the checked exception to propagate as-is
try {
sample.oneDeclared();
fail();
} catch (SomeCheckedException expected) {
}
}
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropagateIfPossible_OneDeclared_UndeclaredThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatThrowsUndeclaredChecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(t, SomeCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect the undeclared exception to have been chained inside another
try {
sample.oneDeclared();
fail();
} catch (SomeChainingException expected) {
}
}
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_NoneThrown()
throws SomeCheckedException, SomeOtherCheckedException {
Sample sample =
new Sample() {
@Override
public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {
try {
methodThatDoesntThrowAnything();
} catch (Throwable t) {
Throwables.propagateIfPossible(
t, SomeCheckedException.class, SomeOtherCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect no exception to be thrown
sample.twoDeclared();
}
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_UncheckedThrown()
throws SomeCheckedException, SomeOtherCheckedException {
Sample sample =
new Sample() {
@Override
public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {
try {
methodThatThrowsUnchecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(
t, SomeCheckedException.class, SomeOtherCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect the unchecked exception to propagate as-is
try {
sample.twoDeclared();
fail();
} catch (SomeUncheckedException expected) {
}
}
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_CheckedThrown() throws SomeOtherCheckedException {
Sample sample =
new Sample() {
@Override
public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {
try {
methodThatThrowsChecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(
t, SomeCheckedException.class, SomeOtherCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect the checked exception to propagate as-is
try {
sample.twoDeclared();
fail();
} catch (SomeCheckedException expected) {
}
}
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropagateIfPossible_TwoDeclared_OtherCheckedThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {
try {
methodThatThrowsOtherChecked();
} catch (Throwable t) {
Throwables.propagateIfPossible(
t, SomeCheckedException.class, SomeOtherCheckedException.class);
throw new SomeChainingException(t);
}
}
};
// Expect the checked exception to propagate as-is
try {
sample.twoDeclared();
fail();
} catch (SomeOtherCheckedException expected) {
}
}
public void testThrowIfUnchecked_null() throws SomeCheckedException {
try {
throwIfUnchecked(null);
fail();
} catch (NullPointerException expected) {
}
}
@GwtIncompatible // propagateIfPossible
public void testPropageIfPossible_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null);
}
@GwtIncompatible // propagateIfPossible(Throwable, Class)
public void testPropageIfPossible_OneDeclared_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null, SomeCheckedException.class);
}
@GwtIncompatible // propagateIfPossible(Throwable, Class, Class)
public void testPropageIfPossible_TwoDeclared_null() throws SomeCheckedException {
Throwables.propagateIfPossible(null, SomeCheckedException.class, SomeUncheckedException.class);
}
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_NoneThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatDoesntThrowAnything();
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
};
// Expect no exception to be thrown
sample.noneDeclared();
}
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_UncheckedThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatThrowsUnchecked();
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
};
// Expect the unchecked exception to propagate as-is
try {
sample.noneDeclared();
fail();
} catch (SomeUncheckedException expected) {
}
}
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_ErrorThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatThrowsError();
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
};
// Expect the error to propagate as-is
try {
sample.noneDeclared();
fail();
} catch (SomeError expected) {
}
}
@GwtIncompatible // propagate
public void testPropagate_NoneDeclared_CheckedThrown() {
Sample sample =
new Sample() {
@Override
public void noneDeclared() {
try {
methodThatThrowsChecked();
} catch (Throwable t) {
throw Throwables.propagate(t);
}
}
};
// Expect the undeclared exception to have been chained inside another
try {
sample.noneDeclared();
fail();
} catch (RuntimeException expected) {
assertThat(expected).hasCauseThat().isInstanceOf(SomeCheckedException.class);
}
}
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_Unchecked() throws SomeCheckedException {
throwIfInstanceOf(new SomeUncheckedException(), SomeCheckedException.class);
}
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedDifferent() throws SomeCheckedException {
throwIfInstanceOf(new SomeOtherCheckedException(), SomeCheckedException.class);
}
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedSame() {
try {
throwIfInstanceOf(new SomeCheckedException(), SomeCheckedException.class);
fail();
} catch (SomeCheckedException expected) {
}
}
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_CheckedSubclass() {
try {
throwIfInstanceOf(new SomeCheckedException() {}, SomeCheckedException.class);
fail();
} catch (SomeCheckedException expected) {
}
}
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_NoneThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatDoesntThrowAnything();
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, SomeCheckedException.class);
throw Throwables.propagate(t);
}
}
};
// Expect no exception to be thrown
sample.oneDeclared();
}
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_DeclaredThrown() {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatThrowsChecked();
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, SomeCheckedException.class);
throw Throwables.propagate(t);
}
}
};
// Expect declared exception to be thrown as-is
try {
sample.oneDeclared();
fail();
} catch (SomeCheckedException expected) {
}
}
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_UncheckedThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatThrowsUnchecked();
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, SomeCheckedException.class);
throw Throwables.propagate(t);
}
}
};
// Expect unchecked exception to be thrown as-is
try {
sample.oneDeclared();
fail();
} catch (SomeUncheckedException expected) {
}
}
@GwtIncompatible // throwIfInstanceOf
public void testPropagateIfInstanceOf_UndeclaredThrown() throws SomeCheckedException {
Sample sample =
new Sample() {
@Override
public void oneDeclared() throws SomeCheckedException {
try {
methodThatThrowsOtherChecked();
} catch (Throwable t) {
Throwables.propagateIfInstanceOf(t, SomeCheckedException.class);
throw Throwables.propagate(t);
}
}
};
// Expect undeclared exception wrapped by RuntimeException to be thrown
try {
sample.oneDeclared();
fail();
} catch (RuntimeException expected) {
assertThat(expected).hasCauseThat().isInstanceOf(SomeOtherCheckedException.class);
}
}
@GwtIncompatible // throwIfInstanceOf
public void testThrowIfInstanceOf_null() throws SomeCheckedException {
try {
throwIfInstanceOf(null, SomeCheckedException.class);
fail();
} catch (NullPointerException expected) {
}
}
@GwtIncompatible // throwIfInstanceOf
public void testPropageIfInstanceOf_null() throws SomeCheckedException {
Throwables.propagateIfInstanceOf(null, SomeCheckedException.class);
}
public void testGetRootCause_NoCause() {
SomeCheckedException exception = new SomeCheckedException();
assertSame(exception, Throwables.getRootCause(exception));
}
public void testGetRootCause_SingleWrapped() {
SomeCheckedException cause = new SomeCheckedException();
SomeChainingException exception = new SomeChainingException(cause);
assertSame(cause, Throwables.getRootCause(exception));
}
public void testGetRootCause_DoubleWrapped() {
SomeCheckedException cause = new SomeCheckedException();
SomeChainingException exception = new SomeChainingException(new SomeChainingException(cause));
assertSame(cause, Throwables.getRootCause(exception));
}
public void testGetRootCause_Loop() {
Exception cause = new Exception();
Exception exception = new Exception(cause);
cause.initCause(exception);
try {
Throwables.getRootCause(cause);
fail("Should have throw IAE");
} catch (IllegalArgumentException expected) {
assertThat(expected).hasCauseThat().isSameInstanceAs(cause);
}
}
private static class SomeError extends Error {}
private static class SomeCheckedException extends Exception {}
private static class SomeOtherCheckedException extends Exception {}
private static class SomeUncheckedException extends RuntimeException {}
private static class SomeUndeclaredCheckedException extends Exception {}
private static class SomeChainingException extends RuntimeException {
public SomeChainingException(Throwable cause) {
super(cause);
}
}
static class Sample {
void noneDeclared() {}
void oneDeclared() throws SomeCheckedException {}
void twoDeclared() throws SomeCheckedException, SomeOtherCheckedException {}
}
static void methodThatDoesntThrowAnything() {}
static void methodThatThrowsError() {
throw new SomeError();
}
static void methodThatThrowsUnchecked() {
throw new SomeUncheckedException();
}
static void methodThatThrowsChecked() throws SomeCheckedException {
throw new SomeCheckedException();
}
static void methodThatThrowsOtherChecked() throws SomeOtherCheckedException {
throw new SomeOtherCheckedException();
}
static void methodThatThrowsUndeclaredChecked() throws SomeUndeclaredCheckedException {
throw new SomeUndeclaredCheckedException();
}
@GwtIncompatible // getStackTraceAsString(Throwable)
public void testGetStackTraceAsString() {
class StackTraceException extends Exception {
StackTraceException(String message) {
super(message);
}
}
StackTraceException e = new StackTraceException("my message");
String firstLine = quote(e.getClass().getName() + ": " + e.getMessage());
String secondLine = "\\s*at " + ThrowablesTest.class.getName() + "\\..*";
String moreLines = "(?:.*\n?)*";
String expected = firstLine + "\n" + secondLine + "\n" + moreLines;
assertThat(getStackTraceAsString(e)).matches(expected);
}
public void testGetCausalChain() {
SomeUncheckedException sue = new SomeUncheckedException();
IllegalArgumentException iae = new IllegalArgumentException(sue);
RuntimeException re = new RuntimeException(iae);
IllegalStateException ex = new IllegalStateException(re);
assertEquals(asList(ex, re, iae, sue), Throwables.getCausalChain(ex));
assertSame(sue, Iterables.getOnlyElement(Throwables.getCausalChain(sue)));
List<Throwable> causes = Throwables.getCausalChain(ex);
try {
causes.add(new RuntimeException());
fail("List should be unmodifiable");
} catch (UnsupportedOperationException expected) {
}
}
public void testGetCasualChainNull() {
try {
Throwables.getCausalChain(null);
fail("Should have throw NPE");
} catch (NullPointerException expected) {
}
}
public void testGetCasualChainLoop() {
Exception cause = new Exception();
Exception exception = new Exception(cause);
cause.initCause(exception);
try {
Throwables.getCausalChain(cause);
fail("Should have throw IAE");
} catch (IllegalArgumentException expected) {
assertThat(expected).hasCauseThat().isSameInstanceAs(cause);
}
}
@GwtIncompatible // Throwables.getCauseAs(Throwable, Class)
public void testGetCauseAs() {
SomeCheckedException cause = new SomeCheckedException();
SomeChainingException thrown = new SomeChainingException(cause);
assertThat(thrown).hasCauseThat().isSameInstanceAs(cause);
assertThat(Throwables.getCauseAs(thrown, SomeCheckedException.class)).isSameInstanceAs(cause);
assertThat(Throwables.getCauseAs(thrown, Exception.class)).isSameInstanceAs(cause);
try {
Throwables.getCauseAs(thrown, IllegalStateException.class);
fail("Should have thrown CCE");
} catch (ClassCastException expected) {
assertThat(expected).hasCauseThat().isSameInstanceAs(thrown);
}
}
@AndroidIncompatible // No getJavaLangAccess in Android (at least not in the version we use).
@GwtIncompatible // lazyStackTraceIsLazy()
public void testLazyStackTraceWorksInProd() {
// TODO(b/64442212): Remove this guard once lazyStackTrace() works in Java 9+.
Integer javaVersion = Ints.tryParse(JAVA_SPECIFICATION_VERSION.value());
if (javaVersion != null && javaVersion >= 9) {
return;
}
// Obviously this isn't guaranteed in every environment, but it works well enough for now:
assertTrue(lazyStackTraceIsLazy());
}
@GwtIncompatible // lazyStackTrace(Throwable)
public void testLazyStackTrace() {
Exception e = new Exception();
StackTraceElement[] originalStackTrace = e.getStackTrace();
assertThat(lazyStackTrace(e)).containsExactly((Object[]) originalStackTrace).inOrder();
try {
lazyStackTrace(e).set(0, null);
fail();
} catch (UnsupportedOperationException expected) {
}
// Now we test a property that holds only for the lazy implementation.
if (!lazyStackTraceIsLazy()) {
return;
}
e.setStackTrace(new StackTraceElement[0]);
assertThat(lazyStackTrace(e)).containsExactly((Object[]) originalStackTrace).inOrder();
}
@GwtIncompatible // lazyStackTrace
private void doTestLazyStackTraceFallback() {
assertFalse(lazyStackTraceIsLazy());
Exception e = new Exception();
assertThat(lazyStackTrace(e)).containsExactly((Object[]) e.getStackTrace()).inOrder();
try {
lazyStackTrace(e).set(0, null);
fail();
} catch (UnsupportedOperationException expected) {
}
e.setStackTrace(new StackTraceElement[0]);
assertThat(lazyStackTrace(e)).isEmpty();
}
@GwtIncompatible // NullPointerTester
public void testNullPointers() {
new NullPointerTester().testAllPublicStaticMethods(Throwables.class);
}
}
| google/guava | guava-tests/test/com/google/common/base/ThrowablesTest.java | Java | apache-2.0 | 23,841 |
/*
* 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.core.lookup;
/**
* A default lookup for others to extend.
*
* @since 2.1
*/
public abstract class AbstractLookup implements StrLookup {
/**
* Calls {@code lookup(null, key);}
*
* @see StrLookup#lookup(LogEvent, String)
*/
@Override
public String lookup(final String key) {
return lookup(null, key);
}
}
| elitecodegroovy/log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/AbstractLookup.java | Java | apache-2.0 | 1,190 |
/*
* Copyright 2017 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.jbpm.designer.epn.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonParseException;
import org.jbpm.designer.epn.EpnMarshallerHelper;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
/**
* an unmarshaller to transform JSON into EPN elements.
*/
public class EpnJsonUnmarshaller {
private Map<Object, String> _objMap = new HashMap<Object, String>();
private Map<String, Object> _idMap = new HashMap<String, Object>();
private List<EpnMarshallerHelper> _helpers;
public EpnJsonUnmarshaller() {
_helpers = new ArrayList<EpnMarshallerHelper>();
// load the helpers to place them in field
if (getClass().getClassLoader() instanceof BundleReference) {
BundleContext context = ((BundleReference) getClass().getClassLoader()).
getBundle().getBundleContext();
try {
ServiceReference[] refs = context.getAllServiceReferences(
EpnMarshallerHelper.class.getName(),
null);
for (ServiceReference ref : refs) {
EpnMarshallerHelper helper = (EpnMarshallerHelper) context.getService(ref);
_helpers.add(helper);
}
} catch (InvalidSyntaxException e) {
}
}
}
public Object unmarshall(String json) throws JsonParseException, IOException {
return ""; //TODO empty for now until we finish the epn ecore model
}
}
| tsurdilo/jbpm-designer | jbpm-designer-backend/src/main/java/org/jbpm/designer/epn/impl/EpnJsonUnmarshaller.java | Java | apache-2.0 | 2,354 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2002, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Robert D. Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser 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 gnu.trove.decorator;
import gnu.trove.map.TByteFloatMap;
import gnu.trove.iterator.TByteFloatIterator;
import java.io.*;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Wrapper class to make a TByteFloatMap conform to the <tt>java.util.Map</tt> API.
* This class simply decorates an underlying TByteFloatMap and translates the Object-based
* APIs into their Trove primitive analogs.
* <p/>
* Note that wrapping and unwrapping primitive values is extremely inefficient. If
* possible, users of this class should override the appropriate methods in this class
* and use a table of canonical values.
* <p/>
* Created: Mon Sep 23 22:07:40 PDT 2002
*
* @author Eric D. Friedman
* @author Robert D. Eden
* @author Jeff Randall
*/
public class TByteFloatMapDecorator extends AbstractMap<Byte, Float>
implements Map<Byte, Float>, Externalizable, Cloneable {
static final long serialVersionUID = 1L;
/** the wrapped primitive map */
protected TByteFloatMap _map;
/**
* FOR EXTERNALIZATION ONLY!!
*/
public TByteFloatMapDecorator() {}
/**
* Creates a wrapper that decorates the specified primitive map.
*
* @param map the <tt>TByteFloatMap</tt> to wrap.
*/
public TByteFloatMapDecorator( TByteFloatMap map ) {
super();
this._map = map;
}
/**
* Returns a reference to the map wrapped by this decorator.
*
* @return the wrapped <tt>TByteFloatMap</tt> instance.
*/
public TByteFloatMap getMap() {
return _map;
}
/**
* Inserts a key/value pair into the map.
*
* @param key an <code>Object</code> value
* @param value an <code>Object</code> value
* @return the previous value associated with <tt>key</tt>,
* or Float(0) if none was found.
*/
public Float put( Byte key, Float value ) {
byte k;
float v;
if ( key == null ) {
k = _map.getNoEntryKey();
} else {
k = unwrapKey( key );
}
if ( value == null ) {
v = _map.getNoEntryValue();
} else {
v = unwrapValue( value );
}
float retval = _map.put( k, v );
if ( retval == _map.getNoEntryValue() ) {
return null;
}
return wrapValue( retval );
}
/**
* Retrieves the value for <tt>key</tt>
*
* @param key an <code>Object</code> value
* @return the value of <tt>key</tt> or null if no such mapping exists.
*/
public Float get( Object key ) {
byte k;
if ( key != null ) {
if ( key instanceof Byte ) {
k = unwrapKey( key );
} else {
return null;
}
} else {
k = _map.getNoEntryKey();
}
float v = _map.get( k );
// There may be a false positive since primitive maps
// cannot return null, so we have to do an extra
// check here.
if ( v == _map.getNoEntryValue() ) {
return null;
} else {
return wrapValue( v );
}
}
/**
* Empties the map.
*/
public void clear() {
this._map.clear();
}
/**
* Deletes a key/value pair from the map.
*
* @param key an <code>Object</code> value
* @return the removed value, or null if it was not found in the map
*/
public Float remove( Object key ) {
byte k;
if ( key != null ) {
if ( key instanceof Byte ) {
k = unwrapKey( key );
} else {
return null;
}
} else {
k = _map.getNoEntryKey();
}
float v = _map.remove( k );
// There may be a false positive since primitive maps
// cannot return null, so we have to do an extra
// check here.
if ( v == _map.getNoEntryValue() ) {
return null;
} else {
return wrapValue( v );
}
}
/**
* Returns a Set view on the entries of the map.
*
* @return a <code>Set</code> value
*/
public Set<Map.Entry<Byte,Float>> entrySet() {
return new AbstractSet<Map.Entry<Byte,Float>>() {
public int size() {
return _map.size();
}
public boolean isEmpty() {
return TByteFloatMapDecorator.this.isEmpty();
}
public boolean contains( Object o ) {
if (o instanceof Map.Entry) {
Object k = ( ( Map.Entry ) o ).getKey();
Object v = ( ( Map.Entry ) o ).getValue();
return TByteFloatMapDecorator.this.containsKey(k)
&& TByteFloatMapDecorator.this.get(k).equals(v);
} else {
return false;
}
}
public Iterator<Map.Entry<Byte,Float>> iterator() {
return new Iterator<Map.Entry<Byte,Float>>() {
private final TByteFloatIterator it = _map.iterator();
public Map.Entry<Byte,Float> next() {
it.advance();
final Byte key = wrapKey( it.key() );
final Float v = wrapValue( it.value() );
return new Map.Entry<Byte,Float>() {
private Float val = v;
public boolean equals( Object o ) {
return o instanceof Map.Entry
&& ( ( Map.Entry ) o ).getKey().equals(key)
&& ( ( Map.Entry ) o ).getValue().equals(val);
}
public Byte getKey() {
return key;
}
public Float getValue() {
return val;
}
public int hashCode() {
return key.hashCode() + val.hashCode();
}
public Float setValue( Float value ) {
val = value;
return put( key, value );
}
};
}
public boolean hasNext() {
return it.hasNext();
}
public void remove() {
it.remove();
}
};
}
public boolean add( Map.Entry<Byte,Float> o ) {
throw new UnsupportedOperationException();
}
public boolean remove( Object o ) {
boolean modified = false;
if ( contains( o ) ) {
//noinspection unchecked
Byte key = ( ( Map.Entry<Byte,Float> ) o ).getKey();
_map.remove( unwrapKey( key ) );
modified = true;
}
return modified;
}
public boolean addAll( Collection<? extends Map.Entry<Byte, Float>> c ) {
throw new UnsupportedOperationException();
}
public void clear() {
TByteFloatMapDecorator.this.clear();
}
};
}
/**
* Checks for the presence of <tt>val</tt> in the values of the map.
*
* @param val an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsValue( Object val ) {
return val instanceof Float && _map.containsValue( unwrapValue( val ) );
}
/**
* Checks for the present of <tt>key</tt> in the keys of the map.
*
* @param key an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean containsKey( Object key ) {
if ( key == null ) return _map.containsKey( _map.getNoEntryKey() );
return key instanceof Byte && _map.containsKey( unwrapKey( key ) );
}
/**
* Returns the number of entries in the map.
*
* @return the map's size.
*/
public int size() {
return this._map.size();
}
/**
* Indicates whether map has any entries.
*
* @return true if the map is empty
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Copies the key/value mappings in <tt>map</tt> into this map.
* Note that this will be a <b>deep</b> copy, as storage is by
* primitive value.
*
* @param map a <code>Map</code> value
*/
public void putAll( Map<? extends Byte, ? extends Float> map ) {
Iterator<? extends Entry<? extends Byte,? extends Float>> it =
map.entrySet().iterator();
for ( int i = map.size(); i-- > 0; ) {
Entry<? extends Byte,? extends Float> e = it.next();
this.put( e.getKey(), e.getValue() );
}
}
/**
* Wraps a key
*
* @param k key in the underlying map
* @return an Object representation of the key
*/
protected Byte wrapKey( byte k ) {
return Byte.valueOf( k );
}
/**
* Unwraps a key
*
* @param key wrapped key
* @return an unwrapped representation of the key
*/
protected byte unwrapKey( Object key ) {
return ( ( Byte ) key ).byteValue();
}
/**
* Wraps a value
*
* @param k value in the underlying map
* @return an Object representation of the value
*/
protected Float wrapValue( float k ) {
return Float.valueOf( k );
}
/**
* Unwraps a value
*
* @param value wrapped value
* @return an unwrapped representation of the value
*/
protected float unwrapValue( Object value ) {
return ( ( Float ) value ).floatValue();
}
// Implements Externalizable
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// MAP
_map = ( TByteFloatMap ) in.readObject();
}
// Implements Externalizable
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte(0);
// MAP
out.writeObject( _map );
}
} // TByteFloatHashMapDecorator
| feesa/easyrec-parent | easyrec-utils/src/main/java/gnu/trove/decorator/TByteFloatMapDecorator.java | Java | apache-2.0 | 11,766 |
/*
* 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.hadoop.hive.ql.udf.generic;
import static org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory.javaDoubleObjectInspector;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer;
import org.apache.hadoop.hive.serde2.io.DoubleWritable;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.io.LongWritable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import com.google.common.collect.Lists;
@RunWith(Parameterized.class)
public class TestGenericUDAFBinarySetFunctions {
private List<Object[]> rowSet;
@Parameters(name = "{0}")
public static List<Object[]> getParameters() {
List<Object[]> ret = new ArrayList<>();
ret.add(new Object[] { "seq/seq", RowSetGenerator.generate(10,
new RowSetGenerator.DoubleSequence(0), new RowSetGenerator.DoubleSequence(0)) });
ret.add(new Object[] { "seq/ones", RowSetGenerator.generate(10,
new RowSetGenerator.DoubleSequence(0), new RowSetGenerator.ConstantSequence(1.0)) });
ret.add(new Object[] { "ones/seq", RowSetGenerator.generate(10,
new RowSetGenerator.ConstantSequence(1.0), new RowSetGenerator.DoubleSequence(0)) });
ret.add(new Object[] { "empty", RowSetGenerator.generate(0,
new RowSetGenerator.DoubleSequence(0), new RowSetGenerator.DoubleSequence(0)) });
ret.add(new Object[] { "lonely", RowSetGenerator.generate(1,
new RowSetGenerator.DoubleSequence(10), new RowSetGenerator.DoubleSequence(10)) });
ret.add(new Object[] { "seq/seq+10", RowSetGenerator.generate(10,
new RowSetGenerator.DoubleSequence(0), new RowSetGenerator.DoubleSequence(10)) });
ret.add(new Object[] { "seq/null", RowSetGenerator.generate(10,
new RowSetGenerator.DoubleSequence(0), new RowSetGenerator.ConstantSequence(null)) });
ret.add(new Object[] { "null/seq0", RowSetGenerator.generate(10,
new RowSetGenerator.ConstantSequence(null), new RowSetGenerator.DoubleSequence(0)) });
return ret;
}
public static class GenericUDAFExecutor {
private GenericUDAFResolver2 evaluatorFactory;
private GenericUDAFParameterInfo info;
private ObjectInspector[] partialOIs;
public GenericUDAFExecutor(GenericUDAFResolver2 evaluatorFactory, GenericUDAFParameterInfo info)
throws Exception {
this.evaluatorFactory = evaluatorFactory;
this.info = info;
GenericUDAFEvaluator eval0 = evaluatorFactory.getEvaluator(info);
partialOIs = new ObjectInspector[] {
eval0.init(GenericUDAFEvaluator.Mode.PARTIAL1, info.getParameterObjectInspectors()) };
}
List<Object> run(List<Object[]> values) throws Exception {
Object r1 = runComplete(values);
Object r2 = runPartialFinal(values);
Object r3 = runPartial2Final(values);
return Lists.newArrayList(r1, r2, r3);
}
private Object runComplete(List<Object[]> values) throws SemanticException, HiveException {
GenericUDAFEvaluator eval = evaluatorFactory.getEvaluator(info);
eval.init(GenericUDAFEvaluator.Mode.COMPLETE, info.getParameterObjectInspectors());
AggregationBuffer agg = eval.getNewAggregationBuffer();
for (Object[] parameters : values) {
eval.iterate(agg, parameters);
}
return eval.terminate(agg);
}
private Object runPartialFinal(List<Object[]> values) throws Exception {
GenericUDAFEvaluator eval = evaluatorFactory.getEvaluator(info);
eval.init(GenericUDAFEvaluator.Mode.FINAL, partialOIs);
AggregationBuffer buf = eval.getNewAggregationBuffer();
for (Object partialResult : runPartial1(values)) {
eval.merge(buf, partialResult);
}
return eval.terminate(buf);
}
private Object runPartial2Final(List<Object[]> values) throws Exception {
GenericUDAFEvaluator eval = evaluatorFactory.getEvaluator(info);
eval.init(GenericUDAFEvaluator.Mode.FINAL, partialOIs);
AggregationBuffer buf = eval.getNewAggregationBuffer();
for (Object partialResult : runPartial2(runPartial1(values))) {
eval.merge(buf, partialResult);
}
return eval.terminate(buf);
}
private List<Object> runPartial1(List<Object[]> values) throws Exception {
List<Object> ret = new ArrayList<>();
int batchSize = 1;
Iterator<Object[]> iter = values.iterator();
do {
GenericUDAFEvaluator eval = evaluatorFactory.getEvaluator(info);
eval.init(GenericUDAFEvaluator.Mode.PARTIAL1, info.getParameterObjectInspectors());
AggregationBuffer buf = eval.getNewAggregationBuffer();
for (int i = 0; i < batchSize - 1 && iter.hasNext(); i++) {
eval.iterate(buf, iter.next());
}
batchSize <<= 1;
ret.add(eval.terminatePartial(buf));
// back-check to force at least 1 output; and this should have a partial which is empty
} while (iter.hasNext());
return ret;
}
private List<Object> runPartial2(List<Object> values) throws Exception {
List<Object> ret = new ArrayList<>();
int batchSize = 1;
Iterator<Object> iter = values.iterator();
do {
GenericUDAFEvaluator eval = evaluatorFactory.getEvaluator(info);
eval.init(GenericUDAFEvaluator.Mode.PARTIAL2, partialOIs);
AggregationBuffer buf = eval.getNewAggregationBuffer();
for (int i = 0; i < batchSize - 1 && iter.hasNext(); i++) {
eval.merge(buf, iter.next());
}
batchSize <<= 1;
ret.add(eval.terminatePartial(buf));
// back-check to force at least 1 output; and this should have a partial which is empty
} while (iter.hasNext());
return ret;
}
}
public static class RowSetGenerator {
public static interface FieldGenerator {
public Object apply(int rowIndex);
}
public static class ConstantSequence implements FieldGenerator {
private Object constant;
public ConstantSequence(Object constant) {
this.constant = constant;
}
@Override
public Object apply(int rowIndex) {
return constant;
}
}
public static class DoubleSequence implements FieldGenerator {
private int offset;
public DoubleSequence(int offset) {
this.offset = offset;
}
@Override
public Object apply(int rowIndex) {
double d = rowIndex + offset;
return d;
}
}
public static List<Object[]> generate(int numRows, FieldGenerator... generators) {
ArrayList<Object[]> ret = new ArrayList<>(numRows);
for (int rowIdx = 0; rowIdx < numRows; rowIdx++) {
ArrayList<Object> row = new ArrayList<>();
for (FieldGenerator g : generators) {
row.add(g.apply(rowIdx));
}
ret.add(row.toArray());
}
return ret;
}
}
public TestGenericUDAFBinarySetFunctions(String label, List<Object[]> rowSet) {
this.rowSet = rowSet;
}
@Test
public void regr_count() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.count(), new GenericUDAFBinarySetFunctions.RegrCount());
}
@Test
public void regr_sxx() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.sxx(), new GenericUDAFBinarySetFunctions.RegrSXX());
}
@Test
public void regr_syy() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.syy(), new GenericUDAFBinarySetFunctions.RegrSYY());
}
@Test
public void regr_sxy() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.sxy(), new GenericUDAFBinarySetFunctions.RegrSXY());
}
@Test
public void regr_avgx() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.avgx(), new GenericUDAFBinarySetFunctions.RegrAvgX());
}
@Test
public void regr_avgy() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.avgy(), new GenericUDAFBinarySetFunctions.RegrAvgY());
}
@Test
public void regr_slope() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.slope(), new GenericUDAFBinarySetFunctions.RegrSlope());
}
@Test
public void regr_r2() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.r2(), new GenericUDAFBinarySetFunctions.RegrR2());
}
@Test
public void regr_intercept() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.intercept(), new GenericUDAFBinarySetFunctions.RegrIntercept());
}
@Test
public void corr() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.corr(), new GenericUDAFCorrelation());
}
@Test
public void covar_pop() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.covar_pop(), new GenericUDAFCovariance());
}
@Test
public void covar_samp() throws Exception {
RegrIntermediate expected = RegrIntermediate.computeFor(rowSet);
validateUDAF(expected.covar_samp(), new GenericUDAFCovarianceSample());
}
private void validateUDAF(Double expectedResult, GenericUDAFResolver2 udaf) throws Exception {
ObjectInspector[] params =
new ObjectInspector[] { javaDoubleObjectInspector, javaDoubleObjectInspector };
GenericUDAFParameterInfo gpi = new SimpleGenericUDAFParameterInfo(params, false, false, false);
GenericUDAFExecutor executor = new GenericUDAFExecutor(udaf, gpi);
List<Object> values = executor.run(rowSet);
if (expectedResult == null) {
for (Object v : values) {
assertNull(v);
}
} else {
for (Object v : values) {
if (v instanceof DoubleWritable) {
assertEquals(expectedResult, ((DoubleWritable) v).get(), 1e-10);
} else {
assertEquals(expectedResult, ((LongWritable) v).get(), 1e-10);
}
}
}
}
static class RegrIntermediate {
public double sum_x2, sum_y2;
public double sum_x, sum_y;
public double sum_xy;
public double n;
public void add(Double y, Double x) {
if (x == null || y == null) {
return;
}
sum_x2 += x * x;
sum_y2 += y * y;
sum_x += x;
sum_y += y;
sum_xy += x * y;
n++;
}
public Double intercept() {
double xx = n * sum_x2 - sum_x * sum_x;
if (n == 0 || xx == 0.0d)
return null;
return (sum_y * sum_x2 - sum_x * sum_xy) / xx;
}
public Double sxy() {
if (n == 0)
return null;
return sum_xy - sum_x * sum_y / n;
}
public Double covar_pop() {
if (n == 0)
return null;
return (sum_xy - sum_x * sum_y / n) / n;
}
public Double covar_samp() {
if (n <= 1)
return null;
return (sum_xy - sum_x * sum_y / n) / (n - 1);
}
public Double corr() {
double xx = n * sum_x2 - sum_x * sum_x;
double yy = n * sum_y2 - sum_y * sum_y;
if (n == 0 || xx == 0.0d || yy == 0.0d)
return null;
double c = n * sum_xy - sum_x * sum_y;
return Math.sqrt(c * c / xx / yy);
}
public Double r2() {
double xx = n * sum_x2 - sum_x * sum_x;
double yy = n * sum_y2 - sum_y * sum_y;
if (n == 0 || xx == 0.0d)
return null;
if (yy == 0.0d)
return 1.0d;
double c = n * sum_xy - sum_x * sum_y;
return c * c / xx / yy;
}
public Double slope() {
if (n == 0 || n * sum_x2 == sum_x * sum_x)
return null;
return (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x * sum_x);
}
public Double avgx() {
if (n == 0)
return null;
return sum_x / n;
}
public Double avgy() {
if (n == 0)
return null;
return sum_y / n;
}
public Double count() {
return n;
}
public Double sxx() {
if (n == 0)
return null;
return sum_x2 - sum_x * sum_x / n;
}
public Double syy() {
if (n == 0)
return null;
return sum_y2 - sum_y * sum_y / n;
}
public static RegrIntermediate computeFor(List<Object[]> rows) {
RegrIntermediate ri = new RegrIntermediate();
for (Object[] objects : rows) {
ri.add((Double) objects[0], (Double) objects[1]);
}
return ri;
}
}
}
| vineetgarg02/hive | ql/src/test/org/apache/hadoop/hive/ql/udf/generic/TestGenericUDAFBinarySetFunctions.java | Java | apache-2.0 | 13,878 |
/*
* Licensed to ElasticSearch and Shay Banon 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.common.joda;
import org.elasticsearch.common.Strings;
import org.joda.time.*;
import org.joda.time.field.DividedDateTimeField;
import org.joda.time.field.OffsetDateTimeField;
import org.joda.time.field.ScaledDurationField;
import org.joda.time.format.*;
/**
*
*/
public class Joda {
/**
* Parses a joda based pattern, including some named ones (similar to the built in Joda ISO ones).
*/
public static FormatDateTimeFormatter forPattern(String input) {
DateTimeFormatter formatter;
if ("basicDate".equals(input) || "basic_date".equals(input)) {
formatter = ISODateTimeFormat.basicDate();
} else if ("basicDateTime".equals(input) || "basic_date_time".equals(input)) {
formatter = ISODateTimeFormat.basicDateTime();
} else if ("basicDateTimeNoMillis".equals(input) || "basic_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicDateTimeNoMillis();
} else if ("basicOrdinalDate".equals(input) || "basic_ordinal_date".equals(input)) {
formatter = ISODateTimeFormat.basicOrdinalDate();
} else if ("basicOrdinalDateTime".equals(input) || "basic_ordinal_date_time".equals(input)) {
formatter = ISODateTimeFormat.basicOrdinalDateTime();
} else if ("basicOrdinalDateTimeNoMillis".equals(input) || "basic_ordinal_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicOrdinalDateTimeNoMillis();
} else if ("basicTime".equals(input) || "basic_time".equals(input)) {
formatter = ISODateTimeFormat.basicTime();
} else if ("basicTimeNoMillis".equals(input) || "basic_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicTimeNoMillis();
} else if ("basicTTime".equals(input) || "basic_t_Time".equals(input)) {
formatter = ISODateTimeFormat.basicTTime();
} else if ("basicTTimeNoMillis".equals(input) || "basic_t_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicTTimeNoMillis();
} else if ("basicWeekDate".equals(input) || "basic_week_date".equals(input)) {
formatter = ISODateTimeFormat.basicWeekDate();
} else if ("basicWeekDateTime".equals(input) || "basic_week_date_time".equals(input)) {
formatter = ISODateTimeFormat.basicWeekDateTime();
} else if ("basicWeekDateTimeNoMillis".equals(input) || "basic_week_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.basicWeekDateTimeNoMillis();
} else if ("date".equals(input)) {
formatter = ISODateTimeFormat.date();
} else if ("dateHour".equals(input) || "date_hour".equals(input)) {
formatter = ISODateTimeFormat.dateHour();
} else if ("dateHourMinute".equals(input) || "date_hour_minute".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinute();
} else if ("dateHourMinuteSecond".equals(input) || "date_hour_minute_second".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinuteSecond();
} else if ("dateHourMinuteSecondFraction".equals(input) || "date_hour_minute_second_fraction".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinuteSecondFraction();
} else if ("dateHourMinuteSecondMillis".equals(input) || "date_hour_minute_second_millis".equals(input)) {
formatter = ISODateTimeFormat.dateHourMinuteSecondMillis();
} else if ("dateOptionalTime".equals(input) || "date_optional_time".equals(input)) {
// in this case, we have a separate parser and printer since the dataOptionalTimeParser can't print
return new FormatDateTimeFormatter(input,
ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC),
ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC));
} else if ("dateTime".equals(input) || "date_time".equals(input)) {
formatter = ISODateTimeFormat.dateTime();
} else if ("dateTimeNoMillis".equals(input) || "date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.dateTimeNoMillis();
} else if ("hour".equals(input)) {
formatter = ISODateTimeFormat.hour();
} else if ("hourMinute".equals(input) || "hour_minute".equals(input)) {
formatter = ISODateTimeFormat.hourMinute();
} else if ("hourMinuteSecond".equals(input) || "hour_minute_second".equals(input)) {
formatter = ISODateTimeFormat.hourMinuteSecond();
} else if ("hourMinuteSecondFraction".equals(input) || "hour_minute_second_fraction".equals(input)) {
formatter = ISODateTimeFormat.hourMinuteSecondFraction();
} else if ("hourMinuteSecondMillis".equals(input) || "hour_minute_second_millis".equals(input)) {
formatter = ISODateTimeFormat.hourMinuteSecondMillis();
} else if ("ordinalDate".equals(input) || "ordinal_date".equals(input)) {
formatter = ISODateTimeFormat.ordinalDate();
} else if ("ordinalDateTime".equals(input) || "ordinal_date_time".equals(input)) {
formatter = ISODateTimeFormat.ordinalDateTime();
} else if ("ordinalDateTimeNoMillis".equals(input) || "ordinal_date_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.ordinalDateTimeNoMillis();
} else if ("time".equals(input)) {
formatter = ISODateTimeFormat.time();
} else if ("tTime".equals(input) || "t_time".equals(input)) {
formatter = ISODateTimeFormat.tTime();
} else if ("tTimeNoMillis".equals(input) || "t_time_no_millis".equals(input)) {
formatter = ISODateTimeFormat.tTimeNoMillis();
} else if ("weekDate".equals(input) || "week_date".equals(input)) {
formatter = ISODateTimeFormat.weekDate();
} else if ("weekDateTime".equals(input) || "week_date_time".equals(input)) {
formatter = ISODateTimeFormat.weekDateTime();
} else if ("weekyear".equals(input) || "week_year".equals(input)) {
formatter = ISODateTimeFormat.weekyear();
} else if ("weekyearWeek".equals(input)) {
formatter = ISODateTimeFormat.weekyearWeek();
} else if ("year".equals(input)) {
formatter = ISODateTimeFormat.year();
} else if ("yearMonth".equals(input) || "year_month".equals(input)) {
formatter = ISODateTimeFormat.yearMonth();
} else if ("yearMonthDay".equals(input) || "year_month_day".equals(input)) {
formatter = ISODateTimeFormat.yearMonthDay();
} else {
String[] formats = Strings.delimitedListToStringArray(input, "||");
if (formats == null || formats.length == 1) {
formatter = DateTimeFormat.forPattern(input);
} else {
DateTimeParser[] parsers = new DateTimeParser[formats.length];
for (int i = 0; i < formats.length; i++) {
parsers[i] = DateTimeFormat.forPattern(formats[i]).withZone(DateTimeZone.UTC).getParser();
}
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.append(DateTimeFormat.forPattern(formats[0]).withZone(DateTimeZone.UTC).getPrinter(), parsers);
formatter = builder.toFormatter();
}
}
return new FormatDateTimeFormatter(input, formatter.withZone(DateTimeZone.UTC));
}
public static final DurationFieldType Quarters = new DurationFieldType("quarters") {
private static final long serialVersionUID = -8167713675442491871L;
public DurationField getField(Chronology chronology) {
return new ScaledDurationField(chronology.months(), Quarters, 3);
}
};
public static final DateTimeFieldType QuarterOfYear = new DateTimeFieldType("quarterOfYear") {
private static final long serialVersionUID = -5677872459807379123L;
public DurationFieldType getDurationType() {
return Quarters;
}
public DurationFieldType getRangeDurationType() {
return DurationFieldType.years();
}
public DateTimeField getField(Chronology chronology) {
return new OffsetDateTimeField(new DividedDateTimeField(new OffsetDateTimeField(chronology.monthOfYear(), -1), QuarterOfYear, 3), 1);
}
};
}
| synhershko/elasticsearch | src/main/java/org/elasticsearch/common/joda/Joda.java | Java | apache-2.0 | 9,289 |
/*
* 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.kylin.invertedindex.index;
import java.util.Iterator;
import it.uniroma3.mat.extendedset.intset.ConciseSet;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
/**
* Within a partition (per timestampGranularity), records are further sliced
* (per sliceLength) to fit into HBASE cell.
*
* @author yangli9
*/
public class Slice implements Iterable<RawTableRecord>, Comparable<Slice> {
TableRecordInfoDigest info;
int nColumns;
short shard;
long timestamp;
int nRecords;
ColumnValueContainer[] containers;
public Slice(TableRecordInfoDigest digest, short shard, long timestamp, ColumnValueContainer[] containers) {
this.info = digest;
this.nColumns = digest.getColumnCount();
this.shard = shard;
this.timestamp = timestamp;
this.nRecords = containers[0].getSize();
this.containers = containers;
assert nColumns == containers.length;
for (int i = 0; i < nColumns; i++) {
assert nRecords == containers[i].getSize();
}
}
public int getRecordCount() {
return this.nRecords;
}
public short getShard() {
return shard;
}
public long getTimestamp() {
return timestamp;
}
public ColumnValueContainer[] getColumnValueContainers() {
return containers;
}
public ColumnValueContainer getColumnValueContainer(int col) {
return containers[col];
}
public Iterator<RawTableRecord> iterateWithBitmap(final ConciseSet resultBitMap) {
if (resultBitMap == null) {
return this.iterator();
} else {
final RawTableRecord rec = info.createTableRecordBytes();
final ImmutableBytesWritable temp = new ImmutableBytesWritable();
return new Iterator<RawTableRecord>() {
int i = 0;
int iteratedCount = 0;
int resultSize = resultBitMap.size();
@Override
public boolean hasNext() {
return iteratedCount < resultSize;
}
@Override
public RawTableRecord next() {
while (!resultBitMap.contains(i)) {
i++;
}
for (int col = 0; col < nColumns; col++) {
containers[col].getValueAt(i, temp);
rec.setValueBytes(col, temp);
}
iteratedCount++;
i++;
return rec;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
@Override
public Iterator<RawTableRecord> iterator() {
return new Iterator<RawTableRecord>() {
int i = 0;
RawTableRecord rec = info.createTableRecordBytes();
ImmutableBytesWritable temp = new ImmutableBytesWritable();
@Override
public boolean hasNext() {
return i < nRecords;
}
@Override
public RawTableRecord next() {
for (int col = 0; col < nColumns; col++) {
containers[col].getValueAt(i, temp);
rec.setValueBytes(col, temp);
}
i++;
return rec;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((info == null) ? 0 : info.hashCode());
result = prime * result + shard;
result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Slice other = (Slice) obj;
if (info == null) {
if (other.info != null)
return false;
} else if (!info.equals(other.info))
return false;
if (shard != other.shard)
return false;
if (timestamp != other.timestamp)
return false;
return true;
}
@Override
public int compareTo(Slice o) {
int comp = this.shard - o.shard;
if (comp != 0)
return comp;
comp = (int) (this.timestamp - o.timestamp);
return comp;
}
}
| 272029252/Kylin | invertedindex/src/main/java/org/apache/kylin/invertedindex/index/Slice.java | Java | apache-2.0 | 5,737 |
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.rest.action.admin.cluster;
import org.elasticsearch.action.admin.cluster.migration.PostFeatureUpgradeAction;
import org.elasticsearch.action.admin.cluster.migration.PostFeatureUpgradeRequest;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.RestToXContentListener;
import java.io.IOException;
import java.util.List;
/**
* Endpoint for triggering a system feature upgrade
*/
public class RestPostFeatureUpgradeAction extends BaseRestHandler {
@Override
public String getName() {
return "post_feature_upgrade";
}
@Override
public List<Route> routes() {
return List.of(new Route(RestRequest.Method.POST, "/_migration/system_features"));
}
@Override
public boolean allowSystemIndexAccessByDefault() {
return true;
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
final PostFeatureUpgradeRequest req = new PostFeatureUpgradeRequest();
req.masterNodeTimeout(request.paramAsTime("master_timeout", req.masterNodeTimeout()));
return restChannel -> { client.execute(PostFeatureUpgradeAction.INSTANCE, req, new RestToXContentListener<>(restChannel)); };
}
}
| GlenRSmith/elasticsearch | server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestPostFeatureUpgradeAction.java | Java | apache-2.0 | 1,730 |
/**
* Copyright (c) 2007-2014 Kaazing Corporation. All rights reserved.
*
* 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.kaazing.gateway.client.impl.http;
import java.util.logging.Logger;
public class HttpRequestUtil {
private static final String CLASS_NAME = HttpRequestUtil.class.getName();
private static final Logger LOG = Logger.getLogger(CLASS_NAME);
private HttpRequestUtil() {
LOG.entering(CLASS_NAME, "<init>");
}
public static void validateHeader(String header) {
LOG.entering(CLASS_NAME, "validateHeader", header);
/*
* From the XMLHttpRequest spec: http://www.w3.org/TR/XMLHttpRequest/#setrequestheader
*
* For security reasons, these steps should be terminated if the header argument case-insensitively matches one of the
* following headers:
*
* Accept-Charset Accept-Encoding Connection Content-Length Content-Transfer-Encoding Date Expect Host Keep-Alive Referer
* TE Trailer Transfer-Encoding Upgrade Via Proxy-* Sec-*
*
* Also for security reasons, these steps should be terminated if the start of the header argument case-insensitively
* matches Proxy- or Se
*/
if (header == null || (header.length() == 0)) {
throw new IllegalArgumentException("Invalid header in the HTTP request");
}
String lowerCaseHeader = header.toLowerCase();
if (lowerCaseHeader.startsWith("proxy-") || lowerCaseHeader.startsWith("sec-")) {
throw new IllegalArgumentException("Headers starting with Proxy-* or Sec-* are prohibited");
}
for (String prohibited : INVALID_HEADERS) {
if (header.equalsIgnoreCase(prohibited)) {
throw new IllegalArgumentException("Headers starting with Proxy-* or Sec-* are prohibited");
}
}
}
private static final String[] INVALID_HEADERS = new String[] { "Accept-Charset", "Accept-Encoding", "Connection",
"Content-Length", "Content-Transfer-Encoding", "Date", "Expect", "Host", "Keep-Alive", "Referer", "TE", "Trailer",
"Transfer-Encoding", "Upgrade", "Via" };
}
| michaelcretzman/java.client | ws/ws/src/main/java/org/kaazing/gateway/client/impl/http/HttpRequestUtil.java | Java | apache-2.0 | 2,967 |
/*
* 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.carbondata.core.scan.executor.infos;
/**
* This method will information about the query dimensions whether they exist in particular block
* and their default value
*/
public class DimensionInfo {
/**
* flag to check whether a given dimension exists in a given block
*/
private boolean[] dimensionExists;
/**
* maintains default value for each dimension
*/
private Object[] defaultValues;
/**
* flag to check whether there exist a dictionary column in the query which
* does not exist in the current block
*/
private boolean isDictionaryColumnAdded;
/**
* flag to check whether there exist a no dictionary column in the query which
* does not exist in the current block
*/
private boolean isNoDictionaryColumnAdded;
/**
* count of dictionary column not existing in the current block
*/
private int newDictionaryColumnCount;
/**
* count of no dictionary columns not existing in the current block
*/
private int newNoDictionaryColumnCount;
/**
* @param dimensionExists
* @param defaultValues
*/
public DimensionInfo(boolean[] dimensionExists, Object[] defaultValues) {
this.dimensionExists = dimensionExists;
this.defaultValues = defaultValues;
}
/**
* @return
*/
public boolean[] getDimensionExists() {
return dimensionExists;
}
/**
* @return
*/
public Object[] getDefaultValues() {
return defaultValues;
}
public boolean isDictionaryColumnAdded() {
return isDictionaryColumnAdded;
}
public void setDictionaryColumnAdded(boolean dictionaryColumnAdded) {
isDictionaryColumnAdded = dictionaryColumnAdded;
}
public boolean isNoDictionaryColumnAdded() {
return isNoDictionaryColumnAdded;
}
public void setNoDictionaryColumnAdded(boolean noDictionaryColumnAdded) {
isNoDictionaryColumnAdded = noDictionaryColumnAdded;
}
public int getNewDictionaryColumnCount() {
return newDictionaryColumnCount;
}
public void setNewDictionaryColumnCount(int newDictionaryColumnCount) {
this.newDictionaryColumnCount = newDictionaryColumnCount;
}
public int getNewNoDictionaryColumnCount() {
return newNoDictionaryColumnCount;
}
public void setNewNoDictionaryColumnCount(int newNoDictionaryColumnCount) {
this.newNoDictionaryColumnCount = newNoDictionaryColumnCount;
}
}
| Sephiroth-Lin/incubator-carbondata | core/src/main/java/org/apache/carbondata/core/scan/executor/infos/DimensionInfo.java | Java | apache-2.0 | 3,174 |
/*
* 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.synapse.commons.executors.queues;
import org.apache.synapse.commons.executors.InternalQueue;
import java.util.*;
import java.util.concurrent.locks.Condition;
/**
* An unbounded queue backed by and ArrayList.
* @param <E>
*/
public class UnboundedQueue<E> extends AbstractQueue<E> implements InternalQueue<E> {
private List<E> elements = new ArrayList<E>();
/**
* Priority of this queue
*/
private int priority;
/**
* A waiting queue when this queue is full
*/
private Condition notFullCond;
public UnboundedQueue(int priority) {
this.priority = priority;
}
public Iterator<E> iterator() {
return elements.iterator();
}
public int size() {
return elements.size();
}
public boolean offer(E e) {
return elements.add(e);
}
public E poll() {
if (elements.size() > 0) {
return elements.remove(elements.size() - 1);
}
return null;
}
public E peek() {
if (elements.size() > 0) {
return elements.get(elements.size() - 1);
}
return null;
}
public int getPriority() {
return priority;
}
public void setPriority(int p) {
this.priority = p;
}
public Condition getNotFullCond() {
return notFullCond;
}
public void setNotFullCond(Condition condition) {
this.notFullCond = condition;
}
public int drainTo(Collection<? super E> c) {
int count = elements.size();
c.addAll(elements);
elements.clear();
return count;
}
public int drainTo(Collection<? super E> c, int maxElements) {
if (maxElements >= elements.size()) {
return drainTo(c);
} else {
elements.subList(elements.size() - maxElements - 1, elements.size());
return maxElements;
}
}
public int remainingCapacity() {
return Integer.MAX_VALUE;
}
public int getCapacity() {
return Integer.MAX_VALUE;
}
@Override
public boolean contains(Object o) {
return elements.contains(o);
}
@Override
public boolean remove(Object o) {
return elements.remove(o);
}
}
| maheshika/wso2-synapse | modules/commons/src/main/java/org/apache/synapse/commons/executors/queues/UnboundedQueue.java | Java | apache-2.0 | 3,113 |
/*
* Copyright Beijing 58 Information Technology Co.,Ltd.
*
* 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.bj58.spat.gaea.server.bootstrap;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import com.bj58.spat.gaea.server.bootstrap.serverframe.ButtonFrame;
import com.bj58.spat.gaea.server.bootstrap.serverframe.MenuBar;
import com.bj58.spat.gaea.server.bootstrap.serverframe.TreeFrame;
import com.bj58.spat.gaea.server.contract.log.ILog;
import com.bj58.spat.gaea.server.contract.log.LogFactory;
/**
* main window
*
* @author Service Platform Architecture Team ([email protected])
*/
public class FrameMain extends JFrame{
private static final long serialVersionUID = 563726381249120291L;
private static ILog logger = null;
public FrameMain(String title){
super(title);
}
public static void main(String []args){
FrameMain frameMain = new FrameMain("授权文件生成器");
frameMain.setSize(450,550);
frameMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/**load log4j*/
logger = LogFactory.getLogger(FrameMain.class);
/**获得显示器大小对象*/
Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize();
/**获得窗口大小对象*/
Dimension frameSize = frameMain.getSize();
if (frameSize.width > displaySize.width){
frameSize.width = displaySize.width;
}
if (frameSize.height > displaySize.height){
frameSize.height = displaySize.height;
}
/**设置窗口居中显示器显示*/
frameMain.setLocation((displaySize.width - frameSize.width) / 2,(displaySize.height - frameSize.height) / 2);
/** Build main MenuBar */
logger.info("-----------------build Menu Start------------------");
frameMain.setJMenuBar(new MenuBar().bulidMenuBar(frameMain));
logger.info("-----------------build Menu End--------------------");
frameMain.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frameMain.setVisible(true);
}
public void createGUI(){
/**tree button*/
JPanel topPanel = new JPanel(new BorderLayout());
JTextArea keyjta = new JTextArea(10,10);
topPanel.add(new JScrollPane(TreeFrame.create().buildTree()),BorderLayout.CENTER);
topPanel.add(new ButtonFrame(keyjta),BorderLayout.SOUTH);
topPanel.setName("top");
/**key生成器*/
JPanel downPanel = new JPanel(new BorderLayout());
downPanel.add(new JScrollPane(keyjta), BorderLayout.CENTER);
downPanel.setName("down");
this.getContentPane().add(topPanel, BorderLayout.CENTER);
this.getContentPane().add(downPanel, BorderLayout.SOUTH);
this.getContentPane().validate();
}
}
| cmqdcyy/Gaea | server/src/bootstrap/com/bj58/spat/gaea/server/bootstrap/FrameMain.java | Java | apache-2.0 | 3,718 |
/*
* 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.dubbo.common.extension;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.remoting.ChannelHandler;
import org.apache.dubbo.remoting.Dispatcher;
public class MockDispatcher implements Dispatcher {
@Override
public ChannelHandler dispatch(ChannelHandler handler, URL url) {
return null;
}
}
| qtvbwfn/dubbo | dubbo-compatible/src/test/java/org/apache/dubbo/common/extension/MockDispatcher.java | Java | apache-2.0 | 1,144 |
/*
* Copyright (c) 2008-2014, Harald Walker (bitwalker.eu) and contributing developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of bitwalker nor the names of its
* contributors may be used to endorse or promote products
* derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package eu.bitwalker.useragentutils;
/**
* Enum constants classifying the different types of applications which are common in referrer strings
* @author harald
*
*/
public enum ApplicationType {
/**
* Webmail service like Windows Live Hotmail and Gmail.
*/
WEBMAIL("Webmail client"),
UNKNOWN("unknown");
private String name;
private ApplicationType(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| KciNKh/user-agent-utils | src/main/java/eu/bitwalker/useragentutils/ApplicationType.java | Java | bsd-3-clause | 2,049 |
/*
* The MIT License
*
* Copyright 2015 CloudBees Inc.
*
* 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 jenkins.model;
import hudson.model.FreeStyleProject;
import hudson.model.LoadStatistics;
import hudson.model.Node;
import hudson.model.ParametersAction;
import hudson.model.Queue;
import hudson.model.StringParameterValue;
import hudson.model.labels.LabelAtom;
import hudson.slaves.DumbSlave;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import static org.junit.Assert.*;
/**
* Tests for {@link UnlabeledLoadStatistics} class.
* @author Oleg Nenashev
*/
public class UnlabeledLoadStatisticsTest {
@Rule
public JenkinsRule j = new JenkinsRule();
private final LoadStatistics unlabeledLoad = new UnlabeledLoadStatistics();
@After
public void clearQueue() {
j.getInstance().getQueue().clear();
}
@Test
@Issue("JENKINS-28446")
public void computeQueueLength() throws Exception {
final Queue queue = j.jenkins.getQueue();
assertEquals("Queue must be empty when the test starts", 0, queue.getBuildableItems().size());
assertEquals("Statistics must return 0 when the test starts", 0, unlabeledLoad.computeQueueLength());
// Disable builds by default, create an agent to prevent assigning of "master" labels
j.jenkins.setNumExecutors(0);
DumbSlave slave = j.createOnlineSlave(new LabelAtom("testLabel"));
slave.setMode(Node.Mode.EXCLUSIVE);
// Init project
FreeStyleProject unlabeledProject = j.createFreeStyleProject("UnlabeledProject");
unlabeledProject.setConcurrentBuild(true);
FreeStyleProject labeledProject = j.createFreeStyleProject("LabeledProject");
labeledProject.setAssignedLabel(new LabelAtom("foo"));
// Put unlabeled build into the queue
unlabeledProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("FOO", "BAR1")));
queue.maintain();
assertEquals("Unlabeled build must be taken into account", 1, unlabeledLoad.computeQueueLength());
unlabeledProject.scheduleBuild2(0, new ParametersAction(new StringParameterValue("FOO", "BAR2")));
queue.maintain();
assertEquals("Second Unlabeled build must be taken into account", 2, unlabeledLoad.computeQueueLength());
// Put labeled build into the queue
labeledProject.scheduleBuild2(0);
queue.maintain();
assertEquals("Labeled builds must be ignored", 2, unlabeledLoad.computeQueueLength());
// Allow executions of unlabeled builds on master, all unlabeled builds should pass
j.jenkins.setNumExecutors(1);
j.buildAndAssertSuccess(unlabeledProject);
queue.maintain();
assertEquals("Queue must contain the labeled project build", 1, queue.getBuildableItems().size());
assertEquals("Statistics must return 0 after all builds", 0, unlabeledLoad.computeQueueLength());
}
}
| stephenc/jenkins | test/src/test/java/jenkins/model/UnlabeledLoadStatisticsTest.java | Java | mit | 4,140 |
/*******************************************************************************
* Copyright 2011 Google Inc. All Rights Reserved.
*
* 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
*
* 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.gdt.eclipse.appsmarketplace.data;
import com.google.api.client.googleapis.GoogleUrl;
import com.google.gdt.eclipse.core.StringUtilities;
/**
* Generates Google apps marketplace related URLs.
*/
public class EnterpriseMarketplaceUrl {
private static final String MARKETPLACE_API_HOST = System.getenv(
"MARKETPLACE_API_HOST");
private static final String MARKETPLACE_FRONTEND_HOST = System.getenv(
"MARKETPLACE_FRONTEND_HOST");
public static String generateAppListingUrl() {
GoogleUrl url = new GoogleUrl(getApiHost());
url.pathParts = GoogleUrl.toPathParts("/appsmarket/v2/appListing/");
return url.toString();
}
public static String generateFrontendCreateListingUrl() {
GoogleUrl url = new GoogleUrl(getFrontendHost());
url.pathParts = GoogleUrl.toPathParts(
"/enterprise/marketplace/blankListing");
return url.toString();
}
public static String generateFrontendCreateVendorProfileUrl() {
GoogleUrl url = new GoogleUrl(getFrontendHost());
url.pathParts = GoogleUrl.toPathParts("/enterprise/marketplace/myProfile");
return url.toString();
}
public static String generateFrontendViewListingUrl() {
GoogleUrl url = new GoogleUrl(getFrontendHost());
url.pathParts = GoogleUrl.toPathParts(
"/enterprise/marketplace/viewVendorProfile");
return url.toString();
}
public static String generateVendorProfileUrl() {
GoogleUrl url = new GoogleUrl(getApiHost());
url.pathParts = GoogleUrl.toPathParts("/appsmarket/v2/vendorProfile");
return url.toString();
}
private static String getApiHost() {
String host;
if (StringUtilities.isEmpty(MARKETPLACE_API_HOST)) {
host = new String("https://www.googleapis.com/");
} else {
host = MARKETPLACE_API_HOST;
}
return host;
}
private static String getFrontendHost() {
String host;
if (StringUtilities.isEmpty(MARKETPLACE_FRONTEND_HOST)) {
host = new String("http://www.google.com/");
} else {
host = MARKETPLACE_FRONTEND_HOST;
}
return host;
}
} | pruebasetichat/google-plugin-for-eclipse | plugins/com.google.gdt.eclipse.appsmarketplace/src/com/google/gdt/eclipse/appsmarketplace/data/EnterpriseMarketplaceUrl.java | Java | epl-1.0 | 2,875 |
/**
* Copyright (c) 2010-2017 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.opensprinkler.internal.api;
import static org.openhab.binding.opensprinkler.internal.api.OpenSprinklerApiConstants.*;
import org.openhab.binding.opensprinkler.internal.api.exception.CommunicationApiException;
import org.openhab.binding.opensprinkler.internal.api.exception.GeneralApiException;
import org.openhab.binding.opensprinkler.internal.util.Http;
import org.openhab.binding.opensprinkler.internal.util.Parse;
/**
* The {@link OpenSprinklerHttpApiV100} class is used for communicating with
* the OpenSprinkler API for firmware versions less than 2.1.0
*
* @author Chris Graham - Initial contribution
*/
public class OpenSprinklerHttpApiV100 implements OpenSprinklerApi {
protected final String hostname;
protected final int port;
protected final String password;
protected int firmwareVersion = -1;
protected int numberOfStations = DEFAULT_STATION_COUNT;
protected boolean connectionOpen = false;
/**
* Constructor for the OpenSprinkler API class to create a connection to the OpenSprinkler
* device for control and obtaining status info.
*
* @param hostname Hostname or IP address as a String of the OpenSprinkler device.
* @param port The port number the OpenSprinkler API is listening on.
* @param password Admin password for the OpenSprinkler device.
* @throws Exception
*/
public OpenSprinklerHttpApiV100(final String hostname, final int port, final String password) throws Exception {
if (hostname == null) {
throw new GeneralApiException("The given url is null.");
}
if (port < 1 || port > 65535) {
throw new GeneralApiException("The given port is invalid.");
}
if (password == null) {
throw new GeneralApiException("The given password is null.");
}
if (hostname.startsWith(HTTP_REQUEST_URL_PREFIX) || hostname.startsWith(HTTPS_REQUEST_URL_PREFIX)) {
throw new GeneralApiException("The given hostname does not need to start with " + HTTP_REQUEST_URL_PREFIX
+ " or " + HTTP_REQUEST_URL_PREFIX);
}
this.hostname = hostname;
this.port = port;
this.password = password;
}
@Override
public boolean isConnected() {
return connectionOpen;
}
@Override
public void openConnection() throws Exception {
try {
Http.sendHttpGet(getBaseUrl(), getRequestRequiredOptions() + "&" + CMD_ENABLE_MANUAL_MODE);
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
this.firmwareVersion = getFirmwareVersion();
this.numberOfStations = getNumberOfStations();
connectionOpen = true;
}
@Override
public void closeConnection() throws Exception {
connectionOpen = false;
try {
Http.sendHttpGet(getBaseUrl(), getRequestRequiredOptions() + "&" + CMD_DISABLE_MANUAL_MODE);
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
}
@Override
public void openStation(int station) throws Exception {
if (station < 0 || station >= numberOfStations) {
throw new GeneralApiException("This OpenSprinkler device only has " + this.numberOfStations
+ " but station " + station + " was requested to be opened.");
}
try {
Http.sendHttpGet(getBaseUrl() + "sn" + station + "=1", null);
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
}
@Override
public void closeStation(int station) throws Exception {
if (station < 0 || station >= numberOfStations) {
throw new GeneralApiException("This OpenSprinkler device only has " + this.numberOfStations
+ " but station " + station + " was requested to be closed.");
}
try {
Http.sendHttpGet(getBaseUrl() + "sn" + station + "=0", null);
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
}
@Override
public boolean isStationOpen(int station) throws Exception {
String returnContent;
if (station < 0 || station >= numberOfStations) {
throw new GeneralApiException("This OpenSprinkler device only has " + this.numberOfStations
+ " but station " + station + " was requested for a status update.");
}
try {
returnContent = Http.sendHttpGet(getBaseUrl() + "sn" + station, null);
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
return returnContent != null && returnContent.equals("1");
}
@Override
public boolean isRainDetected() throws Exception {
String returnContent;
int rainBit = -1;
try {
returnContent = Http.sendHttpGet(getBaseUrl() + CMD_STATUS_INFO, getRequestRequiredOptions());
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
try {
rainBit = Parse.jsonInt(returnContent, JSON_OPTION_RAINSENSOR);
} catch (Exception exp) {
rainBit = -1;
}
if (rainBit == 1) {
return true;
} else if (rainBit == 0) {
return false;
} else {
throw new GeneralApiException("Could not get the current state of the rain sensor.");
}
}
@Override
public int getNumberOfStations() throws Exception {
String returnContent;
try {
returnContent = Http.sendHttpGet(getBaseUrl() + CMD_STATION_INFO, getRequestRequiredOptions());
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
this.numberOfStations = Parse.jsonInt(returnContent, JSON_OPTION_STATION_COUNT);
return this.numberOfStations;
}
@Override
public int getFirmwareVersion() throws Exception {
String returnContent;
try {
returnContent = Http.sendHttpGet(getBaseUrl() + CMD_OPTIONS_INFO, null);
} catch (Exception exp) {
throw new CommunicationApiException(
"There was a problem in the HTTP communication with the OpenSprinkler API: " + exp.getMessage());
}
try {
this.firmwareVersion = Parse.jsonInt(returnContent, JSON_OPTION_FIRMWARE_VERSION);
} catch (Exception exp) {
this.firmwareVersion = -1;
}
return this.firmwareVersion;
}
/**
* Returns the hostname and port formatted URL as a String.
*
* @return String representation of the OpenSprinkler API URL.
*/
protected String getBaseUrl() {
return HTTP_REQUEST_URL_PREFIX + hostname + ":" + port + "/";
}
/**
* Returns the required URL parameters required for every API call.
*
* @return String representation of the parameters needed during an API call.
*/
protected String getRequestRequiredOptions() {
return CMD_PASSWORD + this.password;
}
}
| mvolaart/openhab2-addons | addons/binding/org.openhab.binding.opensprinkler/src/main/java/org/openhab/binding/opensprinkler/internal/api/OpenSprinklerHttpApiV100.java | Java | epl-1.0 | 8,304 |
/*
Copyright 2010 Sun Microsystems, Inc.
All rights reserved. Use is subject to license terms.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package testsuite.clusterj.bindings;
public class NotPersistentTest extends testsuite.clusterj.NotPersistentTest {
}
| greenlion/mysql-server | storage/ndb/clusterj/clusterj-bindings/src/test/java/testsuite/clusterj/bindings/NotPersistentTest.java | Java | gpl-2.0 | 1,273 |
package cn.edu.zju.acm.onlinejudge.action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import cn.edu.zju.acm.onlinejudge.util.PersistenceManager;
public class DeleteAllStudentAction extends BaseAction {
@Override
protected ActionForward execute(ActionMapping mapping, ActionForm form,
ContextAdapter context) throws Exception {
// TODO Auto-generated method stub
System.out.println("update user_profile set active=0 where create_user="+2);
PersistenceManager.getInstance().getUserPersistence().deleteAllUserProfile(context.getUserProfile().getId());
System.out.println("ok");
return handleSuccess(mapping, context, "success");
}
} | lei-cao/zoj | na/judge_server/src/main/cn/edu/zju/acm/onlinejudge/action/DeleteAllStudentAction.java | Java | gpl-3.0 | 764 |
/*
* The Kuali Financial System, a comprehensive financial management system for higher education.
*
* Copyright 2005-2014 The Kuali Foundation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.kuali.kfs.sys.document.web.renderers;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.kns.web.taglib.html.KNSTextTag;
import org.springframework.web.util.HtmlUtils;
/**
* Represents a field rendered as a text field
*/
public class TextRenderer extends FieldRendererBase {
private KNSTextTag tag = new KNSTextTag();
/**
* cleans up the html:text tag
* @see org.kuali.kfs.sys.document.web.renderers.FieldRendererBase#clear()
*/
@Override
public void clear() {
super.clear();
tag.setProperty(null);
tag.setTitle(null);
tag.setSize(null);
tag.setMaxlength(null);
tag.setOnblur(null);
tag.setStyleClass(null);
tag.setValue(null);
tag.setStyleId(null);
tag.setTabindex(null);
}
/**
* Uses a struts html:text tag to render this field
* @see org.kuali.kfs.sys.document.web.renderers.Renderer#render(javax.servlet.jsp.PageContext, javax.servlet.jsp.tagext.Tag)
*/
public void render(PageContext pageContext, Tag parentTag) throws JspException {
tag.setPageContext(pageContext);
tag.setParent(parentTag);
tag.setProperty(getFieldName());
tag.setTitle(getAccessibleTitle());
tag.setSize(getFieldSize());
//tag.setTabIndex();
tag.setMaxlength(getFieldMaxLength());
final String onBlur = buildOnBlur();
if (!StringUtils.isBlank(onBlur)) {
tag.setOnblur(buildOnBlur());
}
tag.setStyleClass(getField().getStyleClass());
tag.setValue(getField().getPropertyValue());
tag.setStyleId(getFieldName());
tag.doStartTag();
tag.doEndTag();
renderQuickFinderIfNecessary(pageContext, parentTag);
if (isShowError()) {
renderErrorIcon(pageContext);
}
}
/**
* Determines the max length of the field
* @return the max length of the field, formatted to a string
*/
protected String getFieldMaxLength() {
return Integer.toString(getField().getMaxLength());
}
/**
* Determines the size of the field
* @return the size of the field, formatted as a String
*/
protected String getFieldSize() {
return Integer.toString(getField().getSize());
}
/**
* Yes, I'd like a quickfinder please
* @see org.kuali.kfs.sys.document.web.renderers.FieldRenderer#renderQuickfinder()
*/
public boolean renderQuickfinder() {
return true;
}
}
| ua-eas/ua-kfs-5.3 | work/src/org/kuali/kfs/sys/document/web/renderers/TextRenderer.java | Java | agpl-3.0 | 3,627 |
/*
* Copyright (c) JForum Team. All rights reserved.
*
* The software in this package is published under the terms of the LGPL
* license a copy of which has been included with this distribution in the
* license.txt file.
*
* The JForum Project
* http://www.jforum.net
*/
package net.jforum.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.ioc.PrototypeScoped;
/**
* @author Rafael Steil
*/
@Entity
@Table(name = "jforum_privmsgs")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Component
@PrototypeScoped
public class PrivateMessage implements Serializable {
@Id
@SequenceGenerator(name = "sequence", sequenceName = "jforum_privmsgs_seq")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "sequence")
@Column(name = "privmsgs_id")
private int id;
@Column(name = "privmsgs_type")
private int type;
@ManyToOne
@JoinColumn(name = "privmsgs_from_userid")
private User fromUser;
@ManyToOne
@JoinColumn(name = "privmsgs_to_userid")
private User toUser;
@Column(name = "privmsgs_date")
private Date date;
@Column(name = "privmsgs_text")
private String text;
@Column(name = "privmsgs_subject")
private String subject;
@Column(name = "privmsgs_enable_bbcode")
private boolean bbCodeEnabled = true;
@Column(name = "privmsgs_enable_html")
private boolean htmlEnabled = true;
@Column(name = "privmsgs_enable_smilies")
private boolean smiliesEnabled = true;
@Column(name = "privmsgs_attach_sig")
private boolean signatureEnabled = true;
@Column(name = "privmsgs_ip")
private String ip;
public PrivateMessage() { }
/**
* Copy constructor
*
* @param pm the object to copy from
*/
public PrivateMessage(PrivateMessage pm) {
this.setId(pm.getId());
this.setType(pm.getType());
this.setText(pm.getText());
this.setSubject(pm.getSubject());
this.setFromUser(pm.getFromUser());
this.setToUser(pm.getToUser());
this.setDate(pm.getDate());
}
/**
* @return Returns the fromUser.
*/
public User getFromUser() {
return fromUser;
}
/**
* @param fromUser The fromUser to set.
*/
public void setFromUser(User fromUser) {
this.fromUser = fromUser;
}
/**
* @return Returns the toUser.
*/
public User getToUser() {
return toUser;
}
/**
* @param toUser The toUser to set.
*/
public void setToUser(User toUser) {
this.toUser = toUser;
}
/**
* @return Returns the type.
*/
public int getType() {
return type;
}
/**
* @param type The type to set.
*/
public void setType(int type) {
this.type = type;
}
/**
* @return Returns the id.
*/
public int getId() {
return id;
}
/**
* @param id The id to set.
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the time
*/
public Date getDate() {
return this.date;
}
/**
* @param date the time to set
*/
public void setDate(Date date) {
this.date = date;
}
/**
* @return the text
*/
public String getText() {
return this.text;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @return the subject
*/
public String getSubject() {
return this.subject;
}
/**
* @param subject the subject to set
*/
public void setSubject(String subject) {
this.subject = subject;
}
/**
* @return the bbCodeEnabled
*/
public boolean isBbCodeEnabled() {
return this.bbCodeEnabled;
}
/**
* @param bbCodeEnabled the bbCodeEnabled to set
*/
public void setBbCodeEnabled(boolean bbCodeEnabled) {
this.bbCodeEnabled = bbCodeEnabled;
}
/**
* @return the htmlEnabled
*/
public boolean isHtmlEnabled() {
return this.htmlEnabled;
}
/**
* @param htmlEnabled the htmlEnabled to set
*/
public void setHtmlEnabled(boolean htmlEnabled) {
this.htmlEnabled = htmlEnabled;
}
/**
* @return the smiliesEnabled
*/
public boolean isSmiliesEnabled() {
return this.smiliesEnabled;
}
/**
* @param smiliesEnabled the smiliesEnabled to set
*/
public void setSmiliesEnabled(boolean smiliesEnabled) {
this.smiliesEnabled = smiliesEnabled;
}
/**
* @return the signatureEnabled
*/
public boolean isSignatureEnabled() {
return this.signatureEnabled;
}
/**
* @param signatureEnabled the signatureEnabled to set
*/
public void setSignatureEnabled(boolean signatureEnabled) {
this.signatureEnabled = signatureEnabled;
}
public boolean isNew() {
return this.type == PrivateMessageType.NEW;
}
/**
* Flag this message as read
*/
public void markAsRead() {
this.type = PrivateMessageType.READ;
}
/**
* Transorm this instance in a post
* Used only for displaying the formatted message
* @return the post
*/
public Post asPost() {
Post post = new Post();
post.setSubject(this.subject);
post.setText(this.text);
post.setBbCodeEnabled(this.isBbCodeEnabled());
post.setHtmlEnabled(this.isHtmlEnabled());
post.setSmiliesEnabled(this.isSmiliesEnabled());
post.setSignatureEnabled(this.isSignatureEnabled());
return post;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof PrivateMessage)) {
return false;
}
return ((PrivateMessage) o).getId() == this.getId();
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return this.getId();
}
/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* @return the ip
*/
public String getIp() {
return ip;
}
}
| 0359xiaodong/jforum3 | src/main/java/net/jforum/entities/PrivateMessage.java | Java | lgpl-2.1 | 6,048 |
/*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation
* of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.examples.network;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletSchedulerTimeShared;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.NetworkTopology;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicySimple;
import org.cloudbus.cloudsim.VmSchedulerTimeShared;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
/**
* A simple example showing how to create
* a datacenter with one host and a network
* topology and and run one cloudlet on it.
* Here, instead of using a BRIE file describing
* the links, links are inserted in the code.
*/
public class NetworkExample4 {
/** The cloudlet list. */
private static List<Cloudlet> cloudletList;
/** The vmlist. */
private static List<Vm> vmlist;
/**
* Creates main() to run this example
*/
public static void main(String[] args) {
Log.printLine("Starting NetworkExample4...");
try {
// First step: Initialize the CloudSim package. It should be called
// before creating any entities.
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
// Initialize the CloudSim library
CloudSim.init(num_user, calendar, trace_flag);
// Second step: Create Datacenters
//Datacenters are the resource providers in CloudSim. We need at list one of them to run a CloudSim simulation
Datacenter datacenter0 = createDatacenter("Datacenter_0");
//Third step: Create Broker
DatacenterBroker broker = createBroker();
int brokerId = broker.getId();
//Fourth step: Create one virtual machine
vmlist = new ArrayList<Vm>();
//VM description
int vmid = 0;
int mips = 250;
long size = 10000; //image size (MB)
int ram = 512; //vm memory (MB)
long bw = 1000;
int pesNumber = 1; //number of cpus
String vmm = "Xen"; //VMM name
//create VM
Vm vm1 = new Vm(vmid, brokerId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
//add the VM to the vmList
vmlist.add(vm1);
//submit vm list to the broker
broker.submitVmList(vmlist);
//Fifth step: Create one Cloudlet
cloudletList = new ArrayList<Cloudlet>();
//Cloudlet properties
int id = 0;
long length = 40000;
long fileSize = 300;
long outputSize = 300;
UtilizationModel utilizationModel = new UtilizationModelFull();
Cloudlet cloudlet1 = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
cloudlet1.setUserId(brokerId);
//add the cloudlet to the list
cloudletList.add(cloudlet1);
//submit cloudlet list to the broker
broker.submitCloudletList(cloudletList);
//Sixth step: configure network
//maps CloudSim entities to BRITE entities
NetworkTopology.addLink(datacenter0.getId(),broker.getId(),10.0,10);
// Seventh step: Starts the simulation
CloudSim.startSimulation();
// Final step: Print results when simulation is over
List<Cloudlet> newList = broker.getCloudletReceivedList();
CloudSim.stopSimulation();
printCloudletList(newList);
//Print the debt of each user to each datacenter
datacenter0.printDebts();
Log.printLine("NetworkExample4 finished!");
}
catch (Exception e) {
e.printStackTrace();
Log.printLine("The simulation has been terminated due to an unexpected error");
}
}
private static Datacenter createDatacenter(String name){
// Here are the steps needed to create a PowerDatacenter:
// 1. We need to create a list to store
// our machine
List<Host> hostList = new ArrayList<Host>();
// 2. A Machine contains one or more PEs or CPUs/Cores.
// In this example, it will have only one core.
List<Pe> peList = new ArrayList<Pe>();
int mips = 1000;
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store Pe id and MIPS Rating
//4. Create Host with its id and list of PEs and add them to the list of machines
int hostId=0;
int ram = 2048; //host memory (MB)
long storage = 1000000; //host storage
int bw = 10000;
hostList.add(
new Host(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerSimple(bw),
storage,
peList,
new VmSchedulerTimeShared(peList)
)
); // This is our machine
// 5. Create a DatacenterCharacteristics object that stores the
// properties of a data center: architecture, OS, list of
// Machines, allocation policy: time- or space-shared, time zone
// and its price (G$/Pe time unit).
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); //we are not adding SAN devices by now
DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
arch, os, vmm, hostList, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
// 6. Finally, we need to create a PowerDatacenter object.
Datacenter datacenter = null;
try {
datacenter = new Datacenter(name, characteristics, new VmAllocationPolicySimple(hostList), storageList, 0);
} catch (Exception e) {
e.printStackTrace();
}
return datacenter;
}
//We strongly encourage users to develop their own broker policies, to submit vms and cloudlets according
//to the specific rules of the simulated scenario
private static DatacenterBroker createBroker(){
DatacenterBroker broker = null;
try {
broker = new DatacenterBroker("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return broker;
}
/**
* Prints the Cloudlet objects
* @param list list of Cloudlets
*/
private static void printCloudletList(List<Cloudlet> list) {
int size = list.size();
Cloudlet cloudlet;
String indent = " ";
Log.printLine();
Log.printLine("========== OUTPUT ==========");
Log.printLine("Cloudlet ID" + indent + "STATUS" + indent +
"Data center ID" + indent + "VM ID" + indent + "Time" + indent + "Start Time" + indent + "Finish Time");
for (int i = 0; i < size; i++) {
cloudlet = list.get(i);
Log.print(indent + cloudlet.getCloudletId() + indent + indent);
if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS){
Log.print("SUCCESS");
DecimalFormat dft = new DecimalFormat("###.##");
Log.printLine( indent + indent + cloudlet.getResourceId() + indent + indent + indent + cloudlet.getVmId() +
indent + indent + dft.format(cloudlet.getActualCPUTime()) + indent + indent + dft.format(cloudlet.getExecStartTime())+
indent + indent + dft.format(cloudlet.getFinishTime()));
}
}
}
}
| Sukoon-Sharma/OpenSim | src/org/cloudbus/cloudsim/examples/network/NetworkExample4.java | Java | lgpl-3.0 | 8,071 |
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube 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 program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.batch.sensor.issue;
import com.google.common.annotations.Beta;
import org.sonar.api.batch.fs.InputComponent;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.fs.TextRange;
/**
* Represents one issue location. See {@link NewIssue#newLocation()}.
*
* @since 5.2
*/
@Beta
public interface NewIssueLocation {
/**
* Maximum number of characters in the message.
*/
int MESSAGE_MAX_SIZE = 4000;
/**
* The {@link InputComponent} the issue location belongs to. Mandatory.
*/
NewIssueLocation on(InputComponent component);
/**
* Position in the file. Only applicable when {@link #on(InputComponent)} has been called with an InputFile.
* See {@link InputFile#newRange(org.sonar.api.batch.fs.TextPointer, org.sonar.api.batch.fs.TextPointer)}
*/
NewIssueLocation at(TextRange location);
/**
* Optional, but recommended, plain-text message for this location.
* <p/>
* Formats like Markdown or HTML are not supported. Size must not be greater than {@link #MESSAGE_MAX_SIZE} characters.
*/
NewIssueLocation message(String message);
}
| abbeyj/sonarqube | sonar-plugin-api/src/main/java/org/sonar/api/batch/sensor/issue/NewIssueLocation.java | Java | lgpl-3.0 | 2,004 |
// Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.actions;
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.Root;
import javax.annotation.Nullable;
/**
* An indirection layer on Path resolution of {@link Artifact} and {@link Root}.
*
* <p>Serves as converter interface primarily for switching the {@link FileSystem} underlying the
* values.
*/
public interface ArtifactPathResolver {
/**
* @return a resolved Path corresponding to the given actionInput.
*/
Path toPath(ActionInput actionInput);
/**
* @return a resolved Path corresponding to the given path.
*/
Path convertPath(Path path);
/**
* @return a resolved Rooth corresponding to the given Root.
*/
Root transformRoot(Root root);
ArtifactPathResolver IDENTITY = new IdentityResolver(null);
static ArtifactPathResolver forExecRoot(Path execRoot) {
return new IdentityResolver(execRoot);
}
static ArtifactPathResolver withTransformedFileSystem(Path execRoot) {
return new TransformResolver(execRoot);
}
static ArtifactPathResolver createPathResolver(@Nullable FileSystem fileSystem,
Path execRoot) {
if (fileSystem == null) {
return forExecRoot(execRoot);
} else {
return withTransformedFileSystem(
fileSystem.getPath(execRoot.asFragment()));
}
}
/**
* Path resolution that uses an Artifact's path directly, or looks up the input execPath relative
* to the given execRoot.
*/
class IdentityResolver implements ArtifactPathResolver {
private final Path execRoot;
private IdentityResolver(Path execRoot) {
this.execRoot = execRoot;
}
@Override
public Path toPath(ActionInput actionInput) {
if (actionInput instanceof Artifact) {
return ((Artifact) actionInput).getPath();
}
return execRoot.getRelative(actionInput.getExecPath());
}
@Override
public Root transformRoot(Root root) {
return Preconditions.checkNotNull(root);
}
@Override
public Path convertPath(Path path) {
return path;
}
};
/**
* A resolver that transforms all results to the same filesystem as the given execRoot.
*/
class TransformResolver implements ArtifactPathResolver {
private final FileSystem fileSystem;
private final Path execRoot;
private TransformResolver(Path execRoot) {
this.execRoot = execRoot;
this.fileSystem = Preconditions.checkNotNull(execRoot.getFileSystem());
}
@Override
public Path toPath(ActionInput input) {
if (input instanceof Artifact) {
return fileSystem.getPath(((Artifact) input).getPath().getPathString());
}
return execRoot.getRelative(input.getExecPath());
}
@Override
public Root transformRoot(Root root) {
return Root.toFileSystem(Preconditions.checkNotNull(root), fileSystem);
}
@Override
public Path convertPath(Path path) {
return fileSystem.getPath(path.asFragment());
}
}
}
| dslomov/bazel | src/main/java/com/google/devtools/build/lib/actions/ArtifactPathResolver.java | Java | apache-2.0 | 3,713 |
/**
* Copyright 2014 Zhenguo Jin
*
* 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.ihongqiqu.util;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* 加密与解密的工具类
*
* @author [email protected]
*/
public final class CipherUtils {
/**
* MD5加密
* <br>http://stackoverflow.com/questions/1057041/difference-between-java-and-php5-md5-hash
* <br>http://code.google.com/p/roboguice/issues/detail?id=89
*
* @param string 源字符串
* @return 加密后的字符串
*/
public static String md5(String string) {
byte[] hash = null;
try {
hash = MessageDigest.getInstance("MD5").digest(
string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10)
hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
/**
* 返回可逆算法DES的密钥
*
* @param key 前8字节将被用来生成密钥。
* @return 生成的密钥
* @throws Exception
*/
public static Key getDESKey(byte[] key) throws Exception {
DESKeySpec des = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(des);
}
/**
* 根据指定的密钥及算法,将字符串进行解密。
*
* @param data 要进行解密的数据,它是由原来的byte[]数组转化为字符串的结果。
* @param key 密钥。
* @param algorithm 算法。
* @return 解密后的结果。它由解密后的byte[]重新创建为String对象。如果解密失败,将返回null。
* @throws Exception
*/
public static String decrypt(String data, Key key, String algorithm)
throws Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
String result = new String(cipher.doFinal(StringUtils
.hexStringToByteArray(data)), "utf8");
return result;
}
/**
* 根据指定的密钥及算法对指定字符串进行可逆加密。
*
* @param data 要进行加密的字符串。
* @param key 密钥。
* @param algorithm 算法。
* @return 加密后的结果将由byte[]数组转换为16进制表示的数组。如果加密过程失败,将返回null。
*/
public static String encrypt(String data, Key key, String algorithm)
throws Exception {
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key);
return StringUtils.byteArrayToHexString(cipher.doFinal(data
.getBytes("utf8")));
}
}
| SoftwareME/android-utils | src/com/ihongqiqu/util/CipherUtils.java | Java | apache-2.0 | 3,756 |
/*
* 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.
*/
@Version("2.0.0")
package org.apache.sling.event.jobs;
import aQute.bnd.annotation.Version;
| nleite/sling | bundles/extensions/event/src/main/java/org/apache/sling/event/jobs/package-info.java | Java | apache-2.0 | 903 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.core.api.util.tree;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a node of the Tree<T, K> class. The Node<T, K> is also a container, and
* can be thought of as instrumentation to determine the location of the type T
* in the Tree<T ,K>.
*/
public class Node<T, K> implements Serializable {
private static final long serialVersionUID = -2650587832812603561L;
private T data;
private List<Node<T, K>> children;
private K nodeLabel;
private String nodeType;
/**
* Default constructor.
*/
public Node() {
super();
children = new ArrayList<Node<T, K>>();
}
/**
* Convenience constructor to create a Node<T, K> with an instance of T.
*
* @param data an instance of T.
*/
public Node(T data) {
this();
setData(data);
}
/**
* Convenience constructor to create a Node<T, K> with an instance of T and K.
*
* @param data an instance of T.
*/
public Node(T data, K label) {
this();
setData(data);
setNodeLabel(label);
}
/**
* Return the children of Node<T, K>. The Tree<T> is represented by a single
* root Node<T, K> whose children are represented by a List<Node<T, K>>. Each of
* these Node<T, K> elements in the List can have children. The getChildren()
* method will return the children of a Node<T, K>.
*
* @return the children of Node<T, K>
*/
public List<Node<T, K>> getChildren() {
if (this.children == null) {
return new ArrayList<Node<T, K>>();
}
return this.children;
}
/**
* Sets the children of a Node<T, K> object. See docs for getChildren() for
* more information.
*
* @param children the List<Node<T, K>> to set.
*/
public void setChildren(List<Node<T, K>> children) {
this.children = children;
}
/**
* Returns the number of immediate children of this Node<T, K>.
*
* @return the number of immediate children.
*/
public int getNumberOfChildren() {
if (children == null) {
return 0;
}
return children.size();
}
/**
* Adds a child to the list of children for this Node<T, K>. The addition of
* the first child will create a new List<Node<T, K>>.
*
* @param child a Node<T, K> object to set.
*/
public void addChild(Node<T, K> child) {
if (children == null) {
children = new ArrayList<Node<T, K>>();
}
children.add(child);
}
/**
* Inserts a Node<T, K> at the specified position in the child list. Will
* throw an ArrayIndexOutOfBoundsException if the index does not exist.
*
* @param index the position to insert at.
* @param child the Node<T, K> object to insert.
* @throws IndexOutOfBoundsException if thrown.
*/
public void insertChildAt(int index, Node<T, K> child) throws IndexOutOfBoundsException {
if (index == getNumberOfChildren()) {
// this is really an append
addChild(child);
return;
} else {
children.get(index); //just to throw the exception, and stop here
children.add(index, child);
}
}
/**
* Remove the Node<T, K> element at index index of the List<Node<T, K>>.
*
* @param index the index of the element to delete.
* @throws IndexOutOfBoundsException if thrown.
*/
public void removeChildAt(int index) throws IndexOutOfBoundsException {
children.remove(index);
}
/**
* Data object contained in the node (a leaf)
*
* @return Object
*/
public T getData() {
return this.data;
}
/**
* Setter for the nodes data
*
* @param data
*/
public void setData(T data) {
this.data = data;
}
/**
* Object containing the data for labeling the node (can be simple String)
*
* @return K
*/
public K getNodeLabel() {
return nodeLabel;
}
/**
* Setter for the nodes label data
*
* @param nodeLabel
*/
public void setNodeLabel(K nodeLabel) {
this.nodeLabel = nodeLabel;
}
/**
* Indicates what type of node is being represented, used to give
* a functional label for the node that can also be used for presentation
* purposes
*
* @return String node type
*/
public String getNodeType() {
return nodeType;
}
/**
* Setter for the node type String
*
* @param nodeType
*/
public void setNodeType(String nodeType) {
this.nodeType = nodeType;
}
public String toString() {
if (getData() != null) {
StringBuilder sb = new StringBuilder();
sb.append("{").append(getData().toString()).append(",[");
int i = 0;
for (Node<T, K> e : getChildren()) {
if (i > 0) {
sb.append(",");
}
sb.append(e.getData().toString());
i++;
}
sb.append("]").append("}");
return sb.toString();
} else {
return super.toString();
}
}
}
| ricepanda/rice-git2 | rice-middleware/core/api/src/main/java/org/kuali/rice/core/api/util/tree/Node.java | Java | apache-2.0 | 6,210 |
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.utils.reflect;
import com.badlogic.gwtref.client.ReflectionCache;
import com.badlogic.gwtref.client.Type;
/** Utilities for Class reflection.
* @author nexsoftware */
public final class ClassReflection {
/** Returns the Class object associated with the class or interface with the supplied string name. */
static public Class forName (String name) throws ReflectionException {
try {
return ReflectionCache.forName(name).getClassOfType();
} catch (ClassNotFoundException e) {
throw new ReflectionException("Class not found: " + name);
}
}
/** Returns the simple name of the underlying class as supplied in the source code. */
static public String getSimpleName (Class c) {
return c.getSimpleName();
}
/** Determines if the supplied Object is assignment-compatible with the object represented by supplied Class. */
static public boolean isInstance (Class c, Object obj) {
return obj != null && isAssignableFrom(c, obj.getClass());
}
/** Determines if the class or interface represented by first Class parameter is either the same as, or is a superclass or
* superinterface of, the class or interface represented by the second Class parameter. */
static public boolean isAssignableFrom (Class c1, Class c2) {
Type c1Type = ReflectionCache.getType(c1);
Type c2Type = ReflectionCache.getType(c2);
return c1Type.isAssignableFrom(c2Type);
}
/** Returns true if the class or interface represented by the supplied Class is a member class. */
static public boolean isMemberClass (Class c) {
return ReflectionCache.getType(c).isMemberClass();
}
/** Returns true if the class or interface represented by the supplied Class is a static class. */
static public boolean isStaticClass (Class c) {
return ReflectionCache.getType(c).isStatic();
}
/** Creates a new instance of the class represented by the supplied Class. */
static public <T> T newInstance (Class<T> c) throws ReflectionException {
try {
return (T)ReflectionCache.getType(c).newInstance();
} catch (NoSuchMethodException e) {
throw new ReflectionException("Could not use default constructor of " + c.getName(), e);
}
}
/** Returns an array of {@link Constructor} containing the public constructors of the class represented by the supplied Class. */
static public Constructor[] getConstructors (Class c) {
com.badlogic.gwtref.client.Constructor[] constructors = ReflectionCache.getType(c).getConstructors();
Constructor[] result = new Constructor[constructors.length];
for (int i = 0, j = constructors.length; i < j; i++) {
result[i] = new Constructor(constructors[i]);
}
return result;
}
/** Returns a {@link Constructor} that represents the public constructor for the supplied class which takes the supplied
* parameter types. */
static public Constructor getConstructor (Class c, Class... parameterTypes) throws ReflectionException {
try {
return new Constructor(ReflectionCache.getType(c).getConstructor(parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
}
}
/** Returns a {@link Constructor} that represents the constructor for the supplied class which takes the supplied parameter
* types. */
static public Constructor getDeclaredConstructor (Class c, Class... parameterTypes) throws ReflectionException {
try {
return new Constructor(ReflectionCache.getType(c).getDeclaredConstructor(parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting constructor for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Constructor not found for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Method} containing the public member methods of the class represented by the supplied Class. */
static public Method[] getMethods (Class c) {
com.badlogic.gwtref.client.Method[] methods = ReflectionCache.getType(c).getMethods();
Method[] result = new Method[methods.length];
for (int i = 0, j = methods.length; i < j; i++) {
result[i] = new Method(methods[i]);
}
return result;
}
/** Returns a {@link Method} that represents the public member method for the supplied class which takes the supplied parameter
* types. */
static public Method getMethod (Class c, String name, Class... parameterTypes) throws ReflectionException {
try {
return new Method(ReflectionCache.getType(c).getMethod(name, parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting method: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Method not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Method} containing the methods declared by the class represented by the supplied Class. */
static public Method[] getDeclaredMethods (Class c) {
com.badlogic.gwtref.client.Method[] methods = ReflectionCache.getType(c).getDeclaredMethods();
Method[] result = new Method[methods.length];
for (int i = 0, j = methods.length; i < j; i++) {
result[i] = new Method(methods[i]);
}
return result;
}
/** Returns a {@link Method} that represents the method declared by the supplied class which takes the supplied parameter types. */
static public Method getDeclaredMethod (Class c, String name, Class... parameterTypes) throws ReflectionException {
try {
return new Method(ReflectionCache.getType(c).getMethod(name, parameterTypes));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting method: " + name + ", for class: " + c.getName(), e);
} catch (NoSuchMethodException e) {
throw new ReflectionException("Method not found: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Field} containing the public fields of the class represented by the supplied Class. */
static public Field[] getFields (Class c) {
com.badlogic.gwtref.client.Field[] fields = ReflectionCache.getType(c).getFields();
Field[] result = new Field[fields.length];
for (int i = 0, j = fields.length; i < j; i++) {
result[i] = new Field(fields[i]);
}
return result;
}
/** Returns a {@link Field} that represents the specified public member field for the supplied class. */
static public Field getField (Class c, String name) throws ReflectionException {
try {
return new Field(ReflectionCache.getType(c).getField(name));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting field: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns an array of {@link Field} objects reflecting all the fields declared by the supplied class. */
static public Field[] getDeclaredFields (Class c) {
com.badlogic.gwtref.client.Field[] fields = ReflectionCache.getType(c).getDeclaredFields();
Field[] result = new Field[fields.length];
for (int i = 0, j = fields.length; i < j; i++) {
result[i] = new Field(fields[i]);
}
return result;
}
/** Returns a {@link Field} that represents the specified declared field for the supplied class. */
static public Field getDeclaredField (Class c, String name) throws ReflectionException {
try {
return new Field(ReflectionCache.getType(c).getField(name));
} catch (SecurityException e) {
throw new ReflectionException("Security violation while getting field: " + name + ", for class: " + c.getName(), e);
}
}
/** Returns true if the supplied class includes an annotation of the given class type. */
static public boolean isAnnotationPresent (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
java.lang.annotation.Annotation[] annotations = ReflectionCache.getType(c).getDeclaredAnnotations();
for (java.lang.annotation.Annotation annotation : annotations) {
if (annotation.annotationType().equals(annotationType)) {
return true;
}
}
return false;
}
/** Returns an array of {@link Annotation} objects reflecting all annotations declared by the supplied class,
* or an empty array if there are none. Does not include inherited annotations. */
static public Annotation[] getDeclaredAnnotations (Class c) {
java.lang.annotation.Annotation[] annotations = ReflectionCache.getType(c).getDeclaredAnnotations();
Annotation[] result = new Annotation[annotations.length];
for (int i = 0; i < annotations.length; i++) {
result[i] = new Annotation(annotations[i]);
}
return result;
}
/** Returns an {@link Annotation} object reflecting the annotation provided, or null of this field doesn't
* have such an annotation. This is a convenience function if the caller knows already which annotation
* type he's looking for. */
static public Annotation getDeclaredAnnotation (Class c, Class<? extends java.lang.annotation.Annotation> annotationType) {
java.lang.annotation.Annotation[] annotations = ReflectionCache.getType(c).getDeclaredAnnotations();
for (java.lang.annotation.Annotation annotation : annotations) {
if (annotation.annotationType().equals(annotationType)) {
return new Annotation(annotation);
}
}
return null;
}
}
| azakhary/libgdx | backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/utils/reflect/ClassReflection.java | Java | apache-2.0 | 10,401 |
/*
* 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.ode.utils;
/**
* An exception to encapsulate issues with system configuration. Examples
* include the inability to find required services (e.g., XML parsing).
*/
public class SystemConfigurationException extends RuntimeException {
private static final long serialVersionUID = -2330515949287155695L;
/**
* Construct a new instance with the specified message.
*
* @param message
* a descriptive message.
* @see RuntimeException#RuntimeException(java.lang.String)
*/
public SystemConfigurationException(String message) {
super(message);
}
/**
* Construct a new instance with the specified message and a
* {@link Throwable} that triggered this exception.
*
* @param message
* a descriptive message
* @param cause
* the cause
* @see RuntimeException#RuntimeException(java.lang.String,
* java.lang.Throwable)
*/
public SystemConfigurationException(String message, Throwable cause) {
super(message, cause);
}
/**
* Construct a new instance with the specified {@link Throwable} as the root
* cause.
*
* @param cause
* the cause
* @see RuntimeException#RuntimeException(java.lang.Throwable)
*/
public SystemConfigurationException(Throwable cause) {
super(cause);
}
}
| Subasinghe/ode | utils/src/main/java/org/apache/ode/utils/SystemConfigurationException.java | Java | apache-2.0 | 2,222 |
/*
* 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.cache.persistence;
import java.util.Set;
import org.apache.geode.distributed.internal.ReplyException;
import org.apache.geode.internal.cache.CacheDistributionAdvisor;
public interface InternalPersistenceAdvisor extends PersistenceAdvisor {
default void beginWaitingForMembershipChange(Set<PersistentMemberID> membersToWaitFor) {}
void checkInterruptedByShutdownAll();
void clearEqualMembers();
default void endWaitingForMembershipChange() {}
Set<PersistentMemberID> getMembersToWaitFor(Set<PersistentMemberID> previouslyOnlineMembers,
Set<PersistentMemberID> offlineMembers) throws ReplyException;
boolean isClosed();
CacheDistributionAdvisor getCacheDistributionAdvisor();
void logWaitingForMembers();
void setWaitingOnMembers(Set<PersistentMemberID> allMembersToWaitFor,
Set<PersistentMemberID> offlineMembersToWaitFor);
}
| masaki-yamakawa/geode | geode-core/src/main/java/org/apache/geode/internal/cache/persistence/InternalPersistenceAdvisor.java | Java | apache-2.0 | 1,692 |
/*******************************************************************************
* Copyright (c) 2005, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.bpel.ui.extensions;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.bpel.ui.BPELUIPlugin;
import org.eclipse.bpel.ui.IBPELUIConstants;
import org.eclipse.bpel.ui.IHoverHelper;
import org.eclipse.bpel.ui.Messages;
import org.eclipse.bpel.ui.bpelactions.AbstractBPELAction;
import org.eclipse.bpel.ui.expressions.DefaultExpressionEditor;
import org.eclipse.bpel.ui.expressions.IExpressionEditor;
import org.eclipse.bpel.ui.factories.AbstractUIObjectFactory;
import org.eclipse.bpel.ui.util.BPELUtil;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.ecore.EClass;
/**
* Responsible for getting information from the BPEL UI extension points.
*/
public class BPELUIRegistry {
static final String EXTPT_HOVERHELPERS = "hoverHelpers"; //$NON-NLS-1$
static final String ELEMENT_HOVERHELPER = "hoverHelper"; //$NON-NLS-1$
static final String EXTPT_EXPRESSION_EDITORS = "expressionEditors"; //$NON-NLS-1$
static final String ELEMENT_EDITOR = "editor"; //$NON-NLS-1$
static final String ATT_EXPRESSION_LANGUAGE = "expressionLanguage"; //$NON-NLS-1$
static final String ATT_CLASS = "class"; //$NON-NLS-1$
static final String ATT_LABEL = "label"; //$NON-NLS-1$
static final String EXTPT_ACTIONS = "actions"; //$NON-NLS-1$
static final String ELEMENT_CATEGORY = "category"; //$NON-NLS-1$
static final String ATT_NAME = "name"; //$NON-NLS-1$
static final String ATT_ID = "id"; //$NON-NLS-1$
static final String ELEMENT_ACTION = "action"; //$NON-NLS-1$
static final String ATT_CATEGORY_ID = "categoryId"; //$NON-NLS-1$
static final String EXTPT_MODELLISTENER = "modelListener"; //$NON-NLS-1$
static final String ELEMENT_LISTENER = "listener"; //$NON-NLS-1$
static final String ATT_SPEC_COMPLIANT = "specCompliant"; //$NON-NLS-1$
static final ExpressionEditorDescriptor[] EMPTY_EDITOR_DESCRIPTORS = {};
private static BPELUIRegistry instance;
private Map<String,ExpressionEditorDescriptor> fLanguageToEditorDescriptor;
private HoverHelperDescriptor hoverHelperDescriptor;
private ActionCategoryDescriptor[] fActionCategoryDescriptors;
private ActionDescriptor[] fActionDescriptors;
private ListenerDescriptor[] fListenerDescriptors;
private UIObjectFactoryDescriptor[] uiObjectFactoryDescriptor;
private IHoverHelper hoverHelper;
private BPELUIRegistry() {
readExpressionLanguageEditors();
readHoverHelpers();
readActions();
readListeners();
readUIObjecFactories();
}
/**
* @return the singleton instance of this regitry.
*/
public static BPELUIRegistry getInstance() {
if (instance == null) {
instance = new BPELUIRegistry();
}
return instance;
}
/**
* Return the hover helper.
* @return the hover helper extension.
* @throws CoreException
*/
public IHoverHelper getHoverHelper() throws CoreException {
if (hoverHelperDescriptor == null) {
return null;
}
if (hoverHelper == null) {
hoverHelper = hoverHelperDescriptor.createHoverHelper();
}
return hoverHelper;
}
/**
* Returns an expression editor for the given expression language.
* @param expressionLanguage
* @return the IExpression editor for the given expression language.
* @throws CoreException
*/
public IExpressionEditor getExpressionEditor (String expressionLanguage) throws CoreException {
ExpressionEditorDescriptor descriptor = fLanguageToEditorDescriptor.get(expressionLanguage);
if (descriptor == null) {
return new DefaultExpressionEditor();
}
IExpressionEditor editor = descriptor.createEditor();
return editor;
}
/**
* Returns an expression editor descriptor for the given expression language.
*
* @param expressionLanguage
* @return the expression language descriptor for the given expression language.
*/
public ExpressionEditorDescriptor getExpressionEditorDescriptor(String expressionLanguage) {
return fLanguageToEditorDescriptor.get(expressionLanguage);
}
private void readExpressionLanguageEditors() {
fLanguageToEditorDescriptor = new HashMap<String,ExpressionEditorDescriptor>();
for(IConfigurationElement editor : getConfigurationElements(EXTPT_EXPRESSION_EDITORS) ) {
if (editor.getName().equals(ELEMENT_EDITOR)) {
String language = editor.getAttribute(ATT_EXPRESSION_LANGUAGE);
String clazz = editor.getAttribute(ATT_CLASS);
if (language == null || clazz == null) {
String pluginId = BPELUIPlugin.INSTANCE.getBundle().getSymbolicName();
IStatus status = new Status(IStatus.ERROR, pluginId, IBPELUIConstants.MISSING_ATTRIBUTE, Messages.BPELUIRegistry_Expression_language_editors_must_provide_expressionLanguage_and_class__8, null);
BPELUIPlugin.INSTANCE.getLog().log(status);
} else {
ExpressionEditorDescriptor descriptor = new ExpressionEditorDescriptor();
descriptor.setExpressionLanguage(language);
descriptor.setElement(editor);
String label = editor.getAttribute(ATT_LABEL);
descriptor.setLabel(label);
fLanguageToEditorDescriptor.put(language, descriptor);
}
}
}
}
/**
* Return the UIObjectFactory descriptors
*/
public UIObjectFactoryDescriptor[] getUIObjectFactoryDescriptors() {
return uiObjectFactoryDescriptor;
}
/**
* Return all action descriptors.
* @return Return all action descriptors.
*/
public ActionDescriptor[] getActionDescriptors() {
return fActionDescriptors;
}
/**
* Returns the ActionDescriptor for the given EClass.
* @param target the target
* @return Returns the ActionDescriptor for the given EClass.
*/
public ActionDescriptor getActionDescriptor(EClass target) {
for(ActionDescriptor descriptor : fActionDescriptors ) {
if (descriptor.getAction().getModelType() == target) {
return descriptor;
}
}
return null;
}
/**
* @return the action category descriptors.
*/
public ActionCategoryDescriptor[] getActionCategoryDescriptors() {
return fActionCategoryDescriptors;
}
/**
* @return the listener descriptors.
*/
public ListenerDescriptor[] getListenerDescriptors() {
return fListenerDescriptors;
}
private void readHoverHelpers() {
for (IConfigurationElement helper : getConfigurationElements(EXTPT_HOVERHELPERS) ) {
if (helper.getName().equals(ELEMENT_HOVERHELPER) == false) {
continue;
}
String clazz = helper.getAttribute(ATT_CLASS);
if (clazz == null) {
continue;
}
HoverHelperDescriptor descriptor = new HoverHelperDescriptor();
descriptor.setElement(helper);
this.hoverHelperDescriptor = descriptor;
}
}
/**
* Read all the actions and categories.
*/
private void readActions() {
List<ActionCategoryDescriptor> categories = new ArrayList<ActionCategoryDescriptor>();
List<ActionDescriptor> actions = new ArrayList<ActionDescriptor>();
for (IConfigurationElement element : getConfigurationElements(EXTPT_ACTIONS)) {
if (element.getName().equals(ELEMENT_CATEGORY)) {
String name = element.getAttribute(ATT_NAME);
String id = element.getAttribute(ATT_ID);
if (name != null && id != null) {
ActionCategoryDescriptor descriptor = new ActionCategoryDescriptor();
descriptor.setName(name);
descriptor.setId(id);
categories.add(descriptor);
}
} else if (element.getName().equals(ELEMENT_ACTION)) {
String id = element.getAttribute(ATT_ID);
String category = element.getAttribute(ATT_CATEGORY_ID);
String specCompliant = element.getAttribute(ATT_SPEC_COMPLIANT);
if (category != null && id != null) {
ActionDescriptor descriptor = new ActionDescriptor();
descriptor.setId(id);
descriptor.setCategoryId(category);
descriptor.setSpecCompliant(Boolean.valueOf(specCompliant).booleanValue());
try {
AbstractBPELAction action = (AbstractBPELAction)element.createExecutableExtension(ATT_CLASS);
descriptor.setAction(action);
} catch (CoreException e) {
BPELUIPlugin.log(e);
}
actions.add(descriptor);
// register AdapterFactory - since it has to be done only once we do it here
AdapterFactory factory = descriptor.getAction().getAdapterFactory();
if (factory != null) {
BPELUtil.registerAdapterFactory(descriptor.getAction().getModelType(), factory);
}
}
}
}
fActionCategoryDescriptors = new ActionCategoryDescriptor[categories.size()];
categories.toArray(fActionCategoryDescriptors);
fActionDescriptors = new ActionDescriptor[actions.size()];
actions.toArray(fActionDescriptors);
}
/**
* Read all the actions and categories.
*/
private void readUIObjecFactories() {
List factories = new ArrayList();
IConfigurationElement[] extensions = getConfigurationElements("uiObjectFactories");
for (int i = 0; i < extensions.length; i++) {
IConfigurationElement element = extensions[i];
if (element.getName().equals("factory")) {
String id = element.getAttribute(ATT_ID);
String category = element.getAttribute(ATT_CATEGORY_ID);
String specCompliant = element.getAttribute(ATT_SPEC_COMPLIANT);
if (category != null && id != null) {
UIObjectFactoryDescriptor descriptor = new UIObjectFactoryDescriptor();
descriptor.setId(id);
descriptor.setCategoryId(category);
descriptor.setSpecCompliant(Boolean.valueOf(specCompliant).booleanValue());
try {
AbstractUIObjectFactory factory = (AbstractUIObjectFactory) element.createExecutableExtension(ATT_CLASS);
descriptor.setFactory(factory);
descriptor.setConfigElement(element);
} catch (CoreException e) {
BPELUIPlugin.log(e);
}
factories.add(descriptor);
}
}
}
uiObjectFactoryDescriptor = new UIObjectFactoryDescriptor[factories.size()];
factories.toArray(uiObjectFactoryDescriptor);
}
/**
* Read all the model listeners
*/
private void readListeners() {
List<ListenerDescriptor> listeners = new ArrayList<ListenerDescriptor>();
for (IConfigurationElement element : getConfigurationElements(EXTPT_MODELLISTENER)) {
if (element.getName().equals(ELEMENT_LISTENER)) {
String id = element.getAttribute(ATT_ID);
if (id != null) {
ListenerDescriptor descriptor = new ListenerDescriptor();
descriptor.setId(id);
try {
IModelListener listener = (IModelListener)element.createExecutableExtension(ATT_CLASS);
descriptor.setModelListener(listener);
} catch (CoreException e) {
BPELUIPlugin.log(e);
}
listeners.add(descriptor);
}
}
}
fListenerDescriptors = new ListenerDescriptor[listeners.size()];
listeners.toArray(fListenerDescriptors);
}
/**
* Given an extension point name returns its configuration elements.
*/
private IConfigurationElement[] getConfigurationElements(String extensionPointId) {
IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(
BPELUIPlugin.PLUGIN_ID, extensionPointId);
if (extensionPoint == null) {
return null;
}
return extensionPoint.getConfigurationElements();
}
/**
* @return an array of ExpressionEditorDescriptor values.
*/
public ExpressionEditorDescriptor[] getExpressionEditorDescriptors() {
return fLanguageToEditorDescriptor.values().toArray( EMPTY_EDITOR_DESCRIPTORS );
}
}
| nwnpallewela/developer-studio | bps/plugins/org.eclipse.bpel.ui/src/org/eclipse/bpel/ui/extensions/BPELUIRegistry.java | Java | apache-2.0 | 12,818 |
package bboss.org.apache.velocity.runtime.directive;
/*
* 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.
*/
/**
* Base class for all directives used in Velocity.
*
* @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a>
* @version $Id: DirectiveConstants.java 463298 2006-10-12 16:10:32Z henning $
*/
public interface DirectiveConstants
{
/** Block directive indicator */
public static final int BLOCK = 1;
/** Line directive indicator */
public static final int LINE = 2;
}
| besom/bbossgroups-mvn | bboss_velocity/src/main/java/bboss/org/apache/velocity/runtime/directive/DirectiveConstants.java | Java | apache-2.0 | 1,308 |
package com.fsck.k9.mailstore;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.internet.MimeMessage;
public class LocalMimeMessage extends MimeMessage implements LocalPart {
private final String accountUuid;
private final LocalMessage message;
private final long messagePartId;
public LocalMimeMessage(String accountUuid, LocalMessage message, long messagePartId)
throws MessagingException {
super();
this.accountUuid = accountUuid;
this.message = message;
this.messagePartId = messagePartId;
}
@Override
public String getAccountUuid() {
return accountUuid;
}
@Override
public long getId() {
return messagePartId;
}
@Override
public LocalMessage getMessage() {
return message;
}
}
| indus1/k-9 | k9mail/src/main/java/com/fsck/k9/mailstore/LocalMimeMessage.java | Java | apache-2.0 | 833 |
/*
* 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.cassandra.db.commitlog;
import org.apache.cassandra.utils.NoSpamLogger;
import org.apache.cassandra.utils.concurrent.WaitQueue;
import org.slf4j.*;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.apache.cassandra.db.commitlog.CommitLogSegment.Allocation;
public abstract class AbstractCommitLogService
{
private Thread thread;
private volatile boolean shutdown = false;
// all Allocations written before this time will be synced
protected volatile long lastSyncedAt = System.currentTimeMillis();
// counts of total written, and pending, log messages
private final AtomicLong written = new AtomicLong(0);
protected final AtomicLong pending = new AtomicLong(0);
// signal that writers can wait on to be notified of a completed sync
protected final WaitQueue syncComplete = new WaitQueue();
private final Semaphore haveWork = new Semaphore(1);
final CommitLog commitLog;
private final String name;
private final long pollIntervalMillis;
private static final Logger logger = LoggerFactory.getLogger(AbstractCommitLogService.class);
/**
* CommitLogService provides a fsync service for Allocations, fulfilling either the
* Batch or Periodic contract.
*
* Subclasses may be notified when a sync finishes by using the syncComplete WaitQueue.
*/
AbstractCommitLogService(final CommitLog commitLog, final String name, final long pollIntervalMillis)
{
this.commitLog = commitLog;
this.name = name;
this.pollIntervalMillis = pollIntervalMillis;
}
// Separated into individual method to ensure relevant objects are constructed before this is started.
void start()
{
if (pollIntervalMillis < 1)
throw new IllegalArgumentException(String.format("Commit log flush interval must be positive: %dms", pollIntervalMillis));
Runnable runnable = new Runnable()
{
public void run()
{
long firstLagAt = 0;
long totalSyncDuration = 0; // total time spent syncing since firstLagAt
long syncExceededIntervalBy = 0; // time that syncs exceeded pollInterval since firstLagAt
int lagCount = 0;
int syncCount = 0;
boolean run = true;
while (run)
{
try
{
// always run once after shutdown signalled
run = !shutdown;
// sync and signal
long syncStarted = System.currentTimeMillis();
commitLog.sync(shutdown);
lastSyncedAt = syncStarted;
syncComplete.signalAll();
// sleep any time we have left before the next one is due
long now = System.currentTimeMillis();
long sleep = syncStarted + pollIntervalMillis - now;
if (sleep < 0)
{
// if we have lagged noticeably, update our lag counter
if (firstLagAt == 0)
{
firstLagAt = now;
totalSyncDuration = syncExceededIntervalBy = syncCount = lagCount = 0;
}
syncExceededIntervalBy -= sleep;
lagCount++;
}
syncCount++;
totalSyncDuration += now - syncStarted;
if (firstLagAt > 0)
{
//Only reset the lag tracking if it actually logged this time
boolean logged = NoSpamLogger.log(
logger,
NoSpamLogger.Level.WARN,
5,
TimeUnit.MINUTES,
"Out of {} commit log syncs over the past {}s with average duration of {}ms, {} have exceeded the configured commit interval by an average of {}ms",
syncCount, (now - firstLagAt) / 1000, String.format("%.2f", (double) totalSyncDuration / syncCount), lagCount, String.format("%.2f", (double) syncExceededIntervalBy / lagCount));
if (logged)
firstLagAt = 0;
}
// if we have lagged this round, we probably have work to do already so we don't sleep
if (sleep < 0 || !run)
continue;
try
{
haveWork.tryAcquire(sleep, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
throw new AssertionError();
}
}
catch (Throwable t)
{
if (!CommitLog.handleCommitError("Failed to persist commits to disk", t))
break;
// sleep for full poll-interval after an error, so we don't spam the log file
try
{
haveWork.tryAcquire(pollIntervalMillis, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
throw new AssertionError();
}
}
}
}
};
thread = new Thread(runnable, name);
thread.start();
}
/**
* Block for @param alloc to be sync'd as necessary, and handle bookkeeping
*/
public void finishWriteFor(Allocation alloc)
{
maybeWaitForSync(alloc);
written.incrementAndGet();
}
protected abstract void maybeWaitForSync(Allocation alloc);
/**
* Sync immediately, but don't block for the sync to cmplete
*/
public WaitQueue.Signal requestExtraSync()
{
WaitQueue.Signal signal = syncComplete.register();
haveWork.release(1);
return signal;
}
public void shutdown()
{
shutdown = true;
haveWork.release(1);
}
/**
* FOR TESTING ONLY
*/
public void startUnsafe()
{
while (haveWork.availablePermits() < 1)
haveWork.release();
while (haveWork.availablePermits() > 1)
{
try
{
haveWork.acquire();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
shutdown = false;
start();
}
public void awaitTermination() throws InterruptedException
{
thread.join();
}
public long getCompletedTasks()
{
return written.get();
}
public long getPendingTasks()
{
return pending.get();
}
}
| emolsson/cassandra | src/java/org/apache/cassandra/db/commitlog/AbstractCommitLogService.java | Java | apache-2.0 | 8,191 |
/*
* 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.action.admin.indices.flush;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.action.support.DefaultShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.BroadcastShardOperationFailedException;
import org.elasticsearch.action.support.broadcast.TransportBroadcastOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.routing.GroupShardsIterator;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.service.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.util.List;
import java.util.concurrent.atomic.AtomicReferenceArray;
import static com.google.common.collect.Lists.newArrayList;
/**
* Flush Action.
*/
public class TransportFlushAction extends TransportBroadcastOperationAction<FlushRequest, FlushResponse, ShardFlushRequest, ShardFlushResponse> {
private final IndicesService indicesService;
@Inject
public TransportFlushAction(Settings settings, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, IndicesService indicesService) {
super(settings, threadPool, clusterService, transportService);
this.indicesService = indicesService;
}
@Override
protected String executor() {
return ThreadPool.Names.FLUSH;
}
@Override
protected String transportAction() {
return FlushAction.NAME;
}
@Override
protected FlushRequest newRequest() {
return new FlushRequest();
}
@Override
protected FlushResponse newResponse(FlushRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
// a non active shard, ignore
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
if (shardFailures == null) {
shardFailures = newArrayList();
}
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new FlushResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
@Override
protected ShardFlushRequest newShardRequest() {
return new ShardFlushRequest();
}
@Override
protected ShardFlushRequest newShardRequest(ShardRouting shard, FlushRequest request) {
return new ShardFlushRequest(shard.index(), shard.id(), request);
}
@Override
protected ShardFlushResponse newShardResponse() {
return new ShardFlushResponse();
}
@Override
protected ShardFlushResponse shardOperation(ShardFlushRequest request) throws ElasticsearchException {
IndexShard indexShard = indicesService.indexServiceSafe(request.index()).shardSafe(request.shardId());
indexShard.flush(new Engine.Flush().type(request.full() ? Engine.Flush.Type.NEW_WRITER : Engine.Flush.Type.COMMIT_TRANSLOG).force(request.force()));
return new ShardFlushResponse(request.index(), request.shardId());
}
/**
* The refresh request works against *all* shards.
*/
@Override
protected GroupShardsIterator shards(ClusterState clusterState, FlushRequest request, String[] concreteIndices) {
return clusterState.routingTable().allActiveShardsGrouped(concreteIndices, true);
}
@Override
protected ClusterBlockException checkGlobalBlock(ClusterState state, FlushRequest request) {
return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA);
}
@Override
protected ClusterBlockException checkRequestBlock(ClusterState state, FlushRequest countRequest, String[] concreteIndices) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, concreteIndices);
}
}
| alexksikes/elasticsearch | src/main/java/org/elasticsearch/action/admin/indices/flush/TransportFlushAction.java | Java | apache-2.0 | 5,538 |
/**
* Copyright The Apache Software Foundation
*
* 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.hadoop.hbase.io.hfile;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
public class InclusiveCombinedBlockCache extends CombinedBlockCache implements BlockCache {
public InclusiveCombinedBlockCache(LruBlockCache l1, BlockCache l2) {
super(l1,l2);
}
@Override
public Cacheable getBlock(BlockCacheKey cacheKey, boolean caching,
boolean repeat, boolean updateCacheMetrics) {
// On all external cache set ups the lru should have the l2 cache set as the victimHandler
// Because of that all requests that miss inside of the lru block cache will be
// tried in the l2 block cache.
return lruCache.getBlock(cacheKey, caching, repeat, updateCacheMetrics);
}
/**
*
* @param cacheKey The block's cache key.
* @param buf The block contents wrapped in a ByteBuffer.
* @param inMemory Whether block should be treated as in-memory. This parameter is only useful for
* the L1 lru cache.
* @param cacheDataInL1 This is totally ignored.
*/
@Override
public void cacheBlock(BlockCacheKey cacheKey, Cacheable buf, boolean inMemory,
final boolean cacheDataInL1) {
// This is the inclusive part of the combined block cache.
// Every block is placed into both block caches.
lruCache.cacheBlock(cacheKey, buf, inMemory, true);
// This assumes that insertion into the L2 block cache is either async or very fast.
l2Cache.cacheBlock(cacheKey, buf, inMemory, true);
}
}
| juwi/hbase | hbase-server/src/main/java/org/apache/hadoop/hbase/io/hfile/InclusiveCombinedBlockCache.java | Java | apache-2.0 | 2,498 |
/*
* Copyright 2017 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.stunner.client.widgets.menu.dev.impl;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.kie.workbench.common.stunner.client.widgets.menu.dev.AbstractMenuDevCommand;
import org.kie.workbench.common.stunner.core.client.api.SessionManager;
import org.kie.workbench.common.stunner.core.util.StunnerLogger;
@Dependent
public class LogGraphDevCommand extends AbstractMenuDevCommand {
protected LogGraphDevCommand() {
this(null);
}
@Inject
public LogGraphDevCommand(final SessionManager sessionManager) {
super(sessionManager);
}
@Override
public String getText() {
return "Log Graph";
}
@Override
public void execute() {
logTask(() -> StunnerLogger.log(getGraph()));
}
}
| jomarko/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-client/kie-wb-common-stunner-widgets/src/main/java/org/kie/workbench/common/stunner/client/widgets/menu/dev/impl/LogGraphDevCommand.java | Java | apache-2.0 | 1,433 |
/*
* 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.flink.test.exampleScalaPrograms;
import java.io.BufferedReader;
import org.apache.flink.examples.scala.graph.TransitiveClosureNaive;
import org.apache.flink.test.testdata.ConnectedComponentsData;
import org.apache.flink.test.testdata.TransitiveClosureData;
import org.apache.flink.test.util.JavaProgramTestBase;
public class TransitiveClosureITCase extends JavaProgramTestBase {
private static final long SEED = 0xBADC0FFEEBEEFL;
private static final int NUM_VERTICES = 100;
private static final int NUM_EDGES = 500;
private String edgesPath;
private String resultPath;
@Override
protected void preSubmit() throws Exception {
edgesPath = createTempFile("edges.txt", ConnectedComponentsData.getRandomOddEvenEdges(NUM_EDGES, NUM_VERTICES, SEED));
resultPath = getTempFilePath("results");
}
@Override
protected void testProgram() throws Exception {
TransitiveClosureNaive.main(new String [] {
"--edges", edgesPath,
"--output", resultPath,
"--iterations", "5"});
}
@Override
protected void postSubmit() throws Exception {
for (BufferedReader reader : getResultReader(resultPath)) {
TransitiveClosureData.checkOddEvenResult(reader);
}
}
}
| hongyuhong/flink | flink-tests/src/test/java/org/apache/flink/test/exampleScalaPrograms/TransitiveClosureITCase.java | Java | apache-2.0 | 2,130 |
/**
* Baidu.com,Inc.
* Copyright (c) 2000-2013 All Rights Reserved.
*/
package com.baidu.hsb.parser.ast.expression.primary.function.encryption;
import java.util.List;
import com.baidu.hsb.parser.ast.expression.Expression;
import com.baidu.hsb.parser.ast.expression.primary.function.FunctionExpression;
/**
* @author [email protected]
*/
public class Sha1 extends FunctionExpression {
public Sha1(List<Expression> arguments) {
super("SHA1", arguments);
}
@Override
public FunctionExpression constructFunction(List<Expression> arguments) {
return new Sha1(arguments);
}
}
| jushanghui/jsh | src/main/parser/com/baidu/hsb/parser/ast/expression/primary/function/encryption/Sha1.java | Java | apache-2.0 | 618 |
/*
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.flex.forks.batik.svggen;
import java.util.HashMap;
import java.util.Map;
import org.apache.flex.forks.batik.ext.awt.g2d.TransformStackElement;
import org.apache.flex.forks.batik.util.SVGConstants;
/**
* Represents the SVG equivalent of a Java 2D API graphic
* context attribute.
*
* @author <a href="mailto:[email protected]">Vincent Hardy</a>
* @version $Id: SVGGraphicContext.java 478176 2006-11-22 14:50:50Z dvholten $
*/
public class SVGGraphicContext implements SVGConstants, ErrorConstants {
// this properties can only be set of leaf nodes =>
// if they have default values they can be ignored
private static final String[] leafOnlyAttributes = {
SVG_OPACITY_ATTRIBUTE,
SVG_FILTER_ATTRIBUTE,
SVG_CLIP_PATH_ATTRIBUTE
};
private static final String[] defaultValues = {
"1",
SVG_NONE_VALUE,
SVG_NONE_VALUE
};
private Map context;
private Map groupContext;
private Map graphicElementContext;
private TransformStackElement[] transformStack;
/**
* @param context Set of style attributes in this context.
* @param transformStack Sequence of transforms that where
* applied to create the context's current transform.
*/
public SVGGraphicContext(Map context,
TransformStackElement[] transformStack) {
if (context == null)
throw new SVGGraphics2DRuntimeException(ERR_MAP_NULL);
if (transformStack == null)
throw new SVGGraphics2DRuntimeException(ERR_TRANS_NULL);
this.context = context;
this.transformStack = transformStack;
computeGroupAndGraphicElementContext();
}
/**
* @param groupContext Set of attributes that apply to group
* @param graphicElementContext Set of attributes that apply to
* elements but not to groups (e.g., opacity, filter).
* @param transformStack Sequence of transforms that where
* applied to create the context's current transform.
*/
public SVGGraphicContext(Map groupContext, Map graphicElementContext,
TransformStackElement[] transformStack) {
if (groupContext == null || graphicElementContext == null)
throw new SVGGraphics2DRuntimeException(ERR_MAP_NULL);
if (transformStack == null)
throw new SVGGraphics2DRuntimeException(ERR_TRANS_NULL);
this.groupContext = groupContext;
this.graphicElementContext = graphicElementContext;
this.transformStack = transformStack;
computeContext();
}
/**
* @return set of all attributes.
*/
public Map getContext() {
return context;
}
/**
* @return set of attributes that can be set on a group
*/
public Map getGroupContext() {
return groupContext;
}
/**
* @return set of attributes that can be set on leaf node
*/
public Map getGraphicElementContext() {
return graphicElementContext;
}
/**
* @return set of TransformStackElement for this context
*/
public TransformStackElement[] getTransformStack() {
return transformStack;
}
private void computeContext() {
if (context != null)
return;
context = new HashMap(groupContext);
context.putAll(graphicElementContext);
}
private void computeGroupAndGraphicElementContext() {
if (groupContext != null)
return;
//
// Now, move attributes that only apply to
// leaf elements to a separate map.
//
groupContext = new HashMap(context);
graphicElementContext = new HashMap();
for (int i=0; i< leafOnlyAttributes.length; i++) {
Object attrValue = groupContext.get(leafOnlyAttributes[i]);
if (attrValue != null){
if (!attrValue.equals(defaultValues[i]))
graphicElementContext.put(leafOnlyAttributes[i], attrValue);
groupContext.remove(leafOnlyAttributes[i]);
}
}
}
}
| shyamalschandra/flex-sdk | modules/thirdparty/batik/sources/org/apache/flex/forks/batik/svggen/SVGGraphicContext.java | Java | apache-2.0 | 4,938 |
/*
* 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.search;
import org.apache.solr.SolrTestCaseJ4;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class RankQueryTest extends SolrTestCaseJ4 {
@BeforeClass
public static void beforeClass() throws Exception {
initCore("solrconfig-plugcollector.xml", "schema15.xml");
}
@Override
@Before
public void setUp() throws Exception {
// if you override setUp or tearDown, you better call
// the super classes version
super.setUp();
clearIndex();
assertU(commit());
}
@Test
public void testPluggableCollector() throws Exception {
String[] doc = {"id","1", "sort_i", "100"};
assertU(adoc(doc));
assertU(commit());
String[] doc1 = {"id","2", "sort_i", "50"};
assertU(adoc(doc1));
String[] doc2 = {"id","3", "sort_i", "1000"};
assertU(adoc(doc2));
assertU(commit());
String[] doc3 = {"id","4", "sort_i", "2000"};
assertU(adoc(doc3));
String[] doc4 = {"id","5", "sort_i", "2"};
assertU(adoc(doc4));
assertU(commit());
String[] doc5 = {"id","6", "sort_i","11"};
assertU(adoc(doc5));
assertU(commit());
ModifiableSolrParams params = new ModifiableSolrParams();
params.add("q", "*:*");
params.add("rq", "{!rank}");
params.add("sort","sort_i asc");
assertQ(req(params), "*[count(//doc)=6]",
"//result/doc[1]/str[@name='id'][.='4']",
"//result/doc[2]/str[@name='id'][.='3']",
"//result/doc[3]/str[@name='id'][.='1']",
"//result/doc[4]/str[@name='id'][.='2']",
"//result/doc[5]/str[@name='id'][.='6']",
"//result/doc[6]/str[@name='id'][.='5']"
);
params = new ModifiableSolrParams();
params.add("q", "{!edismax bf=$bff}*:*");
params.add("bff", "field(sort_i)");
params.add("rq", "{!rank collector=1}");
assertQ(req(params), "*[count(//doc)=6]",
"//result/doc[6]/str[@name='id'][.='4']",
"//result/doc[5]/str[@name='id'][.='3']",
"//result/doc[4]/str[@name='id'][.='1']",
"//result/doc[3]/str[@name='id'][.='2']",
"//result/doc[2]/str[@name='id'][.='6']",
"//result/doc[1]/str[@name='id'][.='5']"
);
params = new ModifiableSolrParams();
params.add("q", "*:*");
params.add("sort","sort_i asc");
assertQ(req(params), "*[count(//doc)=6]",
"//result/doc[6]/str[@name='id'][.='4']",
"//result/doc[5]/str[@name='id'][.='3']",
"//result/doc[4]/str[@name='id'][.='1']",
"//result/doc[3]/str[@name='id'][.='2']",
"//result/doc[2]/str[@name='id'][.='6']",
"//result/doc[1]/str[@name='id'][.='5']"
);
}
}
| q474818917/solr-5.2.0 | solr/core/src/test/org/apache/solr/search/RankQueryTest.java | Java | apache-2.0 | 3,586 |
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.diagram.ui.figures.ResizableCompartmentFigure;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediatorCompartmentEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediatorFlowCompartmentEditPart.Complexity;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.editpolicy.FeedbackIndicateDragDropEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.MediatorFlowMediatorFlowCompartment24CanonicalEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.MediatorFlowMediatorFlowCompartment24ItemSemanticEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.EsbVisualIDRegistry;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.part.Messages;
/**
* @generated NOT
*/
public class MediatorFlowMediatorFlowCompartment24EditPart extends AbstractMediatorCompartmentEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 7051;
/**
* @generated NOT
*/
public MediatorFlowMediatorFlowCompartment24EditPart(View view) {
super(view);
complexity = Complexity.MULTIPLE;
}
/**
* @generated NOT
*/
public String getCompartmentName() {
//return Messages.MediatorFlowMediatorFlowCompartment24EditPart_title;
return null;
}
public IFigure createFigure() {
ResizableCompartmentFigure result = (ResizableCompartmentFigure) super.createFigure();
result.setTitle("Obligations");
result.setTitleVisibility(true);
/*
* Override default border.
* Fixing TOOLS-1864.
*/
LineBorder border = new LineBorder(new Color(null, 0, 0, 204), 1, SWT.BORDER_DASH);
result.setBorder(border);
result.setToolTip("Obligations");
ConstrainedToolbarLayout layoutManager = new ConstrainedToolbarLayout(false);
layoutManager.setSpacing(-15);
result.setLayoutManager(layoutManager);
return result;
}
/**
* @generated NOT
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
new MediatorFlowMediatorFlowCompartment24ItemSemanticEditPolicy());
installEditPolicy(EditPolicyRoles.CREATION_ROLE, new CreationEditPolicyWithCustomReparent(
EsbVisualIDRegistry.TYPED_INSTANCE));
installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new DragDropEditPolicy());
installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE, new FeedbackIndicateDragDropEditPolicy());
installEditPolicy(EditPolicyRoles.CANONICAL_ROLE,
new MediatorFlowMediatorFlowCompartment24CanonicalEditPolicy());
}
public boolean isSelectable() {
return false;
}
/**
* @generated
*/
protected void setRatio(Double ratio) {
if (getFigure().getParent().getLayoutManager() instanceof ConstrainedToolbarLayout) {
super.setRatio(ratio);
}
}
}
| nwnpallewela/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/parts/MediatorFlowMediatorFlowCompartment24EditPart.java | Java | apache-2.0 | 3,477 |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kim.rule.ui;
import org.kuali.rice.kim.rule.event.ui.AddDelegationMemberEvent;
import org.kuali.rice.krad.rules.rule.BusinessRule;
/**
* This is a description of what this class does - shyu don't forget to fill this in.
*
* @author Kuali Rice Team ([email protected])
*
*/
public interface AddDelegationMemberRule extends BusinessRule {
public boolean processAddDelegationMember(AddDelegationMemberEvent addDelegationMemberEvent);
}
| mztaylor/rice-git | rice-middleware/impl/src/main/java/org/kuali/rice/kim/rule/ui/AddDelegationMemberRule.java | Java | apache-2.0 | 1,126 |
/**
* 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.metron.rest.controller;
import org.adrianwalker.multilinestring.Multiline;
import org.apache.metron.rest.service.GlobalConfigService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.apache.metron.integration.utils.TestUtils.assertEventually;
import static org.apache.metron.rest.MetronRestConstants.TEST_PROFILE;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(TEST_PROFILE)
public class GlobalConfigControllerIntegrationTest {
/**
{
"solr.zookeeper": "solr:2181",
"solr.collection": "metron",
"solr.numShards": 1,
"solr.replicationFactor": 1
}
*/
@Multiline
public static String globalJson;
@Autowired
private GlobalConfigService globalConfigService;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
private String globalConfigUrl = "/api/v1/global/config";
private String user = "user";
private String password = "password";
@BeforeEach
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).apply(springSecurity()).build();
}
@Test
public void testSecurity() throws Exception {
this.mockMvc.perform(post(globalConfigUrl).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(globalJson))
.andExpect(status().isUnauthorized());
this.mockMvc.perform(get(globalConfigUrl))
.andExpect(status().isUnauthorized());
this.mockMvc.perform(delete(globalConfigUrl).with(csrf()))
.andExpect(status().isUnauthorized());
}
@Test
public void test() throws Exception {
this.globalConfigService.delete();
assertEventually(() -> this.mockMvc.perform(get(globalConfigUrl).with(httpBasic(user,password)))
.andExpect(status().isNotFound())
);
this.mockMvc.perform(post(globalConfigUrl).with(httpBasic(user,password)).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(globalJson))
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8")));
assertEventually(() -> this.mockMvc.perform(post(globalConfigUrl).with(httpBasic(user,password)).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(globalJson))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8")))
);
this.mockMvc.perform(get(globalConfigUrl).with(httpBasic(user,password)))
.andExpect(status().isOk());
this.mockMvc.perform(delete(globalConfigUrl).with(httpBasic(user,password)).with(csrf()))
.andExpect(status().isOk());
assertEventually(() -> this.mockMvc.perform(delete(globalConfigUrl).with(httpBasic(user,password)).with(csrf()))
.andExpect(status().isNotFound())
);
this.globalConfigService.delete();
}
}
| JonZeolla/metron | metron-interface/metron-rest/src/test/java/org/apache/metron/rest/controller/GlobalConfigControllerIntegrationTest.java | Java | apache-2.0 | 5,183 |
package org.zstack.kvm;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.kvm.KVMAgentCommands.AttachDataVolumeCmd;
import org.zstack.kvm.KVMAgentCommands.DetachDataVolumeCmd;
/**
* Created by frank on 4/24/2015.
*/
public interface KVMDetachVolumeExtensionPoint {
void beforeDetachVolume(KVMHostInventory host, VmInstanceInventory vm, VolumeInventory volume, DetachDataVolumeCmd cmd);
void afterDetachVolume(KVMHostInventory host, VmInstanceInventory vm, VolumeInventory volume, DetachDataVolumeCmd cmd);
void detachVolumeFailed(KVMHostInventory host, VmInstanceInventory vm, VolumeInventory volume, DetachDataVolumeCmd cmd, ErrorCode err);
}
| no2key/zstack | plugin/kvm/src/main/java/org/zstack/kvm/KVMDetachVolumeExtensionPoint.java | Java | apache-2.0 | 792 |
/*
* 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.cassandra.service;
import java.util.Arrays;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.xml.crypto.Data;
import com.google.common.collect.Sets;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.EncryptionOptions;
import org.apache.cassandra.transport.Server;
import org.apache.cassandra.utils.Pair;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NativeTransportServiceTest
{
static EncryptionOptions defaultOptions;
@BeforeClass
public static void setupDD()
{
DatabaseDescriptor.daemonInitialization();
defaultOptions = DatabaseDescriptor.getNativeProtocolEncryptionOptions();
}
@After
public void resetConfig()
{
DatabaseDescriptor.updateNativeProtocolEncryptionOptions(update -> new EncryptionOptions(defaultOptions).applyConfig());
DatabaseDescriptor.setNativeTransportPortSSL(null);
}
@Test
public void testServiceCanBeStopped()
{
withService((NativeTransportService service) -> {
service.stop();
assertFalse(service.isRunning());
});
}
@Test
public void testIgnoresStartOnAlreadyStarted()
{
withService((NativeTransportService service) -> {
service.start();
service.start();
service.start();
});
}
@Test
public void testIgnoresStoppedOnAlreadyStopped()
{
withService((NativeTransportService service) -> {
service.stop();
service.stop();
service.stop();
});
}
@Test
public void testDestroy()
{
withService((NativeTransportService service) -> {
BooleanSupplier allTerminated = () ->
service.getWorkerGroup().isShutdown() && service.getWorkerGroup().isTerminated();
assertFalse(allTerminated.getAsBoolean());
service.destroy();
assertTrue(allTerminated.getAsBoolean());
});
}
@Test
public void testConcurrentStarts()
{
withService(NativeTransportService::start, false, 20);
}
@Test
public void testConcurrentStops()
{
withService(NativeTransportService::stop, true, 20);
}
@Test
public void testConcurrentDestroys()
{
withService(NativeTransportService::destroy, true, 20);
}
@Test
public void testPlainDefaultPort()
{
// default plain settings: client encryption disabled and default native transport port
withService((NativeTransportService service) ->
{
assertEquals(1, service.getServers().size());
Server server = service.getServers().iterator().next();
assertEquals(EncryptionOptions.TlsEncryptionPolicy.UNENCRYPTED, server.tlsEncryptionPolicy);
assertEquals(server.socket.getPort(), DatabaseDescriptor.getNativeTransportPort());
});
}
@Test
public void testSSLOnly()
{
// default ssl settings: client encryption enabled and default native transport port used for ssl only
DatabaseDescriptor.updateNativeProtocolEncryptionOptions(options -> options.withEnabled(true)
.withOptional(false));
withService((NativeTransportService service) ->
{
service.initialize();
assertEquals(1, service.getServers().size());
Server server = service.getServers().iterator().next();
assertEquals(EncryptionOptions.TlsEncryptionPolicy.ENCRYPTED, server.tlsEncryptionPolicy);
assertEquals(server.socket.getPort(), DatabaseDescriptor.getNativeTransportPort());
}, false, 1);
}
@Test
public void testSSLOptional()
{
// default ssl settings: client encryption enabled and default native transport port used for optional ssl
DatabaseDescriptor.updateNativeProtocolEncryptionOptions(options -> options.withEnabled(true)
.withOptional(true));
withService((NativeTransportService service) ->
{
service.initialize();
assertEquals(1, service.getServers().size());
Server server = service.getServers().iterator().next();
assertEquals(EncryptionOptions.TlsEncryptionPolicy.OPTIONAL, server.tlsEncryptionPolicy);
assertEquals(server.socket.getPort(), DatabaseDescriptor.getNativeTransportPort());
}, false, 1);
}
@Test
public void testSSLPortWithOptionalEncryption()
{
// ssl+non-ssl settings: client encryption enabled and additional ssl port specified
DatabaseDescriptor.updateNativeProtocolEncryptionOptions(
options -> options.withEnabled(true)
.withOptional(true)
.withKeyStore("test/conf/cassandra_ssl_test.keystore"));
DatabaseDescriptor.setNativeTransportPortSSL(8432);
withService((NativeTransportService service) ->
{
service.initialize();
assertEquals(2, service.getServers().size());
assertEquals(
Sets.newHashSet(Arrays.asList(
Pair.create(EncryptionOptions.TlsEncryptionPolicy.OPTIONAL,
DatabaseDescriptor.getNativeTransportPortSSL()),
Pair.create(EncryptionOptions.TlsEncryptionPolicy.UNENCRYPTED,
DatabaseDescriptor.getNativeTransportPort())
)
),
service.getServers().stream().map((Server s) ->
Pair.create(s.tlsEncryptionPolicy,
s.socket.getPort())).collect(Collectors.toSet())
);
}, false, 1);
}
@Test(expected=java.lang.IllegalStateException.class)
public void testSSLPortWithDisabledEncryption()
{
// ssl+non-ssl settings: client encryption disabled and additional ssl port specified
// should get an illegal state exception
DatabaseDescriptor.updateNativeProtocolEncryptionOptions(
options -> options.withEnabled(false));
DatabaseDescriptor.setNativeTransportPortSSL(8432);
withService((NativeTransportService service) ->
{
service.initialize();
assertEquals(1, service.getServers().size());
assertEquals(
Sets.newHashSet(Arrays.asList(
Pair.create(EncryptionOptions.TlsEncryptionPolicy.UNENCRYPTED,
DatabaseDescriptor.getNativeTransportPort())
)
),
service.getServers().stream().map((Server s) ->
Pair.create(s.tlsEncryptionPolicy,
s.socket.getPort())).collect(Collectors.toSet())
);
}, false, 1);
}
@Test
public void testSSLPortWithEnabledSSL()
{
// ssl+non-ssl settings: client encryption enabled and additional ssl port specified
// encryption is enabled and not optional, so listen on both ports requiring encryption
DatabaseDescriptor.updateNativeProtocolEncryptionOptions(
options -> options.withEnabled(true)
.withOptional(false)
.withKeyStore("test/conf/cassandra_ssl_test.keystore"));
DatabaseDescriptor.setNativeTransportPortSSL(8432);
withService((NativeTransportService service) ->
{
service.initialize();
assertEquals(2, service.getServers().size());
assertEquals(
Sets.newHashSet(Arrays.asList(
Pair.create(EncryptionOptions.TlsEncryptionPolicy.ENCRYPTED,
DatabaseDescriptor.getNativeTransportPortSSL()),
Pair.create(EncryptionOptions.TlsEncryptionPolicy.UNENCRYPTED,
DatabaseDescriptor.getNativeTransportPort())
)
),
service.getServers().stream().map((Server s) ->
Pair.create(s.tlsEncryptionPolicy,
s.socket.getPort())).collect(Collectors.toSet())
);
}, false, 1);
}
private static void withService(Consumer<NativeTransportService> f)
{
withService(f, true, 1);
}
private static void withService(Consumer<NativeTransportService> f, boolean start, int concurrently)
{
NativeTransportService service = new NativeTransportService();
assertFalse(service.isRunning());
if (start)
{
service.start();
assertTrue(service.isRunning());
}
try
{
if (concurrently == 1)
{
f.accept(service);
}
else
{
IntStream.range(0, concurrently).parallel().map((int i) -> {
f.accept(service);
return 1;
}).sum();
}
}
finally
{
service.stop();
}
}
}
| beobal/cassandra | test/unit/org/apache/cassandra/service/NativeTransportServiceTest.java | Java | apache-2.0 | 11,495 |
package com.djs.learn.spring_sample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.djs.learn.spring_sample.greeting.GreetingService;
import com.djs.learn.spring_sample.knight.Knight;
public class AppMain
{
public static void main( String [] args ) throws Exception
{
// Notes: AOP doesn't work while using XmlBeanFactory!
// BeanFactory factory = new XmlBeanFactory( new FileSystemResource( "application-context.xml" ) );
// BeanFactory factory = new XmlBeanFactory( new ClassPathResource( "application-context.xml" ) );
ApplicationContext appContext = new ClassPathXmlApplicationContext( new String []
{ "greeting.xml", "knight.xml", "music.xml", "db.xml" } );
GreetingService greetingService = (GreetingService)appContext.getBean( "greetingService" );
greetingService.sayGreeting();
Knight knightA = (Knight)appContext.getBean( "knightA" );
knightA.embarkOnQuest();
Knight knightB = (Knight)appContext.getBean( "knightB" );
knightB.embarkOnQuest();
}
}
| djsilenceboy/LearnTest | Java_Test/AppSpringSample1/Backup/Spring3.0.6+Hibernate3.6.7/src/main/java/com/djs/test/spring_sample/AppMain.java | Java | apache-2.0 | 1,083 |
/*******************************************************************************
* Copyright 2014 Open Networking Laboratory
*
* 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 net.onrc.openvirtex.exceptions;
import org.openflow.protocol.OFError.OFBadActionCode;
public class ActionVirtualizationDenied extends Exception {
private static final long serialVersionUID = 1L;
private final OFBadActionCode code;
public ActionVirtualizationDenied(final String msg,
final OFBadActionCode code) {
super(msg);
this.code = code;
}
public OFBadActionCode getErrorCode() {
return this.code;
}
}
| opennetworkinglab/OpenVirteX | src/main/java/net/onrc/openvirtex/exceptions/ActionVirtualizationDenied.java | Java | apache-2.0 | 1,244 |
/*
* 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.flink.orc;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.expressions.CallExpression;
import org.apache.flink.table.expressions.FieldReferenceExpression;
import org.apache.flink.table.expressions.ResolvedExpression;
import org.apache.flink.table.expressions.ValueLiteralExpression;
import org.apache.flink.table.functions.BuiltInFunctionDefinitions;
import org.apache.hadoop.hive.ql.io.sarg.PredicateLeaf;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
/** Unit Tests for {@link OrcFileFormatFactory}. */
public class OrcFileSystemFilterTest {
@Test
@SuppressWarnings("unchecked")
public void testApplyPredicate() {
List<ResolvedExpression> args = new ArrayList<>();
// equal
FieldReferenceExpression fieldReferenceExpression =
new FieldReferenceExpression("long1", DataTypes.BIGINT(), 0, 0);
ValueLiteralExpression valueLiteralExpression = new ValueLiteralExpression(10);
args.add(fieldReferenceExpression);
args.add(valueLiteralExpression);
CallExpression equalExpression =
new CallExpression(BuiltInFunctionDefinitions.EQUALS, args, DataTypes.BOOLEAN());
OrcFilters.Predicate predicate1 = OrcFilters.toOrcPredicate(equalExpression);
OrcFilters.Predicate predicate2 =
new OrcFilters.Equals("long1", PredicateLeaf.Type.LONG, 10);
assertTrue(predicate1.toString().equals(predicate2.toString()));
// greater than
CallExpression greaterExpression =
new CallExpression(
BuiltInFunctionDefinitions.GREATER_THAN, args, DataTypes.BOOLEAN());
OrcFilters.Predicate predicate3 = OrcFilters.toOrcPredicate(greaterExpression);
OrcFilters.Predicate predicate4 =
new OrcFilters.Not(
new OrcFilters.LessThanEquals("long1", PredicateLeaf.Type.LONG, 10));
assertTrue(predicate3.toString().equals(predicate4.toString()));
// less than
CallExpression lessExpression =
new CallExpression(BuiltInFunctionDefinitions.LESS_THAN, args, DataTypes.BOOLEAN());
OrcFilters.Predicate predicate5 = OrcFilters.toOrcPredicate(lessExpression);
OrcFilters.Predicate predicate6 =
new OrcFilters.LessThan("long1", PredicateLeaf.Type.LONG, 10);
assertTrue(predicate5.toString().equals(predicate6.toString()));
}
}
| lincoln-lil/flink | flink-formats/flink-orc/src/test/java/org/apache/flink/orc/OrcFileSystemFilterTest.java | Java | apache-2.0 | 3,348 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.externalnav;
import android.content.ComponentName;
import android.content.Intent;
import org.chromium.chrome.browser.externalnav.ExternalNavigationHandler.OverrideUrlLoadingResult;
import org.chromium.chrome.browser.tab.Tab;
import java.util.List;
/**
* A delegate for the class responsible for navigating to external applications from Chrome. Used
* by {@link ExternalNavigationHandler}.
*/
interface ExternalNavigationDelegate {
/**
* Get the list of component name of activities which can resolve |intent|.
*/
List<ComponentName> queryIntentActivities(Intent intent);
/**
* Determine if the given intent can be resolved to at least one activity.
*/
boolean canResolveActivity(Intent intent);
/**
* Determine if Chrome is the default or only handler for a given intent. If true, Chrome
* will handle the intent when started.
*/
boolean willChromeHandleIntent(Intent intent);
/**
* Search for intent handlers that are specific to this URL aka, specialized apps like
* google maps or youtube
*/
boolean isSpecializedHandlerAvailable(Intent intent);
/**
* Get the name of the package of the currently running activity so that incoming intents
* can be identified as originating from this activity.
*/
String getPackageName();
/**
* Start an activity for the intent. Used for intents that must be handled externally.
*/
void startActivity(Intent intent);
/**
* Start an activity for the intent. Used for intents that may be handled internally or
* externally. If the user chooses to handle the intent internally, this routine must return
* false.
*/
boolean startActivityIfNeeded(Intent intent);
/**
* Display a dialog warning the user that they may be leaving Chrome by starting this
* intent. Give the user the opportunity to cancel the action. And if it is canceled, a
* navigation will happen in Chrome.
*/
void startIncognitoIntent(Intent intent, String referrerUrl, String fallbackUrl, Tab tab,
boolean needsToCloseTab);
/**
* @param tab The current tab.
* @return Whether we should block the navigation and request file access before proceeding.
*/
boolean shouldRequestFileAccess(Tab tab);
/**
* Trigger a UI affordance that will ask the user to grant file access. After the access
* has been granted or denied, continue loading the specified file URL.
*
* @param intent The intent to continue loading the file URL.
* @param referrerUrl The HTTP referrer URL.
* @param tab The current tab.
* @param needsToCloseTab Whether this action should close the current tab.
*/
void startFileIntent(Intent intent, String referrerUrl, Tab tab, boolean needsToCloseTab);
/**
* Clobber the current tab and try not to pass an intent when it should be handled by Chrome
* so that we can deliver HTTP referrer information safely.
*
* @param url The new URL after clobbering the current tab.
* @param referrerUrl The HTTP referrer URL.
* @param tab The current tab.
* @return OverrideUrlLoadingResult (if the tab has been clobbered, or we're launching an
* intent.)
*/
OverrideUrlLoadingResult clobberCurrentTab(String url, String referrerUrl, Tab tab);
/**
* Determine if the Chrome app is in the foreground.
*/
boolean isChromeAppInForeground();
/**
* Check if Chrome is running in document mode.
*/
boolean isDocumentMode();
}
| Chilledheart/chromium | chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegate.java | Java | bsd-3-clause | 3,800 |
/**
* Copyright (c) 2005-2007, Paul Tuckey
* All rights reserved.
* ====================================================================
* Licensed under the BSD License. Text as follows.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* - Neither the name tuckey.org nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
package org.tuckey.web.filters.urlrewrite;
import junit.framework.TestCase;
import org.tuckey.web.filters.urlrewrite.utils.Log;
import org.tuckey.web.filters.urlrewrite.utils.URLDecoder;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
/**
*/
public class UrlDecoderTest extends TestCase {
final static String AllChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?";
public void setUp() {
Log.setLevel("DEBUG");
}
public void testPathSpaces() throws URISyntaxException {
String encoded = "/foo%20bar/foo+bar";
String decoded = URLDecoder.decodeURL(encoded, "UTF-8");
assertEquals("/foo bar/foo+bar", decoded);
}
public void testQuerySpacesFixed() throws URISyntaxException, UnsupportedEncodingException {
String encoded = URLEncoder.encode("/foo bar/foo+bar", "UTF-8");
String decoded = URLDecoder.decodeURL(encoded, "UTF-8");
assertEquals("/foo+bar/foo+bar", decoded);
}
public void testQueryEncodingUTF8() throws URISyntaxException, UnsupportedEncodingException {
String encoded = "/?foo=" + URLEncoder.encode(AllChars, "UTF-8");
String decoded = URLDecoder.decodeURL(encoded, "UTF-8");
assertEquals("/?foo=" + AllChars, decoded);
}
public void testQueryEncodingLatin1() throws URISyntaxException, UnsupportedEncodingException {
String encoded = "/?foo=" + URLEncoder.encode(AllChars, "ISO-8859-1");
String decoded = URLDecoder.decodeURL(encoded, "ISO-8859-1");
assertEquals("/?foo=" + AllChars, decoded);
}
public void testRealEncoding() throws URISyntaxException, UnsupportedEncodingException {
String katakana = "/???????????????" +
"????????????????" +
"????????????????" +
"????????????????" +
"????????????????" +
"????????????????";
String encoded = URLEncoder.encode(katakana, "UTF-8");
String decoded = URLDecoder.decodeURL(encoded, "UTF-8");
assertEquals(katakana, decoded);
}
}
| safarijv/urlrewritefilter | src/test/java/org/tuckey/web/filters/urlrewrite/UrlDecoderTest.java | Java | bsd-3-clause | 4,002 |
package edu.gemini.itc.base;
/**
* ErrorFunction
* This class exists so that the client can calculate a value
* from the Error function given a z.
*/
public class ErrorFunction {
private static final String DEFAULT_ERROR_FILENAME = ITCConstants.CALC_LIB + "/"
+ "Error_Function" + ITCConstants.DATA_SUFFIX;
private static final double MAX_Z_VALUE = 2.9;
private static final double MIN_Z_VALUE = -3.0;
private final DefaultArraySpectrum errorFunction;
public ErrorFunction() {
this(ErrorFunction.DEFAULT_ERROR_FILENAME);
}
public ErrorFunction(String file) {
errorFunction = new DefaultArraySpectrum(file);
}
public double getERF(double z) {
if (z > ErrorFunction.MAX_Z_VALUE)
return 1;
else if (z <= ErrorFunction.MIN_Z_VALUE)
return -1;
else
return errorFunction.getY(z);
}
public String toString() {
final StringBuilder sb = new StringBuilder("ErrorFuntion:\n");
final double[][] data = errorFunction.getData();
for (int i = 0; i < data[0].length; i++) {
sb.append(data[0][i]);
sb.append("\t");
sb.append(data[1][i]);
sb.append("\n");
}
return sb.toString();
}
}
| arturog8m/ocs | bundle/edu.gemini.itc/src/main/java/edu/gemini/itc/base/ErrorFunction.java | Java | bsd-3-clause | 1,304 |
/*
* Copyright (c) 1997, 2016, 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.
*/
/**
* <h1>Tree drivers</h1>
* Different drivers to perform a tree operations.<br>
*
* @since 17 Apr 2002
* <hr>
*/
package org.netbeans.jemmy.drivers.trees;
| md-5/jdk10 | test/jdk/sanity/client/lib/jemmy/src/org/netbeans/jemmy/drivers/trees/package-info.java | Java | gpl-2.0 | 1,375 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via [email protected] or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.compiere.util.KeyNamePair;
/** Generated Interface for C_RfQ
* @author Adempiere (generated)
* @version Release 3.8.0
*/
public interface I_C_RfQ
{
/** TableName=C_RfQ */
public static final String Table_Name = "C_RfQ";
/** AD_Table_ID=677 */
public static final int Table_ID = MTable.getTable_ID(Table_Name);
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 1 - Org
*/
BigDecimal accessLevel = BigDecimal.valueOf(1);
/** Load Meta Data */
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name AD_User_ID */
public static final String COLUMNNAME_AD_User_ID = "AD_User_ID";
/** Set User/Contact.
* User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID);
/** Get User/Contact.
* User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID();
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException;
/** Column name C_BPartner_ID */
public static final String COLUMNNAME_C_BPartner_ID = "C_BPartner_ID";
/** Set Business Partner .
* Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID);
/** Get Business Partner .
* Identifies a Business Partner
*/
public int getC_BPartner_ID();
public org.compiere.model.I_C_BPartner getC_BPartner() throws RuntimeException;
/** Column name C_BPartner_Location_ID */
public static final String COLUMNNAME_C_BPartner_Location_ID = "C_BPartner_Location_ID";
/** Set Partner Location.
* Identifies the (ship to) address for this Business Partner
*/
public void setC_BPartner_Location_ID (int C_BPartner_Location_ID);
/** Get Partner Location.
* Identifies the (ship to) address for this Business Partner
*/
public int getC_BPartner_Location_ID();
public org.compiere.model.I_C_BPartner_Location getC_BPartner_Location() throws RuntimeException;
/** Column name C_Currency_ID */
public static final String COLUMNNAME_C_Currency_ID = "C_Currency_ID";
/** Set Currency.
* The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID);
/** Get Currency.
* The Currency for this record
*/
public int getC_Currency_ID();
public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException;
/** Column name C_Order_ID */
public static final String COLUMNNAME_C_Order_ID = "C_Order_ID";
/** Set Order.
* Order
*/
public void setC_Order_ID (int C_Order_ID);
/** Get Order.
* Order
*/
public int getC_Order_ID();
public org.compiere.model.I_C_Order getC_Order() throws RuntimeException;
/** Column name C_RfQ_ID */
public static final String COLUMNNAME_C_RfQ_ID = "C_RfQ_ID";
/** Set RfQ.
* Request for Quotation
*/
public void setC_RfQ_ID (int C_RfQ_ID);
/** Get RfQ.
* Request for Quotation
*/
public int getC_RfQ_ID();
/** Column name C_RfQ_Topic_ID */
public static final String COLUMNNAME_C_RfQ_Topic_ID = "C_RfQ_Topic_ID";
/** Set RfQ Topic.
* Topic for Request for Quotations
*/
public void setC_RfQ_Topic_ID (int C_RfQ_Topic_ID);
/** Get RfQ Topic.
* Topic for Request for Quotations
*/
public int getC_RfQ_Topic_ID();
public org.compiere.model.I_C_RfQ_Topic getC_RfQ_Topic() throws RuntimeException;
/** Column name CopyLines */
public static final String COLUMNNAME_CopyLines = "CopyLines";
/** Set Copy Lines */
public void setCopyLines (String CopyLines);
/** Get Copy Lines */
public String getCopyLines();
/** Column name CreatePO */
public static final String COLUMNNAME_CreatePO = "CreatePO";
/** Set Create PO.
* Create Purchase Order
*/
public void setCreatePO (String CreatePO);
/** Get Create PO.
* Create Purchase Order
*/
public String getCreatePO();
/** Column name CreateSO */
public static final String COLUMNNAME_CreateSO = "CreateSO";
/** Set Create SO */
public void setCreateSO (String CreateSO);
/** Get Create SO */
public String getCreateSO();
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name DateResponse */
public static final String COLUMNNAME_DateResponse = "DateResponse";
/** Set Response Date.
* Date of the Response
*/
public void setDateResponse (Timestamp DateResponse);
/** Get Response Date.
* Date of the Response
*/
public Timestamp getDateResponse();
/** Column name DateWorkComplete */
public static final String COLUMNNAME_DateWorkComplete = "DateWorkComplete";
/** Set Work Complete.
* Date when work is (planned to be) complete
*/
public void setDateWorkComplete (Timestamp DateWorkComplete);
/** Get Work Complete.
* Date when work is (planned to be) complete
*/
public Timestamp getDateWorkComplete();
/** Column name DateWorkStart */
public static final String COLUMNNAME_DateWorkStart = "DateWorkStart";
/** Set Work Start.
* Date when work is (planned to be) started
*/
public void setDateWorkStart (Timestamp DateWorkStart);
/** Get Work Start.
* Date when work is (planned to be) started
*/
public Timestamp getDateWorkStart();
/** Column name DeliveryDays */
public static final String COLUMNNAME_DeliveryDays = "DeliveryDays";
/** Set Delivery Days.
* Number of Days (planned) until Delivery
*/
public void setDeliveryDays (int DeliveryDays);
/** Get Delivery Days.
* Number of Days (planned) until Delivery
*/
public int getDeliveryDays();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name DocumentNo */
public static final String COLUMNNAME_DocumentNo = "DocumentNo";
/** Set Document No.
* Document sequence number of the document
*/
public void setDocumentNo (String DocumentNo);
/** Get Document No.
* Document sequence number of the document
*/
public String getDocumentNo();
/** Column name Help */
public static final String COLUMNNAME_Help = "Help";
/** Set Comment/Help.
* Comment or Hint
*/
public void setHelp (String Help);
/** Get Comment/Help.
* Comment or Hint
*/
public String getHelp();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsInvitedVendorsOnly */
public static final String COLUMNNAME_IsInvitedVendorsOnly = "IsInvitedVendorsOnly";
/** Set Invited Vendors Only.
* Only invited vendors can respond to an RfQ
*/
public void setIsInvitedVendorsOnly (boolean IsInvitedVendorsOnly);
/** Get Invited Vendors Only.
* Only invited vendors can respond to an RfQ
*/
public boolean isInvitedVendorsOnly();
/** Column name IsQuoteAllQty */
public static final String COLUMNNAME_IsQuoteAllQty = "IsQuoteAllQty";
/** Set Quote All Quantities.
* Suppliers are requested to provide responses for all quantities
*/
public void setIsQuoteAllQty (boolean IsQuoteAllQty);
/** Get Quote All Quantities.
* Suppliers are requested to provide responses for all quantities
*/
public boolean isQuoteAllQty();
/** Column name IsQuoteTotalAmt */
public static final String COLUMNNAME_IsQuoteTotalAmt = "IsQuoteTotalAmt";
/** Set Quote Total Amt.
* The response can have just the total amount for the RfQ
*/
public void setIsQuoteTotalAmt (boolean IsQuoteTotalAmt);
/** Get Quote Total Amt.
* The response can have just the total amount for the RfQ
*/
public boolean isQuoteTotalAmt();
/** Column name IsRfQResponseAccepted */
public static final String COLUMNNAME_IsRfQResponseAccepted = "IsRfQResponseAccepted";
/** Set Responses Accepted.
* Are Responses to the Request for Quotation accepted
*/
public void setIsRfQResponseAccepted (boolean IsRfQResponseAccepted);
/** Get Responses Accepted.
* Are Responses to the Request for Quotation accepted
*/
public boolean isRfQResponseAccepted();
/** Column name IsSelfService */
public static final String COLUMNNAME_IsSelfService = "IsSelfService";
/** Set Self-Service.
* This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService);
/** Get Self-Service.
* This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService();
/** Column name Margin */
public static final String COLUMNNAME_Margin = "Margin";
/** Set Margin %.
* Margin for a product as a percentage
*/
public void setMargin (BigDecimal Margin);
/** Get Margin %.
* Margin for a product as a percentage
*/
public BigDecimal getMargin();
/** Column name Name */
public static final String COLUMNNAME_Name = "Name";
/** Set Name.
* Alphanumeric identifier of the entity
*/
public void setName (String Name);
/** Get Name.
* Alphanumeric identifier of the entity
*/
public String getName();
/** Column name Processed */
public static final String COLUMNNAME_Processed = "Processed";
/** Set Processed.
* The document has been processed
*/
public void setProcessed (boolean Processed);
/** Get Processed.
* The document has been processed
*/
public boolean isProcessed();
/** Column name Processing */
public static final String COLUMNNAME_Processing = "Processing";
/** Set Process Now */
public void setProcessing (boolean Processing);
/** Get Process Now */
public boolean isProcessing();
/** Column name PublishRfQ */
public static final String COLUMNNAME_PublishRfQ = "PublishRfQ";
/** Set Publish RfQ */
public void setPublishRfQ (String PublishRfQ);
/** Get Publish RfQ */
public String getPublishRfQ();
/** Column name QuoteType */
public static final String COLUMNNAME_QuoteType = "QuoteType";
/** Set RfQ Type.
* Request for Quotation Type
*/
public void setQuoteType (String QuoteType);
/** Get RfQ Type.
* Request for Quotation Type
*/
public String getQuoteType();
/** Column name RankRfQ */
public static final String COLUMNNAME_RankRfQ = "RankRfQ";
/** Set Rank RfQ */
public void setRankRfQ (String RankRfQ);
/** Get Rank RfQ */
public String getRankRfQ();
/** Column name SalesRep_ID */
public static final String COLUMNNAME_SalesRep_ID = "SalesRep_ID";
/** Set Sales Representative.
* Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID);
/** Get Sales Representative.
* Sales Representative or Company Agent
*/
public int getSalesRep_ID();
public org.compiere.model.I_AD_User getSalesRep() throws RuntimeException;
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
}
| armenrz/adempiere | base/src/org/compiere/model/I_C_RfQ.java | Java | gpl-2.0 | 13,723 |
package edu.stanford.rsl.conrad.rendering;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import edu.stanford.rsl.conrad.geometry.AbstractCurve;
import edu.stanford.rsl.conrad.geometry.AbstractShape;
import edu.stanford.rsl.conrad.geometry.shapes.compound.CompoundShape;
import edu.stanford.rsl.conrad.geometry.shapes.compound.TriangleMesh;
import edu.stanford.rsl.conrad.geometry.shapes.simple.PointND;
import edu.stanford.rsl.conrad.geometry.shapes.simple.ProjectPointToLineComparator;
import edu.stanford.rsl.conrad.geometry.shapes.simple.StraightLine;
import edu.stanford.rsl.conrad.geometry.shapes.simple.Triangle;
import edu.stanford.rsl.conrad.numerics.SimpleOperators;
import edu.stanford.rsl.conrad.numerics.SimpleVector;
import edu.stanford.rsl.conrad.physics.PhysicalObject;
import edu.stanford.rsl.conrad.physics.PhysicalPoint;
import edu.stanford.rsl.conrad.utils.CONRAD;
/**
* Abstract Class to model a ray caster. The ray caster casts rays through the scene and determines all his along a ray.
* Then the ray caster determines the line segments between the objects and determines their representation.
*
* @author akmaier
*
*/
public abstract class AbstractRayTracer {
protected AbstractScene scene;
protected ProjectPointToLineComparator comparator =null;
/**
* Inconsistent data correction will slow down the projection process, but will help to correct for problems in the data like an uneven number of hits of an object.
*/
protected boolean inconsistentDataCorrection = true;
// Cache the information whether an object is a triangle or not
private HashMap<PhysicalObject, Boolean> objIsTriangleCache = new HashMap<>();
/**
* @return the scene
*/
public AbstractScene getScene() {
return scene;
}
/**
* @param scene the scene to set
*/
public void setScene(AbstractScene scene) {
this.scene = scene;
}
/**
* Method to cast a ray through the scene. Returns the edge segments which pass through different materials.
* <BR><BR>
* Rays must be normalized!
* <BR>
* @param ray
* @return the list of line segments which were hit by the ray in the correct order
*/
public ArrayList<PhysicalObject> castRay(AbstractCurve ray) {
ArrayList<PhysicalPoint> rayList = intersectWithScene(ray);
if (rayList == null || rayList.size() == 0) {
return null;
}
boolean doubles = false;
// Filter double hits
while (doubles){
boolean foundMore = false;
int size = rayList.size();
for (int i = 0; i < size; i++){
for (int j = i+1; j < size; j++){
if (rayList.get(i).equals(rayList.get(j))){
foundMore = true;
rayList.remove(j);
size--;
j--;
}
}
}
if (!foundMore) doubles = false;
}
if (rayList.size() > 0){
// sort the points along the ray direction in ascending or descending order
ProjectPointToLineComparator clone = comparator.clone();
clone.setProjectionLine((StraightLine) ray);
Collections.sort(rayList, clone);
// filter consecutive points entering or leaving the object
rayList = filterDoubles(rayList);
if (rayList.size() == 0) {
return null;
}
PhysicalPoint [] points = new PhysicalPoint[rayList.size()];
points = rayList.toArray(points);
if (inconsistentDataCorrection){
// Count hits per object
ArrayList<PhysicalObject> objects = new ArrayList<PhysicalObject>();
ArrayList<Integer> count = new ArrayList<Integer>();
for (int i = 0; i < points.length; i++){
PhysicalPoint p = points[i];
boolean found = false;
for (int j =0; j< objects.size(); j++){
if (objects.get(j).equals(p.getObject())){
found = true;
count.set(j, count.get(j) + 1);
}
}
if (!found){
objects.add(p.getObject());
count.add(new Integer(1));
}
}
boolean rewrite = false;
for (int i = 0; i < objects.size(); i++){
if (count.get(i) % 2 == 1){
boolean resolved = false;
// Iterate over hits to find all hits on object i
for (int j = 0; j < points.length; j++){
if (!resolved) {
if (points[j].getObject().equals(objects.get(i))){
// only one hit of this object. no problem
if (count.get(i) == 1){
points[j] = null;
rewrite = true;
resolved = true;
}
// three hits in a row of the same object. no problem.
if (j > 0 && j < points.length-1) {
// If we have three hits in a row on an object, remove the center hit (j)
if (points[j-1].getObject().equals(objects.get(i)) && (points[j+1].getObject().equals(objects.get(i)))){
points[j] = null;
rewrite = true;
resolved = true;
}
}
}
}
}
if (!resolved){
// Still not resolved
// remove center hit
int toRemove = (count.get(i) + 1) / 2;
int current = 0;
for (int j = 0; j < points.length; j++){
if (points[j].getObject().equals(objects.get(i))){
current ++;
if (current == toRemove){
points[j] = null;
rewrite = true;
resolved = true;
}
}
}
}
}
rayList = new ArrayList<PhysicalPoint>();
if (rewrite){
for (int j = 0; j < points.length; j++){
if (points[j] != null){
rayList.add(points[j]);
}
}
points = new PhysicalPoint[rayList.size()];
points = rayList.toArray(points);
}
}
}
if (points.length == 0) {
return null;
}
return computeMaterialIntersectionSegments(points);
} else {
return null;
}
}
/**
* Method to resolve the priority of the elements of the scene.
* @param rayList
* @return the correct line segments ordered according to the specified ray tracing order
*/
protected abstract ArrayList<PhysicalObject> computeMaterialIntersectionSegments(PhysicalPoint[] rayList);
/**
* Computes all intersection of the ray with the scene.
* @param ray the ray through the scene
* @return the intersection points.
*/
protected ArrayList<PhysicalPoint> intersectWithScene(AbstractCurve ray){
ArrayList<PhysicalPoint> rayList = new ArrayList<PhysicalPoint>();
SimpleVector smallIncrementAlongRay = SimpleOperators.subtract(ray.evaluate(CONRAD.SMALL_VALUE).getAbstractVector(), ray.evaluate(0).getAbstractVector());
// compute ray intersections:
for (PhysicalObject shape: scene) {
if (shape.getShape().getHitsOnBoundingBox(ray).size() > 0) {
ArrayList<PointND> intersection = shape.intersectWithHitOrientation(ray);
if (intersection != null && intersection.size() > 0){
for (PointND p : intersection){
PhysicalPoint point;
// Clean coordinates of intersecting points with triangles, as the last coordinate is abused to return the inclination of the triangle
if (objIsTriangle(shape)) {
point = cleanTriangleIntersection(p);
} else {
point = new PhysicalPoint(p);
}
point.setObject(shape);
rayList.add(point);
}
if(intersection.size() == 1) {
PointND p = intersection.get(0);
PhysicalPoint point;
// When creating an opposing point, use the negative inclination
if (objIsTriangle(shape)) {
PhysicalPoint clean = cleanTriangleIntersection(p);
p = new PointND(clean.getAbstractVector());
point = new PhysicalPoint(SimpleOperators.add(p.getAbstractVector(), smallIncrementAlongRay));
point.setHitOrientation(-clean.getHitOrientation());
} else {
point = new PhysicalPoint(SimpleOperators.add(p.getAbstractVector(), smallIncrementAlongRay));
}
point.setObject(shape);
rayList.add(point);
}
else if(intersection.size() == 3) {
PointND p = intersection.get(1);
PhysicalPoint point;
// Same as above
if (objIsTriangle(shape)) {
PhysicalPoint clean = cleanTriangleIntersection(p);
p = new PointND(clean.getAbstractVector());
point = new PhysicalPoint(SimpleOperators.add(p.getAbstractVector(), smallIncrementAlongRay));
point.setHitOrientation(-clean.getHitOrientation());
} else {
point = new PhysicalPoint(SimpleOperators.add(p.getAbstractVector(), smallIncrementAlongRay));
}
point.setObject(shape);
rayList.add(point);
}
}
}
}
return rayList;
}
/**
* When we hit a triangle, we store the inner product between the direction of the ray and the normal of the triangle to determine whether we just entered or left an object
* Remove the point's abused coordinate and store this information in the physical point object
* @param triangleHit point of intersection between ray and triangle. The point's last coordinate isn't a real coordinate
* @return physical point with clean coordinates, the hit orientation and the object
*/
private PhysicalPoint cleanTriangleIntersection(PointND triangleHit) {
double[] coordinates = triangleHit.getCoordinates();
double[] cleanCoordinates = Arrays.copyOf(coordinates, coordinates.length - 1);
PhysicalPoint point = new PhysicalPoint(new PointND(cleanCoordinates));
point.setHitOrientation(coordinates[coordinates.length - 1]);
return point;
}
/**
* Determines whether the given object is a triangle or is composed out of (and only out of) triangles
* The result is stored in a cache-like hash map such that the result can be quickly retrieved from the map
* @param obj to check
* @return true if the given object is a triangle, a triangle mesh or a compound shape which does not hold other objects than triangles
*/
private boolean objIsTriangle(PhysicalObject obj) {
// First, try to retrieve the cached information
if (objIsTriangleCache.containsKey(obj)) {
return objIsTriangleCache.get(obj);
}
AbstractShape shape = obj.getShape();
if (shape instanceof Triangle || shape instanceof TriangleMesh) {
objIsTriangleCache.put(obj, true);
return true;
}
// do breadth first search on nested compound shapes
else if (shape instanceof CompoundShape) {
LinkedList<AbstractShape> queue = new LinkedList<>();
queue.add(shape);
while(queue.size() > 0) {
CompoundShape cs = (CompoundShape) queue.poll();
for (int i=0; i<cs.getInternalDimension(); i++) {
shape = cs.get(i);
if (shape instanceof Triangle || shape instanceof TriangleMesh) {
continue;
} else if (shape instanceof CompoundShape) {
queue.add(shape);
} else {
objIsTriangleCache.put(obj, false);
return false;
}
}
}
// if all the nested compound shapes do not hold more than triangles in the end, we're certainly dealing with a triangle
objIsTriangleCache.put(obj, true);
return true;
}
// otherwise it is another shape and thus not a triangle
objIsTriangleCache.put(obj, false);
return false;
}
/**
* A ray is supposed to enter and leave a closed object composed out of triangles in an alternating order. If the ray e.g. enters the object twice, it's likely that the two intersections considered as entry are very close.
* An intersecting point is considered an entry if the dot product of the ray's direction and the hit triangle's normal vector is smaller than 0
* @param rayList list of points where the ray intersects with an object
* @return filtered list of points
*/
protected ArrayList<PhysicalPoint> filterDoubles(ArrayList<PhysicalPoint> rayList) {
ArrayList<PhysicalPoint> filtered = new ArrayList<>();
Map<PhysicalObject, Boolean> nextEntersObject = new HashMap<>(); // object-specific switch whether the next intersection with a particular object enters or leaves the object
// First intersection enters the object
boolean normalsPointOutside = false; // yet to determine (but compiler forces to initialize this variable here)
boolean init = false; // true if normalsPointOutside was truly initialized
for (int i=0; i<rayList.size(); i++) {
PhysicalPoint p = rayList.get(i);
// Only for triangles
if (!objIsTriangle(p.getObject())) {
filtered.add(p);
continue;
}
if (!init) {
// Usually, the normal is defined to point out of the 3-D polygon.
// However, some applications seem to export their polygons with normals pointing in the opposite way.
// To be sure, we go by the direction of the first intersection.
normalsPointOutside = (p.getHitOrientation() < 0);
init = true;
}
// If this is the first intersection (by this ray) with the p's polygon, then add the polygon to the map
if (!nextEntersObject.containsKey(p.getObject())) {
nextEntersObject.put(p.getObject(), normalsPointOutside);
}
if (nextEntersObject.get(p.getObject()) && p.getHitOrientation() < 0) {
// Ray enters the object
filtered.add(p);
nextEntersObject.put(p.getObject(), false); // toggle
}
else if (!nextEntersObject.get(p.getObject()) && p.getHitOrientation() > 0) {
// Ray leaves the object
filtered.add(p);
nextEntersObject.put(p.getObject(), true); // toggle
}
else if (p.getHitOrientation() == 0) {
// Ray is parallel to the triangle's surface
// Or the hit orientation attribute was not set by the intersection test
filtered.add(p);
}
// if we come to here, the point is discarded
}
return filtered;
}
}
/*
* Copyright (C) 2010-2014 Andreas Maier
* CONRAD is developed as an Open Source project under the GNU General Public License (GPL).
*/ | YixingHuang/CONRAD-1 | src/edu/stanford/rsl/conrad/rendering/AbstractRayTracer.java | Java | gpl-3.0 | 14,122 |
package pct.droid.base.beaming;
import com.connectsdk.device.ConnectableDevice;
import com.connectsdk.device.ConnectableDeviceListener;
import com.connectsdk.service.DeviceService;
import com.connectsdk.service.command.ServiceCommandError;
import java.util.List;
public class BeamDeviceListener implements ConnectableDeviceListener {
@Override
public void onDeviceReady(ConnectableDevice device) {
}
@Override
public void onDeviceDisconnected(ConnectableDevice device) {
}
@Override
public void onPairingRequired(ConnectableDevice device, DeviceService service, DeviceService.PairingType pairingType) {
}
@Override
public void onCapabilityUpdated(ConnectableDevice device, List<String> added, List<String> removed) {
}
@Override
public void onConnectionFailed(ConnectableDevice device, ServiceCommandError error) {
}
} | moria/popcorn-android | base/src/main/java/pct/droid/base/beaming/BeamDeviceListener.java | Java | gpl-3.0 | 892 |
/*
* Licensed to ElasticSearch and Shay Banon 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.discovery;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
*
*/
public class DiscoveryService extends AbstractLifecycleComponent<DiscoveryService> {
private final TimeValue initialStateTimeout;
private final Discovery discovery;
private volatile boolean initialStateReceived;
@Inject
public DiscoveryService(Settings settings, Discovery discovery) {
super(settings);
this.discovery = discovery;
this.initialStateTimeout = componentSettings.getAsTime("initial_state_timeout", TimeValue.timeValueSeconds(30));
}
@Override
protected void doStart() throws ElasticSearchException {
final CountDownLatch latch = new CountDownLatch(1);
InitialStateDiscoveryListener listener = new InitialStateDiscoveryListener() {
@Override
public void initialStateProcessed() {
latch.countDown();
}
};
discovery.addListener(listener);
try {
discovery.start();
try {
logger.trace("waiting for {} for the initial state to be set by the discovery", initialStateTimeout);
if (latch.await(initialStateTimeout.millis(), TimeUnit.MILLISECONDS)) {
logger.trace("initial state set from discovery");
initialStateReceived = true;
} else {
initialStateReceived = false;
logger.warn("waited for {} and no initial state was set by the discovery", initialStateTimeout);
}
} catch (InterruptedException e) {
// ignore
}
} finally {
discovery.removeListener(listener);
}
logger.info(discovery.nodeDescription());
}
@Override
protected void doStop() throws ElasticSearchException {
discovery.stop();
}
@Override
protected void doClose() throws ElasticSearchException {
discovery.close();
}
public DiscoveryNode localNode() {
return discovery.localNode();
}
/**
* Returns <tt>true</tt> if the initial state was received within the timeout waiting for it
* on {@link #doStart()}.
*/
public boolean initialStateReceived() {
return initialStateReceived;
}
public String nodeDescription() {
return discovery.nodeDescription();
}
/**
* Publish all the changes to the cluster from the master (can be called just by the master). The publish
* process should not publish this state to the master as well! (the master is sending it...).
*/
public void publish(ClusterState clusterState) {
if (!lifecycle.started()) {
return;
}
discovery.publish(clusterState);
}
}
| Kreolwolf1/Elastic | src/main/java/org/elasticsearch/discovery/DiscoveryService.java | Java | apache-2.0 | 4,032 |
/*
* 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.hyracks.dataflow.std.sort;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.exceptions.HyracksDataException;
public interface ISorter {
boolean hasRemaining();
void reset() throws HyracksDataException;
void sort() throws HyracksDataException;
void close() throws HyracksDataException;
int flush(IFrameWriter writer) throws HyracksDataException;
}
| apache/incubator-asterixdb-hyracks | hyracks/hyracks-dataflow-std/src/main/java/org/apache/hyracks/dataflow/std/sort/ISorter.java | Java | apache-2.0 | 1,233 |
/*
* 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 java.nio.ByteBuffer;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.MutableEntry;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectTransient;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.plugin.extensions.communication.Message;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
import org.jetbrains.annotations.Nullable;
/**
*
*/
public class CacheInvokeDirectResult implements Message {
/** */
private static final long serialVersionUID = 0L;
/** */
private KeyCacheObject key;
/** */
@GridToStringInclude
private CacheObject res;
/** */
@GridToStringInclude(sensitive = true)
@GridDirectTransient
private Exception err;
/** */
private byte[] errBytes;
/**
* Required for {@link Message}.
*/
public CacheInvokeDirectResult() {
// No-op.
}
/**
* @param key Key.
* @param res Result.
*/
public CacheInvokeDirectResult(KeyCacheObject key, CacheObject res) {
this.key = key;
this.res = res;
}
/**
* @param key Key.
* @param err Exception thrown by {@link EntryProcessor#process(MutableEntry, Object...)}.
*/
public CacheInvokeDirectResult(KeyCacheObject key, Exception err) {
this.key = key;
this.err = err;
}
/**
* @return Key.
*/
public KeyCacheObject key() {
return key;
}
/**
* @return Result.
*/
public CacheObject result() {
return res;
}
/**
* @return Error.
*/
@Nullable public Exception error() {
return err;
}
/**
* @param ctx Cache context.
* @throws IgniteCheckedException If failed.
*/
public void prepareMarshal(GridCacheContext ctx) throws IgniteCheckedException {
key.prepareMarshal(ctx.cacheObjectContext());
if (err != null && errBytes == null)
errBytes = U.marshal(ctx.marshaller(), err);
if (res != null)
res.prepareMarshal(ctx.cacheObjectContext());
}
/**
* @param ctx Cache context.
* @param ldr Class loader.
* @throws IgniteCheckedException If failed.
*/
public void finishUnmarshal(GridCacheContext ctx, ClassLoader ldr) throws IgniteCheckedException {
key.finishUnmarshal(ctx.cacheObjectContext(), ldr);
if (errBytes != null && err == null)
err = U.unmarshal(ctx.marshaller(), errBytes, U.resolveClassLoader(ldr, ctx.gridConfig()));
if (res != null)
res.finishUnmarshal(ctx.cacheObjectContext(), ldr);
}
/** {@inheritDoc} */
@Override public void onAckReceived() {
// No-op.
}
/** {@inheritDoc} */
@Override public short directType() {
return 93;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 0:
if (!writer.writeByteArray("errBytes", errBytes))
return false;
writer.incrementState();
case 1:
if (!writer.writeMessage("key", key))
return false;
writer.incrementState();
case 2:
if (!writer.writeMessage("res", res))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
switch (reader.state()) {
case 0:
errBytes = reader.readByteArray("errBytes");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 1:
key = reader.readMessage("key");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 2:
res = reader.readMessage("res");
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(CacheInvokeDirectResult.class);
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 3;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheInvokeDirectResult.class, this);
}
} | mcherkasov/ignite | modules/core/src/main/java/org/apache/ignite/internal/processors/cache/CacheInvokeDirectResult.java | Java | apache-2.0 | 5,937 |
/*
* Copyright (c) 2005-2014, 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 org.wso2.carbon.identity.provisioning.listener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener;
import org.wso2.carbon.identity.provisioning.cache.ServiceProviderProvisioningConnectorCache;
import org.wso2.carbon.identity.provisioning.cache.ServiceProviderProvisioningConnectorCacheEntry;
import org.wso2.carbon.identity.provisioning.cache.ServiceProviderProvisioningConnectorCacheKey;
import org.wso2.carbon.identity.provisioning.cache.ServiceProviderProvisioningConnectorCacheKey;
import org.wso2.carbon.identity.provisioning.cache.ServiceProviderProvisioningConnectorCache;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
public class ApplicationMgtProvisioningListener implements ApplicationMgtListener {
private static Log log = LogFactory.getLog(ApplicationMgtProvisioningListener.class);
@Override
public void createApplication(ServiceProvider serviceProvider) {
// TODO Auto-generated method stub
}
@Override
public void updateApplication(ServiceProvider serviceProvider) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
log.debug("Clearing cache entry for " + serviceProvider.getApplicationName());
destroySpProvConnectors(serviceProvider.getApplicationName(), tenantDomain);
}
@Override
public void deleteApplication(String applicationName) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
log.debug("Clearing cache entry for " + applicationName);
destroySpProvConnectors(applicationName, tenantDomain);
}
private void destroySpProvConnectors(String applicationName, String tenantDomain) {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext
.getThreadLocalCarbonContext();
carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
// reading from the cache
ServiceProviderProvisioningConnectorCacheKey key =
new ServiceProviderProvisioningConnectorCacheKey(applicationName, tenantDomain);
ServiceProviderProvisioningConnectorCacheEntry entry = (ServiceProviderProvisioningConnectorCacheEntry) ServiceProviderProvisioningConnectorCache
.getInstance().getValueFromCache(key);
// cache hit
if (entry != null) {
ServiceProviderProvisioningConnectorCache.getInstance().clearCacheEntry(key);
if (log.isDebugEnabled()) {
log.debug("Provisioning cached entry removed for sp " + applicationName);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Provisioning cached entry not found for sp " + applicationName);
}
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
| maheshika/carbon-identity | components/identity/org.wso2.carbon.identity.provisioning/src/main/java/org/wso2/carbon/identity/provisioning/listener/ApplicationMgtProvisioningListener.java | Java | apache-2.0 | 3,864 |
package org.jolokia.history;
/*
* Copyright 2009-2013 Roland Huss
*
* 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.
*/
import java.io.Serializable;
/**
* Helper class used for specifying history entry limits
*
* @author roland
* @since 05.03.12
*/
public class HistoryLimit implements Serializable {
private static final long serialVersionUID = 42L;
// maximum number of entries
private int maxEntries;
// maximum duration to keep
private long maxDuration;
/**
* Create a limit with either or both maxEntries and maxDuration set
*
* @param pMaxEntries maximum number of entries to keep
* @param pMaxDuration maximum duration for entries to keep (in seconds)
*/
public HistoryLimit(int pMaxEntries, long pMaxDuration) {
if (pMaxEntries == 0 && pMaxDuration == 0) {
throw new IllegalArgumentException("Invalid limit, either maxEntries or maxDuration must be != 0");
}
if (pMaxEntries < 0) {
throw new IllegalArgumentException("Invalid limit, maxEntries must be >= 0");
}
if (pMaxDuration < 0) {
throw new IllegalArgumentException("Invalid limit, maxDuration must be >= 0");
}
maxEntries = pMaxEntries;
maxDuration = pMaxDuration;
}
public int getMaxEntries() {
return maxEntries;
}
public long getMaxDuration() {
return maxDuration;
}
// Return a limit which has for sure as upper limit the given argument
/**
* Return a limit whose max entries are smaller or equals the given upper limit. For effieciency reasons, this object's
* state might change with this method (i.e. the maxEntry number might be set or decreased)
*
* @param pGlobalMaxEntries upper limit
* @return this if this limit already is below the upper limit or a new limit which lies in this limit
*/
public HistoryLimit respectGlobalMaxEntries(int pGlobalMaxEntries) {
if (maxEntries > pGlobalMaxEntries || maxEntries == 0) {
maxEntries = pGlobalMaxEntries;
}
return this;
}
@Override
public String toString() {
return "HistoryLimit{" +
"maxEntries=" + maxEntries +
", maxDuration=" + maxDuration +
'}';
}
}
| cinhtau/jolokia | agent/core/src/main/java/org/jolokia/history/HistoryLimit.java | Java | apache-2.0 | 2,837 |
/*
* Copyright 2015 Open Networking Laboratory
*
* 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.ui.table.cell;
import org.junit.Test;
import org.onosproject.ui.table.CellComparator;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link AbstractCellComparator}.
*/
public class AbstractCellComparatorTest {
private static class Concrete extends AbstractCellComparator {
@Override
protected int nonNullCompare(Object o1, Object o2) {
return 42;
}
}
private CellComparator cmp = new Concrete();
@Test
public void twoNullArgs() {
assertTrue("two nulls", cmp.compare(null, null) == 0);
}
@Test
public void nullArgOne() {
assertTrue("null one", cmp.compare(null, 1) < 0);
}
@Test
public void nullArgTwo() {
assertTrue("null two", cmp.compare(1, null) > 0);
}
// mock output, but check that our method was invoked...
@Test
public void noNulls() {
assertTrue("no Nulls", cmp.compare(1, 2) == 42);
}
}
| packet-tracker/onos | core/api/src/test/java/org/onosproject/ui/table/cell/AbstractCellComparatorTest.java | Java | apache-2.0 | 1,592 |
/*
* 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.xpack.ccr;
import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksRequest;
import org.elasticsearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.core.CheckedConsumer;
import org.elasticsearch.core.CheckedRunnable;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.persistent.PersistentTasksCustomMetadata;
import org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException;
import org.elasticsearch.tasks.TaskInfo;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.CcrIntegTestCase;
import org.elasticsearch.xpack.core.ccr.action.PutFollowAction;
import org.elasticsearch.xpack.core.ccr.action.ShardFollowTask;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
public class CcrAliasesIT extends CcrIntegTestCase {
public void testAliasOnIndexCreation() throws Exception {
final String aliasName = randomAlphaOfLength(16);
final String aliases;
try (XContentBuilder builder = jsonBuilder()) {
builder.startObject();
{
builder.startObject("aliases");
{
builder.startObject(aliasName);
{
}
builder.endObject();
}
builder.endObject();
}
builder.endObject();
aliases = BytesReference.bytes(builder).utf8ToString();
}
assertAcked(leaderClient().admin().indices().prepareCreate("leader").setSource(aliases, XContentType.JSON));
final PutFollowAction.Request followRequest = putFollow("leader", "follower");
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, "follower");
// wait for the shard follow task to exist
assertBusy(() -> assertShardFollowTask(1));
assertAliasesExist("leader", "follower", aliasName);
}
public void testAddAlias() throws Exception {
runAddAliasTest(null);
}
public void testAddExplicitNotWriteAlias() throws Exception {
runAddAliasTest(false);
}
public void testWriteAliasIsIgnored() throws Exception {
runAddAliasTest(true);
}
private void runAddAliasTest(final Boolean isWriteAlias) throws Exception {
runAddAliasTest(isWriteAlias, aliasName -> {});
}
/**
* Runs an add alias test which adds a random alias to the leader exist, and then asserts that the alias is replicated to the follower.
* The specified post assertions gives the caller the opportunity to add additional assertions on the alias that is added. These
* assertions are executed after all other assertions that the alias exists.
*
* @param isWriteIndex whether or not the leader index is the write index for the alias
* @param postAssertions the post assertions to execute
* @param <E> the type of checked exception the post assertions callback can throw
* @throws Exception if a checked exception is thrown while executing the add alias test
*/
private <E extends Exception> void runAddAliasTest(final Boolean isWriteIndex, final CheckedConsumer<String, E> postAssertions)
throws Exception {
assertAcked(leaderClient().admin().indices().prepareCreate("leader"));
final PutFollowAction.Request followRequest = putFollow("leader", "follower");
// we set a low poll timeout so that shard changes requests are responded to quickly even without indexing
followRequest.getParameters().setReadPollTimeout(TimeValue.timeValueMillis(100));
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, "follower");
assertBusy(() -> assertShardFollowTask(1));
final String aliasName = randomAlphaOfLength(16);
addRandomAlias("leader", aliasName, isWriteIndex);
assertAliasesExist("leader", "follower", aliasName);
postAssertions.accept(aliasName);
}
private void addRandomAlias(final String index, final String aliasName, final Boolean isWriteIndex) {
final IndicesAliasesRequest.AliasActions add = IndicesAliasesRequest.AliasActions.add();
add.index(index);
add.alias(aliasName);
add.writeIndex(isWriteIndex);
if (randomBoolean()) {
add.routing(randomAlphaOfLength(16));
} else {
if (randomBoolean()) {
add.indexRouting(randomAlphaOfLength(16));
}
if (randomBoolean()) {
add.searchRouting(randomAlphaOfLength(16));
}
}
if (randomBoolean()) {
add.filter(termQuery(randomAlphaOfLength(16), randomAlphaOfLength(16)));
}
assertAcked(leaderClient().admin().indices().prepareAliases().addAliasAction(add));
}
public void testAddMultipleAliasesAtOnce() throws Exception {
assertAcked(leaderClient().admin().indices().prepareCreate("leader"));
final PutFollowAction.Request followRequest = putFollow("leader", "follower");
// we set a low poll timeout so that shard changes requests are responded to quickly even without indexing
followRequest.getParameters().setReadPollTimeout(TimeValue.timeValueMillis(100));
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, "follower");
assertBusy(() -> assertShardFollowTask(1));
final int numberOfAliases = randomIntBetween(2, 8);
final IndicesAliasesRequestBuilder builder = leaderClient().admin().indices().prepareAliases();
for (int i = 0; i < numberOfAliases; i++) {
builder.addAlias("leader", "alias_" + i);
}
assertAcked(builder);
final String[] aliases = new String[numberOfAliases];
for (int i = 0; i < numberOfAliases; i++) {
aliases[i] = "alias_" + i;
}
assertAliasesExist("leader", "follower", aliases);
}
public void testAddMultipleAliasesSequentially() throws Exception {
assertAcked(leaderClient().admin().indices().prepareCreate("leader"));
final PutFollowAction.Request followRequest = putFollow("leader", "follower");
// we set a low poll timeout so that shard changes requests are responded to quickly even without indexing
followRequest.getParameters().setReadPollTimeout(TimeValue.timeValueMillis(100));
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
ensureFollowerGreen(true, "follower");
assertBusy(() -> assertShardFollowTask(1));
final int numberOfAliases = randomIntBetween(2, 8);
for (int i = 0; i < numberOfAliases; i++) {
assertAcked(leaderClient().admin().indices().prepareAliases().addAlias("leader", "alias_" + i));
final String[] aliases = new String[i + 1];
for (int j = 0; j < i + 1; j++) {
aliases[j] = "alias_" + j;
}
assertAliasesExist("leader", "follower", aliases);
}
}
public void testUpdateExistingAlias() throws Exception {
runAddAliasTest(
null,
/*
* After the alias is added (via runAddAliasTest) we modify the alias in place, and then assert that the modification is
* eventually replicated.
*/
aliasName -> {
assertAcked(
leaderClient().admin()
.indices()
.prepareAliases()
.addAlias("leader", aliasName, termQuery(randomAlphaOfLength(16), randomAlphaOfLength(16)))
);
assertAliasesExist("leader", "follower", aliasName);
}
);
}
public void testRemoveExistingAlias() throws Exception {
runAddAliasTest(false, aliasName -> {
removeAlias(aliasName);
assertAliasExistence(aliasName, false);
});
}
private void removeAlias(final String aliasName) {
assertAcked(leaderClient().admin().indices().prepareAliases().removeAlias("leader", aliasName));
}
public void testStress() throws Exception {
assertAcked(leaderClient().admin().indices().prepareCreate("leader"));
final PutFollowAction.Request followRequest = putFollow("leader", "follower");
// we set a low poll timeout so that shard changes requests are responded to quickly even without indexing
followRequest.getParameters().setReadPollTimeout(TimeValue.timeValueMillis(100));
followerClient().execute(PutFollowAction.INSTANCE, followRequest).get();
final int numberOfThreads = randomIntBetween(2, 4);
final int numberOfIterations = randomIntBetween(4, 32);
final CyclicBarrier barrier = new CyclicBarrier(numberOfThreads + 1);
final List<Thread> threads = new ArrayList<>(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
final Thread thread = new Thread(() -> {
try {
barrier.await();
} catch (final BrokenBarrierException | InterruptedException e) {
throw new RuntimeException(e);
}
for (int j = 0; j < numberOfIterations; j++) {
final String action = randomFrom("create", "update", "delete");
switch (action) {
case "create":
addRandomAlias("leader", randomAlphaOfLength(16), randomFrom(new Boolean[] { null, false, true }));
break;
case "update":
try {
final String[] aliases = getAliasesOnLeader();
if (aliases.length == 0) {
continue;
}
final String alias = randomFrom(aliases);
/*
* Add an alias with the same name, which acts as an update (although another thread could concurrently
* remove).
*/
addRandomAlias("leader", alias, randomFrom(new Boolean[] { null, false, true }));
} catch (final Exception e) {
throw new RuntimeException(e);
}
break;
case "delete":
try {
final String[] aliases = getAliasesOnLeader();
if (aliases.length == 0) {
continue;
}
final String alias = randomFrom(aliases);
try {
removeAlias(alias);
} catch (final AliasesNotFoundException e) {
// ignore, it could have been deleted by another thread
continue;
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
break;
default:
assert false : action;
}
}
try {
barrier.await();
} catch (final BrokenBarrierException | InterruptedException e) {
throw new RuntimeException(e);
}
});
thread.start();
threads.add(thread);
}
barrier.await();
barrier.await();
for (final Thread thread : threads) {
thread.join();
}
assertAliasesExist("leader", "follower", getAliasesOnLeader());
}
private String[] getAliasesOnLeader() throws InterruptedException, ExecutionException {
final GetAliasesResponse response = leaderClient().admin().indices().getAliases(new GetAliasesRequest().indices("leader")).get();
return response.getAliases().get("leader").stream().map(AliasMetadata::alias).toArray(String[]::new);
}
private void assertAliasesExist(final String leaderIndex, final String followerIndex, final String... aliases) throws Exception {
assertAliasesExist(leaderIndex, followerIndex, (alias, aliasMetadata) -> {}, aliases);
}
private <E extends Exception> void assertAliasesExist(
final String leaderIndex,
final String followerIndex,
final CheckedBiConsumer<String, AliasMetadata, E> aliasMetadataAssertion,
final String... aliases
) throws Exception {
// we must check serially because aliases exist will return true if any but not necessarily all of the requested aliases exist
for (final String alias : aliases) {
assertAliasExistence(alias, true);
}
assertBusy(() -> {
final GetAliasesResponse followerResponse = followerClient().admin()
.indices()
.getAliases(new GetAliasesRequest().indices(followerIndex))
.get();
assertThat(
"expected follower to have [" + aliases.length + "] aliases, but was " + followerResponse.getAliases().toString(),
followerResponse.getAliases().get(followerIndex),
hasSize(aliases.length)
);
for (final String alias : aliases) {
final AliasMetadata followerAliasMetadata = getAliasMetadata(followerResponse, followerIndex, alias);
final GetAliasesResponse leaderResponse = leaderClient().admin()
.indices()
.getAliases(new GetAliasesRequest().indices(leaderIndex).aliases(alias))
.get();
final AliasMetadata leaderAliasMetadata = getAliasMetadata(leaderResponse, leaderIndex, alias);
assertThat(
"alias [" + alias + "] index routing did not replicate, but was " + followerAliasMetadata.toString(),
followerAliasMetadata.indexRouting(),
equalTo(leaderAliasMetadata.indexRouting())
);
assertThat(
"alias [" + alias + "] search routing did not replicate, but was " + followerAliasMetadata.toString(),
followerAliasMetadata.searchRoutingValues(),
equalTo(leaderAliasMetadata.searchRoutingValues())
);
assertThat(
"alias [" + alias + "] filtering did not replicate, but was " + followerAliasMetadata.toString(),
followerAliasMetadata.filter(),
equalTo(leaderAliasMetadata.filter())
);
assertThat(
"alias [" + alias + "] should not be a write index, but was " + followerAliasMetadata.toString(),
followerAliasMetadata.writeIndex(),
equalTo(false)
);
aliasMetadataAssertion.accept(alias, followerAliasMetadata);
}
});
}
private void assertAliasExistence(final String alias, final boolean exists) throws Exception {
assertBusy(() -> {
// we must check serially because aliases exist will return true if any but not necessarily all of the requested aliases exist
final GetAliasesResponse response = followerClient().admin()
.indices()
.getAliases(new GetAliasesRequest().indices("follower").aliases(alias))
.get();
if (exists) {
assertFalse("alias [" + alias + "] did not exist", response.getAliases().isEmpty());
} else {
assertTrue("alias [" + alias + "] exists", response.getAliases().isEmpty());
}
});
}
private AliasMetadata getAliasMetadata(final GetAliasesResponse response, final String index, final String alias) {
final Optional<AliasMetadata> maybeAliasMetadata = response.getAliases()
.get(index)
.stream()
.filter(a -> a.getAlias().equals(alias))
.findFirst();
assertTrue("alias [" + alias + "] did not exist", maybeAliasMetadata.isPresent());
return maybeAliasMetadata.get();
}
private CheckedRunnable<Exception> assertShardFollowTask(final int numberOfPrimaryShards) {
return () -> {
final ClusterState clusterState = followerClient().admin().cluster().prepareState().get().getState();
final PersistentTasksCustomMetadata taskMetadata = clusterState.getMetadata().custom(PersistentTasksCustomMetadata.TYPE);
assertNotNull("task metadata for follower should exist", taskMetadata);
final ListTasksRequest listTasksRequest = new ListTasksRequest();
listTasksRequest.setDetailed(true);
listTasksRequest.setActions(ShardFollowTask.NAME + "[c]");
final ListTasksResponse listTasksResponse = followerClient().admin().cluster().listTasks(listTasksRequest).actionGet();
assertThat("expected no node failures", listTasksResponse.getNodeFailures().size(), equalTo(0));
assertThat("expected no task failures", listTasksResponse.getTaskFailures().size(), equalTo(0));
final List<TaskInfo> taskInfos = listTasksResponse.getTasks();
assertThat("expected a task for each shard", taskInfos.size(), equalTo(numberOfPrimaryShards));
final Collection<PersistentTasksCustomMetadata.PersistentTask<?>> shardFollowTasks = taskMetadata.findTasks(
ShardFollowTask.NAME,
Objects::nonNull
);
for (final PersistentTasksCustomMetadata.PersistentTask<?> shardFollowTask : shardFollowTasks) {
TaskInfo taskInfo = null;
final String expectedId = "id=" + shardFollowTask.getId();
for (final TaskInfo info : taskInfos) {
if (expectedId.equals(info.getDescription())) {
taskInfo = info;
break;
}
}
assertNotNull("task info for shard follow task [" + expectedId + "] should exist", taskInfo);
}
};
}
}
| jmluy/elasticsearch | x-pack/plugin/ccr/src/internalClusterTest/java/org/elasticsearch/xpack/ccr/CcrAliasesIT.java | Java | apache-2.0 | 20,136 |
/*
* Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp.parsing;
import com.google.common.base.Preconditions;
import com.google.javascript.rhino.head.ScriptRuntime;
/**
* This class implements the scanner for JsDoc strings.
*
* It is heavily based on Rhino's TokenStream.
*
*/
class JsDocTokenStream {
/*
* For chars - because we need something out-of-range
* to check. (And checking EOF by exception is annoying.)
* Note distinction from EOF token type!
*/
private final static int
EOF_CHAR = -1;
JsDocTokenStream(String sourceString) {
this(sourceString, 0);
}
JsDocTokenStream(String sourceString, int lineno) {
this(sourceString, lineno, 0);
}
JsDocTokenStream(String sourceString, int lineno, int initCharno) {
Preconditions.checkNotNull(sourceString);
this.lineno = lineno;
this.sourceString = sourceString;
this.sourceEnd = sourceString.length();
this.sourceCursor = this.cursor = 0;
this.initLineno = lineno;
this.initCharno = initCharno;
}
/**
* Tokenizes JSDoc comments.
*/
@SuppressWarnings("fallthrough")
final JsDocToken getJsDocToken() {
int c;
stringBufferTop = 0;
for (;;) {
// eat white spaces
for (;;) {
charno = -1;
c = getChar();
if (c == EOF_CHAR) {
return JsDocToken.EOF;
} else if (c == '\n') {
return JsDocToken.EOL;
} else if (!isJSSpace(c)) {
break;
}
}
switch (c) {
// annotation, e.g. @type or @constructor
case '@':
do {
c = getChar();
if (isAlpha(c)) {
addToString(c);
} else {
ungetChar(c);
this.string = getStringFromBuffer();
stringBufferTop = 0;
return JsDocToken.ANNOTATION;
}
} while (true);
case '*':
if (matchChar('/')) {
return JsDocToken.EOC;
} else {
return JsDocToken.STAR;
}
case ',':
return JsDocToken.COMMA;
case '>':
return JsDocToken.GT;
case '(':
return JsDocToken.LP;
case ')':
return JsDocToken.RP;
case '{':
return JsDocToken.LC;
case '}':
return JsDocToken.RC;
case '[':
return JsDocToken.LB;
case ']':
return JsDocToken.RB;
case '?':
return JsDocToken.QMARK;
case '!':
return JsDocToken.BANG;
case ':':
return JsDocToken.COLON;
case '=':
return JsDocToken.EQUALS;
case '|':
matchChar('|');
return JsDocToken.PIPE;
case '.':
c = getChar();
if (c == '<') {
return JsDocToken.LT;
} else {
if (c == '.') {
c = getChar();
if (c == '.') {
return JsDocToken.ELLIPSIS;
} else {
addToString('.');
}
}
// we may backtrack across line boundary
ungetBuffer[ungetCursor++] = c;
c = '.';
}
// fall through
default: {
// recognize a JsDoc string but discard last . if it is followed by
// a non-JsDoc comment char, e.g. Array.<
int c1 = c;
addToString(c);
int c2 = getChar();
if (!isJSDocString(c2)) {
ungetChar(c2);
this.string = getStringFromBuffer();
stringBufferTop = 0;
return JsDocToken.STRING;
} else {
do {
c1 = c2;
c2 = getChar();
if (c1 == '.' && c2 == '<') {
ungetChar(c2);
ungetChar(c1);
this.string = getStringFromBuffer();
stringBufferTop = 0;
return JsDocToken.STRING;
} else {
if (isJSDocString(c2)) {
addToString(c1);
} else {
ungetChar(c2);
addToString(c1);
this.string = getStringFromBuffer();
stringBufferTop = 0;
return JsDocToken.STRING;
}
}
} while (true);
}
}
}
}
}
/**
* Gets the remaining JSDoc line without the {@link JsDocToken#EOL},
* {@link JsDocToken#EOF} or {@link JsDocToken#EOC}.
*/
@SuppressWarnings("fallthrough")
String getRemainingJSDocLine() {
int c;
for (;;) {
c = getChar();
switch (c) {
case '*':
if (peekChar() != '/') {
addToString(c);
break;
}
// fall through
case EOF_CHAR:
case '\n':
ungetChar(c);
this.string = getStringFromBuffer();
stringBufferTop = 0;
return this.string;
default:
addToString(c);
break;
}
}
}
final int getLineno() { return lineno; }
final int getCharno() {
return lineno == initLineno? initCharno + charno : charno;
}
final String getString() { return string; }
final boolean eof() { return hitEOF; }
private String getStringFromBuffer() {
tokenEnd = cursor;
return new String(stringBuffer, 0, stringBufferTop);
}
private void addToString(int c) {
int N = stringBufferTop;
if (N == stringBuffer.length) {
char[] tmp = new char[stringBuffer.length * 2];
System.arraycopy(stringBuffer, 0, tmp, 0, N);
stringBuffer = tmp;
}
stringBuffer[N] = (char)c;
stringBufferTop = N + 1;
}
void ungetChar(int c) {
// can not unread past across line boundary
assert(!(ungetCursor != 0 && ungetBuffer[ungetCursor - 1] == '\n'));
ungetBuffer[ungetCursor++] = c;
cursor--;
}
private boolean matchChar(int test) {
int c = getCharIgnoreLineEnd();
if (c == test) {
tokenEnd = cursor;
return true;
} else {
ungetCharIgnoreLineEnd(c);
return false;
}
}
private static boolean isAlpha(int c) {
// Use 'Z' < 'a'
if (c <= 'Z') {
return 'A' <= c;
} else {
return 'a' <= c && c <= 'z';
}
}
private boolean isJSDocString(int c) {
switch (c) {
case '@':
case '*':
case ',':
case '>':
case ':':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '?':
case '!':
case '|':
case '=':
case EOF_CHAR:
case '\n':
return false;
default:
return !isJSSpace(c);
}
}
/* As defined in ECMA. jsscan.c uses C isspace() (which allows
* \v, I think.) note that code in getChar() implicitly accepts
* '\r' == \u000D as well.
*/
static boolean isJSSpace(int c) {
if (c <= 127) {
return c == 0x20 || c == 0x9 || c == 0xC || c == 0xB;
} else {
return c == 0xA0
|| Character.getType((char)c) == Character.SPACE_SEPARATOR;
}
}
private static boolean isJSFormatChar(int c) {
return c > 127 && Character.getType((char)c) == Character.FORMAT;
}
/**
* Allows the JSDocParser to update the character offset
* so that getCharno() returns a valid character position.
*/
void update() {
charno = getOffset();
}
private int peekChar() {
int c = getChar();
ungetChar(c);
return c;
}
protected int getChar() {
if (ungetCursor != 0) {
cursor++;
--ungetCursor;
if (charno == -1) {
charno = getOffset();
}
return ungetBuffer[ungetCursor];
}
for(;;) {
int c;
if (sourceCursor == sourceEnd) {
hitEOF = true;
if (charno == -1) {
charno = getOffset();
}
return EOF_CHAR;
}
cursor++;
c = sourceString.charAt(sourceCursor++);
if (lineEndChar >= 0) {
if (lineEndChar == '\r' && c == '\n') {
lineEndChar = '\n';
continue;
}
lineEndChar = -1;
lineStart = sourceCursor - 1;
lineno++;
}
if (c <= 127) {
if (c == '\n' || c == '\r') {
lineEndChar = c;
c = '\n';
}
} else {
if (isJSFormatChar(c)) {
continue;
}
if (ScriptRuntime.isJSLineTerminator(c)) {
lineEndChar = c;
c = '\n';
}
}
if (charno == -1) {
charno = getOffset();
}
return c;
}
}
private int getCharIgnoreLineEnd() {
if (ungetCursor != 0) {
cursor++;
--ungetCursor;
if (charno == -1) {
charno = getOffset();
}
return ungetBuffer[ungetCursor];
}
for(;;) {
int c;
if (sourceCursor == sourceEnd) {
hitEOF = true;
if (charno == -1) {
charno = getOffset();
}
return EOF_CHAR;
}
cursor++;
c = sourceString.charAt(sourceCursor++);
if (c <= 127) {
if (c == '\n' || c == '\r') {
lineEndChar = c;
c = '\n';
}
} else {
if (isJSFormatChar(c)) {
continue;
}
if (ScriptRuntime.isJSLineTerminator(c)) {
lineEndChar = c;
c = '\n';
}
}
if (charno == -1) {
charno = getOffset();
}
return c;
}
}
private void ungetCharIgnoreLineEnd(int c) {
ungetBuffer[ungetCursor++] = c;
cursor--;
}
/**
* Returns the offset into the current line.
*/
final int getOffset() {
return sourceCursor - lineStart - ungetCursor - 1;
}
// Set this to an initial non-null value so that the Parser has
// something to retrieve even if an error has occurred and no
// string is found. Fosters one class of error, but saves lots of
// code.
private String string = "";
private char[] stringBuffer = new char[128];
private int stringBufferTop;
// Room to backtrace from to < on failed match of the last - in <!--
private final int[] ungetBuffer = new int[3];
private int ungetCursor;
private boolean hitEOF = false;
private int lineStart = 0;
private int lineEndChar = -1;
int lineno;
private int charno = -1;
private int initCharno;
private int initLineno;
private String sourceString;
private int sourceEnd;
// sourceCursor is an index into a small buffer that keeps a
// sliding window of the source stream.
int sourceCursor;
// cursor is a monotonically increasing index into the original
// source stream, tracking exactly how far scanning has progressed.
// Its value is the index of the next character to be scanned.
int cursor;
// Record start and end positions of last scanned token.
int tokenBeg;
int tokenEnd;
}
| weitzj/closure-compiler | src/com/google/javascript/jscomp/parsing/JsDocTokenStream.java | Java | apache-2.0 | 11,499 |
package com.crawljax.web;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
public class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) throws Exception {
final ParameterInterpeter options = new ParameterInterpeter(args);
String outFolder = options.specifiesOutputDir() ? options.getSpecifiedOutputDir() : "out";
int port = options.specifiesPort() ? options.getSpecifiedPort() : 8080;
final CrawljaxServer server = new CrawljaxServer(new CrawljaxServerConfigurationBuilder()
.setPort(port).setOutputDir(new File(outFolder)));
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LOG.info("Shutdown hook initiated");
try {
server.stop();
} catch (Exception e) {
LOG.warn("Could not stop the server in properly {}", e.getMessage());
LOG.debug("Stop error was ", e);
}
}
});
server.start(true);
}
public static String getCrawljaxVersion() {
try {
String[] lines = Resources.toString(Main.class.getResource("/crawljax.version"), Charsets.UTF_8)
.split(System.getProperty("line.separator"));
for(String line : lines) {
String[] keyValue = line.split("=");
if(keyValue[0].trim().toLowerCase().equals("version")) {
return keyValue[1].trim();
}
}
return null;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
| mmayorivera/crawljax | web/src/main/java/com/crawljax/web/Main.java | Java | apache-2.0 | 1,554 |
/**
* 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.codehaus.groovy.runtime.metaclass;
import org.codehaus.groovy.reflection.CachedClass;
import org.codehaus.groovy.reflection.CachedMethod;
/**
* Base class for NewInstanceMetaMethod and NewStaticMetaMethod
*/
public class NewMetaMethod extends ReflectionMetaMethod {
protected static final CachedClass[] EMPTY_TYPE_ARRAY = {};
protected CachedClass[] bytecodeParameterTypes ;
public NewMetaMethod(CachedMethod method) {
super(method);
bytecodeParameterTypes = method.getParameterTypes();
int size = bytecodeParameterTypes.length;
CachedClass[] logicalParameterTypes;
if (size <= 1) {
logicalParameterTypes = EMPTY_TYPE_ARRAY;
} else {
logicalParameterTypes = new CachedClass[--size];
System.arraycopy(bytecodeParameterTypes, 1, logicalParameterTypes, 0, size);
}
setParametersTypes(logicalParameterTypes);
}
public CachedClass getDeclaringClass() {
return getBytecodeParameterTypes()[0];
}
public CachedClass[] getBytecodeParameterTypes() {
return bytecodeParameterTypes;
}
public CachedClass getOwnerClass() {
return getBytecodeParameterTypes()[0];
}
}
| OpenBEL/kam-nav | tools/groovy/src/src/main/org/codehaus/groovy/runtime/metaclass/NewMetaMethod.java | Java | apache-2.0 | 2,061 |
// Copyright 2000-2018 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.intellij.laf.win10;
import com.intellij.ide.ui.laf.darcula.ui.DarculaRadioButtonUI;
import com.intellij.ui.scale.JBUIScale;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.JBInsets;
import javax.swing.*;
import javax.swing.plaf.ComponentUI;
import java.awt.*;
/**
* @author Konstantin Bulenkov
*/
public class WinIntelliJRadioButtonUI extends DarculaRadioButtonUI {
private static final Icon DEFAULT_ICON = JBUIScale.scaleIcon(EmptyIcon.create(13)).asUIResource();
@Override
protected Rectangle updateViewRect(AbstractButton b, Rectangle viewRect) {
JBInsets.removeFrom(viewRect, b.getInsets());
return viewRect;
}
@Override
protected Dimension computeOurPreferredSize(JComponent c) {
return null;
}
@SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
public static ComponentUI createUI(JComponent c) {
AbstractButton b = (AbstractButton)c;
b.setRolloverEnabled(true);
return new WinIntelliJRadioButtonUI();
}
@Override
protected void paintIcon(JComponent c, Graphics2D g, Rectangle viewRect, Rectangle iconRect) {
AbstractButton b = (AbstractButton)c;
ButtonModel bm = b.getModel();
boolean focused = c.hasFocus() || bm.isRollover();
Icon icon = WinIconLookup.getIcon("radio", bm.isSelected(), focused, bm.isEnabled(), false, bm.isPressed());
icon.paintIcon(c, g, iconRect.x, iconRect.y);
}
@Override
public Icon getDefaultIcon() {
return DEFAULT_ICON;
}
@Override
protected int getMnemonicIndex(AbstractButton b) {
return b.getDisplayedMnemonicIndex();
}
}
| GunoH/intellij-community | plugins/laf/win10/src/com/intellij/laf/win10/WinIntelliJRadioButtonUI.java | Java | apache-2.0 | 1,764 |
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.samples.petclinic.repository;
import java.util.Collection;
import org.springframework.dao.DataAccessException;
import org.springframework.samples.petclinic.model.BaseEntity;
import org.springframework.samples.petclinic.model.Owner;
/**
* Repository class for <code>Owner</code> domain objects All method names are compliant with Spring Data naming
* conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
*
* @author Ken Krebs
* @author Juergen Hoeller
* @author Sam Brannen
* @author Michael Isvy
*/
public interface OwnerRepository {
/**
* Retrieve <code>Owner</code>s from the data store by last name, returning all owners whose last name <i>starts</i>
* with the given name.
*
* @param lastName Value to search for
* @return a <code>Collection</code> of matching <code>Owner</code>s (or an empty <code>Collection</code> if none
* found)
*/
Collection<Owner> findByLastName(String lastName) throws DataAccessException;
/**
* Retrieve an <code>Owner</code> from the data store by id.
*
* @param id the id to search for
* @return the <code>Owner</code> if found
* @throws org.springframework.dao.DataRetrievalFailureException if not found
*/
Owner findById(int id) throws DataAccessException;
/**
* Save an <code>Owner</code> to the data store, either inserting or updating it.
*
* @param owner the <code>Owner</code> to save
* @see BaseEntity#isNew
*/
void save(Owner owner) throws DataAccessException;
}
| hslee9397/jboss-eap-quickstarts | spring-petclinic/src/main/java/org/springframework/samples/petclinic/repository/OwnerRepository.java | Java | apache-2.0 | 2,341 |
package org.dspace.content.packager;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import org.apache.log4j.Logger;
import org.dspace.content.packager.utils.DirFileFilter;
import org.dspace.core.ConfigurationManager;
public class BagItBuilder {
private static final Logger LOGGER = Logger.getLogger(BagItBuilder.class);
private static final String JAVA_OPTS = "-Djava.awt.headless=true -Xmx64M -XX:+UseConcMarkSweepGC -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager";
private static final String BAGIT_ACTION = "create";
private static final String BAG_INFO = "--baginfotxt";
private static final String WRITER = "--writer";
private static final String[] TAR_GZIP = new String[] { "tar.gz", "tar_gz" };
public static final File buildIt(File aWorkingDir)
throws BagItDisseminatorException {
String destDir = ConfigurationManager.getProperty("bagit.download.dir");
String bagitExec = ConfigurationManager.getProperty("bagit.executable");
File dataDir = aWorkingDir.listFiles(new DirFileFilter())[0];
File bagItDir = new File(destDir, aWorkingDir.getName());
if (!bagItDir.mkdir()) {
throw new BagItDisseminatorException("Configuration error: "
+ bagItDir.getAbsolutePath()
+ " doesn't exist and can't be created");
}
File dest = new File(bagItDir, dataDir.getName() + "." + TAR_GZIP[0]);
File bagInfoFile = new File(aWorkingDir, "bag-info.txt");
// This is hard-coded for Linux/Solaris (TODO: move to maven profile)
String[] command = new String[] {
"/bin/bash",
"-c",
bagitExec + " " + BAGIT_ACTION + " " + BAG_INFO + " "
+ bagInfoFile.getAbsolutePath() + " " + WRITER + " "
+ TAR_GZIP[1] + " " + dest.getAbsolutePath() + " "
+ dataDir.getAbsolutePath() + "/*" };
if (LOGGER.isInfoEnabled()) {
LOGGER.info("RUNNING: " + Arrays.toString(command));
}
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> env = processBuilder.environment();
String javaOptsValue = env.remove("JAVA_OPTS");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Removing script JAVA_OPTS=" + javaOptsValue);
}
// Setting a new java_opts with a lower memory amount
env.put("JAVA_OPTS", JAVA_OPTS);
Process process = processBuilder.start();
byte[] bytes = new byte[0];
int result = process.waitFor();
int available = 0;
switch (result) {
case 0:
LOGGER.info("Successfully created bagit file");
break;
case 1:
InputStream iStream = process.getErrorStream();
BufferedInputStream bStream = new BufferedInputStream(iStream);
available = bStream.available();
bytes = new byte[available];
bStream.read(bytes);
default:
throw new BagItDisseminatorException(
"BagItBuilder couldn't build bagit file ("
+ result
+ ")"
+ (available > 0 ? ": " + new String(bytes)
: ""));
}
}
catch (InterruptedException details) {
throw new BagItDisseminatorException(details);
}
catch (IOException details) {
throw new BagItDisseminatorException(details);
}
return dest;
}
}
| jamie-dryad/dryad-repo | dspace/modules/bagit/dspace-bagit-api/src/main/java/org/dspace/content/packager/BagItBuilder.java | Java | bsd-3-clause | 3,223 |
package headfirst.iterator.dinermerger;
public class DinerMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems;
public DinerMenu() {
menuItems = new MenuItem[MAX_ITEMS];
addItem("Vegetarian BLT",
"(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
addItem("BLT",
"Bacon with lettuce & tomato on whole wheat", false, 2.99);
addItem("Soup of the day",
"Soup of the day, with a side of potato salad", false, 3.29);
addItem("Hotdog",
"A hot dog, with saurkraut, relish, onions, topped with cheese",
false, 3.05);
addItem("Steamed Veggies and Brown Rice",
"Steamed vegetables over brown rice", true, 3.99);
addItem("Pasta",
"Spaghetti with Marinara Sauce, and a slice of sourdough bread",
true, 3.89);
}
public void addItem(String name, String description,
boolean vegetarian, double price)
{
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
if (numberOfItems >= MAX_ITEMS) {
System.err.println("Sorry, menu is full! Can't add item to menu");
} else {
menuItems[numberOfItems] = menuItem;
numberOfItems = numberOfItems + 1;
}
}
public MenuItem[] getMenuItems() {
return menuItems;
}
public Iterator createIterator() {
return new DinerMenuIterator(menuItems);
}
// other menu methods here
}
| KunkkaCoco/java-base | src/main/java/headfirst/iterator/dinermerger/DinerMenu.java | Java | epl-1.0 | 1,383 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -----------
* Vector.java
* -----------
* (C) Copyright 2007, 2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 30-Jan-2007 : Version 1 (DG);
* 24-May-2007 : Added getLength() and getAngle() methods, thanks to
* matinh (DG);
* 25-May-2007 : Moved from experimental to the main source tree (DG);
*
*/
package org.jfree.data.xy;
import java.io.Serializable;
/**
* A vector.
*
* @since 1.0.6
*/
public class Vector implements Serializable {
/** The vector x. */
private double x;
/** The vector y. */
private double y;
/**
* Creates a new instance of <code>Vector</code>.
*
* @param x the x-component.
* @param y the y-component.
*/
public Vector(double x, double y) {
this.x = x;
this.y = y;
}
/**
* Returns the x-value.
*
* @return The x-value.
*/
public double getX() {
return this.x;
}
/**
* Returns the y-value.
*
* @return The y-value.
*/
public double getY() {
return this.y;
}
/**
* Returns the length of the vector.
*
* @return The vector length.
*/
public double getLength() {
return Math.sqrt((this.x * this.x) + (this.y * this.y));
}
/**
* Returns the angle of the vector.
*
* @return The angle of the vector.
*/
public double getAngle() {
return Math.atan2(this.y, this.x);
}
/**
* Tests this vector for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> not permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Vector)) {
return false;
}
Vector that = (Vector) obj;
if (this.x != that.x) {
return false;
}
if (this.y != that.y) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
public int hashCode() {
int result = 193;
long temp = Double.doubleToLongBits(this.x);
result = 37 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(this.y);
result = 37 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
| apetresc/JFreeChart | src/main/java/org/jfree/data/xy/Vector.java | Java | lgpl-2.1 | 3,879 |
/*
* SK's Minecraft Launcher
* Copyright (C) 2010-2014 Albert Pham <http://www.sk89q.com> and contributors
* Please see LICENSE.txt for license information.
*/
package com.skcraft.launcher.persistence;
import com.fasterxml.jackson.core.PrettyPrinter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter.Lf2SpacesIndenter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
import com.google.common.io.Closer;
import com.google.common.io.Files;
import lombok.NonNull;
import lombok.extern.java.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.WeakHashMap;
import java.util.logging.Level;
/**
* Simple persistence framework that can read an object from a file, bind
* that object to that file, and allow any code having a reference to the
* object make changes to the object and save those changes back to disk.
* </p>
* For example:
* <pre>config = Persistence.load(file, Configuration.class);
* config.changeSomething();
* Persistence.commit(config);</pre>
*/
@Log
public final class Persistence {
private static final ObjectMapper mapper = new ObjectMapper();
private static final WeakHashMap<Object, ByteSink> bound = new WeakHashMap<Object, ByteSink>();
public static final DefaultPrettyPrinter L2F_LIST_PRETTY_PRINTER;
static {
L2F_LIST_PRETTY_PRINTER = new DefaultPrettyPrinter();
L2F_LIST_PRETTY_PRINTER.indentArraysWith(Lf2SpacesIndenter.instance);
}
private Persistence() {
}
/**
* Bind an object to a path where the object will be saved.
*
* @param object the object
* @param sink the byte sink
*/
public static void bind(@NonNull Object object, @NonNull ByteSink sink) {
synchronized (bound) {
bound.put(object, sink);
}
}
/**
* Save an object to file.
*
* @param object the object
* @throws java.io.IOException on save error
*/
public static void commit(@NonNull Object object) throws IOException {
ByteSink sink;
synchronized (bound) {
sink = bound.get(object);
if (sink == null) {
throw new IOException("Cannot persist unbound object: " + object);
}
}
Closer closer = Closer.create();
try {
OutputStream os = closer.register(sink.openBufferedStream());
mapper.writeValue(os, object);
} finally {
closer.close();
}
}
/**
* Save an object to file, and send all errors to the log.
*
* @param object the object
*/
public static void commitAndForget(@NonNull Object object) {
try {
commit(object);
} catch (IOException e) {
log.log(Level.WARNING, "Failed to save " + object.getClass() + ": " + object.toString(), e);
}
}
/**
* Read an object from a byte source, without binding it.
*
* @param source byte source
* @param cls the class
* @param returnNull true to return null if the object could not be loaded
* @param <V> the type of class
* @return an object
*/
public static <V> V read(ByteSource source, Class<V> cls, boolean returnNull) {
V object;
Closer closer = Closer.create();
try {
object = mapper.readValue(closer.register(source.openBufferedStream()), cls);
} catch (IOException e) {
if (!(e instanceof FileNotFoundException)) {
log.log(Level.INFO, "Failed to load" + cls.getCanonicalName(), e);
}
if (returnNull) {
return null;
}
try {
object = cls.newInstance();
} catch (InstantiationException e1) {
throw new RuntimeException(
"Failed to construct object with no-arg constructor", e1);
} catch (IllegalAccessException e1) {
throw new RuntimeException(
"Failed to construct object with no-arg constructor", e1);
}
} finally {
try {
closer.close();
} catch (IOException e) {
}
}
return object;
}
/**
* Read an object from file, without binding it.
*
* @param file the file
* @param cls the class
* @param returnNull true to return null if the object could not be loaded
* @param <V> the type of class
* @return an object
*/
public static <V> V read(File file, Class<V> cls, boolean returnNull) {
return read(Files.asByteSource(file), cls, returnNull);
}
/**
* Read an object from file, without binding it.
*
* @param file the file
* @param cls the class
* @param <V> the type of class
* @return an object
*/
public static <V> V read(File file, Class<V> cls) {
return read(file, cls, false);
}
/**
* Read an object from file.
*
* @param file the file
* @param cls the class
* @param returnNull true to return null if the object could not be loaded
* @param <V> the type of class
* @return an object
*/
public static <V> V load(File file, Class<V> cls, boolean returnNull) {
ByteSource source = Files.asByteSource(file);
ByteSink sink = new MkdirByteSink(Files.asByteSink(file), file.getParentFile());
Scrambled scrambled = cls.getAnnotation(Scrambled.class);
if (cls.getAnnotation(Scrambled.class) != null) {
source = new ScramblingSourceFilter(source, scrambled.value());
sink = new ScramblingSinkFilter(sink, scrambled.value());
}
V object = read(source, cls, returnNull);
Persistence.bind(object, sink);
return object;
}
/**
* Read an object from file.
*
* <p>If the file does not exist or loading fails, construct a new instance of
* the given class by using its no-arg constructor.</p>
*
* @param file the file
* @param cls the class
* @param <V> the type of class
* @return an object
*/
public static <V> V load(File file, Class<V> cls) {
return load(file, cls, false);
}
/**
* Write an object to file.
*
* @param file the file
* @param object the object
* @throws java.io.IOException on I/O error
*/
public static void write(File file, Object object) throws IOException {
write(file, object, null);
}
/**
* Write an object to file.
*
* @param file the file
* @param object the object
* @param prettyPrinter a pretty printer to use, or null
* @throws java.io.IOException on I/O error
*/
public static void write(File file, Object object, PrettyPrinter prettyPrinter) throws IOException {
file.getParentFile().mkdirs();
if (prettyPrinter != null) {
mapper.writer(prettyPrinter).writeValue(file, object);
} else {
mapper.writeValue(file, object);
}
}
/**
* Write an object to a string.
*
* @param object the object
* @param prettyPrinter a pretty printer to use, or null
* @throws java.io.IOException on I/O error
*/
public static String writeValueAsString(Object object, PrettyPrinter prettyPrinter) throws IOException {
if (prettyPrinter != null) {
return mapper.writer(prettyPrinter).writeValueAsString(object);
} else {
return mapper.writeValueAsString(object);
}
}
}
| Ganjalf-Amsterdoom/CdA-launcher | launcher/src/main/java/com/skcraft/launcher/persistence/Persistence.java | Java | lgpl-3.0 | 7,809 |
package org.keycloak.models.jpa;
import org.keycloak.Config;
import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.UserProvider;
import org.keycloak.models.UserProviderFactory;
import javax.persistence.EntityManager;
/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
* @version $Revision: 1 $
*/
public class JpaUserProviderFactory implements UserProviderFactory {
@Override
public void init(Config.Scope config) {
}
@Override
public void postInit(KeycloakSessionFactory factory) {
}
@Override
public String getId() {
return "jpa";
}
@Override
public UserProvider create(KeycloakSession session) {
EntityManager em = session.getProvider(JpaConnectionProvider.class).getEntityManager();
return new JpaUserProvider(session, em);
}
@Override
public void close() {
}
}
| eugene-chow/keycloak | model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProviderFactory.java | Java | apache-2.0 | 1,007 |
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.test.rest.yaml.section;
import org.elasticsearch.common.xcontent.XContentLocation;
import org.elasticsearch.test.rest.yaml.ClientYamlTestExecutionContext;
import java.io.IOException;
import java.util.Map;
/**
* Base class for executable sections that hold assertions
*/
public abstract class Assertion implements ExecutableSection {
private final XContentLocation location;
private final String field;
private final Object expectedValue;
protected Assertion(XContentLocation location, String field, Object expectedValue) {
this.location = location;
this.field = field;
this.expectedValue = expectedValue;
}
public final String getField() {
return field;
}
public final Object getExpectedValue() {
return expectedValue;
}
protected final Object resolveExpectedValue(ClientYamlTestExecutionContext executionContext) throws IOException {
if (expectedValue instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) expectedValue;
return executionContext.stash().replaceStashedValues(map);
}
if (executionContext.stash().containsStashedValue(expectedValue)) {
return executionContext.stash().getValue(expectedValue.toString());
}
return expectedValue;
}
protected final Object getActualValue(ClientYamlTestExecutionContext executionContext) throws IOException {
if (executionContext.stash().containsStashedValue(field)) {
return executionContext.stash().getValue(field);
}
return executionContext.response(field);
}
@Override
public XContentLocation getLocation() {
return location;
}
@Override
public final void execute(ClientYamlTestExecutionContext executionContext) throws IOException {
doAssert(getActualValue(executionContext), resolveExpectedValue(executionContext));
}
/**
* Executes the assertion comparing the actual value (parsed from the response) with the expected one
*/
protected abstract void doAssert(Object actualValue, Object expectedValue);
/**
* a utility to get the class of an object, protecting for null (i.e., returning null if the input is null)
*/
protected Class<?> safeClass(Object o) {
return o == null ? null : o.getClass();
}
}
| robin13/elasticsearch | test/framework/src/main/java/org/elasticsearch/test/rest/yaml/section/Assertion.java | Java | apache-2.0 | 2,793 |
/*
* Copyright (c) 2012-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package org.dna.mqtt.moquette.parser.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.util.Attribute;
import io.netty.util.AttributeMap;
import java.io.UnsupportedEncodingException;
import org.dna.mqtt.moquette.proto.messages.AbstractMessage;
import org.slf4j.LoggerFactory;
/**
*
* @author andrea
*/
public class Utils {
public static final int MAX_LENGTH_LIMIT = 268435455;
public static final byte VERSION_3_1 = 3;
public static final byte VERSION_3_1_1 = 4;
static byte readMessageType(ByteBuf in) {
byte h1 = in.readByte();
byte messageType = (byte) ((h1 & 0x00F0) >> 4);
return messageType;
}
static boolean checkHeaderAvailability(ByteBuf in) {
if (in.readableBytes() < 1) {
return false;
}
//byte h1 = in.get();
//byte messageType = (byte) ((h1 & 0x00F0) >> 4);
in.skipBytes(1); //skip the messageType byte
int remainingLength = Utils.decodeRemainingLenght(in);
if (remainingLength == -1) {
return false;
}
//check remaining length
if (in.readableBytes() < remainingLength) {
return false;
}
//return messageType == type ? MessageDecoderResult.OK : MessageDecoderResult.NOT_OK;
return true;
}
/**
* Decode the variable remaining length as defined in MQTT v3.1 specification
* (section 2.1).
*
* @return the decoded length or -1 if needed more data to decode the length field.
*/
static int decodeRemainingLenght(ByteBuf in) {
int multiplier = 1;
int value = 0;
byte digit;
do {
if (in.readableBytes() < 1) {
return -1;
}
digit = in.readByte();
value += (digit & 0x7F) * multiplier;
multiplier *= 128;
} while ((digit & 0x80) != 0);
return value;
}
/**
* Encode the value in the format defined in specification as variable length
* array.
*
* @throws IllegalArgumentException if the value is not in the specification bounds
* [0..268435455].
*/
static ByteBuf encodeRemainingLength(int value) throws CorruptedFrameException {
if (value > MAX_LENGTH_LIMIT || value < 0) {
throw new CorruptedFrameException("Value should in range 0.." + MAX_LENGTH_LIMIT + " found " + value);
}
ByteBuf encoded = Unpooled.buffer(4);
byte digit;
do {
digit = (byte) (value % 128);
value = value / 128;
// if there are more digits to encode, set the top bit of this digit
if (value > 0) {
digit = (byte) (digit | 0x80);
}
encoded.writeByte(digit);
} while (value > 0);
return encoded;
}
/**
* Load a string from the given buffer, reading first the two bytes of len
* and then the UTF-8 bytes of the string.
*
* @return the decoded string or null if NEED_DATA
*/
static String decodeString(ByteBuf in) throws UnsupportedEncodingException {
if (in.readableBytes() < 2) {
return null;
}
//int strLen = Utils.readWord(in);
int strLen = in.readUnsignedShort();
if (in.readableBytes() < strLen) {
return null;
}
byte[] strRaw = new byte[strLen];
in.readBytes(strRaw);
return new String(strRaw, "UTF-8");
}
/**
* Return the IoBuffer with string encoded as MSB, LSB and UTF-8 encoded
* string content.
*/
static ByteBuf encodeString(String str) {
ByteBuf out = Unpooled.buffer(2);
byte[] raw;
try {
raw = str.getBytes("UTF-8");
//NB every Java platform has got UTF-8 encoding by default, so this
//exception are never raised.
} catch (UnsupportedEncodingException ex) {
LoggerFactory.getLogger(Utils.class).error(null, ex);
return null;
}
//Utils.writeWord(out, raw.length);
out.writeShort(raw.length);
out.writeBytes(raw);
return out;
}
/**
* Return the number of bytes to encode the given remaining length value
*/
static int numBytesToEncode(int len) {
if (0 <= len && len <= 127) return 1;
if (128 <= len && len <= 16383) return 2;
if (16384 <= len && len <= 2097151) return 3;
if (2097152 <= len && len <= 268435455) return 4;
throw new IllegalArgumentException("value shoul be in the range [0..268435455]");
}
static byte encodeFlags(AbstractMessage message) {
byte flags = 0;
if (message.isDupFlag()) {
flags |= 0x08;
}
if (message.isRetainFlag()) {
flags |= 0x01;
}
flags |= ((message.getQos().ordinal() & 0x03) << 1);
return flags;
}
static boolean isMQTT3_1_1(AttributeMap attrsMap) {
Attribute<Integer> versionAttr = attrsMap.attr(MQTTDecoder.PROTOCOL_VERSION);
Integer protocolVersion = versionAttr.get();
if (protocolVersion == null) {
return true;
}
return protocolVersion == VERSION_3_1_1;
}
}
| zuiliucc/moquette-mqtt | netty_parser/src/main/java/org/dna/mqtt/moquette/parser/netty/Utils.java | Java | apache-2.0 | 6,042 |
package org.apache.aries.blueprint.itests.authz.helper;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class JAASHelper {
public static <T> void doAs(final String[] groups, PrivilegedAction<T> action) {
Configuration config = new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("username", "dummy"); // The user does not matter
options.put("groups", groups);
AppConfigurationEntry entry = new AppConfigurationEntry(SimpleLoginModule.class.getName(),
LoginModuleControlFlag.REQUIRED,
options);
return new AppConfigurationEntry[] {
entry
};
}
};
try {
LoginContext lc = new LoginContext("test", new Subject(), null, config);
lc.login();
Subject.doAs(lc.getSubject(), action);
lc.logout();
} catch (LoginException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
| WouterBanckenACA/aries | blueprint/itests/blueprint-itests/src/test/java/org/apache/aries/blueprint/itests/authz/helper/JAASHelper.java | Java | apache-2.0 | 1,679 |
/*
* 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.flink.runtime.io.network.partition;
import org.apache.flink.runtime.io.network.buffer.Buffer;
import org.apache.flink.runtime.io.network.util.TestBufferFactory;
import org.apache.flink.util.TestLogger;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
/**
* Basic subpartition behaviour tests.
*/
public abstract class SubpartitionTestBase extends TestLogger {
/**
* Return the subpartition to be tested.
*/
abstract ResultSubpartition createSubpartition();
// ------------------------------------------------------------------------
@Test
public void testAddAfterFinish() throws Exception {
final ResultSubpartition subpartition = createSubpartition();
try {
subpartition.finish();
assertFalse(subpartition.add(mock(Buffer.class)));
} finally {
if (subpartition != null) {
subpartition.release();
}
}
}
@Test
public void testAddAfterRelease() throws Exception {
final ResultSubpartition subpartition = createSubpartition();
try {
subpartition.release();
assertFalse(subpartition.add(mock(Buffer.class)));
} finally {
if (subpartition != null) {
subpartition.release();
}
}
}
@Test
public void testReleaseParent() throws Exception {
final ResultSubpartition partition = createSubpartition();
verifyViewReleasedAfterParentRelease(partition);
}
@Test
public void testReleaseParentAfterSpilled() throws Exception {
final ResultSubpartition partition = createSubpartition();
partition.releaseMemory();
verifyViewReleasedAfterParentRelease(partition);
}
private void verifyViewReleasedAfterParentRelease(ResultSubpartition partition) throws Exception {
// Add a buffer
Buffer buffer = TestBufferFactory.createBuffer();
partition.add(buffer);
partition.finish();
// Create the view
BufferAvailabilityListener listener = mock(BufferAvailabilityListener.class);
ResultSubpartitionView view = partition.createReadView(listener);
// The added buffer and end-of-partition event
assertNotNull(view.getNextBuffer());
assertNotNull(view.getNextBuffer());
// Release the parent
assertFalse(view.isReleased());
partition.release();
// Verify that parent release is reflected at partition view
assertTrue(view.isReleased());
}
}
| hongyuhong/flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/SubpartitionTestBase.java | Java | apache-2.0 | 3,214 |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.transform;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.LatchedActionListener;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.common.CheckedConsumer;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.reindex.ReindexPlugin;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.test.ESSingleNodeTestCase;
import org.elasticsearch.xpack.core.template.TemplateUtils;
import org.elasticsearch.xpack.core.transform.transforms.persistence.TransformInternalIndexConstants;
import org.junit.Before;
import java.util.Collection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static org.hamcrest.Matchers.equalTo;
public abstract class TransformSingleNodeTestCase extends ESSingleNodeTestCase {
@Before
public void waitForTemplates() throws Exception {
assertBusy(() -> {
ClusterState state = client().admin().cluster().prepareState().get().getState();
assertTrue("Timed out waiting for the transform templates to be installed", TemplateUtils
.checkTemplateExistsAndVersionIsGTECurrentVersion(TransformInternalIndexConstants.LATEST_INDEX_VERSIONED_NAME, state));
});
}
@Override
protected Settings nodeSettings() {
Settings.Builder newSettings = Settings.builder();
newSettings.put(super.nodeSettings());
return newSettings.build();
}
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return pluginList(LocalStateTransform.class, ReindexPlugin.class);
}
protected <T> void assertAsync(Consumer<ActionListener<T>> function, T expected, CheckedConsumer<T, ? extends Exception> onAnswer,
Consumer<Exception> onException) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
LatchedActionListener<T> listener = new LatchedActionListener<>(ActionListener.wrap(r -> {
if (expected == null) {
fail("expected an exception but got a response");
} else {
assertThat(r, equalTo(expected));
}
if (onAnswer != null) {
onAnswer.accept(r);
}
}, e -> {
if (onException == null) {
logger.error("got unexpected exception", e);
fail("got unexpected exception: " + e.getMessage());
} else {
onException.accept(e);
}
}), latch);
function.accept(listener);
assertTrue("timed out after 20s", latch.await(20, TimeUnit.SECONDS));
}
}
| gingerwizard/elasticsearch | x-pack/plugin/transform/src/test/java/org/elasticsearch/xpack/transform/TransformSingleNodeTestCase.java | Java | apache-2.0 | 2,998 |
// Copyright 2016 Twitter. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.twitter.heron.api.spout;
import com.twitter.heron.api.topology.IComponent;
/**
* When writing topologies using Java, {@link com.twitter.heron.api.bolt.IRichBolt} and
* {@link IRichSpout} are the main interfaces
* to use to implement components of the topology.
*/
public interface IRichSpout extends ISpout, IComponent {
}
| zhangzhonglai/heron | heron/api/src/java/com/twitter/heron/api/spout/IRichSpout.java | Java | apache-2.0 | 948 |
/*
* Copyright 2012-2018 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.
*/
/**
* Actuator support for InfluxDB.
*/
package org.springframework.boot.actuate.influx;
| hello2009chen/spring-boot | spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/influx/package-info.java | Java | apache-2.0 | 713 |
/*
* 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.forms.services.backend.serialization;
import org.kie.workbench.common.forms.model.FormDefinition;
public interface FormDefinitionSerializer {
String serialize(FormDefinition form);
FormDefinition deserialize(String serializedForm);
}
| jomarko/kie-wb-common | kie-wb-common-forms/kie-wb-common-forms-commons/kie-wb-common-forms-services/kie-wb-common-forms-backend-services/src/main/java/org/kie/workbench/common/forms/services/backend/serialization/FormDefinitionSerializer.java | Java | apache-2.0 | 900 |
/*
* 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.gobblin.metadata.types;
import java.io.IOException;
import org.apache.gobblin.metadata.MetadataMerger;
import org.apache.gobblin.writer.FsWriterMetrics;
/**
* Merges a set of GlobalMetadata objects that have been serialized as JSON together to
* create a final output.
*/
public class GlobalMetadataJsonMerger implements MetadataMerger<String> {
private GlobalMetadata mergedMetadata;
public GlobalMetadataJsonMerger() {
mergedMetadata = new GlobalMetadata();
}
@Override
public void update(String metadata) {
try {
GlobalMetadata parsedMetadata = GlobalMetadata.fromJson(metadata);
mergedMetadata.addAll(parsedMetadata);
} catch (IOException e) {
throw new IllegalArgumentException("Error parsing metadata", e);
}
}
@Override
public void update(FsWriterMetrics metrics) {
long numRecords = mergedMetadata.getNumRecords();
int numFiles = mergedMetadata.getNumFiles();
for (FsWriterMetrics.FileInfo fileInfo: metrics.getFileInfos()) {
numRecords += fileInfo.getNumRecords();
numFiles += 1;
mergedMetadata.setFileMetadata(fileInfo.getFileName(), GlobalMetadata.NUM_RECORDS_KEY,
Long.valueOf(fileInfo.getNumRecords()));
}
mergedMetadata.setNumRecords(numRecords);
mergedMetadata.setNumOutputFiles(numFiles);
}
@Override
public String getMergedMetadata() {
try {
return mergedMetadata.toJson();
} catch (IOException e) {
throw new AssertionError("Unexpected IOException serializing to JSON", e);
}
}
}
| jack-moseley/gobblin | gobblin-modules/gobblin-metadata/src/main/java/org/apache/gobblin/metadata/types/GlobalMetadataJsonMerger.java | Java | apache-2.0 | 2,366 |
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.action.search;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermStatistics;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.breaker.NoopCircuitBreaker;
import org.elasticsearch.common.lucene.search.TopDocsAndMaxScore;
import org.elasticsearch.common.util.concurrent.AtomicArray;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.SearchPhaseResult;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.search.dfs.DfsSearchResult;
import org.elasticsearch.search.internal.ShardSearchContextId;
import org.elasticsearch.search.query.QuerySearchRequest;
import org.elasticsearch.search.query.QuerySearchResult;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.InternalAggregationTestCase;
import org.elasticsearch.transport.Transport;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.concurrent.atomic.AtomicReference;
public class DfsQueryPhaseTests extends ESTestCase {
private static DfsSearchResult newSearchResult(int shardIndex, ShardSearchContextId contextId, SearchShardTarget target) {
DfsSearchResult result = new DfsSearchResult(contextId, target, null);
result.setShardIndex(shardIndex);
return result;
}
public void testDfsWith2Shards() throws IOException {
AtomicArray<DfsSearchResult> results = new AtomicArray<>(2);
AtomicReference<AtomicArray<SearchPhaseResult>> responseRef = new AtomicReference<>();
results.set(
0,
newSearchResult(0, new ShardSearchContextId("", 1), new SearchShardTarget("node1", new ShardId("test", "na", 0), null))
);
results.set(
1,
newSearchResult(1, new ShardSearchContextId("", 2), new SearchShardTarget("node2", new ShardId("test", "na", 0), null))
);
results.get(0).termsStatistics(new Term[0], new TermStatistics[0]);
results.get(1).termsStatistics(new Term[0], new TermStatistics[0]);
SearchTransportService searchTransportService = new SearchTransportService(null, null, null) {
@Override
public void sendExecuteQuery(
Transport.Connection connection,
QuerySearchRequest request,
SearchTask task,
SearchActionListener<QuerySearchResult> listener
) {
if (request.contextId().getId() == 1) {
QuerySearchResult queryResult = new QuerySearchResult(
new ShardSearchContextId("", 123),
new SearchShardTarget("node1", new ShardId("test", "na", 0), null),
null
);
queryResult.topDocs(
new TopDocsAndMaxScore(
new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(42, 1.0F) }),
2.0F
),
new DocValueFormat[0]
);
queryResult.size(2); // the size of the result set
listener.onResponse(queryResult);
} else if (request.contextId().getId() == 2) {
QuerySearchResult queryResult = new QuerySearchResult(
new ShardSearchContextId("", 123),
new SearchShardTarget("node2", new ShardId("test", "na", 0), null),
null
);
queryResult.topDocs(
new TopDocsAndMaxScore(
new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(84, 2.0F) }),
2.0F
),
new DocValueFormat[0]
);
queryResult.size(2); // the size of the result set
listener.onResponse(queryResult);
} else {
fail("no such request ID: " + request.contextId());
}
}
};
SearchPhaseController searchPhaseController = searchPhaseController();
MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(2);
mockSearchPhaseContext.searchTransport = searchTransportService;
QueryPhaseResultConsumer consumer = searchPhaseController.newSearchPhaseResults(
EsExecutors.DIRECT_EXECUTOR_SERVICE,
new NoopCircuitBreaker(CircuitBreaker.REQUEST),
() -> false,
SearchProgressListener.NOOP,
mockSearchPhaseContext.searchRequest,
results.length(),
exc -> {}
);
DfsQueryPhase phase = new DfsQueryPhase(results.asList(), null, consumer, (response) -> new SearchPhase("test") {
@Override
public void run() throws IOException {
responseRef.set(response.results);
}
}, mockSearchPhaseContext);
assertEquals("dfs_query", phase.getName());
phase.run();
mockSearchPhaseContext.assertNoFailure();
assertNotNull(responseRef.get());
assertNotNull(responseRef.get().get(0));
assertNull(responseRef.get().get(0).fetchResult());
assertEquals(1, responseRef.get().get(0).queryResult().topDocs().topDocs.totalHits.value);
assertEquals(42, responseRef.get().get(0).queryResult().topDocs().topDocs.scoreDocs[0].doc);
assertNotNull(responseRef.get().get(1));
assertNull(responseRef.get().get(1).fetchResult());
assertEquals(1, responseRef.get().get(1).queryResult().topDocs().topDocs.totalHits.value);
assertEquals(84, responseRef.get().get(1).queryResult().topDocs().topDocs.scoreDocs[0].doc);
assertTrue(mockSearchPhaseContext.releasedSearchContexts.isEmpty());
assertEquals(2, mockSearchPhaseContext.numSuccess.get());
}
public void testDfsWith1ShardFailed() throws IOException {
AtomicArray<DfsSearchResult> results = new AtomicArray<>(2);
AtomicReference<AtomicArray<SearchPhaseResult>> responseRef = new AtomicReference<>();
results.set(
0,
newSearchResult(0, new ShardSearchContextId("", 1), new SearchShardTarget("node1", new ShardId("test", "na", 0), null))
);
results.set(
1,
newSearchResult(1, new ShardSearchContextId("", 2), new SearchShardTarget("node2", new ShardId("test", "na", 0), null))
);
results.get(0).termsStatistics(new Term[0], new TermStatistics[0]);
results.get(1).termsStatistics(new Term[0], new TermStatistics[0]);
SearchTransportService searchTransportService = new SearchTransportService(null, null, null) {
@Override
public void sendExecuteQuery(
Transport.Connection connection,
QuerySearchRequest request,
SearchTask task,
SearchActionListener<QuerySearchResult> listener
) {
if (request.contextId().getId() == 1) {
QuerySearchResult queryResult = new QuerySearchResult(
new ShardSearchContextId("", 123),
new SearchShardTarget("node1", new ShardId("test", "na", 0), null),
null
);
queryResult.topDocs(
new TopDocsAndMaxScore(
new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(42, 1.0F) }),
2.0F
),
new DocValueFormat[0]
);
queryResult.size(2); // the size of the result set
listener.onResponse(queryResult);
} else if (request.contextId().getId() == 2) {
listener.onFailure(new MockDirectoryWrapper.FakeIOException());
} else {
fail("no such request ID: " + request.contextId());
}
}
};
SearchPhaseController searchPhaseController = searchPhaseController();
MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(2);
mockSearchPhaseContext.searchTransport = searchTransportService;
QueryPhaseResultConsumer consumer = searchPhaseController.newSearchPhaseResults(
EsExecutors.DIRECT_EXECUTOR_SERVICE,
new NoopCircuitBreaker(CircuitBreaker.REQUEST),
() -> false,
SearchProgressListener.NOOP,
mockSearchPhaseContext.searchRequest,
results.length(),
exc -> {}
);
DfsQueryPhase phase = new DfsQueryPhase(results.asList(), null, consumer, (response) -> new SearchPhase("test") {
@Override
public void run() throws IOException {
responseRef.set(response.results);
}
}, mockSearchPhaseContext);
assertEquals("dfs_query", phase.getName());
phase.run();
mockSearchPhaseContext.assertNoFailure();
assertNotNull(responseRef.get());
assertNotNull(responseRef.get().get(0));
assertNull(responseRef.get().get(0).fetchResult());
assertEquals(1, responseRef.get().get(0).queryResult().topDocs().topDocs.totalHits.value);
assertEquals(42, responseRef.get().get(0).queryResult().topDocs().topDocs.scoreDocs[0].doc);
assertNull(responseRef.get().get(1));
assertEquals(1, mockSearchPhaseContext.numSuccess.get());
assertEquals(1, mockSearchPhaseContext.failures.size());
assertTrue(mockSearchPhaseContext.failures.get(0).getCause() instanceof MockDirectoryWrapper.FakeIOException);
assertEquals(1, mockSearchPhaseContext.releasedSearchContexts.size());
assertTrue(mockSearchPhaseContext.releasedSearchContexts.contains(new ShardSearchContextId("", 2L)));
assertNull(responseRef.get().get(1));
}
public void testFailPhaseOnException() throws IOException {
AtomicArray<DfsSearchResult> results = new AtomicArray<>(2);
AtomicReference<AtomicArray<SearchPhaseResult>> responseRef = new AtomicReference<>();
results.set(
0,
newSearchResult(0, new ShardSearchContextId("", 1), new SearchShardTarget("node1", new ShardId("test", "na", 0), null))
);
results.set(
1,
newSearchResult(1, new ShardSearchContextId("", 2), new SearchShardTarget("node2", new ShardId("test", "na", 0), null))
);
results.get(0).termsStatistics(new Term[0], new TermStatistics[0]);
results.get(1).termsStatistics(new Term[0], new TermStatistics[0]);
SearchTransportService searchTransportService = new SearchTransportService(null, null, null) {
@Override
public void sendExecuteQuery(
Transport.Connection connection,
QuerySearchRequest request,
SearchTask task,
SearchActionListener<QuerySearchResult> listener
) {
if (request.contextId().getId() == 1) {
QuerySearchResult queryResult = new QuerySearchResult(
new ShardSearchContextId("", 123),
new SearchShardTarget("node1", new ShardId("test", "na", 0), null),
null
);
queryResult.topDocs(
new TopDocsAndMaxScore(
new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(42, 1.0F) }),
2.0F
),
new DocValueFormat[0]
);
queryResult.size(2); // the size of the result set
listener.onResponse(queryResult);
} else if (request.contextId().getId() == 2) {
throw new UncheckedIOException(new MockDirectoryWrapper.FakeIOException());
} else {
fail("no such request ID: " + request.contextId());
}
}
};
SearchPhaseController searchPhaseController = searchPhaseController();
MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(2);
mockSearchPhaseContext.searchTransport = searchTransportService;
QueryPhaseResultConsumer consumer = searchPhaseController.newSearchPhaseResults(
EsExecutors.DIRECT_EXECUTOR_SERVICE,
new NoopCircuitBreaker(CircuitBreaker.REQUEST),
() -> false,
SearchProgressListener.NOOP,
mockSearchPhaseContext.searchRequest,
results.length(),
exc -> {}
);
DfsQueryPhase phase = new DfsQueryPhase(results.asList(), null, consumer, (response) -> new SearchPhase("test") {
@Override
public void run() throws IOException {
responseRef.set(response.results);
}
}, mockSearchPhaseContext);
assertEquals("dfs_query", phase.getName());
expectThrows(UncheckedIOException.class, phase::run);
assertTrue(mockSearchPhaseContext.releasedSearchContexts.isEmpty()); // phase execution will clean up on the contexts
}
private SearchPhaseController searchPhaseController() {
return new SearchPhaseController((task, request) -> InternalAggregationTestCase.emptyReduceContextBuilder());
}
}
| GlenRSmith/elasticsearch | server/src/test/java/org/elasticsearch/action/search/DfsQueryPhaseTests.java | Java | apache-2.0 | 14,401 |
/*
* 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.jackrabbit.oak.plugins.index.lucene.reader;
import java.io.Closeable;
import java.io.IOException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.suggest.analyzing.AnalyzingInfixSuggester;
import org.apache.lucene.store.Directory;
import org.jetbrains.annotations.Nullable;
public interface LuceneIndexReader extends Closeable{
IndexReader getReader();
@Nullable
AnalyzingInfixSuggester getLookup();
@Nullable
Directory getSuggestDirectory();
long getIndexSize() throws IOException;
}
| stillalex/jackrabbit-oak | oak-lucene/src/main/java/org/apache/jackrabbit/oak/plugins/index/lucene/reader/LuceneIndexReader.java | Java | apache-2.0 | 1,372 |
// Copyright 2020 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.android.r8.desugar.basic;
/** Test class */
public interface I {
default void foo() {
System.out.println("I::foo");
}
}
| katre/bazel | src/test/java/com/google/devtools/build/android/r8/desugar/basic/I.java | Java | apache-2.0 | 778 |
/*
* Copyright (c) 2002-2012, the original author or authors.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*
* http://www.opensource.org/licenses/bsd-license.php
*/
package jdk.internal.jline.internal;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Marker annotation for members which are exposed for testing access.
*
* @since 2.7
*/
@Retention(RUNTIME)
@Target({TYPE, CONSTRUCTOR, METHOD, FIELD, PARAMETER})
@Documented
public @interface TestAccessible
{
// empty
}
| FauxFaux/jdk9-jdk | src/jdk.internal.le/share/classes/jdk/internal/jline/internal/TestAccessible.java | Java | gpl-2.0 | 998 |
/*
* Copyright 2017 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.stunner.core.client.shape.view.event;
public abstract class TextDoubleClickHandler extends AbstractViewHandler<TextDoubleClickEvent> {
@Override
public ViewEventType getType() {
return ViewEventType.TEXT_DBL_CLICK;
}
}
| jomarko/kie-wb-common | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-api/kie-wb-common-stunner-client-api/src/main/java/org/kie/workbench/common/stunner/core/client/shape/view/event/TextDoubleClickHandler.java | Java | apache-2.0 | 895 |
/* 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.activiti.engine.management;
/**
* Allows programmatic querying of {@link TablePage}s.
*
* @author Joram Barrez
*/
public interface TablePageQuery {
/**
* The name of the table of which a page must be fetched.
*/
TablePageQuery tableName(String tableName);
/**
* Orders the resulting table page rows by the given column in ascending order.
*/
TablePageQuery orderAsc(String column);
/**
* Orders the resulting table page rows by the given column in descending order.
*/
TablePageQuery orderDesc(String column);
/**
* Executes the query and returns the {@link TablePage}.
*/
TablePage listPage(int firstResult, int maxResults);
}
| robsoncardosoti/flowable-engine | modules/flowable5-engine/src/main/java/org/activiti/engine/management/TablePageQuery.java | Java | apache-2.0 | 1,284 |
package de.plushnikov.intellij.plugin;
import com.intellij.codeInsight.ExceptionUtil;
import com.intellij.psi.*;
import com.intellij.testFramework.LightJavaCodeInsightTestCase;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* Based on logic from com.intellij.codeInsight.ExceptionCheckingTest
*/
public class SneakyThrowsTest extends LightJavaCodeInsightTestCase {
public void testCatchAllException() {
PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows void foo() { throwsMyException(); }");
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertTrue(exceptions.isEmpty());
}
public void testCatchSpecificException() {
PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows(MyException.class) void foo() { throwsMyException(); }");
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertTrue(exceptions.isEmpty());
}
public void testCatchGeneralException() {
PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows(Exception.class) void foo() { throwsMyException(); }");
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertTrue(exceptions.isEmpty());
}
public void testNotCatchException() {
PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows(SomeException.class) void foo() { throwsMyException(); }");
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertEquals(1, exceptions.size());
assertEquals("Test.MyException", exceptions.get(0).getCanonicalText());
}
public void testLambdaSneakyThrowsWrongCatch() {
PsiFile file = createTestFile("@lombok.SneakyThrows" +
" public void m1() {\n" +
" Runnable runnable = () -> {\n" +
" throwsMyException();" +
" };\n" +
" }\n");
PsiMethodCallExpression methodCall = findMethodCall(file);
assertNotNull(methodCall);
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertEquals(1, exceptions.size());
assertEquals("Test.MyException", exceptions.get(0).getCanonicalText());
}
public void testAnonymousClassCorrectCatch() {
PsiFile file = createTestFile("@lombok.SneakyThrows" +
" public void m1() {\n" +
" Runnable runnable = new Runnable() {\n" +
" public void run() { throwsMyException(); }" +
" };\n" +
" }\n");
PsiMethodCallExpression methodCall = findMethodCall(file);
assertNotNull(methodCall);
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertEquals(1, exceptions.size());
assertEquals("Test.MyException", exceptions.get(0).getCanonicalText());
}
public void testTryCatchThatCatchAnotherException() {
PsiFile file = createTestFile("@lombok.SneakyThrows\n" +
" public void m() {\n" +
" try {\n" +
" throwsMyException();" +
" throwsSomeException();" +
" } catch (Test.SomeException e) {\n" +
" }\n" +
" }");
PsiMethodCallExpression methodCall = findMethodCall(file);
assertNotNull(methodCall);
PsiTryStatement tryStatement = findFirstChild(file, PsiTryStatement.class);
assertNotNull(tryStatement);
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, tryStatement);
assertSize(0, exceptions);
}
public void testTryCatchThatCatchAnotherExceptionWithNullTopElement() {
PsiMethodCallExpression methodCall = createCall("@lombok.SneakyThrows\n" +
" public void m() {\n" +
" try {\n" +
" throwsMyException();" +
" throwsSomeException();" +
" } catch (Test.SomeException e) {\n" +
" }\n" +
" }");
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertSize(0, exceptions);
}
public void testTryCatchThatCatchAnotherExceptionHierarchy() {
PsiFile file = createTestFile("@lombok.SneakyThrows\n" +
" public void m() {\n" +
" try {\n" +
" try {" +
" throwsMyException();\n" +
" throwsSomeException();" +
" throwsAnotherException();" +
" } catch (Test.SomeException e) {}\n" +
" } catch (Test.AnotherException e) {}\n" +
" }");
PsiMethodCallExpression methodCall = findMethodCall(file);
assertNotNull(methodCall);
PsiTryStatement tryStatement = findFirstChild(file, PsiTryStatement.class);
assertNotNull(tryStatement);
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertSize(0, exceptions);
}
/**
* to avoid catching all exceptions by default by accident
*/
public void testRegularThrows() {
PsiMethodCallExpression methodCall = createCall("void foo() { throwsMyException(); }");
List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(methodCall, null);
assertEquals(1, exceptions.size());
assertEquals("Test.MyException", exceptions.get(0).getCanonicalText());
}
private PsiMethodCallExpression createCall(@NonNls final String body) {
final PsiFile file = createTestFile(body);
PsiMethodCallExpression methodCall = findMethodCall(file);
assertNotNull(methodCall);
return methodCall;
}
@NotNull
private PsiFile createTestFile(@NonNls String body) {
return createFile("test.java", "class Test { " + body +
"void throwsAnotherException() throws AnotherException {}" +
"void throwsMyException() throws MyException {}" +
"void throwsSomeException() throws SomeException {}" +
"static class MyException extends Exception {}" +
"static class SomeException extends Exception {}" +
"static class AnotherException extends Exception {}" +
"static class Exception{}" +
"}");
}
@Nullable
private static PsiMethodCallExpression findMethodCall(@NotNull PsiElement element) {
return findFirstChild(element, PsiMethodCallExpression.class);
}
@Nullable
private static <T extends PsiElement> T findFirstChild(@NotNull PsiElement element, Class<T> aClass) {
if (aClass.isInstance(element)) {
return (T) element;
}
for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
final T call = findFirstChild(child, aClass);
if (call != null) {
return call;
}
}
return null;
}
}
| siosio/intellij-community | plugins/lombok/src/test/java/de/plushnikov/intellij/plugin/SneakyThrowsTest.java | Java | apache-2.0 | 6,828 |
/*
* Copyright 2009-2012 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.apache.ibatis.submitted.extends_with_constructor;
import java.util.List;
public class Teacher {
private int id;
private String name;
private List<StudentConstructor> students;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<StudentConstructor> getStudents() {
return students;
}
public void setStudents(List<StudentConstructor> students) {
this.students = students;
}
}
| shurun19851206/mybaties | src/test/java/org/apache/ibatis/submitted/extends_with_constructor/Teacher.java | Java | apache-2.0 | 1,231 |
package org.jgroups.util;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* @author Bela Ban
*/
public class NullFuture<T> implements NotifyingFuture<T> {
final T retval;
public NullFuture(T retval) {
this.retval=retval;
}
public boolean cancel(boolean mayInterruptIfRunning) {
return true;
}
public boolean isCancelled() {
return true;
}
public boolean isDone() {
return true;
}
public T get() throws InterruptedException, ExecutionException {
return retval;
}
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return retval;
}
public NotifyingFuture setListener(FutureListener<T> listener) {
if(listener != null)
listener.futureDone(this);
return this;
}
}
| tekcomms/JGroups | src/org/jgroups/util/NullFuture.java | Java | apache-2.0 | 954 |
package org.springframework.ldap.query;
import org.junit.Test;
import org.springframework.ldap.support.LdapUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
/**
* @author Mattias Hellborg Arthursson
*/
public class LdapQueryBuilderTest {
@Test
public void buildSimpleWithDefaults() {
LdapQuery result = query().where("cn").is("John Doe");
assertEquals(LdapUtils.emptyLdapName(), result.base());
assertNull(result.searchScope());
assertNull(result.timeLimit());
assertNull(result.countLimit());
assertEquals("(cn=John Doe)", result.filter().encode());
}
@Test
public void buildGreaterThanOrEquals() {
LdapQuery result = query().where("cn").gte("John Doe");
assertEquals("(cn>=John Doe)", result.filter().encode());
}
@Test
public void buildLessThanOrEquals() {
LdapQuery result = query().where("cn").lte("John Doe");
assertEquals("(cn<=John Doe)", result.filter().encode());
}
@Test
public void buildLike() {
LdapQuery result = query().where("cn").like("J*hn Doe");
assertEquals("(cn=J*hn Doe)", result.filter().encode());
}
@Test
public void buildWhitespaceWildcards() {
LdapQuery result = query().where("cn").whitespaceWildcardsLike("John Doe");
assertEquals("(cn=*John*Doe*)", result.filter().encode());
}
@Test
public void buildPresent() {
LdapQuery result = query().where("cn").isPresent();
assertEquals("(cn=*)", result.filter().encode());
}
@Test
public void buildHardcodedFilter() {
LdapQuery result = query().filter("(cn=Person*)");
assertEquals("(cn=Person*)", result.filter().encode());
}
@Test(expected = IllegalStateException.class)
public void verifyThatHardcodedFilterFailsIfFilterAlreadySpecified() {
LdapQueryBuilder query = query();
query.where("sn").is("Doe");
query.filter("(cn=Person*)");
}
@Test(expected = IllegalStateException.class)
public void verifyThatFilterFormatFailsIfFilterAlreadySpecified() {
LdapQueryBuilder query = query();
query.where("sn").is("Doe");
query.filter("(|(cn={0})(cn={1}))", "Person*", "Parson*");
}
@Test
public void buildFilterFormat() {
LdapQuery result = query().filter("(|(cn={0})(cn={1}))", "Person*", "Parson*");
assertEquals("(|(cn=Person\\2a)(cn=Parson\\2a))", result.filter().encode());
}
@Test
public void testBuildSimpleAnd() {
LdapQuery query = query()
.base("dc=261consulting, dc=com")
.searchScope(SearchScope.ONELEVEL)
.timeLimit(200)
.countLimit(221)
.where("objectclass").is("person").and("cn").is("John Doe");
assertEquals(LdapUtils.newLdapName("dc=261consulting, dc=com"), query.base());
assertEquals(SearchScope.ONELEVEL, query.searchScope());
assertEquals(Integer.valueOf(200), query.timeLimit());
assertEquals(Integer.valueOf(221), query.countLimit());
assertEquals("(&(objectclass=person)(cn=John Doe))", query.filter().encode());
}
@Test
public void buildSimpleOr() {
LdapQuery result = query().where("objectclass").is("person").or("cn").is("John Doe");
assertEquals("(|(objectclass=person)(cn=John Doe))", result.filter().encode());
}
@Test
public void buildAndOrPrecedence() {
LdapQuery result = query().where("objectclass").is("person")
.and("cn").is("John Doe")
.or(query().where("sn").is("Doe"));
assertEquals("(|(&(objectclass=person)(cn=John Doe))(sn=Doe))", result.filter().encode());
}
@Test
public void buildOrNegatedSubQueries() {
LdapQuery result = query().where("objectclass").not().is("person").or("sn").not().is("Doe");
assertEquals("(|(!(objectclass=person))(!(sn=Doe)))", result.filter().encode());
}
@Test
public void buildNestedAnd() {
LdapQuery result = query()
.where("objectclass").is("person")
.and(query()
.where("sn").is("Doe")
.or("sn").like("Die"));
assertEquals("(&(objectclass=person)(|(sn=Doe)(sn=Die)))", result.filter().encode());
}
@Test(expected = IllegalStateException.class)
public void verifyEmptyFilterThrowsIllegalState() {
query().filter();
}
@Test(expected = IllegalStateException.class)
public void verifyThatNewAttemptToStartSpecifyingFilterThrowsIllegalState() {
LdapQueryBuilder query = query();
query.where("sn").is("Doe");
query.where("cn").is("John Doe");
}
@Test(expected = IllegalStateException.class)
public void verifyThatAttemptToStartSpecifyingBasePropertiesThrowsIllegalStateWhenFilterStarted() {
LdapQueryBuilder query = query();
query.where("sn").is("Doe");
query.base("dc=261consulting,dc=com");
}
@Test(expected = IllegalStateException.class)
public void verifyThatOperatorChangeIsIllegal() {
query().where("cn").is("John Doe").and("sn").is("Doe").or("objectclass").is("person");
}
}
| wilkinsona/spring-ldap | core/src/test/java/org/springframework/ldap/query/LdapQueryBuilderTest.java | Java | apache-2.0 | 5,371 |
/*
* 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.cassandra.net;
import java.io.*;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataInputBuffer;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.streaming.messages.StreamMessage;
/*
* As of version 4.0 the endpoint description includes a port number as an unsigned short
*/
public class CompactEndpointSerializationHelper implements IVersionedSerializer<InetAddressAndPort>
{
public static final IVersionedSerializer<InetAddressAndPort> instance = new CompactEndpointSerializationHelper();
/**
* Streaming uses its own version numbering so we need to ignore it and always use currrent version.
* There is no cross version streaming so it will always use the latest address serialization.
**/
public static final IVersionedSerializer<InetAddressAndPort> streamingInstance = new IVersionedSerializer<InetAddressAndPort>()
{
public void serialize(InetAddressAndPort inetAddressAndPort, DataOutputPlus out, int version) throws IOException
{
instance.serialize(inetAddressAndPort, out, MessagingService.current_version);
}
public InetAddressAndPort deserialize(DataInputPlus in, int version) throws IOException
{
return instance.deserialize(in, MessagingService.current_version);
}
public long serializedSize(InetAddressAndPort inetAddressAndPort, int version)
{
return instance.serializedSize(inetAddressAndPort, MessagingService.current_version);
}
};
private CompactEndpointSerializationHelper() {}
public void serialize(InetAddressAndPort endpoint, DataOutputPlus out, int version) throws IOException
{
if (version >= MessagingService.VERSION_40)
{
byte[] buf = endpoint.addressBytes;
out.writeByte(buf.length + 2);
out.write(buf);
out.writeShort(endpoint.port);
}
else
{
byte[] buf = endpoint.addressBytes;
out.writeByte(buf.length);
out.write(buf);
}
}
public InetAddressAndPort deserialize(DataInputPlus in, int version) throws IOException
{
int size = in.readByte() & 0xFF;
switch(size)
{
//The original pre-4.0 serialiation of just an address
case 4:
case 16:
{
byte[] bytes = new byte[size];
in.readFully(bytes, 0, bytes.length);
return InetAddressAndPort.getByAddress(bytes);
}
//Address and one port
case 6:
case 18:
{
byte[] bytes = new byte[size - 2];
in.readFully(bytes);
int port = in.readShort() & 0xFFFF;
return InetAddressAndPort.getByAddressOverrideDefaults(InetAddress.getByAddress(bytes), bytes, port);
}
default:
throw new AssertionError("Unexpected size " + size);
}
}
public long serializedSize(InetAddressAndPort from, int version)
{
//4.0 includes a port number
if (version >= MessagingService.VERSION_40)
{
if (from.address instanceof Inet4Address)
return 1 + 4 + 2;
assert from.address instanceof Inet6Address;
return 1 + 16 + 2;
}
else
{
if (from.address instanceof Inet4Address)
return 1 + 4;
assert from.address instanceof Inet6Address;
return 1 + 16;
}
}
}
| josh-mckenzie/cassandra | src/java/org/apache/cassandra/net/CompactEndpointSerializationHelper.java | Java | apache-2.0 | 4,689 |
/**
* 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.storm.topology;
import org.apache.storm.state.State;
/**
* A windowed bolt abstraction for supporting windowing operation with state.
*/
public interface IStatefulWindowedBolt<T extends State> extends IStatefulComponent<T>, IWindowedBolt {
/**
* If the stateful windowed bolt should have its windows persisted in state and maintain a subset
* of events in memory.
* <p>
* The default is to keep all the window events in memory.
* </p>
*
* @return true if the windows should be persisted
*/
default boolean isPersistent() {
return false;
}
/**
* The maximum number of window events to keep in memory.
*/
default long maxEventsInMemory() {
return 1_000_000L; // default
}
}
| sakanaou/storm | storm-client/src/jvm/org/apache/storm/topology/IStatefulWindowedBolt.java | Java | apache-2.0 | 1,590 |
/*
* Copyright 2006 Sascha Weinreuter
*
* 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.intellij.plugins.intelliLang.inject.config.ui;
import com.intellij.CommonBundle;
import com.intellij.ide.util.TreeClassChooser;
import com.intellij.ide.util.TreeClassChooserFactory;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.event.DocumentListener;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiFormatUtil;
import com.intellij.psi.util.PsiFormatUtilBase;
import com.intellij.ui.*;
import com.intellij.ui.dualView.TreeTableView;
import com.intellij.ui.treeStructure.treetable.ListTreeTableModelOnColumns;
import com.intellij.ui.treeStructure.treetable.TreeColumnInfo;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.tree.TreeUtil;
import org.intellij.plugins.intelliLang.IntelliLangBundle;
import org.intellij.plugins.intelliLang.inject.config.MethodParameterInjection;
import org.intellij.plugins.intelliLang.util.PsiUtilEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.*;
public final class MethodParameterPanel extends AbstractInjectionPanel<MethodParameterInjection> {
LanguagePanel myLanguagePanel; // read by reflection
AdvancedPanel myAdvancedPanel;
private JPanel myRoot;
private JPanel myClassPanel;
private TreeTableView myParamsTable;
private final ReferenceEditorWithBrowseButton myClassField;
private DefaultMutableTreeNode myRootNode;
private final Map<PsiMethod, MethodParameterInjection.MethodInfo> myData = new HashMap<>();
public MethodParameterPanel(MethodParameterInjection injection, final Project project) {
super(injection, project);
$$$setupUI$$$();
myClassField = new ReferenceEditorWithBrowseButton(new BrowseClassListener(project), project, s -> {
final Document document = PsiUtilEx.createDocument(s, project);
document.addDocumentListener(new DocumentListener() {
@Override
public void documentChanged(@NotNull final DocumentEvent e) {
updateParamTree();
updateInjectionPanelTree();
}
});
return document;
}, "");
myClassPanel.add(myClassField, BorderLayout.CENTER);
myParamsTable.setTableHeader(null);
myParamsTable.getTree().setShowsRootHandles(true);
myParamsTable.getTree().setCellRenderer(new ColoredTreeCellRenderer() {
@Override
public void customizeCellRenderer(@NotNull JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
final Object o = ((DefaultMutableTreeNode)value).getUserObject();
setIcon(o instanceof PsiMethod ? PlatformIcons.METHOD_ICON : o instanceof PsiParameter ? PlatformIcons.PARAMETER_ICON : null);
final String name;
if (o instanceof PsiMethod) {
name = PsiFormatUtil.formatMethod((PsiMethod)o, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS,
PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_TYPE);
}
else if (o instanceof PsiParameter) {
name = PsiFormatUtil.formatVariable((PsiParameter)o, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_TYPE, PsiSubstitutor.EMPTY);
}
else name = null;
final boolean missing = o instanceof PsiElement && !((PsiElement)o).isPhysical();
if (name != null) {
append(name, missing? SimpleTextAttributes.ERROR_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
}
}
});
init(injection.copy());
new TreeTableSpeedSearch(myParamsTable, o -> {
final Object userObject = ((DefaultMutableTreeNode)o.getLastPathComponent()).getUserObject();
return userObject instanceof PsiNamedElement? ((PsiNamedElement)userObject).getName() : null;
});
new AnAction(CommonBundle.message("action.text.toggle")) {
@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
performToggleAction();
}
}.registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0)), myParamsTable);
}
private void updateInjectionPanelTree() {
updateTree();
}
private void performToggleAction() {
final Collection<DefaultMutableTreeNode> selectedInjections = myParamsTable.getSelection();
boolean enabledExists = false;
boolean disabledExists = false;
for (DefaultMutableTreeNode node : selectedInjections) {
final Boolean nodeSelected = isNodeSelected(node);
if (Boolean.TRUE == nodeSelected) enabledExists = true;
else if (Boolean.FALSE == nodeSelected) disabledExists = true;
if (enabledExists && disabledExists) break;
}
boolean allEnabled = !enabledExists && disabledExists;
for (DefaultMutableTreeNode node : selectedInjections) {
setNodeSelected(node, allEnabled);
}
myParamsTable.updateUI();
}
@Nullable
private PsiType getClassType() {
final Document document = myClassField.getEditorTextField().getDocument();
final PsiDocumentManager dm = PsiDocumentManager.getInstance(myProject);
dm.commitDocument(document);
final PsiFile psiFile = dm.getPsiFile(document);
if (psiFile == null) return null;
try {
return ((PsiTypeCodeFragment)psiFile).getType();
}
catch (PsiTypeCodeFragment.TypeSyntaxException | PsiTypeCodeFragment.NoTypeException e1) {
return null;
}
}
private void setPsiClass(String name) {
myClassField.setText(name);
}
private void updateParamTree() {
rebuildTreeModel();
refreshTreeStructure();
}
private void rebuildTreeModel() {
myData.clear();
ApplicationManager.getApplication().runReadAction(() -> {
final PsiType classType = getClassType();
final PsiClass[] classes = classType instanceof PsiClassType? JavaPsiFacade.getInstance(myProject).
findClasses(classType.getCanonicalText(), GlobalSearchScope.allScope(myProject)) : PsiClass.EMPTY_ARRAY;
if (classes.length == 0) return;
final Set<String> visitedSignatures = new HashSet<>();
for (PsiClass psiClass : classes) {
for (PsiMethod method : psiClass.getMethods()) {
final PsiModifierList modifiers = method.getModifierList();
if (modifiers.hasModifierProperty(PsiModifier.PRIVATE) || modifiers.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) continue;
if (MethodParameterInjection.isInjectable(method.getReturnType(), method.getProject()) ||
ContainerUtil.find(method.getParameterList().getParameters(),
p -> MethodParameterInjection.isInjectable(p.getType(), p.getProject())) != null) {
final MethodParameterInjection.MethodInfo info = MethodParameterInjection.createMethodInfo(method);
if (!visitedSignatures.add(info.getMethodSignature())) continue;
myData.put(method, info);
}
}
}
});
}
private void refreshTreeStructure() {
myRootNode.removeAllChildren();
final ArrayList<PsiMethod> methods = new ArrayList<>(myData.keySet());
methods.sort(Comparator.comparing(PsiMethod::getName).thenComparingInt(o -> o.getParameterList().getParametersCount()));
for (PsiMethod method : methods) {
final PsiParameter[] params = method.getParameterList().getParameters();
final DefaultMutableTreeNode methodNode = new DefaultMutableTreeNode(method, true);
myRootNode.add(methodNode);
for (final PsiParameter parameter : params) {
methodNode.add(new DefaultMutableTreeNode(parameter, false));
}
}
final ListTreeTableModelOnColumns tableModel = (ListTreeTableModelOnColumns)myParamsTable.getTableModel();
tableModel.reload();
TreeUtil.expandAll(myParamsTable.getTree());
myParamsTable.revalidate();
}
private String getClassName() {
final PsiType type = getClassType();
if (type == null) {
return myClassField.getText();
}
return type.getCanonicalText();
}
@Override
protected void apply(final MethodParameterInjection other) {
final boolean applyMethods = ReadAction.compute(() -> {
other.setClassName(getClassName());
return getClassType() != null;
}).booleanValue();
if (applyMethods) {
other.setMethodInfos(ContainerUtil.findAll(myData.values(), methodInfo -> methodInfo.isEnabled()));
}
}
@Override
protected void resetImpl() {
setPsiClass(myOrigInjection.getClassName());
rebuildTreeModel();
final Map<String, MethodParameterInjection.MethodInfo> map = new HashMap<>();
for (PsiMethod method : myData.keySet()) {
final MethodParameterInjection.MethodInfo methodInfo = myData.get(method);
map.put(methodInfo.getMethodSignature(), methodInfo);
}
for (MethodParameterInjection.MethodInfo info : myOrigInjection.getMethodInfos()) {
final MethodParameterInjection.MethodInfo curInfo = map.get(info.getMethodSignature());
if (curInfo != null) {
System.arraycopy(info.getParamFlags(), 0, curInfo.getParamFlags(), 0, Math.min(info.getParamFlags().length, curInfo.getParamFlags().length));
curInfo.setReturnFlag(info.isReturnFlag());
}
else {
final PsiMethod missingMethod = MethodParameterInjection.makeMethod(myProject, info.getMethodSignature());
myData.put(missingMethod, info.copy());
}
}
refreshTreeStructure();
final Enumeration enumeration = myRootNode.children();
while (enumeration.hasMoreElements()) {
PsiMethod method = (PsiMethod)((DefaultMutableTreeNode)enumeration.nextElement()).getUserObject();
assert myData.containsKey(method);
}
}
@Override
public JPanel getComponent() {
return myRoot;
}
private void createUIComponents() {
myLanguagePanel = new LanguagePanel(myProject, myOrigInjection);
myRootNode = new DefaultMutableTreeNode(null, true);
myParamsTable = new MyView(new ListTreeTableModelOnColumns(myRootNode, createColumnInfos()));
myAdvancedPanel = new AdvancedPanel(myProject, myOrigInjection);
}
@Nullable
private Boolean isNodeSelected(final DefaultMutableTreeNode o) {
final Object userObject = o.getUserObject();
if (userObject instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)userObject;
return MethodParameterInjection.isInjectable(method.getReturnType(), method.getProject()) ? myData.get(method).isReturnFlag() : null;
}
else if (userObject instanceof PsiParameter) {
final PsiMethod method = getMethodByNode(o);
final PsiParameter parameter = (PsiParameter)userObject;
final int index = method.getParameterList().getParameterIndex(parameter);
return MethodParameterInjection.isInjectable(parameter.getType(), method.getProject()) ? myData.get(method).getParamFlags()[index] : null;
}
return null;
}
private void setNodeSelected(final DefaultMutableTreeNode o, final boolean value) {
final Object userObject = o.getUserObject();
if (userObject instanceof PsiMethod) {
myData.get((PsiMethod)userObject).setReturnFlag(value);
}
else if (userObject instanceof PsiParameter) {
final PsiMethod method = getMethodByNode(o);
final int index = method.getParameterList().getParameterIndex((PsiParameter)userObject);
myData.get(method).getParamFlags()[index] = value;
}
}
private static PsiMethod getMethodByNode(final DefaultMutableTreeNode o) {
final Object userObject = o.getUserObject();
if (userObject instanceof PsiMethod) return (PsiMethod)userObject;
return (PsiMethod)((DefaultMutableTreeNode)o.getParent()).getUserObject();
}
private ColumnInfo[] createColumnInfos() {
return new ColumnInfo[]{
new ColumnInfo<DefaultMutableTreeNode, Boolean>(" ") { // "" for the first column's name isn't a good idea
final BooleanTableCellRenderer myRenderer = new BooleanTableCellRenderer();
@Override
public Boolean valueOf(DefaultMutableTreeNode o) {
return isNodeSelected(o);
}
@Override
public int getWidth(JTable table) {
return myRenderer.getPreferredSize().width;
}
@Override
public TableCellEditor getEditor(DefaultMutableTreeNode o) {
return new DefaultCellEditor(new JCheckBox());
}
@Override
public TableCellRenderer getRenderer(DefaultMutableTreeNode o) {
myRenderer.setEnabled(isCellEditable(o));
return myRenderer;
}
@Override
public void setValue(DefaultMutableTreeNode o, Boolean value) {
setNodeSelected(o, Boolean.TRUE.equals(value));
}
@Override
public Class<Boolean> getColumnClass() {
return Boolean.class;
}
@Override
public boolean isCellEditable(DefaultMutableTreeNode o) {
return valueOf(o) != null;
}
}, new TreeColumnInfo(" ")
};
}
private class BrowseClassListener implements ActionListener {
private final Project myProject;
BrowseClassListener(Project project) {
myProject = project;
}
@Override
public void actionPerformed(ActionEvent e) {
final TreeClassChooserFactory factory = TreeClassChooserFactory.getInstance(myProject);
final TreeClassChooser chooser = factory.createAllProjectScopeChooser(IntelliLangBundle.message("dialog.title.select.class"));
chooser.showDialog();
final PsiClass psiClass = chooser.getSelected();
if (psiClass != null) {
setPsiClass(psiClass.getQualifiedName());
updateParamTree();
updateInjectionPanelTree();
}
}
}
private static class MyView extends TreeTableView implements DataProvider {
MyView(ListTreeTableModelOnColumns treeTableModel) {
super(treeTableModel);
}
@Nullable
@Override
public Object getData(@NotNull String dataId) {
if (CommonDataKeys.PSI_ELEMENT.is(dataId)) {
Object userObject = TreeUtil.getUserObject(ContainerUtil.getFirstItem(getSelection()));
return userObject instanceof PsiElement ? userObject : null;
}
return null;
}
}
private void $$$setupUI$$$() {
}
}
| jwren/intellij-community | plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/config/ui/MethodParameterPanel.java | Java | apache-2.0 | 15,798 |
/*
* Copyright 2015 LG CNS.
*
* 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 scouter.server.plugin;
import scouter.lang.pack.XLogPack;
public interface IServiceGroup extends IPlugIn{
public int grouping(XLogPack p);
} | jahnaviancha/scouter | scouter.server/src/scouter/server/plugin/IServiceGroup.java | Java | apache-2.0 | 759 |
package org.bouncycastle.asn1.x500;
import org.bouncycastle.asn1.ASN1Choice;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1String;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERBMPString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERT61String;
import org.bouncycastle.asn1.DERUTF8String;
import org.bouncycastle.asn1.DERUniversalString;
public class DirectoryString
extends ASN1Object
implements ASN1Choice, ASN1String
{
private ASN1String string;
public static DirectoryString getInstance(Object o)
{
if (o == null || o instanceof DirectoryString)
{
return (DirectoryString)o;
}
if (o instanceof DERT61String)
{
return new DirectoryString((DERT61String)o);
}
if (o instanceof DERPrintableString)
{
return new DirectoryString((DERPrintableString)o);
}
if (o instanceof DERUniversalString)
{
return new DirectoryString((DERUniversalString)o);
}
if (o instanceof DERUTF8String)
{
return new DirectoryString((DERUTF8String)o);
}
if (o instanceof DERBMPString)
{
return new DirectoryString((DERBMPString)o);
}
throw new IllegalArgumentException("illegal object in getInstance: " + o.getClass().getName());
}
public static DirectoryString getInstance(ASN1TaggedObject o, boolean explicit)
{
if (!explicit)
{
throw new IllegalArgumentException("choice item must be explicitly tagged");
}
return getInstance(o.getObject());
}
private DirectoryString(
DERT61String string)
{
this.string = string;
}
private DirectoryString(
DERPrintableString string)
{
this.string = string;
}
private DirectoryString(
DERUniversalString string)
{
this.string = string;
}
private DirectoryString(
DERUTF8String string)
{
this.string = string;
}
private DirectoryString(
DERBMPString string)
{
this.string = string;
}
public DirectoryString(String string)
{
this.string = new DERUTF8String(string);
}
public String getString()
{
return string.getString();
}
public String toString()
{
return string.getString();
}
/**
* <pre>
* DirectoryString ::= CHOICE {
* teletexString TeletexString (SIZE (1..MAX)),
* printableString PrintableString (SIZE (1..MAX)),
* universalString UniversalString (SIZE (1..MAX)),
* utf8String UTF8String (SIZE (1..MAX)),
* bmpString BMPString (SIZE (1..MAX)) }
* </pre>
*/
public ASN1Primitive toASN1Primitive()
{
return ((ASN1Encodable)string).toASN1Primitive();
}
}
| sake/bouncycastle-java | src/org/bouncycastle/asn1/x500/DirectoryString.java | Java | mit | 3,136 |
/**
* Copyright (c) 2010-2019 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.rfxcom.internal.messages;
import org.eclipse.smarthome.config.discovery.DiscoveryResultBuilder;
import org.eclipse.smarthome.core.types.State;
import org.openhab.binding.rfxcom.internal.config.RFXComDeviceConfiguration;
import org.openhab.binding.rfxcom.internal.exceptions.RFXComException;
import org.openhab.binding.rfxcom.internal.exceptions.RFXComUnsupportedChannelException;
import org.openhab.binding.rfxcom.internal.exceptions.RFXComUnsupportedValueException;
/**
* An interface for message about devices, so interface message do not (have to) implement this
*
* @author Martin van Wingerden - Simplify some code in the RFXCOM binding
*/
public interface RFXComDeviceMessage<T> extends RFXComMessage {
/**
* Procedure for converting RFXCOM value to openHAB state.
*
* @param channelId id of the channel
* @return openHAB state.
* @throws RFXComUnsupportedChannelException if the channel is not supported
*/
State convertToState(String channelId) throws RFXComUnsupportedChannelException;
/**
* Procedure to get device id.
*
* @return device Id.
*/
String getDeviceId();
/**
* Get the packet type for this device message
*
* @return the message its packet type
*/
RFXComBaseMessage.PacketType getPacketType();
/**
* Given a DiscoveryResultBuilder add any new properties to the builder for the given message
*
* @param discoveryResultBuilder existing builder containing some early details
* @throws RFXComException
*/
void addDevicePropertiesTo(DiscoveryResultBuilder discoveryResultBuilder) throws RFXComException;
/**
* Procedure for converting sub type as string to sub type object.
*
* @param subType
* @return sub type object.
* @throws RFXComUnsupportedValueException if the given subType cannot be converted
*/
T convertSubType(String subType) throws RFXComUnsupportedValueException;
/**
* Procedure to set sub type.
*
* @param subType
*/
void setSubType(T subType);
/**
* Procedure to set device id.
*
* @param deviceId
* @throws RFXComException
*/
void setDeviceId(String deviceId) throws RFXComException;
/**
* Set the config to be applied to this message
*
* @param config
* @throws RFXComException
*/
@Override
void setConfig(RFXComDeviceConfiguration config) throws RFXComException;
}
| theoweiss/openhab2 | bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComDeviceMessage.java | Java | epl-1.0 | 2,888 |
package com.dotmarketing.portlets.workflows.actionlet;
import java.util.List;
import java.util.Map;
import com.dotmarketing.business.APILocator;
import com.dotmarketing.exception.DotDataException;
import com.dotmarketing.portlets.workflows.model.WorkflowActionClassParameter;
import com.dotmarketing.portlets.workflows.model.WorkflowActionFailureException;
import com.dotmarketing.portlets.workflows.model.WorkflowActionletParameter;
import com.dotmarketing.portlets.workflows.model.WorkflowProcessor;
import com.dotmarketing.portlets.workflows.model.WorkflowTask;
import com.dotmarketing.util.Logger;
public class ResetTaskActionlet extends WorkFlowActionlet {
/**
*
*/
private static final long serialVersionUID = -3399186955215452961L;
@Override
public String getName() {
return "Reset Workflow";
}
@Override
public String getHowTo() {
return "This actionlet will complety delete all workflow task information, including history for the content item and reset the content items workflow state. It will also STOP all further subaction processing";
}
@Override
public void executeAction(WorkflowProcessor processor,Map<String,WorkflowActionClassParameter> params) throws WorkflowActionFailureException {
WorkflowTask task = processor.getTask();
task.setStatus(null);
try {
APILocator.getWorkflowAPI().deleteWorkflowTask(task);
processor.setTask(null);
} catch (DotDataException e) {
Logger.error(ResetTaskActionlet.class,e.getMessage(),e);
}
}
@Override
public boolean stopProcessing() {
return true;
}
@Override
public List<WorkflowActionletParameter> getParameters() {
return null;
}
}
| zhiqinghuang/core | src/com/dotmarketing/portlets/workflows/actionlet/ResetTaskActionlet.java | Java | gpl-3.0 | 1,657 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.