gt
stringclasses
1 value
context
stringlengths
2.05k
161k
// Copyright 2016 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.rules.objc; import static com.google.devtools.build.lib.rules.objc.AppleWatch1ExtensionRule.WATCH_APP_DEPS_ATTR; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.FLAG; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.Flag.HAS_WATCH1_EXTENSION; import static com.google.devtools.build.lib.rules.objc.ObjcProvider.MERGE_ZIP; import static com.google.devtools.build.lib.rules.objc.ObjcRuleClasses.WatchApplicationBundleRule.WATCH_APP_NAME_ATTR; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.RuleConfiguredTarget.Mode; import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.config.BuildOptions; import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder; import com.google.devtools.build.lib.packages.Attribute.SplitTransition; import com.google.devtools.build.lib.rules.RuleConfiguredTargetFactory; import com.google.devtools.build.lib.rules.objc.IosExtension.ExtensionSplitArchTransition; import com.google.devtools.build.lib.rules.objc.ReleaseBundlingSupport.SplitArchTransition.ConfigurationDistinguisher; import com.google.devtools.build.lib.rules.objc.WatchUtils.WatchOSVersion; import com.google.devtools.build.lib.rules.test.InstrumentedFilesCollector; import com.google.devtools.build.lib.rules.test.InstrumentedFilesProvider; import com.google.devtools.build.lib.syntax.Type; /** * Implementation for {@code apple_watch1_extension}. */ public class AppleWatch1Extension implements RuleConfiguredTargetFactory { static final SplitTransition<BuildOptions> MINIMUM_OS_AND_SPLIT_ARCH_TRANSITION = new ExtensionSplitArchTransition(WatchUtils.MINIMUM_OS_VERSION, ConfigurationDistinguisher.WATCH_OS1_EXTENSION); private static final ImmutableSet<Attribute> extensionDependencyAttributes = ImmutableSet.of(new Attribute("binary", Mode.SPLIT)); private static final ImmutableSet<Attribute> applicationDependencyAttributes = ImmutableSet.of(new Attribute(WATCH_APP_DEPS_ATTR, Mode.SPLIT)); @Override public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException { ObjcProvider.Builder applicationObjcProviderBuilder = new ObjcProvider.Builder(); ObjcProvider.Builder extensionObjcProviderBuilder = new ObjcProvider.Builder(); XcodeProvider.Builder applicationXcodeProviderBuilder = new XcodeProvider.Builder(); XcodeProvider.Builder extensionXcodeProviderBuilder = new XcodeProvider.Builder(); NestedSetBuilder<Artifact> applicationFilesToBuild = NestedSetBuilder.stableOrder(); NestedSetBuilder<Artifact> extensionfilesToBuild = NestedSetBuilder.stableOrder(); // 1. Build watch application bundle. createWatchApplicationBundle(ruleContext, applicationXcodeProviderBuilder, applicationObjcProviderBuilder, applicationFilesToBuild); // 2. Build watch extension bundle. createWatchExtensionBundle(ruleContext, extensionXcodeProviderBuilder, applicationXcodeProviderBuilder, extensionObjcProviderBuilder, extensionfilesToBuild); // 3. Extract the watch application bundle into the extension bundle. registerWatchApplicationUnBundlingAction(ruleContext); RuleConfiguredTargetBuilder targetBuilder = ObjcRuleClasses.ruleConfiguredTarget(ruleContext, extensionfilesToBuild.build()) .addProvider(XcodeProvider.class, extensionXcodeProviderBuilder.build()) .addProvider( InstrumentedFilesProvider.class, InstrumentedFilesCollector.forward(ruleContext, "binary")); // 4. Exposed {@ObjcProvider} for bundling into final IPA. exposeObjcProvider(ruleContext, targetBuilder); return targetBuilder.build(); } /** * Exposes an {@link ObjcProvider} with the following to create the final IPA: * 1. Watch extension bundle. * 2. WatchKitSupport. * 3. A flag to indicate that watch os 1 extension is included. */ private void exposeObjcProvider(RuleContext ruleContext, RuleConfiguredTargetBuilder targetBuilder) throws InterruptedException { ObjcProvider.Builder exposedObjcProviderBuilder = new ObjcProvider.Builder(); exposedObjcProviderBuilder.add(MERGE_ZIP, ruleContext.getImplicitOutputArtifact(ReleaseBundlingSupport.IPA)); WatchUtils.registerActionsToAddWatchSupport(ruleContext, exposedObjcProviderBuilder, WatchOSVersion.OS1); exposedObjcProviderBuilder.add(FLAG, HAS_WATCH1_EXTENSION); targetBuilder.addProvider(ObjcProvider.class, exposedObjcProviderBuilder.build()); } /** * Creates a watch extension bundle. * * @param ruleContext rule context in which to create the bundle * @param extensionXcodeProviderBuilder {@link XcodeProvider.Builder} for the extension * @param applicationXcodeProviderBuilder {@link XcodeProvider.Builder} for the watch application * which is added as a dependency to the extension * @param objcProviderBuilder {@link ObjcProvider.Builder} for the extension * @param filesToBuild the list to contain the files to be built for this extension bundle */ private void createWatchExtensionBundle(RuleContext ruleContext, XcodeProvider.Builder extensionXcodeProviderBuilder, XcodeProvider.Builder applicationXcodeProviderBuilder, ObjcProvider.Builder objcProviderBuilder, NestedSetBuilder<Artifact> filesToBuild) throws InterruptedException { new WatchExtensionSupport(ruleContext, WatchOSVersion.OS1, extensionDependencyAttributes, ObjcRuleClasses.intermediateArtifacts(ruleContext), watchExtensionBundleName(ruleContext), watchExtensionIpaArtifact(ruleContext), watchApplicationBundle(ruleContext), applicationXcodeProviderBuilder.build(), ConfigurationDistinguisher.WATCH_OS1_EXTENSION) .createBundle(filesToBuild, objcProviderBuilder, extensionXcodeProviderBuilder); } /** * Creates a watch application bundle. * * @param ruleContext rule context in which to create the bundle * @param xcodeProviderBuilder {@link XcodeProvider.Builder} for the application * @param objcProviderBuilder {@link ObjcProvider.Builder} for the application * @param filesToBuild the list to contain the files to be built for this bundle */ private void createWatchApplicationBundle(RuleContext ruleContext, XcodeProvider.Builder xcodeProviderBuilder, ObjcProvider.Builder objcProviderBuilder, NestedSetBuilder<Artifact> filesToBuild) throws InterruptedException { new WatchApplicationSupport(ruleContext, WatchOSVersion.OS1, applicationDependencyAttributes, new IntermediateArtifacts(ruleContext, "", watchApplicationBundleName(ruleContext)), watchApplicationBundleName(ruleContext), watchApplicationIpaArtifact(ruleContext), watchApplicationBundleName(ruleContext), ConfigurationDistinguisher.WATCH_OS1_EXTENSION) .createBundle(xcodeProviderBuilder, objcProviderBuilder, filesToBuild); } /** * Registers action to extract the watch application ipa (after signing if required) to the * extension bundle. * * For example, TestWatchApp.ipa will be unbundled into, * PlugIns/TestWatchExtension.appex * PlugIns/TestWatchExtension.appex/TestWatchApp.app */ private void registerWatchApplicationUnBundlingAction(RuleContext ruleContext) { Artifact watchApplicationIpa = watchApplicationIpaArtifact(ruleContext); Artifact watchApplicationBundle = watchApplicationBundle(ruleContext); String workingDirectory = watchApplicationBundle.getExecPathString().substring(0, watchApplicationBundle.getExecPathString().lastIndexOf('/')); ImmutableList<String> command = ImmutableList.of( "mkdir -p " + workingDirectory, "&&", String.format("/usr/bin/unzip -q -o %s -d %s", watchApplicationIpa.getExecPathString(), workingDirectory), "&&", String.format("cd %s/Payload", workingDirectory), "&&", String.format("/usr/bin/zip -q -r -0 ../%s *", watchApplicationBundle.getFilename())); ruleContext.registerAction( ObjcRuleClasses.spawnOnDarwinActionBuilder() .setProgressMessage("Extracting watch app: " + ruleContext.getLabel()) .setShellCommand(ImmutableList.of("/bin/bash", "-c", Joiner.on(" ").join(command))) .addInput(watchApplicationIpa) .addOutput(watchApplicationBundle) .build(ruleContext)); } /** * Returns a zip {@Artifact} containing extracted watch application - "TestWatchApp.app" * which is to be merged into the extension bundle. */ private Artifact watchApplicationBundle(RuleContext ruleContext) { return ruleContext.getRelatedArtifact(ruleContext.getUniqueDirectory( "_watch"), String.format("/%s", watchApplicationIpaArtifact(ruleContext) .getFilename().replace(".ipa", ".zip"))); } /** * Returns the {@Artifact} containing final watch application bundle. */ private Artifact watchApplicationIpaArtifact(RuleContext ruleContext) { return ruleContext.getRelatedArtifact(ruleContext.getUniqueDirectory("_watch"), String.format("/%s.ipa", watchApplicationBundleName(ruleContext))); } /** * Returns the {@Artifact} containing final watch extension bundle. */ private Artifact watchExtensionIpaArtifact(RuleContext ruleContext) throws InterruptedException { return ruleContext.getImplicitOutputArtifact(ReleaseBundlingSupport.IPA); } private String watchApplicationBundleName(RuleContext ruleContext) { return ruleContext.attributes().get(WATCH_APP_NAME_ATTR, Type.STRING); } private String watchExtensionBundleName(RuleContext ruleContext) { return ruleContext.getLabel().getName(); } }
// Copyright Eagle Legacy Modernization, LLC, 2010-date // Original author: Steven A. O'Hara, Nov 3, 2015 package com.eagle.programmar.JavaP.Statements; import com.eagle.programmar.JavaP.JavaP_CodeBlock; import com.eagle.programmar.JavaP.JavaP_Syntax; import com.eagle.programmar.JavaP.JavaP_Value; import com.eagle.programmar.JavaP.Blocks.JavaP_CodeLineNumbers; import com.eagle.programmar.JavaP.Blocks.JavaP_CodeLocalValues; import com.eagle.programmar.JavaP.Statements.JavaP_Classes.JavaP_OneClass.JavaP_MethodArgument.JavaP_MethodArg.JavaP_EmptySubscript; import com.eagle.programmar.JavaP.Terminals.JavaP_EndOfLine; import com.eagle.programmar.JavaP.Terminals.JavaP_Identifier; import com.eagle.programmar.JavaP.Terminals.JavaP_Keyword; import com.eagle.programmar.JavaP.Terminals.JavaP_KeywordChoice; import com.eagle.programmar.JavaP.Terminals.JavaP_Punctuation; import com.eagle.programmar.JavaP.Terminals.JavaP_QualifiedName; import com.eagle.programmar.JavaP.Terminals.JavaP_RestOfLine; import com.eagle.tokens.SeparatedList; import com.eagle.tokens.TokenChooser; import com.eagle.tokens.TokenList; import com.eagle.tokens.TokenSequence; import com.eagle.tokens.punctuation.PunctuationColon; import com.eagle.tokens.punctuation.PunctuationComma; import com.eagle.tokens.punctuation.PunctuationLeftBrace; import com.eagle.tokens.punctuation.PunctuationLeftBracket; import com.eagle.tokens.punctuation.PunctuationLeftParen; import com.eagle.tokens.punctuation.PunctuationRightBrace; import com.eagle.tokens.punctuation.PunctuationRightBracket; import com.eagle.tokens.punctuation.PunctuationRightParen; import com.eagle.tokens.punctuation.PunctuationSemicolon; public class JavaP_Classes extends TokenSequence { public PunctuationLeftBrace leftBrace; public JavaP_EndOfLine eoln1; public @OPT TokenList<JavaP_OneClass> oneClass; public PunctuationRightBrace rightBrace; public JavaP_EndOfLine eoln2; public static class JavaP_OneClass extends TokenSequence { public @OPT TokenList<JavaP_Modifier> modifier; public JavaP_OneClassHeader header; public PunctuationSemicolon semicolon; public JavaP_EndOfLine eoln1; public TokenList<JavaP_OneClassParameter> parameters; public @OPT JavaP_EndOfLine eoln2; public static class JavaP_OneClassHeader extends TokenChooser { public @CHOICE static class JavaP_OneClassRegularHeader extends TokenSequence { public JavaP_QualifiedName type; public @OPT JavaP_OneClassGeneric generic; public @OPT JavaP_EmptySubscript subscript; public JavaP_OneClassWhat what; } public @CHOICE static class JavaP_OneClassStaticHeader extends TokenSequence { public PunctuationLeftBrace leftBrace; public PunctuationRightBrace rightBrace; } } public static class JavaP_Modifier extends TokenSequence { public JavaP_KeywordChoice PUBLIC = new JavaP_KeywordChoice( "abstract", "final", "private", "protected", "public", "static", "synchronized" ); } public static class JavaP_OneClassWhat extends TokenChooser { public @LAST JavaP_QualifiedName data; public @CHOICE static class JavaP_OneClassMethod extends TokenSequence { public @OPT JavaP_QualifiedName name; public PunctuationLeftParen leftParen; public @OPT SeparatedList<JavaP_MethodArgument, PunctuationComma> params; public PunctuationRightParen rightParen; public @OPT JavaP_OneClassThrows classThrows; public static class JavaP_OneClassThrows extends TokenSequence { public JavaP_Keyword THROWS = new JavaP_Keyword("throws"); public SeparatedList<JavaP_QualifiedName,PunctuationComma> name; } } } public static class JavaP_MethodArgument extends TokenChooser { public @CHOICE JavaP_Punctuation question = new JavaP_Punctuation('?'); public @CHOICE static class JavaP_MethodArg extends TokenSequence { public @OPT JavaP_QuestionExtends question; public @OPT JavaP_TypeExtends type; public JavaP_QualifiedName name; public @OPT JavaP_OneClassGeneric generic; public @OPT JavaP_EmptySubscript subscript; public static class JavaP_QuestionExtends extends TokenSequence { public JavaP_Punctuation question = new JavaP_Punctuation('?'); public JavaP_Keyword EXTENDS = new JavaP_Keyword("extends"); } public static class JavaP_TypeExtends extends TokenSequence { public JavaP_Identifier typeName; public JavaP_Keyword EXTENDS = new JavaP_Keyword("extends"); } public static class JavaP_EmptySubscript extends TokenSequence { public PunctuationLeftBracket leftBracket; public PunctuationRightBracket rightBracket; } } } public static class JavaP_OneClassGeneric extends TokenSequence { public JavaP_Punctuation lessThan = new JavaP_Punctuation('<'); public SeparatedList<JavaP_MethodArgument,PunctuationComma> names; public JavaP_Punctuation greaterThan = new JavaP_Punctuation('>'); } public static class JavaP_OneClassParameter extends TokenChooser { public @CHOICE JavaP_CodeBlock code; public @CHOICE JavaP_Signature signature; public @CHOICE JavaP_RuntimeVisibleAnnotations runtimeAnnotation; public @CHOICE JavaP_CodeLineNumbers lineNumbers; public @CHOICE JavaP_CodeLocalValues localValues; public @CHOICE static class JavaP_OneClassDescriptor extends TokenSequence { public JavaP_Keyword DESCRIPTOR = new JavaP_Keyword("descriptor"); public PunctuationColon colon; public JavaP_Value value; public JavaP_EndOfLine eoln; } public @CHOICE static class JavaP_OneClassFlags extends TokenSequence { public JavaP_Keyword FLAGS = new JavaP_Keyword("flags"); public PunctuationColon colon; public @OPT SeparatedList<JavaP_OneClassFlag, PunctuationComma> flags; public JavaP_EndOfLine eoln; public static class JavaP_OneClassFlag extends TokenChooser { public @CHOICE JavaP_KeywordChoice ACC = new JavaP_KeywordChoice(JavaP_Syntax.ACC_CODES); } } public @CHOICE static class JavaP_OneClassConstantValue extends TokenSequence { public JavaP_KeywordChoice CONSTANTVALUE = new JavaP_KeywordChoice("Constant", "ConstantValue"); public @OPT JavaP_Keyword VALUE = new JavaP_Keyword("value"); public PunctuationColon colon; public JavaP_KeywordChoice type = new JavaP_KeywordChoice("int", "long", "String"); public JavaP_RestOfLine value; public JavaP_EndOfLine eoln; } public @CHOICE static class JavaP_OneClassExceptions extends TokenSequence { public JavaP_Keyword EXCEPTIONS = new JavaP_Keyword("Exceptions"); public PunctuationColon colon1; public JavaP_EndOfLine eoln1; public JavaP_Keyword THROWS = new JavaP_Keyword("throws"); public SeparatedList<JavaP_QualifiedName,PunctuationComma> name; public @OPT JavaP_EndOfLine eoln2; } public @CHOICE static class JavaP_OneClassMethodParameters extends TokenSequence { public JavaP_Keyword METHODPARAMETERS = new JavaP_Keyword("MethodParameters"); public PunctuationColon colon; public JavaP_EndOfLine eoln1; public JavaP_Keyword NAME = new JavaP_Keyword("Name"); public JavaP_Keyword FLAGS = new JavaP_Keyword("Flags"); public JavaP_EndOfLine eoln2; public @OPT TokenList<JavaP_OneClassMethodParameter> params; public static class JavaP_OneClassMethodParameter extends TokenSequence { public JavaP_QualifiedName name; public @OPT TokenList<JavaP_Value> values; public JavaP_EndOfLine eoln; } } } } }
/* * 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.cocoon.servlet.multipart; import java.io.IOException; import java.io.PushbackInputStream; /** * Utility class for MultipartParser. Divides the inputstream into parts * separated by a given boundary. * * A newline is espected after each boundary and is parsed away. * @version $Id$ */ class TokenStream extends PushbackInputStream { /** * Initial state, no boundary has been set. */ public static final int STATE_NOBOUNDARY = -1; /** * Fully read a part, now at the beginning of a new part */ public static final int STATE_NEXTPART = -2; /** * Read last boundary, end of multipart block */ public static final int STATE_ENDMULTIPART = -3; /** * End of stream, this should not happen */ public static final int STATE_ENDOFSTREAM = -4; /** * Currently reading a part */ public static final int STATE_READING = -5; /** Field in */ private PushbackInputStream in = null; /** Field boundary */ private byte[] boundary = null; /** Field state */ private int state = STATE_NOBOUNDARY; /** * Creates a new pushback token stream from in. * * @param in The input stream */ public TokenStream(PushbackInputStream in) { this(in,1); } /** * Creates a new pushback token stream from in. * * @param in The input stream * @param size Size (in bytes) of the pushback buffer */ public TokenStream(PushbackInputStream in, int size) { super(in,size); this.in = in; } /** * Sets the boundary to scan for * * @param boundary A byte array containg the boundary * * @throws MultipartException */ public void setBoundary(byte[] boundary) throws MultipartException { this.boundary = boundary; if (state == STATE_NOBOUNDARY) { state = STATE_READING; } } /** * Start reading the next part in the stream. This method may only be called * if state is STATE_NEXTPART. It will throw a MultipartException if not. * * @throws MultipartException */ public void nextPart() throws MultipartException { if (state != STATE_NEXTPART) { throw new MultipartException("Illegal state"); } state = STATE_READING; } /** * Return the stream state * */ public int getState() { return state; } /** * Fill the ouput buffer until either it's full, the boundary has been reached or * the end of the inputstream has been reached. * When a boundary is reached it is entirely read away including trailing \r's and \n's. * It will not be written to the output buffer. * The stream state is updated after each call. * * @param out The output buffer * * @throws IOException */ private int readToBoundary(byte[] out) throws IOException { if (state != STATE_READING) { return 0; } int boundaryIndex = 0; int written = 0; int b = in.read(); while (true) { while ((byte) b != boundary[0]) { if (b == -1) { state = STATE_ENDOFSTREAM; return written; } out[written++] = (byte) b; if (written == out.length) { return written; } b = in.read(); } boundaryIndex = 0; // we know the first byte matched // check for boundary while ((boundaryIndex < boundary.length) && ((byte) b == boundary[boundaryIndex])) { b = in.read(); boundaryIndex++; } if (boundaryIndex == boundary.length) { // matched boundary if (b != -1) { if (b == '\r') { // newline, another part follows state = STATE_NEXTPART; in.read(); } else if (b == '-') { // hyphen, end of multipart state = STATE_ENDMULTIPART; in.read(); // read next hyphen in.read(); // read \r in.read(); // read \n } else { // something else, error throw new IOException( "Unexpected character after boundary"); } } else { // nothing after boundary, this shouldn't happen either state = STATE_ENDOFSTREAM; } return written; } // did not match boundary // bytes skipped, write first skipped byte, push back the rest if (b != -1) { // b may be -1 in.unread(b); // the non-matching byte } in.unread(boundary, 1, boundaryIndex - 1); // unread skipped boundary data out[written++] = boundary[0]; if (written == out.length) { return written; } b = in.read(); } } /** * @see java.io.InputStream#read(byte[]) * * @param out * * @throws IOException */ public int read(byte[] out) throws IOException { if (state != STATE_READING) { return 0; } return readToBoundary(out); } /** * @see java.io.InputStream#read(byte[],int,int) * * @param out * @param off * @param len * * @throws IOException */ public int read(byte[] out, int off, int len) throws IOException { if ((off < 0) || (off >= out.length)) { throw new IOException("Buffer offset outside buffer"); } if (off + len >= out.length) { throw new IOException("Buffer end outside buffer"); } if (len < 0) { throw new IOException("Length must be a positive integer"); } byte[] buf = new byte[len]; int read = read(buf); if (read > 0) { System.arraycopy(buf, 0, out, off, read); } return read; } /** * @see java.io.InputStream#read() * * @throws IOException */ public int read() throws IOException { byte[] buf = new byte[1]; int read = read(buf); if (read == 0) { return -1; } return buf[0]; } }
/* * 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.streaming; import java.net.InetAddress; import java.nio.ByteBuffer; import java.sql.Date; import java.util.*; import java.util.concurrent.TimeUnit; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.OrderedJUnit4ClassRunner; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.Util; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.db.*; import org.apache.cassandra.db.columniterator.IdentityQueryFilter; import org.apache.cassandra.db.context.CounterContext; import org.apache.cassandra.db.filter.IDiskAtomFilter; import org.apache.cassandra.db.filter.QueryFilter; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.dht.Range; import org.apache.cassandra.dht.Token; import org.apache.cassandra.io.sstable.SSTableReader; import org.apache.cassandra.io.sstable.SSTableUtils; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.CounterId; import org.apache.cassandra.utils.FBUtilities; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.apache.cassandra.Util.cellname; import static org.apache.cassandra.Util.column; @RunWith(OrderedJUnit4ClassRunner.class) public class StreamingTransferTest extends SchemaLoader { private static final Logger logger = LoggerFactory.getLogger(StreamingTransferTest.class); public static final InetAddress LOCAL = FBUtilities.getBroadcastAddress(); @BeforeClass public static void setup() throws Exception { StorageService.instance.initServer(); } /** * Test if empty {@link StreamPlan} returns success with empty result. */ @Test public void testEmptyStreamPlan() throws Exception { StreamResultFuture futureResult = new StreamPlan("StreamingTransferTest").execute(); final UUID planId = futureResult.planId; Futures.addCallback(futureResult, new FutureCallback<StreamState>() { public void onSuccess(StreamState result) { assert planId.equals(result.planId); assert result.description.equals("StreamingTransferTest"); assert result.sessions.isEmpty(); } public void onFailure(Throwable t) { fail(); } }); // should be complete immediately futureResult.get(100, TimeUnit.MILLISECONDS); } @Test public void testRequestEmpty() throws Exception { // requesting empty data should succeed IPartitioner p = StorageService.getPartitioner(); List<Range<Token>> ranges = new ArrayList<>(); ranges.add(new Range<>(p.getMinimumToken(), p.getToken(ByteBufferUtil.bytes("key1")))); ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("key2")), p.getMinimumToken())); StreamResultFuture futureResult = new StreamPlan("StreamingTransferTest") .requestRanges(LOCAL, LOCAL, "Keyspace2", ranges) .execute(); UUID planId = futureResult.planId; StreamState result = futureResult.get(); assert planId.equals(result.planId); assert result.description.equals("StreamingTransferTest"); // we should have completed session with empty transfer assert result.sessions.size() == 1; SessionInfo session = Iterables.get(result.sessions, 0); assert session.peer.equals(LOCAL); assert session.getTotalFilesReceived() == 0; assert session.getTotalFilesSent() == 0; assert session.getTotalSizeReceived() == 0; assert session.getTotalSizeSent() == 0; } /** * Create and transfer a single sstable, and return the keys that should have been transferred. * The Mutator must create the given column, but it may also create any other columns it pleases. */ private List<String> createAndTransfer(ColumnFamilyStore cfs, Mutator mutator, boolean transferSSTables) throws Exception { // write a temporary SSTable, and unregister it logger.debug("Mutating " + cfs.name); long timestamp = 1234; for (int i = 1; i <= 3; i++) mutator.mutate("key" + i, "col" + i, timestamp); cfs.forceBlockingFlush(); Util.compactAll(cfs, Integer.MAX_VALUE).get(); assertEquals(1, cfs.getSSTables().size()); // transfer the first and last key logger.debug("Transferring " + cfs.name); int[] offs; if (transferSSTables) { SSTableReader sstable = cfs.getSSTables().iterator().next(); cfs.clearUnsafe(); transferSSTables(sstable); offs = new int[]{1, 3}; } else { long beforeStreaming = System.currentTimeMillis(); transferRanges(cfs); cfs.discardSSTables(beforeStreaming); offs = new int[]{2, 3}; } // confirm that a single SSTable was transferred and registered assertEquals(1, cfs.getSSTables().size()); // and that the index and filter were properly recovered List<Row> rows = Util.getRangeSlice(cfs); assertEquals(offs.length, rows.size()); for (int i = 0; i < offs.length; i++) { String key = "key" + offs[i]; String col = "col" + offs[i]; assert cfs.getColumnFamily(QueryFilter.getIdentityFilter(Util.dk(key), cfs.name, System.currentTimeMillis())) != null; assert rows.get(i).key.getKey().equals(ByteBufferUtil.bytes(key)); assert rows.get(i).cf.getColumn(cellname(col)) != null; } // and that the max timestamp for the file was rediscovered assertEquals(timestamp, cfs.getSSTables().iterator().next().getMaxTimestamp()); List<String> keys = new ArrayList<>(); for (int off : offs) keys.add("key" + off); logger.debug("... everything looks good for " + cfs.name); return keys; } private void transferSSTables(SSTableReader sstable) throws Exception { IPartitioner p = StorageService.getPartitioner(); List<Range<Token>> ranges = new ArrayList<>(); ranges.add(new Range<>(p.getMinimumToken(), p.getToken(ByteBufferUtil.bytes("key1")))); ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("key2")), p.getMinimumToken())); transfer(sstable, ranges); } private void transferRanges(ColumnFamilyStore cfs) throws Exception { IPartitioner p = StorageService.getPartitioner(); List<Range<Token>> ranges = new ArrayList<>(); // wrapped range ranges.add(new Range<Token>(p.getToken(ByteBufferUtil.bytes("key1")), p.getToken(ByteBufferUtil.bytes("key0")))); new StreamPlan("StreamingTransferTest").transferRanges(LOCAL, cfs.keyspace.getName(), ranges, cfs.getColumnFamilyName()).execute().get(); } private void transfer(SSTableReader sstable, List<Range<Token>> ranges) throws Exception { new StreamPlan("StreamingTransferTest").transferFiles(LOCAL, makeStreamingDetails(ranges, Arrays.asList(sstable))).execute().get(); } private Collection<StreamSession.SSTableStreamingSections> makeStreamingDetails(List<Range<Token>> ranges, Collection<SSTableReader> sstables) { ArrayList<StreamSession.SSTableStreamingSections> details = new ArrayList<>(); for (SSTableReader sstable : sstables) { details.add(new StreamSession.SSTableStreamingSections(sstable, sstable.getPositionsForRanges(ranges), sstable.estimatedKeysForRanges(ranges), sstable.getSSTableMetadata().repairedAt)); } return details; } private void doTransferTable(boolean transferSSTables) throws Exception { final Keyspace keyspace = Keyspace.open("Keyspace1"); final ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("Indexed1"); List<String> keys = createAndTransfer(cfs, new Mutator() { public void mutate(String key, String col, long timestamp) throws Exception { long val = key.hashCode(); ColumnFamily cf = ArrayBackedSortedColumns.factory.create(keyspace.getName(), cfs.name); cf.addColumn(column(col, "v", timestamp)); cf.addColumn(new BufferCell(cellname("birthdate"), ByteBufferUtil.bytes(val), timestamp)); Mutation rm = new Mutation("Keyspace1", ByteBufferUtil.bytes(key), cf); logger.debug("Applying row to transfer " + rm); rm.apply(); } }, transferSSTables); // confirm that the secondary index was recovered for (String key : keys) { long val = key.hashCode(); IndexExpression expr = new IndexExpression(ByteBufferUtil.bytes("birthdate"), IndexExpression.Operator.EQ, ByteBufferUtil.bytes(val)); List<IndexExpression> clause = Arrays.asList(expr); IDiskAtomFilter filter = new IdentityQueryFilter(); Range<RowPosition> range = Util.range("", ""); List<Row> rows = cfs.search(range, clause, filter, 100); assertEquals(1, rows.size()); assert rows.get(0).key.getKey().equals(ByteBufferUtil.bytes(key)); } } /** * Test to make sure RangeTombstones at column index boundary transferred correctly. */ @Test public void testTransferRangeTombstones() throws Exception { String ks = "Keyspace1"; String cfname = "StandardInteger1"; Keyspace keyspace = Keyspace.open(ks); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfname); String key = "key1"; Mutation rm = new Mutation(ks, ByteBufferUtil.bytes(key)); // add columns of size slightly less than column_index_size to force insert column index rm.add(cfname, cellname(1), ByteBuffer.wrap(new byte[DatabaseDescriptor.getColumnIndexSize() - 64]), 2); rm.add(cfname, cellname(6), ByteBuffer.wrap(new byte[DatabaseDescriptor.getColumnIndexSize()]), 2); ColumnFamily cf = rm.addOrGet(cfname); // add RangeTombstones cf.delete(new DeletionInfo(cellname(2), cellname(3), cf.getComparator(), 1, (int) (System.currentTimeMillis() / 1000))); cf.delete(new DeletionInfo(cellname(5), cellname(7), cf.getComparator(), 1, (int) (System.currentTimeMillis() / 1000))); rm.apply(); cfs.forceBlockingFlush(); SSTableReader sstable = cfs.getSSTables().iterator().next(); cfs.clearUnsafe(); transferSSTables(sstable); // confirm that a single SSTable was transferred and registered assertEquals(1, cfs.getSSTables().size()); List<Row> rows = Util.getRangeSlice(cfs); assertEquals(1, rows.size()); } @Test public void testTransferTableViaRanges() throws Exception { doTransferTable(false); } @Test public void testTransferTableViaSSTables() throws Exception { doTransferTable(true); } @Test public void testTransferTableCounter() throws Exception { final Keyspace keyspace = Keyspace.open("Keyspace1"); final ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("Counter1"); final CounterContext cc = new CounterContext(); final Map<String, ColumnFamily> cleanedEntries = new HashMap<>(); List<String> keys = createAndTransfer(cfs, new Mutator() { /** Creates a new SSTable per key: all will be merged before streaming. */ public void mutate(String key, String col, long timestamp) throws Exception { Map<String, ColumnFamily> entries = new HashMap<>(); ColumnFamily cf = ArrayBackedSortedColumns.factory.create(cfs.metadata); ColumnFamily cfCleaned = ArrayBackedSortedColumns.factory.create(cfs.metadata); CounterContext.ContextState state = CounterContext.ContextState.allocate(0, 1, 3); state.writeLocal(CounterId.fromInt(2), 9L, 3L); state.writeRemote(CounterId.fromInt(4), 4L, 2L); state.writeRemote(CounterId.fromInt(6), 3L, 3L); state.writeRemote(CounterId.fromInt(8), 2L, 4L); cf.addColumn(new BufferCounterCell(cellname(col), state.context, timestamp)); cfCleaned.addColumn(new BufferCounterCell(cellname(col), cc.clearAllLocal(state.context), timestamp)); entries.put(key, cf); cleanedEntries.put(key, cfCleaned); cfs.addSSTable(SSTableUtils.prepare() .ks(keyspace.getName()) .cf(cfs.name) .generation(0) .write(entries)); } }, true); // filter pre-cleaned entries locally, and ensure that the end result is equal cleanedEntries.keySet().retainAll(keys); SSTableReader cleaned = SSTableUtils.prepare() .ks(keyspace.getName()) .cf(cfs.name) .generation(0) .write(cleanedEntries); SSTableReader streamed = cfs.getSSTables().iterator().next(); SSTableUtils.assertContentEquals(cleaned, streamed); // Retransfer the file, making sure it is now idempotent (see CASSANDRA-3481) cfs.clearUnsafe(); transferSSTables(streamed); SSTableReader restreamed = cfs.getSSTables().iterator().next(); SSTableUtils.assertContentEquals(streamed, restreamed); } @Test public void testTransferTableMultiple() throws Exception { // write temporary SSTables, but don't register them Set<String> content = new HashSet<>(); content.add("test"); content.add("test2"); content.add("test3"); SSTableReader sstable = SSTableUtils.prepare().write(content); String keyspaceName = sstable.getKeyspaceName(); String cfname = sstable.getColumnFamilyName(); content = new HashSet<>(); content.add("transfer1"); content.add("transfer2"); content.add("transfer3"); SSTableReader sstable2 = SSTableUtils.prepare().write(content); // transfer the first and last key IPartitioner p = StorageService.getPartitioner(); List<Range<Token>> ranges = new ArrayList<>(); ranges.add(new Range<>(p.getMinimumToken(), p.getToken(ByteBufferUtil.bytes("test")))); ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("transfer2")), p.getMinimumToken())); // Acquiring references, transferSSTables needs it sstable.acquireReference(); sstable2.acquireReference(); new StreamPlan("StreamingTransferTest").transferFiles(LOCAL, makeStreamingDetails(ranges, Arrays.asList(sstable, sstable2))).execute().get(); // confirm that the sstables were transferred and registered and that 2 keys arrived ColumnFamilyStore cfstore = Keyspace.open(keyspaceName).getColumnFamilyStore(cfname); List<Row> rows = Util.getRangeSlice(cfstore); assertEquals(2, rows.size()); assert rows.get(0).key.getKey().equals(ByteBufferUtil.bytes("test")); assert rows.get(1).key.getKey().equals(ByteBufferUtil.bytes("transfer3")); assert rows.get(0).cf.getColumnCount() == 1; assert rows.get(1).cf.getColumnCount() == 1; // these keys fall outside of the ranges and should not be transferred assert cfstore.getColumnFamily(QueryFilter.getIdentityFilter(Util.dk("transfer1"), "Standard1", System.currentTimeMillis())) == null; assert cfstore.getColumnFamily(QueryFilter.getIdentityFilter(Util.dk("transfer2"), "Standard1", System.currentTimeMillis())) == null; assert cfstore.getColumnFamily(QueryFilter.getIdentityFilter(Util.dk("test2"), "Standard1", System.currentTimeMillis())) == null; assert cfstore.getColumnFamily(QueryFilter.getIdentityFilter(Util.dk("test3"), "Standard1", System.currentTimeMillis())) == null; } @Test public void testTransferOfMultipleColumnFamilies() throws Exception { String keyspace = "KeyCacheSpace"; IPartitioner p = StorageService.getPartitioner(); String[] columnFamilies = new String[] { "Standard1", "Standard2", "Standard3" }; List<SSTableReader> ssTableReaders = new ArrayList<>(); NavigableMap<DecoratedKey,String> keys = new TreeMap<>(); for (String cf : columnFamilies) { Set<String> content = new HashSet<>(); content.add("data-" + cf + "-1"); content.add("data-" + cf + "-2"); content.add("data-" + cf + "-3"); SSTableUtils.Context context = SSTableUtils.prepare().ks(keyspace).cf(cf); ssTableReaders.add(context.write(content)); // collect dks for each string key for (String str : content) keys.put(Util.dk(str), cf); } // transfer the first and last keys Map.Entry<DecoratedKey,String> first = keys.firstEntry(); Map.Entry<DecoratedKey,String> last = keys.lastEntry(); Map.Entry<DecoratedKey,String> secondtolast = keys.lowerEntry(last.getKey()); List<Range<Token>> ranges = new ArrayList<>(); ranges.add(new Range<>(p.getMinimumToken(), first.getKey().getToken())); // the left hand side of the range is exclusive, so we transfer from the second-to-last token ranges.add(new Range<>(secondtolast.getKey().getToken(), p.getMinimumToken())); // Acquiring references, transferSSTables needs it if (!SSTableReader.acquireReferences(ssTableReaders)) throw new AssertionError(); new StreamPlan("StreamingTransferTest").transferFiles(LOCAL, makeStreamingDetails(ranges, ssTableReaders)).execute().get(); // check that only two keys were transferred for (Map.Entry<DecoratedKey,String> entry : Arrays.asList(first, last)) { ColumnFamilyStore store = Keyspace.open(keyspace).getColumnFamilyStore(entry.getValue()); List<Row> rows = Util.getRangeSlice(store); assertEquals(rows.toString(), 1, rows.size()); assertEquals(entry.getKey(), rows.get(0).key); } } @Test public void testRandomSSTableTransfer() throws Exception { final Keyspace keyspace = Keyspace.open("Keyspace1"); final ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("Standard1"); Mutator mutator = new Mutator() { public void mutate(String key, String colName, long timestamp) throws Exception { ColumnFamily cf = ArrayBackedSortedColumns.factory.create(keyspace.getName(), cfs.name); cf.addColumn(column(colName, "value", timestamp)); cf.addColumn(new BufferCell(cellname("birthdate"), ByteBufferUtil.bytes(new Date(timestamp).toString()), timestamp)); Mutation rm = new Mutation("Keyspace1", ByteBufferUtil.bytes(key), cf); logger.debug("Applying row to transfer " + rm); rm.apply(); } }; // write a lot more data so the data is spread in more than 1 chunk. for (int i = 1; i <= 6000; i++) mutator.mutate("key" + i, "col" + i, System.currentTimeMillis()); cfs.forceBlockingFlush(); Util.compactAll(cfs, Integer.MAX_VALUE).get(); SSTableReader sstable = cfs.getSSTables().iterator().next(); cfs.clearUnsafe(); IPartitioner p = StorageService.getPartitioner(); List<Range<Token>> ranges = new ArrayList<>(); ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("key1")), p.getToken(ByteBufferUtil.bytes("key1000")))); ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("key5")), p.getToken(ByteBufferUtil.bytes("key500")))); ranges.add(new Range<>(p.getToken(ByteBufferUtil.bytes("key9")), p.getToken(ByteBufferUtil.bytes("key900")))); transfer(sstable, ranges); assertEquals(1, cfs.getSSTables().size()); assertEquals(7, Util.getRangeSlice(cfs).size()); } public interface Mutator { public void mutate(String key, String col, long timestamp) throws Exception; } }
/*************************************** * Copyright (c) 2008 * Helen Kaltegaertner * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************/ package org.b3mn.poem.sketching; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.batik.dom.svg.SAXSVGDocumentFactory; import org.apache.batik.dom.svg.SVGDOMImplementation; import org.apache.batik.svggen.SVGGeneratorContext; import org.apache.batik.svggen.SVGGraphics2D; import org.apache.batik.svggen.SVGSyntax; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.util.XMLResourceDescriptor; import org.apache.fop.svg.PDFTranscoder; import org.w3c.dom.CDATASection; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.svg.SVGDocument; import org.w3c.dom.svg.SVGSVGElement; public class SketchyTransformer extends PDFTranscoder{ private SVGDocument doc; private SVGSVGElement root; private SVGGeneratorContext ctx; private CSSStyleHandler styleHandler; private CDATASection styleSheet; private String fontSize = "15px"; private boolean createPDF; private OutputStream out; public SketchyTransformer(InputStream in, OutputStream out, boolean createPDF) { try { this.createPDF = createPDF; this.out = out; String parser = XMLResourceDescriptor.getXMLParserClassName(); SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser); //this.doc = f.createSVGDocument(svg); this.doc = f.createSVGDocument(null, in); this.root = (SVGSVGElement) this.doc.getDocumentElement(); this.ctx = SVGGeneratorContext.createDefault(this.doc); this.ctx.setEmbeddedFontsOn(true); this.styleSheet = this.doc.createCDATASection(""); this.styleHandler = new CSSStyleHandler(this.styleSheet, this.ctx); this.ctx.setStyleHandler(this.styleHandler); } catch (IOException e) { // TODO: handle exception } this.createArrowEnd(); } public SVGDocument getDoc() { return doc; } public void setDoc(SVGDocument doc) { this.doc = doc; } public SVGSVGElement getRoot() { return root; } public void setRoot(SVGSVGElement root) { this.root = root; } public SVGGeneratorContext getCtx() { return ctx; } public void setCtx(SVGGeneratorContext ctx) { this.ctx = ctx; } public CSSStyleHandler getStyleHandler() { return styleHandler; } public void setStyleHandler(CSSStyleHandler styleHandler) { this.styleHandler = styleHandler; } public CDATASection getStyleSheet() { return styleSheet; } public void setStyleSheet(CDATASection styleSheet) { this.styleSheet = styleSheet; } public String getFontSize() { return fontSize; } public void setFontSize(String fontSize) { this.fontSize = fontSize; } public boolean isCreatePDF() { return createPDF; } public void setCreatePDF(boolean createPDF) { this.createPDF = createPDF; } public OutputStream getOut() { return out; } public void setOut(OutputStream out) { this.out = out; } public void transform() throws IOException, TranscoderException{ this.transformPaths(); this.transformRectangles(); this.transformEllipses(); this.setFont("PapaMano AOE", "18px"); //this.setFont("Helenas Hand", "18px"); this.produceOutput(); } public void produceOutput() throws IOException, TranscoderException{ this.applyStyles(); // Create an instance of the SVG Generator. SVGGraphics2D svgGenerator = new SVGGraphics2D(this.doc); boolean useCSS = true; boolean escaped = false; // Setup output OutputStream dest; if (this.createPDF) dest = new ByteArrayOutputStream(); else dest = new FileOutputStream("outcome.svg"); Writer outWriter = new OutputStreamWriter(dest, "UTF-8"); try { // stream to output svgGenerator.stream(this.root, outWriter, useCSS, escaped); outWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (this.createPDF) this.exportPdf( ((ByteArrayOutputStream)dest).toByteArray()); } private void exportPdf(byte[] svg) throws IOException, TranscoderException{ // required for pdf creation otherwise default font-size is selected NodeList texts = this.doc.getElementsByTagName("tspan"); for (int i = 0; i < texts.getLength(); i++) ((Element)texts.item(i)).setAttribute("font-size", "15px"); PDFTranscoder transcoder = new PDFTranscoder(); try { // setup input InputStream in = new ByteArrayInputStream(svg); TranscoderInput input = new TranscoderInput(in); //Setup output TranscoderOutput output = new TranscoderOutput(this.out); try { // apply transformation transcoder.transcode(input, output); } finally { this.out.close(); in.close(); } } finally {} } private void applyStyles() { //this.doc.normalizeDocument(); // append CDATASection for CSS styles Element defs = (Element)this.root.getElementsByTagName("defs").item(0); Element style = this.doc.createElementNS(SVGSyntax.SVG_NAMESPACE_URI, SVGSyntax.SVG_STYLE_TAG); style.setAttributeNS(null, SVGSyntax.SVG_TYPE_ATTRIBUTE, "text/css"); style.appendChild(this.styleSheet); defs.appendChild(style); } private void createArrowEnd(){ Element marker = this.doc.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "marker"); marker.setAttribute("id", "oryx_arrow"); marker.setAttribute("refX", "7"); marker.setAttribute("refY", "6"); marker.setAttribute("markerWidth", "7"); marker.setAttribute("markerHeight", "12"); marker.setAttribute("orient", "auto"); Element path = this.doc.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "path"); path.setAttribute("d", "M 0 0 L 7 6 L 0 10"); Map<String, String> styles = new HashMap<String, String>(); styles.put("fill", "none"); styles.put("stroke", "black"); styles.put("stroke-width", "1"); this.styleHandler.setStyle(path, styles); marker.appendChild(path); this.root.getFirstChild().appendChild(marker); } public void transformPaths() { NodeList paths = this.doc.getElementsByTagName("path"); for (int i = 0; i < paths.getLength(); i++) { Element e = (Element) paths.item(i); if (!((Element) e.getParentNode()).getAttribute("display").equals("none") && !e.getParentNode().getNodeName().equals("marker") && !((Element)e.getParentNode()).hasAttribute("oryx:anchors")) { SVGPath path = new SVGPath(e, this.doc, this.styleHandler); try { path.transform(); } catch (SketchyException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } } public void transformRectangles() { NodeList rectangles = this.doc.getElementsByTagName("rect"); HashMap<Element, Element> replaceMap = new HashMap<Element, Element>(); for (int i = 0; i < rectangles.getLength(); i++) { Element e = (Element) rectangles.item(i); SVGRectangle rect; if ( ((Element)e.getParentNode()).getAttribute("title").contains("Data Object") ){ rect = new SVGRectangle(e, this.doc, this.styleHandler, true); } else if (e.getAttribute("stroke").equals("none")) continue; else { rect = new SVGRectangle(e, this.doc, this.styleHandler, false); } replaceMap.put(e, rect.transform()); } // replace rectangles by sketchy paths for (Element rect : replaceMap.keySet()){ if (replaceMap.get(rect) != null) rect.getParentNode().replaceChild(replaceMap.get(rect), rect); } } public void transformEllipses() { HashMap<Element, ArrayList<Element>> replaceMap = new HashMap<Element, ArrayList<Element>>(); NodeList circles = this.doc.getElementsByTagName("circle"); for (int i = 0; i < circles.getLength(); i++) { Element e = (Element) circles.item(i); if (e.getAttribute("stroke").equals("none")) continue; SVGEllipse ellipse = new SVGEllipse(e, this.doc, this.styleHandler); replaceMap.put(e, ellipse.transform()); } NodeList ellipses = this.doc.getElementsByTagName("ellipse"); for (int i = 0; i < ellipses.getLength(); i++) { Element e = (Element) ellipses.item(i); if (e.getAttribute("stroke").equals("none")) continue; SVGEllipse ellipse = new SVGEllipse(e, this.doc, this.styleHandler); replaceMap.put(e, ellipse.transform()); } // replace rectangles by sketchy paths for (Element ellipse : replaceMap.keySet()){ if (replaceMap.get(ellipse) != null){ // insert stroke before old element ellipse.getParentNode().insertBefore(replaceMap.get(ellipse).get(1), ellipse); // replce old element by new ellipse ellipse.getParentNode().replaceChild(replaceMap.get(ellipse).get(0), ellipse); } } } public void setFont(String font, String size) { this.fontSize = size; ((Element)this.root.getLastChild()).setAttribute("font-family", font); ((Element)this.root.getLastChild()).setAttribute("font-size", size); Map<String, String> styles = new HashMap<String, String>(); styles.put("font-size", size); if (this.createPDF) { NodeList texts = this.doc.getElementsByTagName("tspan"); for (int i = 0; i < texts.getLength(); i++) this.styleHandler.setStyle((Element) texts.item(i), styles); } } }
/* * Extremely Compiler Collection * Copyright (c) 2015-2020, Jianping Zeng. * * 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 backend.codegen.dagisel; import backend.codegen.MachineInstr; import backend.mc.MCRegisterClass; import tools.Util; import java.io.PrintStream; import java.util.ArrayList; import java.util.Objects; import java.util.Stack; import static backend.codegen.dagisel.SDep.Kind.Data; public class SUnit { private SDNode node; private MachineInstr instr; public SUnit originNode; public ArrayList<SDep> preds; public ArrayList<SDep> succs; public int nodeNum; public int nodeQueueId; public int latency; /** * number of Data dependency preds. */ public int numPreds; /** * number of Data dependency succs. */ public int numSuccs; public int numPredsLeft; public int numSuccsLeft; public boolean isTwoAddress; public boolean isCommutable; public boolean hasPhysRegDefs; public boolean hasPhysRegClobbers; public boolean isPending; public boolean isAvailable; public boolean isScheduled; public boolean isScheduleHigh; public boolean isCloned; private boolean isDepthCurrent; private boolean isHeightCurrent; private int depth; private int height; public MCRegisterClass copyDstRC, copySrcRC; /** * Constructor for DAGNode based Scheduler(pre-ra). */ public SUnit(SDNode node, int nodeNum) { this.node = node; this.nodeNum = nodeNum; preds = new ArrayList<>(); succs = new ArrayList<>(); } /** * Constructor for MachineInstr based Scheduler(post-ra). */ public SUnit(MachineInstr instr, int nodeNum) { this.instr = instr; this.nodeNum = nodeNum; preds = new ArrayList<>(); succs = new ArrayList<>(); } /** * Constructor for placeholder SUnit. */ public SUnit() { preds = new ArrayList<>(); succs = new ArrayList<>(); } public void setNode(SDNode n) { Util.assertion(instr == null); node = n; } public SDNode getNode() { Util.assertion(instr == null); return node; } public void setInstr(MachineInstr mi) { Util.assertion(node == null); instr = mi; } public MachineInstr getInstr() { Util.assertion(node == null); return instr; } /** * This adds specified edge as a pred of the current * node if not added already. It also adds the current * node as successor of the specified node. */ public void addPred(SDep d) { if (preds.contains(d)) return; SDep p = d.clone(); p.setSUnit(this); SUnit n = d.getSUnit(); if (d.getDepKind() == Data) { ++numPreds; ++n.numSuccs; } if (!n.isScheduled) ++numPredsLeft; if (!isScheduled) ++n.numSuccsLeft; preds.add(d); n.succs.add(p); if (p.getLatency() != 0) { setDepthDirty(); n.setHeightDirty(); } } /** * Remove the specified SDep from the preds of current node. * Terminates directly if the specified SDep doesn't exists in * preds set. */ public void removePred(SDep d) { for (int i = 0, e = preds.size(); i < e; i++) { if (Objects.equals(preds.get(i), e)) { boolean foundSucc = false; // remove the corresponding succ SDep from pred. SDep p = d.clone(); p.setSUnit(this); SUnit n = d.getSUnit(); for (int j = 0, sz = n.succs.size(); j < sz; j++) { if (Objects.equals(p, n.succs.get(j))) { foundSucc = true; n.succs.remove(j); break; } } Util.assertion(foundSucc, "Mismatch pred/succ pair!"); preds.remove(i); if (d.getDepKind() == Data) { --numPreds; --n.numSuccs; } if (!n.isScheduled) --numPredsLeft; if (isScheduled) --n.numSuccsLeft; if (p.getLatency() != 0) { setDepthDirty(); n.setHeightDirty(); } return; } } } public int getDepth() { if (!isDepthCurrent) { computeDepth(); } return depth; } public int getHeight() { if (!isHeightCurrent) computeHeight(); return height; } public void setDepthToAtLeast(int newDepth) { if (newDepth <= getDepth()) return; setDepthDirty(); depth = newDepth; isDepthCurrent = true; } public void setHeightToAtLeast(int newHeight) { if (newHeight <= getHeight()) return; setHeightDirty(); height = newHeight; isHeightCurrent = true; } public void setDepthDirty() { if (!isDepthCurrent) return; Stack<SUnit> worklist = new Stack<>(); worklist.push(this); do { SUnit su = worklist.pop(); su.isDepthCurrent = false; succs.forEach(succ -> { SUnit succSU = succ.getSUnit(); if (succSU.isDepthCurrent) worklist.push(succSU); }); } while (!worklist.isEmpty()); } public void setHeightDirty() { if (!isHeightCurrent) return; Stack<SUnit> worklist = new Stack<>(); worklist.push(this); do { SUnit su = worklist.pop(); su.isHeightCurrent = false; preds.forEach(pred -> { SUnit predSU = pred.getSUnit(); if (predSU.isHeightCurrent) worklist.push(predSU); }); } while (!worklist.isEmpty()); } public boolean isPred(SUnit u) { for (SDep d : preds) { if (Objects.equals(d.getSUnit(), u)) return true; } return false; } public boolean isSucc(SUnit u) { for (SDep d : succs) { if (Objects.equals(d.getSUnit(), u)) return true; } return false; } public void dump(ScheduleDAG dag) { System.err.printf("SU(%d):", nodeNum); dag.dumpNode(this); } public void dumpAll(ScheduleDAG dag) { dump(dag); System.err.printf(" # preds left : %d%n", numPredsLeft); System.err.printf(" # succs left : %d%n", numSuccsLeft); System.err.printf(" Latency : %d%n", latency); System.err.printf(" Depth : %d%n", depth); System.err.printf(" Height : %d%n", height); if (!preds.isEmpty()) { System.err.println(" Predecessors:"); for (SDep d : preds) { System.err.print(" "); switch (d.getDepKind()) { case Data: System.err.print("val "); break; case Anti: System.err.print("anti "); break; case Output: System.err.print("output"); break; case Order: System.err.print("ch "); break; } System.err.print("#"); System.err.printf("0x%x - SU(%d)", d.getSUnit().hashCode(), d.getSUnit().nodeNum); if (d.isArtificial()) System.err.print(" *"); System.err.printf(": Latency=%d", d.getLatency()); System.err.println(); } } if (!succs.isEmpty()) { System.err.println(" Successors:"); for (SDep d : succs) { System.err.print(" "); switch (d.getDepKind()) { case Data: System.err.print("val "); break; case Anti: System.err.print("anti "); break; case Output: System.err.print("output"); break; case Order: System.err.print("ch "); break; } System.err.print("#"); System.err.printf("0x%x - SU(%d)", d.getSUnit().hashCode(), d.getSUnit().nodeNum); if (d.isArtificial()) System.err.print(" *"); System.err.printf(": Latency=%d", d.getLatency()); System.err.println(); } } System.err.println(); } public void print(PrintStream os, ScheduleDAG dag) { // TODO } private void computeHeight() { Stack<SUnit> worklist = new Stack<>(); worklist.push(this); do { SUnit su = worklist.peek(); boolean done = true; int maxSuccHeight = 0; for (SDep d : succs) { SUnit succSU = d.getSUnit(); if (succSU.isHeightCurrent) { maxSuccHeight = Math.max(maxSuccHeight, succSU.height + d.getLatency()); } else { done = false; worklist.add(succSU); } } if (done) { worklist.pop(); if (maxSuccHeight != su.height) { su.setHeightDirty(); su.height = maxSuccHeight; } su.isHeightCurrent = true; } } while (!worklist.isEmpty()); } private void computeDepth() { Stack<SUnit> worklist = new Stack<>(); worklist.push(this); do { SUnit su = worklist.peek(); boolean done = true; int maxPredDepth = 0; for (SDep d : preds) { SUnit predSU = d.getSUnit(); if (predSU.isDepthCurrent) { maxPredDepth = Math.max(maxPredDepth, predSU.getDepth() + d.getLatency()); } else { done = false; worklist.add(predSU); } } if (done) { worklist.pop(); if (maxPredDepth != su.getDepth()) { su.setDepthDirty(); su.depth = maxPredDepth; } su.isDepthCurrent = true; } } while (!worklist.isEmpty()); } }
package com.adarsh.apps.campusstore; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; /** * Created by poliveira on 24/10/2014. */ public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks { private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; private static final String PREFERENCES_FILE = "my_app_settings"; //TODO: change this to your file private NavigationDrawerCallbacks mCallbacks; private RecyclerView mDrawerList; private View mFragmentContainerView; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mActionBarDrawerToggle; private boolean mUserLearnedDrawer; private boolean mFromSavedInstanceState; public static int mCurrentSelectedPosition; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false); mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mDrawerList.setLayoutManager(layoutManager); mDrawerList.setHasFixedSize(true); final List<NavigationItem> navigationItems = getMenu(); NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems); adapter.setNavigationDrawerCallbacks(this); mDrawerList.setAdapter(adapter); selectItem(mCurrentSelectedPosition); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false")); if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstanceState = true; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); } } public ActionBarDrawerToggle getActionBarDrawerToggle() { return mActionBarDrawerToggle; } public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) { mActionBarDrawerToggle = actionBarDrawerToggle; } public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; mDrawerLayout.setStatusBarBackgroundColor( getResources().getColor(R.color.myPrimaryDarkColor)); mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) return; getActivity().invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) return; if (!mUserLearnedDrawer) { mUserLearnedDrawer = true; saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true"); } getActivity().invalidateOptionsMenu(); } }; if (!mUserLearnedDrawer && !mFromSavedInstanceState) mDrawerLayout.openDrawer(mFragmentContainerView); mDrawerLayout.post(new Runnable() { @Override public void run() { mActionBarDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mActionBarDrawerToggle); } public void openDrawer() { mDrawerLayout.openDrawer(mFragmentContainerView); } public void closeDrawer() { mDrawerLayout.closeDrawer(mFragmentContainerView); } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } public List<NavigationItem> getMenu() { List<NavigationItem> items = new ArrayList<NavigationItem>(); items.add(new NavigationItem("Choose a Category", getResources().getDrawable(R.drawable.ic_menu_check))); //items.add(new NavigationItem("Trending Items", getResources().getDrawable(R.drawable.ic_menu_check))); items.add(new NavigationItem("My Dashboard", getResources().getDrawable(R.drawable.ic_menu_check))); // items.add(new NavigationItem("Favorites", getResources().getDrawable(R.drawable.ic_menu_check))); items.add(new NavigationItem("About Us", getResources().getDrawable(R.drawable.ic_menu_check))); items.add(new NavigationItem("Send Feedback", getResources().getDrawable(R.drawable.ic_menu_check))); items.add(new NavigationItem("Sign Out", getResources().getDrawable(R.drawable.ic_menu_check))); return items; } void selectItem(int position) { mCurrentSelectedPosition = position; if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } ((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position); } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mActionBarDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); } @Override public void onNavigationDrawerItemSelected(int position) { selectItem(position); } public DrawerLayout getDrawerLayout() { return mDrawerLayout; } public void setDrawerLayout(DrawerLayout drawerLayout) { mDrawerLayout = drawerLayout; } public static void saveSharedSetting(Context ctx, String settingName, String settingValue) { SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putString(settingName, settingValue); editor.apply(); } public static String readSharedSetting(Context ctx, String settingName, String defaultValue) { SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE); return sharedPref.getString(settingName, defaultValue); } }
/* * Copyright (c) 1999, 2002, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.jndi.ldap; import javax.naming.*; import javax.naming.directory.*; import javax.naming.spi.*; import java.net.URL; import java.net.MalformedURLException; import java.io.UnsupportedEncodingException; import java.util.StringTokenizer; import com.sun.jndi.toolkit.url.Uri; import com.sun.jndi.toolkit.url.UrlUtil; /* * Extract components of an LDAP URL. * * The format of an LDAP URL is defined in RFC 2255 as follows: * * ldapurl = scheme "://" [hostport] ["/" * [dn ["?" [attributes] ["?" [scope] * ["?" [filter] ["?" extensions]]]]]] * scheme = "ldap" * attributes = attrdesc *("," attrdesc) * scope = "base" / "one" / "sub" * dn = distinguishedName from Section 3 of [1] * hostport = hostport from Section 5 of RFC 1738 [5] * attrdesc = AttributeDescription from Section 4.1.5 of [2] * filter = filter from Section 4 of [4] * extensions = extension *("," extension) * extension = ["!"] extype ["=" exvalue] * extype = token / xtoken * exvalue = LDAPString from section 4.1.2 of [2] * token = oid from section 4.1 of [3] * xtoken = ("X-" / "x-") token * * For example, * * ldap://ldap.itd.umich.edu/o=University%20of%20Michigan,c=US * ldap://host.com:6666/o=IMC,c=US??sub?(cn=Babs%20Jensen) * * This class also supports ldaps URLs. */ final public class LdapURL extends Uri { private boolean useSsl = false; private String DN = null; private String attributes = null; private String scope = null; private String filter = null; private String extensions = null; /** * Creates an LdapURL object from an LDAP URL string. */ public LdapURL(String url) throws NamingException { super(); try { init(url); // scheme, host, port, path, query useSsl = scheme.equalsIgnoreCase("ldaps"); if (! (scheme.equalsIgnoreCase("ldap") || useSsl)) { throw new MalformedURLException("Not an LDAP URL: " + url); } parsePathAndQuery(); // DN, attributes, scope, filter, extensions } catch (MalformedURLException e) { NamingException ne = new NamingException("Cannot parse url: " + url); ne.setRootCause(e); throw ne; } catch (UnsupportedEncodingException e) { NamingException ne = new NamingException("Cannot parse url: " + url); ne.setRootCause(e); throw ne; } } /** * Returns true if the URL is an LDAPS URL. */ public boolean useSsl() { return useSsl; } /** * Returns the LDAP URL's distinguished name. */ public String getDN() { return DN; } /** * Returns the LDAP URL's attributes. */ public String getAttributes() { return attributes; } /** * Returns the LDAP URL's scope. */ public String getScope() { return scope; } /** * Returns the LDAP URL's filter. */ public String getFilter() { return filter; } /** * Returns the LDAP URL's extensions. */ public String getExtensions() { return extensions; } /** * Given a space-separated list of LDAP URLs, returns an array of strings. */ public static String[] fromList(String urlList) throws NamingException { String[] urls = new String[(urlList.length() + 1) / 2]; int i = 0; // next available index in urls StringTokenizer st = new StringTokenizer(urlList, " "); while (st.hasMoreTokens()) { urls[i++] = st.nextToken(); } String[] trimmed = new String[i]; System.arraycopy(urls, 0, trimmed, 0, i); return trimmed; } /** * Derermines whether an LDAP URL has query components. */ public static boolean hasQueryComponents(String url) { return (url.lastIndexOf('?') != -1); } /* * Assembles an LDAP or LDAPS URL string from its components. * If "host" is an IPv6 literal, it may optionally include delimiting * brackets. */ static String toUrlString(String host, int port, String dn, boolean useSsl) { try { String h = (host != null) ? host : ""; if ((h.indexOf(':') != -1) && (h.charAt(0) != '[')) { h = "[" + h + "]"; // IPv6 literal } String p = (port != -1) ? (":" + port) : ""; String d = (dn != null) ? ("/" + UrlUtil.encode(dn, "UTF8")) : ""; return useSsl ? "ldaps://" + h + p + d : "ldap://" + h + p + d; } catch (UnsupportedEncodingException e) { // UTF8 should always be supported throw new IllegalStateException("UTF-8 encoding unavailable"); } } /* * Parses the path and query components of an URL and sets this * object's fields accordingly. */ private void parsePathAndQuery() throws MalformedURLException, UnsupportedEncodingException { // path begins with a '/' or is empty if (path.equals("")) { return; } DN = path.startsWith("/") ? path.substring(1) : path; if (DN.length() > 0) { DN = UrlUtil.decode(DN, "UTF8"); } // query begins with a '?' or is null if (query == null) { return; } int qmark2 = query.indexOf('?', 1); if (qmark2 < 0) { attributes = query.substring(1); return; } else if (qmark2 != 1) { attributes = query.substring(1, qmark2); } int qmark3 = query.indexOf('?', qmark2 + 1); if (qmark3 < 0) { scope = query.substring(qmark2 + 1); return; } else if (qmark3 != qmark2 + 1) { scope = query.substring(qmark2 + 1, qmark3); } int qmark4 = query.indexOf('?', qmark3 + 1); if (qmark4 < 0) { filter = query.substring(qmark3 + 1); } else { if (qmark4 != qmark3 + 1) { filter = query.substring(qmark3 + 1, qmark4); } extensions = query.substring(qmark4 + 1); if (extensions.length() > 0) { extensions = UrlUtil.decode(extensions, "UTF8"); } } if (filter != null && filter.length() > 0) { filter = UrlUtil.decode(filter, "UTF8"); } } /* public static void main(String[] args) throws Exception { LdapURL url = new LdapURL(args[0]); System.out.println("Example LDAP URL: " + url.toString()); System.out.println(" scheme: " + url.getScheme()); System.out.println(" host: " + url.getHost()); System.out.println(" port: " + url.getPort()); System.out.println(" DN: " + url.getDN()); System.out.println(" attrs: " + url.getAttributes()); System.out.println(" scope: " + url.getScope()); System.out.println(" filter: " + url.getFilter()); System.out.println(" extens: " + url.getExtensions()); System.out.println(""); } */ }
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSetMultimap; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import javax.annotation.Nullable; import javax.tools.FileObject; import javax.tools.ForwardingJavaFileObject; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.StandardLocation; /** * Tracks which classes are actually read by the compiler by providing a special * {@link JavaFileManager}. */ class ClassUsageTracker { private static final String FILE_SCHEME = "file"; private static final String JAR_SCHEME = "jar"; private static final String JIMFS_SCHEME = "jimfs"; // Used in tests // Examples: First anonymous class is Foo$1.class. First local class named Bar is Foo$1Bar.class. private static final Pattern LOCAL_OR_ANONYMOUS_CLASS = Pattern.compile("^.*\\$\\d.*.class$"); private final ImmutableSetMultimap.Builder<Path, Path> resultBuilder = ImmutableSetMultimap.builder(); @Nullable private ImmutableSetMultimap<Path, Path> result; /** * Returns a {@link JavaFileManager} that tracks which files are opened. Provide this to * {@code JavaCompiler.getTask} anytime file usage tracking is desired. */ public StandardJavaFileManager wrapFileManager(StandardJavaFileManager inner) { return new UsageTrackingFileManager(inner); } /** * Returns a multimap from JAR path on disk to .class file paths within the jar for any classes * that were used. */ public ImmutableSetMultimap<Path, Path> getClassUsageMap() { if (result == null) { result = resultBuilder.build(); } return result; } private void addReadFile(FileObject fileObject) { Preconditions.checkState(result == null); // Can't add after having built if (!(fileObject instanceof JavaFileObject)) { return; } JavaFileObject javaFileObject = (JavaFileObject) fileObject; URI classFileJarUri = javaFileObject.toUri(); if (!classFileJarUri.getScheme().equals(JAR_SCHEME)) { // Not in a jar; must not have been built with java_library return; } // The jar: scheme is somewhat underspecified. See the JarURLConnection docs // for the closest thing it has to documentation. String jarUriSchemeSpecificPart = classFileJarUri.getRawSchemeSpecificPart(); final String[] split = jarUriSchemeSpecificPart.split("!/"); Preconditions.checkState(split.length == 2); if (isLocalOrAnonymousClass(split[1])) { // The compiler reads local and anonymous classes because of the naive way in which it // completes the enclosing class, but changes to them can't affect compilation of dependent // classes so we don't need to consider them "used". return; } URI jarFileUri = URI.create(split[0]); Preconditions.checkState(jarFileUri.getScheme().equals(FILE_SCHEME) || jarFileUri.getScheme().equals(JIMFS_SCHEME)); // jimfs is used in tests Path jarFilePath = Paths.get(jarFileUri); // Using URI.create here for de-escaping Path classPath = Paths.get(URI.create(split[1]).toString()); Preconditions.checkState(jarFilePath.isAbsolute()); Preconditions.checkState(!classPath.isAbsolute()); resultBuilder.put(jarFilePath, classPath); } private boolean isLocalOrAnonymousClass(String className) { return LOCAL_OR_ANONYMOUS_CLASS.matcher(className).matches(); } private class UsageTrackingFileManager extends ForwardingStandardJavaFileManager { private final FileObjectTracker fileTracker = new FileObjectTracker(); public UsageTrackingFileManager(StandardJavaFileManager fileManager) { super(fileManager); } @Override public String inferBinaryName(Location location, JavaFileObject file) { // javac does not play nice with wrapped file objects in this method; so we unwrap return super.inferBinaryName(location, unwrap(file)); } @Override public boolean isSameFile(FileObject a, FileObject b) { // javac does not play nice with wrapped file objects in this method; so we unwrap return super.isSameFile(unwrap(a), unwrap(b)); } private JavaFileObject unwrap(JavaFileObject file) { if (file instanceof TrackingJavaFileObject) { return ((TrackingJavaFileObject) file).getJavaFileObject(); } return file; } private FileObject unwrap(FileObject file) { if (file instanceof JavaFileObject) { return unwrap((JavaFileObject) file); } return file; } @Override public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles( Iterable<? extends File> files) { return fileManager.getJavaFileObjectsFromFiles(files); } @Override public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) { return fileManager.getJavaFileObjects(files); } @Override public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings( Iterable<String> names) { return fileManager.getJavaFileObjectsFromStrings(names); } @Override public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) { return fileManager.getJavaFileObjects(names); } @Override public Iterable<JavaFileObject> list( Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException { Iterable<JavaFileObject> listIterator = super.list(location, packageName, kinds, recurse); if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) { return listIterator; } else { return new TrackingIterable(listIterator); } } @Override public JavaFileObject getJavaFileForInput( Location location, String className, JavaFileObject.Kind kind) throws IOException { JavaFileObject javaFileObject = super.getJavaFileForInput(location, className, kind); if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) { return javaFileObject; } else { return fileTracker.wrap(javaFileObject); } } @Override public JavaFileObject getJavaFileForOutput( Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException { JavaFileObject javaFileObject = super.getJavaFileForOutput( location, className, kind, sibling); if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) { return javaFileObject; } else { return fileTracker.wrap(javaFileObject); } } @Override public FileObject getFileForInput( Location location, String packageName, String relativeName) throws IOException { FileObject fileObject = super.getFileForInput(location, packageName, relativeName); if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) { return fileObject; } else { return fileTracker.wrap(fileObject); } } @Override public FileObject getFileForOutput( Location location, String packageName, String relativeName, FileObject sibling) throws IOException { FileObject fileObject = super.getFileForOutput( location, packageName, relativeName, sibling); if (location == StandardLocation.ANNOTATION_PROCESSOR_PATH) { return fileObject; } else { return fileTracker.wrap(fileObject); } } private class TrackingIterable implements Iterable<JavaFileObject> { private final Iterable<? extends JavaFileObject> inner; public TrackingIterable(final Iterable<? extends JavaFileObject> inner) { this.inner = inner; } @Override public Iterator<JavaFileObject> iterator() { return new TrackingIterator(inner.iterator()); } } private class TrackingIterator implements Iterator<JavaFileObject> { private final Iterator<? extends JavaFileObject> inner; public TrackingIterator(final Iterator<? extends JavaFileObject> inner) { this.inner = inner; } @Override public boolean hasNext() { return inner.hasNext(); } @Override public JavaFileObject next() { return fileTracker.wrap(inner.next()); } @Override public void remove() { inner.remove(); } } } private class FileObjectTracker { private final Map<JavaFileObject, JavaFileObject> javaFileObjectCache = new IdentityHashMap<>(); public FileObject wrap(FileObject inner) { if (inner instanceof JavaFileObject) { return wrap((JavaFileObject) inner); } return inner; } public JavaFileObject wrap(JavaFileObject inner) { if (!javaFileObjectCache.containsKey(inner)) { javaFileObjectCache.put(inner, new TrackingJavaFileObject(inner)); } return Preconditions.checkNotNull(javaFileObjectCache.get(inner)); } } private class TrackingJavaFileObject extends ForwardingJavaFileObject<JavaFileObject> { public TrackingJavaFileObject(JavaFileObject fileObject) { super(fileObject); } public JavaFileObject getJavaFileObject() { return fileObject; } @Override public InputStream openInputStream() throws IOException { addReadFile(fileObject); return super.openInputStream(); } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { addReadFile(fileObject); return super.openReader(ignoreEncodingErrors); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { addReadFile(fileObject); return super.getCharContent(ignoreEncodingErrors); } } }
/* * Copyright (c) 2013 Ramon Servadei * * 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.fimtra.channel; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import com.fimtra.util.Log; /** * This class checks that the {@link ITransportChannel} objects it knows about are still alive. This * is done by periodically sending a heartbeat message to each channel it knows about and listening * for heartbeats received on each channel. * <p> * The watchdog can be configured to allow a specified number of missed heartbeats before closing a * channel. * <p> * Can be configured with the following system properties: * * <pre> * -DChannelWatchdog.periodMillis={period in milliseconds for heartbeats} * -DChannelWatchdog.missedHbCount={missed heartbeats} * </pre> * * @author Ramon Servadei */ public final class ChannelWatchdog implements Runnable { int heartbeatPeriodMillis; int missedHeartbeatCount; final Set<ITransportChannel> channels; /** Tracks channels that receive a HB */ final Set<ITransportChannel> channelsReceivingHeartbeat; final Map<ITransportChannel, Integer> channelsMissingHeartbeat; private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private final AtomicInteger threadNumber = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r, "channel-watchdog-" + this.threadNumber.getAndIncrement()); t.setDaemon(true); return t; } }); private ScheduledFuture<?> current; public ChannelWatchdog() { super(); this.channels = new CopyOnWriteArraySet<ITransportChannel>(); this.channelsReceivingHeartbeat = new HashSet<ITransportChannel>(); this.channelsMissingHeartbeat = new HashMap<ITransportChannel, Integer>(); configure(Integer.parseInt(System.getProperty("ChannelWatchdog.periodMillis", "5000")), Integer.parseInt(System.getProperty("ChannelWatchdog.missedHbCount", "3"))); } public int getHeartbeatPeriodMillis() { return this.heartbeatPeriodMillis; } public int getMissedHeartbeatCount() { return this.missedHeartbeatCount; } /** * Configure the watchdog period. This also defines 3 allowed missed heartbeats. * * @param periodMillis * the period to scan for heartbeats and to send heartbeats down each channel * @see #configure(int, int) */ public void configure(int periodMillis) { configure(periodMillis, Integer.parseInt(System.getProperty("ChannelWatchdog.missedHbCount", "3"))); } /** * Configure the watchdog period and heartbeat * * @param periodMillis * the period to scan for heartbeats and to send heartbeats down each channel * @param missedHeartbeats * the number of allowed missed heartbeats for a channel */ public void configure(int periodMillis, int missedHeartbeats) { if (this.current != null) { this.current.cancel(false); } this.heartbeatPeriodMillis = periodMillis; this.missedHeartbeatCount = missedHeartbeats; this.current = this.executor.scheduleWithFixedDelay(this, this.heartbeatPeriodMillis, this.heartbeatPeriodMillis, TimeUnit.MILLISECONDS); Log.log(this, "Heartbeat period is ", Integer.toString(this.heartbeatPeriodMillis), "ms, missed heartbeat count is ", Integer.toString(this.missedHeartbeatCount)); } /** * Add the channel to be monitored by this watchdog. This immediately sends a heartbeat down * this channel. */ public void addChannel(final ITransportChannel channel) { // Log.log(this, "Monitoring " + channel); this.channels.add(channel); this.executor.execute(new Runnable() { @Override public void run() { channel.sendAsync(ChannelUtils.HEARTBEAT_SIGNAL); } }); } @Override public void run() { for (ITransportChannel channel : this.channels) { try { // send HB if (!channel.sendAsync(ChannelUtils.HEARTBEAT_SIGNAL)) { channel.destroy("Could not send heartbeat"); stopMonitoring(channel); } else { // if the channel has received data, then its still alive... if (channel.hasRxData()) { this.channelsMissingHeartbeat.remove(channel); } else { // now check for missed heartbeat Integer missedCount = this.channelsMissingHeartbeat.get(channel); if (missedCount != null && missedCount.intValue() > this.missedHeartbeatCount) { channel.destroy("Heartbeat not received"); stopMonitoring(channel); } // prepare for missed heartbeat on the next cycle if (!this.channelsReceivingHeartbeat.contains(channel)) { Integer count = missedCount; if (count == null) { count = Integer.valueOf(1); } else { count = Integer.valueOf(count.intValue() + 1); } this.channelsMissingHeartbeat.put(channel, count); } } } } catch (Exception e) { channel.destroy("Could not verify channel status", e); stopMonitoring(channel); } } this.channelsReceivingHeartbeat.clear(); } /** * @param channel * the channel to stop monitoring */ private void stopMonitoring(ITransportChannel channel) { if (this.channels.remove(channel)) { ChannelWatchdog.this.channelsReceivingHeartbeat.remove(channel); ChannelWatchdog.this.channelsMissingHeartbeat.remove(channel); // Log.log(this, "Not monitoring " + channel); } } public void onHeartbeat(final ITransportChannel channel) { this.executor.execute(new Runnable() { @Override public void run() { if (ChannelWatchdog.this.channels.contains(channel)) { ChannelWatchdog.this.channelsReceivingHeartbeat.add(channel); ChannelWatchdog.this.channelsMissingHeartbeat.remove(channel); } } }); } }
/* * 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.management.internal.api; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.apache.geode.annotations.VisibleForTesting; import org.apache.geode.cache.configuration.CacheConfig; import org.apache.geode.cache.configuration.CacheElement; import org.apache.geode.cache.configuration.GatewayReceiverConfig; import org.apache.geode.cache.configuration.PdxType; import org.apache.geode.cache.configuration.RegionConfig; import org.apache.geode.cache.execute.Execution; import org.apache.geode.cache.execute.Function; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.execute.ResultCollector; import org.apache.geode.distributed.ConfigurationPersistenceService; import org.apache.geode.distributed.DistributedMember; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.execute.AbstractExecution; import org.apache.geode.internal.logging.LogService; import org.apache.geode.management.api.ClusterManagementResult; import org.apache.geode.management.api.ClusterManagementService; import org.apache.geode.management.api.RealizationResult; import org.apache.geode.management.api.RespondsWith; import org.apache.geode.management.configuration.MemberConfig; import org.apache.geode.management.internal.CacheElementOperation; import org.apache.geode.management.internal.cli.functions.UpdateCacheFunction; import org.apache.geode.management.internal.configuration.mutators.ConfigurationManager; import org.apache.geode.management.internal.configuration.mutators.GatewayReceiverConfigManager; import org.apache.geode.management.internal.configuration.mutators.MemberConfigManager; import org.apache.geode.management.internal.configuration.mutators.PdxManager; import org.apache.geode.management.internal.configuration.mutators.RegionConfigManager; import org.apache.geode.management.internal.configuration.validators.CacheElementValidator; import org.apache.geode.management.internal.configuration.validators.ConfigurationValidator; import org.apache.geode.management.internal.configuration.validators.GatewayReceiverConfigValidator; import org.apache.geode.management.internal.configuration.validators.MemberValidator; import org.apache.geode.management.internal.configuration.validators.RegionConfigValidator; import org.apache.geode.management.internal.exceptions.EntityNotFoundException; public class LocatorClusterManagementService implements ClusterManagementService { private static final Logger logger = LogService.getLogger(); private ConfigurationPersistenceService persistenceService; private Map<Class, ConfigurationManager> managers; private Map<Class, ConfigurationValidator> validators; private MemberValidator memberValidator; private CacheElementValidator commonValidator; public LocatorClusterManagementService(InternalCache cache, ConfigurationPersistenceService persistenceService) { this(persistenceService, new HashMap<>(), new HashMap<>(), null, null); // initialize the list of managers managers.put(RegionConfig.class, new RegionConfigManager(cache)); managers.put(MemberConfig.class, new MemberConfigManager(cache)); managers.put(PdxType.class, new PdxManager()); managers.put(GatewayReceiverConfig.class, new GatewayReceiverConfigManager(cache)); // initialize the list of validators commonValidator = new CacheElementValidator(); validators.put(RegionConfig.class, new RegionConfigValidator(cache)); validators.put(GatewayReceiverConfig.class, new GatewayReceiverConfigValidator()); memberValidator = new MemberValidator(cache, persistenceService); } @VisibleForTesting public LocatorClusterManagementService(ConfigurationPersistenceService persistenceService, Map<Class, ConfigurationManager> managers, Map<Class, ConfigurationValidator> validators, MemberValidator memberValidator, CacheElementValidator commonValidator) { this.persistenceService = persistenceService; this.managers = managers; this.validators = validators; this.memberValidator = memberValidator; this.commonValidator = commonValidator; } @Override public <T extends CacheElement & RespondsWith<R>, R extends CacheElement> ClusterManagementResult<T> create( T config) { // validate that user used the correct config object type ConfigurationManager configurationManager = getConfigurationManager(config); if (persistenceService == null) { return new ClusterManagementResult<>(false, "Cluster configuration service needs to be enabled"); } // first validate common attributes of all configuration object commonValidator.validate(CacheElementOperation.CREATE, config); String group = config.getConfigGroup(); ConfigurationValidator validator = validators.get(config.getClass()); if (validator != null) { validator.validate(CacheElementOperation.CREATE, config); } // check if this config already exists on all/some members of this group memberValidator.validateCreate(config, configurationManager); // execute function on all members Set<DistributedMember> targetedMembers = memberValidator.findMembers(group); ClusterManagementResult<T> result = new ClusterManagementResult<>(); List<RealizationResult> functionResults = executeAndGetFunctionResult( new UpdateCacheFunction(), Arrays.asList(config, CacheElementOperation.CREATE), targetedMembers); functionResults.forEach(result::addMemberStatus); // if any false result is added to the member list if (result.getStatusCode() != ClusterManagementResult.StatusCode.OK) { result.setStatus(false, "Failed to apply the update on all members"); return result; } // persist configuration in cache config final String finalGroup = group; // the below lambda requires a reference that is final persistenceService.updateCacheConfig(finalGroup, cacheConfigForGroup -> { try { configurationManager.add(config, cacheConfigForGroup); result.setStatus(true, "Successfully updated config for " + finalGroup); } catch (Exception e) { String message = "Failed to update cluster config for " + finalGroup; logger.error(message, e); result.setStatus(ClusterManagementResult.StatusCode.FAIL_TO_PERSIST, message); return null; } return cacheConfigForGroup; }); // add the config object which includes the HATOS information of the element created if (result.isSuccessful()) { result.setResult(Collections.singletonList(config)); } return result; } @Override public <T extends CacheElement & RespondsWith<R>, R extends CacheElement> ClusterManagementResult<T> delete( T config) { // validate that user used the correct config object type ConfigurationManager configurationManager = getConfigurationManager(config); if (persistenceService == null) { return new ClusterManagementResult<>(false, "Cluster configuration service needs to be enabled"); } // first validate common attributes of all configuration object commonValidator.validate(CacheElementOperation.DELETE, config); ConfigurationValidator validator = validators.get(config.getClass()); if (validator != null) { validator.validate(CacheElementOperation.DELETE, config); } String[] groupsWithThisElement = memberValidator.findGroupsWithThisElement(config.getId(), configurationManager); if (groupsWithThisElement.length == 0) { throw new EntityNotFoundException("Cache element '" + config.getId() + "' does not exist"); } // execute function on all members ClusterManagementResult<T> result = new ClusterManagementResult<>(); List<RealizationResult> functionResults = executeAndGetFunctionResult( new UpdateCacheFunction(), Arrays.asList(config, CacheElementOperation.DELETE), memberValidator.findMembers(groupsWithThisElement)); functionResults.forEach(result::addMemberStatus); // if any false result is added to the member list if (result.getStatusCode() != ClusterManagementResult.StatusCode.OK) { result.setStatus(false, "Failed to apply the update on all members"); return result; } // persist configuration in cache config List<String> updatedGroups = new ArrayList<>(); List<String> failedGroups = new ArrayList<>(); for (String finalGroup : groupsWithThisElement) { persistenceService.updateCacheConfig(finalGroup, cacheConfigForGroup -> { try { configurationManager.delete(config, cacheConfigForGroup); updatedGroups.add(finalGroup); } catch (Exception e) { logger.error("Failed to update cluster config for " + finalGroup, e); failedGroups.add(finalGroup); return null; } return cacheConfigForGroup; }); } if (failedGroups.isEmpty()) { result.setStatus(true, "Successfully removed config for " + updatedGroups); } else { String message = "Failed to update cluster config for " + failedGroups; result.setStatus(ClusterManagementResult.StatusCode.FAIL_TO_PERSIST, message); } return result; } @Override public <T extends CacheElement & RespondsWith<R>, R extends CacheElement> ClusterManagementResult<T> update( T config) { throw new NotImplementedException("Not implemented"); } @Override public <T extends CacheElement & RespondsWith<R>, R extends CacheElement> ClusterManagementResult<R> list( T filter) { ConfigurationManager<T, R> manager = managers.get(filter.getClass()); ClusterManagementResult<R> result = new ClusterManagementResult<>(); if (filter instanceof MemberConfig) { List<R> listResults = manager.list(filter, null); result.setResult(listResults); return result; } if (persistenceService == null) { return new ClusterManagementResult<>(false, "Cluster configuration service needs to be enabled"); } List<R> resultList = new ArrayList<>(); for (String group : persistenceService.getGroups()) { CacheConfig currentPersistedConfig = persistenceService.getCacheConfig(group, true); List<R> listInGroup = manager.list(filter, currentPersistedConfig); for (R element : listInGroup) { element.setGroup(group); resultList.add(element); } } // if empty result, return immediately if (resultList.size() == 0) { return result; } // right now the list contains [{regionA, group1}, {regionA, group2}...], if the elements are // MultiGroupCacheElement, we need to consolidate the list into [{regionA, [group1, group2]} List<R> consolidatedConfigList = new ArrayList<>(); for (R element : resultList) { int index = consolidatedConfigList.indexOf(element); if (index >= 0) { R exist = consolidatedConfigList.get(index); exist.getGroups().add(element.getGroup()); } else { consolidatedConfigList.add(element); } } if (StringUtils.isNotBlank(filter.getGroup())) { consolidatedConfigList = consolidatedConfigList.stream() .filter(e -> (e.getGroups().contains(filter.getConfigGroup()))) .collect(Collectors.toList()); } // if "cluster" is the only group, clear it for (R element : consolidatedConfigList) { if (element.getGroups().size() == 1 && CacheElement.CLUSTER.equals(element.getGroup())) { element.getGroups().clear(); } } resultList = consolidatedConfigList; result.setResult(resultList); return result; } @Override public <T extends CacheElement & RespondsWith<R>, R extends CacheElement> ClusterManagementResult<R> get( T config) { ClusterManagementResult<R> list = list(config); List<R> result = list.getResult(); if (result.size() == 0) { throw new EntityNotFoundException( config.getClass().getSimpleName() + " with id = " + config.getId() + " not found."); } if (result.size() > 1) { throw new IllegalStateException( "Expect only one matching " + config.getClass().getSimpleName()); } return list; } @Override public boolean isConnected() { return true; } @VisibleForTesting List<RealizationResult> executeAndGetFunctionResult(Function function, Object args, Set<DistributedMember> targetMembers) { if (targetMembers.size() == 0) { return Collections.emptyList(); } Execution execution = FunctionService.onMembers(targetMembers).setArguments(args); ((AbstractExecution) execution).setIgnoreDepartedMembers(true); ResultCollector rc = execution.execute(function); return (List<RealizationResult>) rc.getResult(); } @SuppressWarnings("unchecked") private <T extends CacheElement & RespondsWith<R>, R extends CacheElement> ConfigurationManager<T, R> getConfigurationManager( T config) { ConfigurationManager configurationManager = managers.get(config.getClass()); if (configurationManager == null) { throw new IllegalArgumentException(String.format("Configuration type %s is not supported", config.getClass().getSimpleName())); } return configurationManager; } }
/* * The MIT License * * Copyright 2015 Andrew Gjerness. * * 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 ezquery; //import statements import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import javax.swing.JOptionPane; /** * EZQuery GUI view class * * @author Andrew Gjerness */ public class View extends javax.swing.JFrame { //fields private String user = ""; private String pass = ""; private String url = ""; private String sql = ""; private Utilities util; private String connection = ""; private String[] header; private String[][] table_data; /** * Constructor for View Class */ public View() { initComponents(); util = new Utilities(); }//constructor /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); view_table = new javax.swing.JTable(); urlText = new javax.swing.JTextField(); userText = new javax.swing.JTextField(); jScrollPane5 = new javax.swing.JScrollPane(); sql_text = new javax.swing.JTextArea(); connect = new javax.swing.JButton(); disconnect = new javax.swing.JButton(); url_label = new javax.swing.JLabel(); user_label = new javax.swing.JLabel(); pw_label = new javax.swing.JLabel(); sql_label = new javax.swing.JLabel(); results_label = new javax.swing.JLabel(); passText = new javax.swing.JPasswordField(); sql_button = new javax.swing.JButton(); connStatusLabel = new javax.swing.JLabel(); connStatusText = new javax.swing.JLabel(); results_text = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); about = new javax.swing.JMenu(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("EZQuery - Version 1.0"); setResizable(false); view_table.setModel(new javax.swing.table.DefaultTableModel(table_data,header)); jScrollPane1.setViewportView(view_table); sql_text.setColumns(20); sql_text.setRows(5); jScrollPane5.setViewportView(sql_text); connect.setText("Connect"); connect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { connectActionPerformed(evt); } }); disconnect.setText("Disconnect"); disconnect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { disconnectActionPerformed(evt); } }); url_label.setText("URL"); user_label.setText("Username"); pw_label.setText("Password"); sql_label.setText("SQL Statements"); results_label.setText("Results"); sql_button.setText("Execute SQL"); sql_button.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sql_buttonActionPerformed(evt); } }); connStatusLabel.setText("Connection Status:"); connStatusText.setText("Disconnected from database"); results_text.setText(" "); about.setText("About"); about.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { aboutMouseClicked(evt); } }); jMenuBar1.add(about); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(results_text, javax.swing.GroupLayout.PREFERRED_SIZE, 334, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(sql_button)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(results_label) .addComponent(sql_label) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(connStatusLabel) .addGap(5, 5, 5) .addComponent(connStatusText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(urlText, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(url_label)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(user_label) .addComponent(userText, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(passText, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(connect) .addGap(18, 18, 18) .addComponent(disconnect)) .addComponent(pw_label)))))) .addContainerGap(32, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(url_label) .addComponent(user_label) .addComponent(pw_label)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(urlText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(userText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(connect) .addComponent(disconnect) .addComponent(passText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(connStatusLabel) .addComponent(connStatusText)) .addGap(29, 29, 29) .addComponent(sql_label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sql_button) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(results_text) .addGap(18, 18, 18))) .addComponent(results_label) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * Action Listener for about button * * @param evt */ private void aboutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_aboutMouseClicked JOptionPane.showMessageDialog(null, "Created by Andrew Gjerness\n" + '\u00A9' + " 2015", "About EZQuery", JOptionPane.PLAIN_MESSAGE); }//GEN-LAST:event_aboutMouseClicked /** * Action listener for connect button * * @param evt */ private void connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectActionPerformed url = urlText.getText(); user = userText.getText(); char[] passArray = passText.getPassword(); for (int i = 0; i < passArray.length; i++) { pass += passArray[i]; }//for Arrays.fill(passArray, '0'); //reset pass char array to all 0s connection = util.openDB(url, user, pass); connStatusText.setText(connection); //reset input url = null; user = null; pass = ""; }//GEN-LAST:event_connectActionPerformed /** * Disconnect button action listener * * @param evt */ private void disconnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectActionPerformed connection = util.closeDB(); connStatusText.setText(connection); }//GEN-LAST:event_disconnectActionPerformed /** * Action listener for execute sql button * * @param evt */ private void sql_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sql_buttonActionPerformed if (util.getConn() == null) { sql_text.setText("You must connect to the database first!"); } else { sql = sql_text.getText(); if (sql.equals("")) { results_text.setText("You must enter a query!"); } else { if (sql.charAt(0) == 's' || sql.charAt(0) == 'S') { //if select query //try for select SQL statements try { Result meta_data = util.sqlQuery(sql); sql_text.setText(meta_data.getSql()); try { int cols = meta_data.getMetaData().getColumnCount(); header = new String[cols]; for (int i = 1; i <= cols; i++) { header[i - 1] = meta_data.getMetaData().getColumnName(i); }//for //get rows int rows = 0; ResultSet getRows = meta_data.getResultSet(); while (getRows.next()) { rows += 1; }//while table_data = new String[rows][cols]; Result r = util.sqlQuery(sql); if (rows < 1) { results_text.setText("Your query returned 0 results"); } else { int i = 0; while(r.getResultSet().next()) { for (int j = 0; j < cols; j++) { table_data[i][j] = r.getResultSet().getString(j + 1); }//for i++; }//while results_text.setText("Rows: " + rows); }//else view_table.setModel(new javax.swing.table.DefaultTableModel(table_data, header)); } catch (NullPointerException e) { }//catch } catch (SQLException e) { System.out.println(e + ""); }//catch }//if else { //All other queries Result update = util.sqlUpdate(sql); results_text.setText("Rows updated: " + update.getUpdates()); table_data = null; header = null; view_table.setModel(new javax.swing.table.DefaultTableModel(table_data, header)); }//else }//else }//else }//GEN-LAST:event_sql_buttonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenu about; private javax.swing.JLabel connStatusLabel; private javax.swing.JLabel connStatusText; private javax.swing.JButton connect; private javax.swing.JButton disconnect; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JPasswordField passText; private javax.swing.JLabel pw_label; private javax.swing.JLabel results_label; private javax.swing.JLabel results_text; private javax.swing.JButton sql_button; private javax.swing.JLabel sql_label; private javax.swing.JTextArea sql_text; private javax.swing.JTextField urlText; private javax.swing.JLabel url_label; private javax.swing.JTextField userText; private javax.swing.JLabel user_label; private javax.swing.JTable view_table; // End of variables declaration//GEN-END:variables }
/*L * Copyright Duke Comprehensive Cancer Center * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/catrip/LICENSE.txt for details. */ package edu.duke.cabig.catrip.gui.querysharing; import gov.nih.nci.cagrid.cqlquery.Attribute; import gov.nih.nci.cagrid.dcql.Association; import gov.nih.nci.cagrid.dcql.DCQLQuery; import gov.nih.nci.cagrid.dcql.ForeignAssociation; import gov.nih.nci.catrip.cagrid.catripquery.client.QueryServiceClient; import gov.nih.nci.catrip.cagrid.catripquery.server.AttributeDb; import gov.nih.nci.catrip.cagrid.catripquery.server.ClassDb; import gov.nih.nci.catrip.cagrid.catripquery.server.QueryDb; import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Iterator; import javax.xml.namespace.QName; import junit.framework.TestCase; import org.globus.wsrf.encoding.DeserializationException; import org.globus.wsrf.encoding.ObjectDeserializer; import org.globus.wsrf.encoding.ObjectSerializer; import org.globus.wsrf.encoding.SerializationException; import org.xml.sax.InputSource; public class TestParser extends TestCase { @SuppressWarnings("unused") private QueryServiceClient client; //private String dcqlQueryFile = "C:\\catrip\\catrip\\codebase\\projects\\queryengine-2.0\\test\\resources\\simpleQuery1.xml"; //private String dcqlQueryFile = "C:\\catrip\\catrip\\codebase\\projects\\queryengine\\testDCQL\\catissuecore_tissuespecimens_cae_greatest.xml"; private String dcqlQueryFile = "C:\\catrip\\catrip\\codebase\\projects\\queryservice\\DemoUseCase1-CGEMSTARGET.xml"; //private String dcqlQueryFile = "C:\\catrip\\catrip\\codebase\\projects\\queryservice\\groupdcql.xml"; private DCQLQuery dcql = null; private QueryDb decomposedCatripQuery; private final boolean DEBUG = true; protected void setUp() throws Exception { super.setUp(); String serviceURI = "http://localhost:8181/wsrf/services/cagrid/QueryService"; client = new QueryServiceClient(serviceURI); } @SuppressWarnings("unused") private DCQLQuery getDCQLObject() throws DeserializationException, FileNotFoundException { dcql = (DCQLQuery) ObjectDeserializer.deserialize(new InputSource(new FileInputStream(dcqlQueryFile)),DCQLQuery.class); return dcql; } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testParser() { decomposedCatripQuery = new QueryDb(); DCQLQuery dcql = new DCQLQuery(); File t = new File(dcqlQueryFile); try { dcql = convertStringToDCQL(getContents(t)); System.out.println("target object : " + dcql.getTargetObject().getName()); ClassDb targetObject = new ClassDb(); targetObject.setName(dcql.getTargetObject().getName()); populateObjectFromDCQLObject(dcql.getTargetObject(), targetObject); printDCQL(dcql); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") private void populateObjectFromDCQLObject(gov.nih.nci.cagrid.dcql.Object dcqlObject, ClassDb aDCQLClass){ ClassDb aClass; if (dcqlObject.getAttribute() != null){ processAttribute(dcqlObject.getAttribute(), aDCQLClass); //decomposedCatripQuery.addClass(aDCQLClass); add(aDCQLClass); } else{ if (dcqlObject.getGroup() != null) processGroup(dcqlObject.getGroup(), aDCQLClass); if (aDCQLClass != null && aDCQLClass.getName() != null) //decomposedCatripQuery.addClass(aDCQLClass); add(aDCQLClass); } if (dcqlObject.getAssociation() != null) { processAssociation(dcqlObject.getAssociation(), new ClassDb()); populateObjectFromDCQLObject(dcqlObject.getAssociation(), null); } if (dcqlObject.getGroup() != null) { ClassDb aGroupAssociation = new ClassDb(); aGroupAssociation.setName(dcqlObject.getName()); processGroup(dcqlObject.getGroup(),new ClassDb()); } if (dcqlObject.getForeignAssociation() != null) { gov.nih.nci.cagrid.dcql.Object o = processForeignAssociation(dcqlObject.getForeignAssociation(), new ClassDb()); populateObjectFromDCQLObject(o, new ClassDb()); } // // // processAttribute(dcqlObject.getAttribute(), aDCQLClass); } private void processAttribute(Attribute dcqlObject, ClassDb aDCQLClass){ if (dcqlObject != null) { if (DEBUG){ System.out.println("processAttribute : " + dcqlObject.getName()); } if (aDCQLClass != null){ AttributeDb attr = new AttributeDb(); attr.setName(dcqlObject.getName()); aDCQLClass.getAttributeCollection().add(attr); } } } private void processAttributes(gov.nih.nci.cagrid.dcql.Object dcqlObject, ClassDb aDCQLClass){ if (dcqlObject.getAttribute() != null){ processAttribute(dcqlObject.getAttribute(), aDCQLClass); } else{ if (dcqlObject.getGroup() != null){ Attribute[] groupAttributes = dcqlObject.getGroup().getAttribute(); if (groupAttributes != null){ for (int i = 0; i < groupAttributes.length; i++) { System.out.println(" group attrs : " + groupAttributes[i].getName()); processAttribute(groupAttributes[i], aDCQLClass); } } } } // if (dcqlObject != null) { // if (dcqlObject.getG) // if (aDCQLClass != null){ // for (int i = 0; i < dcqlObject.length; i++) { // System.out.println(" group attrs : " + dcqlObject[i].getName()); // processAttribute(dcqlObject[i], aDCQLClass); // } // } // } } private void processGroup(gov.nih.nci.cagrid.dcql.Group dcqlGroup, ClassDb aClass) { Attribute[] groupAttributes = dcqlGroup.getAttribute(); if (groupAttributes != null){ for (int i = 0; i < groupAttributes.length; i++) { System.out.println(" group attrs : " + groupAttributes[i].getName()); processAttribute(groupAttributes[i], aClass); } } // associations if (dcqlGroup.getAssociation() != null && dcqlGroup.getAssociation().length > 0) { Association dcqlAssociationArray[] = dcqlGroup.getAssociation(); gov.nih.nci.cagrid.cqlquery.Association[] cqlAssociationArray = new gov.nih.nci.cagrid.cqlquery.Association[dcqlAssociationArray.length]; for (int i = 0; i < dcqlAssociationArray.length; i++) { ClassDb aClassDb = new ClassDb(); processAssociation(dcqlAssociationArray[i],aClassDb); } } // groups if (dcqlGroup.getGroup() != null && dcqlGroup.getGroup().length > 0) { gov.nih.nci.cagrid.dcql.Group[] dcqlGroupArray = dcqlGroup.getGroup(); gov.nih.nci.cagrid.cqlquery.Group[] cqlGroupArray = new gov.nih.nci.cagrid.cqlquery.Group[dcqlGroupArray.length]; for (int i = 0; i < dcqlGroupArray.length; i++) { processGroup(dcqlGroupArray[i], new ClassDb()); } } if (dcqlGroup.getForeignAssociation() != null) { ForeignAssociation[] fa = dcqlGroup.getForeignAssociation(); if (fa != null){ for (int i = 0; i < fa.length; i++) { gov.nih.nci.cagrid.dcql.Object o = processForeignAssociation(fa[i], new ClassDb()); populateObjectFromDCQLObject(o, new ClassDb()); } } } } private Association processAssociation(Association dcqlAssociation, ClassDb aClass){ // create a new CQL Association from the DCQL Association if (DEBUG){ System.out.println("processAssociation : " +dcqlAssociation.getName()); } aClass.setName(dcqlAssociation.getName()); processAttributes(dcqlAssociation, aClass); //decomposedCatripQuery.addClass(aClass); add(aClass); populateObjectFromDCQLObject(dcqlAssociation, new ClassDb()); return dcqlAssociation; } @SuppressWarnings("unchecked") private gov.nih.nci.cagrid.dcql.Object processForeignAssociation(ForeignAssociation foreignAssociation, ClassDb aClass) { // get Foreign Object gov.nih.nci.cagrid.dcql.Object dcqlObject = foreignAssociation.getForeignObject(); if (DEBUG){ System.out.println("processForeignAssociation : " + dcqlObject.getName()); } aClass.setName(dcqlObject.getName()); String foreignAttribute = foreignAssociation.getJoinCondition().getForeignAttributeName(); AttributeDb attribute = new AttributeDb(); attribute.setName(foreignAttribute); aClass.getAttributeCollection().add(attribute); add(aClass); //decomposedCatripQuery.addClass(aClass); if (DEBUG){ System.out.println("foreignAttribute = " + foreignAttribute); } // ClassDb aaClass = new ClassDb(); // aaClass.setName(dcqlObject.getAssociation().getName()); // processAttribute(dcqlObject.getAssociation().getAttribute(), aaClass); // // // decomposedCatripQuery.addClass(aaClass); //populateObjectFromDCQLObject(dcqlObject, new ClassDb()); return dcqlObject; } private void add(ClassDb aClass) { if (aClass == null || aClass.getName() == null) return; // Do not add duplicates boolean duplicateFound = false; Collection queryCollection = decomposedCatripQuery.getClassCollection(); if (queryCollection == null){ decomposedCatripQuery.addClass(aClass); } else{ for (Iterator iter = queryCollection.iterator(); iter.hasNext();) { ClassDb element = (ClassDb) iter.next(); if (element != null && element.getName() != null && !(element.getName().trim().equalsIgnoreCase(aClass.getName().trim()))){ duplicateFound = false; } else{ duplicateFound = true; System.out.println("Found a duplicate " + aClass.getName()); break; } } if (!duplicateFound){ decomposedCatripQuery.addClass(aClass); System.out.println("adding : " + aClass.getName()); } } } private DCQLQuery convertStringToDCQL(String cqlString){ StringBuffer buf = new StringBuffer(cqlString); char[] chars = new char[buf.length()]; buf.getChars(0, chars.length, chars, 0); CharArrayReader car = new CharArrayReader(chars); InputSource source = new InputSource(car); Object obj = null ; try { obj = ObjectDeserializer.deserialize(source,DCQLQuery.class); } catch (DeserializationException e) { e.printStackTrace(); } return ((DCQLQuery)obj); } private String getContents(File aFile) { //...checks on aFile are elided StringBuffer contents = new StringBuffer(); //declared here only to make visible to finally clause BufferedReader input = null; try { //use buffering, reading one line at a time //FileReader always assumes default encoding is OK! input = new BufferedReader( new FileReader(aFile) ); String line = null; //not declared within while loop /* * readLine is a bit quirky : * it returns the content of a line MINUS the newline. * it returns null only for the END of the stream. * it returns an empty String if two newlines appear in a row. */ while (( line = input.readLine()) != null){ contents.append(line); contents.append(System.getProperty("line.separator")); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex){ ex.printStackTrace(); } finally { try { if (input!= null) { //flush and close both "input" and its underlying FileReader input.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return contents.toString(); } private static void printDCQL(DCQLQuery cqlQuery) { QName qname = new QName("http://caGrid.caBIG/1.0/gov.nih.nci.cagrid.cql"); Writer w = new StringWriter(); try { ObjectSerializer.serialize(w, cqlQuery, qname); } catch (SerializationException e) { e.printStackTrace(); } System.out.println(w); } }
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client; import com.hazelcast.client.config.ClientConfig; import com.hazelcast.client.connection.ClientConnectionManager; import com.hazelcast.client.impl.ClientTestUtil; import com.hazelcast.client.impl.HazelcastClientInstanceImpl; import com.hazelcast.client.spi.properties.ClientProperty; import com.hazelcast.client.test.TestHazelcastFactory; import com.hazelcast.core.Client; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.IExecutorService; import com.hazelcast.core.LifecycleEvent; import com.hazelcast.core.LifecycleListener; import com.hazelcast.core.Member; import com.hazelcast.nio.Address; import com.hazelcast.nio.Connection; import com.hazelcast.nio.ConnectionListener; import com.hazelcast.security.UsernamePasswordCredentials; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.HazelcastTestSupport; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import com.hazelcast.util.EmptyStatement; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import java.net.InetSocketAddress; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class ClientConnectionTest extends HazelcastTestSupport { private final TestHazelcastFactory hazelcastFactory = new TestHazelcastFactory(); @After public void cleanup() { hazelcastFactory.terminateAll(); } @Test(expected = IllegalStateException.class) public void testWithIllegalAddress() { String illegalAddress = randomString(); hazelcastFactory.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.getNetworkConfig().setConnectionAttemptPeriod(1); config.getNetworkConfig().addAddress(illegalAddress); hazelcastFactory.newHazelcastClient(config); } @Test public void testWithLegalAndIllegalAddressTogether() { String illegalAddress = randomString(); HazelcastInstance server = hazelcastFactory.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.setProperty(ClientProperty.SHUFFLE_MEMBER_LIST.getName(), "false"); config.getNetworkConfig().addAddress(illegalAddress).addAddress("localhost"); HazelcastInstance client = hazelcastFactory.newHazelcastClient(config); Collection<Client> connectedClients = server.getClientService().getConnectedClients(); assertEquals(connectedClients.size(), 1); Client serverSideClientInfo = connectedClients.iterator().next(); assertEquals(serverSideClientInfo.getUuid(), client.getLocalEndpoint().getUuid()); } @Test public void testMemberConnectionOrder() { HazelcastInstance server1 = hazelcastFactory.newHazelcastInstance(); HazelcastInstance server2 = hazelcastFactory.newHazelcastInstance(); ClientConfig config = new ClientConfig(); config.setProperty(ClientProperty.SHUFFLE_MEMBER_LIST.getName(), "false"); config.getNetworkConfig().setSmartRouting(false); InetSocketAddress socketAddress1 = server1.getCluster().getLocalMember().getSocketAddress(); InetSocketAddress socketAddress2 = server2.getCluster().getLocalMember().getSocketAddress(); config.getNetworkConfig(). addAddress(socketAddress1.getHostName() + ":" + socketAddress1.getPort()). addAddress(socketAddress2.getHostName() + ":" + socketAddress2.getPort()); hazelcastFactory.newHazelcastClient(config); Collection<Client> connectedClients1 = server1.getClientService().getConnectedClients(); assertEquals(connectedClients1.size(), 1); Collection<Client> connectedClients2 = server2.getClientService().getConnectedClients(); assertEquals(connectedClients2.size(), 0); } @Test public void destroyConnection_whenDestroyedMultipleTimes_thenListenerRemoveCalledOnce() { HazelcastInstance server = hazelcastFactory.newHazelcastInstance(); HazelcastInstance client = hazelcastFactory.newHazelcastClient(); HazelcastClientInstanceImpl clientImpl = ClientTestUtil.getHazelcastClientInstanceImpl(client); ClientConnectionManager connectionManager = clientImpl.getConnectionManager(); final CountingConnectionRemoveListener listener = new CountingConnectionRemoveListener(); connectionManager.addConnectionListener(listener); final Address serverAddress = new Address(server.getCluster().getLocalMember().getSocketAddress()); final Connection connectionToServer = connectionManager.getConnection(serverAddress); final CountDownLatch isConnected = new CountDownLatch(1); clientImpl.getLifecycleService().addLifecycleListener(new LifecycleListener() { @Override public void stateChanged(LifecycleEvent event) { if (LifecycleEvent.LifecycleState.CLIENT_CONNECTED == event.getState()) { isConnected.countDown(); } } }); connectionToServer.close(null, null); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertTrue(isConnected.await(5, TimeUnit.SECONDS)); } }); connectionToServer.close(null, null); assertEquals("connection removed should be called only once", 1, listener.count.get()); } private class CountingConnectionRemoveListener implements ConnectionListener { final AtomicInteger count = new AtomicInteger(); @Override public void connectionAdded(Connection connection) { } @Override public void connectionRemoved(Connection connection) { count.incrementAndGet(); } } @Test public void testAsyncConnectionCreationInAsyncMethods() throws ExecutionException, InterruptedException { hazelcastFactory.newHazelcastInstance(); CountDownLatch countDownLatch = new CountDownLatch(1); ClientConfig config = new ClientConfig(); WaitingCredentials credentials = new WaitingCredentials("dev", "dev-pass", countDownLatch); config.setCredentials(credentials); HazelcastInstance client = hazelcastFactory.newHazelcastClient(config); final IExecutorService executorService = client.getExecutorService(randomString()); credentials.waitFlag.set(true); final HazelcastInstance secondInstance = hazelcastFactory.newHazelcastInstance(); final AtomicReference<Future> atomicReference = new AtomicReference<Future>(); Thread thread = new Thread(new Runnable() { @Override public void run() { Member secondMember = secondInstance.getCluster().getLocalMember(); Future future = executorService.submitToMember(new DummySerializableCallable(), secondMember); atomicReference.set(future); } }); thread.start(); try { assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { assertNotNull(atomicReference.get()); } }, 30); } finally { thread.interrupt(); thread.join(); countDownLatch.countDown(); } } static class WaitingCredentials extends UsernamePasswordCredentials { private final CountDownLatch countDownLatch; AtomicBoolean waitFlag = new AtomicBoolean(); WaitingCredentials(String username, String password, CountDownLatch countDownLatch) { super(username, password); this.countDownLatch = countDownLatch; } @Override public String getUsername() { return super.getUsername(); } @Override public String getPassword() { if (waitFlag.get()) { try { countDownLatch.await(); } catch (InterruptedException e) { EmptyStatement.ignore(e); } } return super.getPassword(); } } }
/* * 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.operators.sort; import org.apache.flink.api.common.functions.FlatJoinFunction; import org.apache.flink.api.common.typeutils.GenericPairComparator; import org.apache.flink.api.common.typeutils.TypeComparator; import org.apache.flink.api.common.typeutils.TypePairComparator; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.common.typeutils.base.IntComparator; import org.apache.flink.api.common.typeutils.base.IntSerializer; import org.apache.flink.api.common.typeutils.base.StringSerializer; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.typeutils.runtime.TupleComparator; import org.apache.flink.api.java.typeutils.runtime.TupleSerializer; import org.apache.flink.runtime.io.disk.iomanager.IOManager; import org.apache.flink.runtime.io.disk.iomanager.IOManagerAsync; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.memory.MemoryManager; import org.apache.flink.runtime.operators.testutils.DiscardingOutputCollector; import org.apache.flink.runtime.operators.testutils.DummyInvokable; import org.apache.flink.runtime.operators.testutils.Match; import org.apache.flink.runtime.operators.testutils.MatchRemovingJoiner; import org.apache.flink.runtime.operators.testutils.TestData; import org.apache.flink.runtime.operators.testutils.TestData.TupleGenerator; import org.apache.flink.runtime.operators.testutils.TestData.TupleGenerator.KeyMode; import org.apache.flink.runtime.operators.testutils.TestData.TupleGenerator.ValueMode; import org.apache.flink.util.Collector; import org.apache.flink.util.MutableObjectIterator; import org.apache.flink.util.TestLogger; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; @SuppressWarnings("deprecation") public class NonReusingSortMergeInnerJoinIteratorITCase extends TestLogger { // total memory private static final int MEMORY_SIZE = 1024 * 1024 * 16; private static final int PAGES_FOR_BNLJN = 2; // the size of the left and right inputs private static final int INPUT_1_SIZE = 20000; private static final int INPUT_2_SIZE = 1000; // random seeds for the left and right input data generators private static final long SEED1 = 561349061987311L; private static final long SEED2 = 231434613412342L; // dummy abstract task private final AbstractInvokable parentTask = new DummyInvokable(); private IOManager ioManager; private MemoryManager memoryManager; private TypeSerializer<Tuple2<Integer, String>> serializer1; private TypeSerializer<Tuple2<Integer, String>> serializer2; private TypeComparator<Tuple2<Integer, String>> comparator1; private TypeComparator<Tuple2<Integer, String>> comparator2; private TypePairComparator<Tuple2<Integer, String>, Tuple2<Integer, String>> pairComparator; @SuppressWarnings("unchecked") @Before public void beforeTest() { serializer1 = new TupleSerializer<Tuple2<Integer, String>>( (Class<Tuple2<Integer, String>>) (Class<?>) Tuple2.class, new TypeSerializer<?>[] { IntSerializer.INSTANCE, StringSerializer.INSTANCE }); serializer2 = new TupleSerializer<Tuple2<Integer, String>>( (Class<Tuple2<Integer, String>>) (Class<?>) Tuple2.class, new TypeSerializer<?>[] { IntSerializer.INSTANCE, StringSerializer.INSTANCE }); comparator1 = new TupleComparator<Tuple2<Integer, String>>( new int[]{0}, new TypeComparator<?>[] { new IntComparator(true) }, new TypeSerializer<?>[] { IntSerializer.INSTANCE }); comparator2 = new TupleComparator<Tuple2<Integer, String>>( new int[]{0}, new TypeComparator<?>[] { new IntComparator(true) }, new TypeSerializer<?>[] { IntSerializer.INSTANCE }); pairComparator = new GenericPairComparator<Tuple2<Integer, String>, Tuple2<Integer, String>>(comparator1, comparator2); this.memoryManager = new MemoryManager(MEMORY_SIZE, 1); this.ioManager = new IOManagerAsync(); } @After public void afterTest() throws Exception { if (this.ioManager != null) { this.ioManager.close(); this.ioManager = null; } if (this.memoryManager != null) { Assert.assertTrue("Memory Leak: Not all memory has been returned to the memory manager.", this.memoryManager.verifyEmpty()); this.memoryManager.shutdown(); this.memoryManager = null; } } @Test public void testMerge() { try { final TupleGenerator generator1 = new TupleGenerator(SEED1, 500, 4096, KeyMode.SORTED, ValueMode.RANDOM_LENGTH); final TupleGenerator generator2 = new TupleGenerator(SEED2, 500, 2048, KeyMode.SORTED, ValueMode.RANDOM_LENGTH); final TestData.TupleGeneratorIterator input1 = new TestData.TupleGeneratorIterator(generator1, INPUT_1_SIZE); final TestData.TupleGeneratorIterator input2 = new TestData.TupleGeneratorIterator(generator2, INPUT_2_SIZE); // collect expected data final Map<Integer, Collection<Match>> expectedMatchesMap = matchValues( collectData(input1), collectData(input2)); final FlatJoinFunction<Tuple2<Integer, String>, Tuple2<Integer, String>, Tuple2<Integer, String>> joinFunction = new MatchRemovingJoiner(expectedMatchesMap); final Collector<Tuple2<Integer, String>> collector = new DiscardingOutputCollector<Tuple2<Integer, String>>(); // reset the generators generator1.reset(); generator2.reset(); input1.reset(); input2.reset(); // compare with iterator values NonReusingMergeInnerJoinIterator<Tuple2<Integer, String>, Tuple2<Integer, String>, Tuple2<Integer, String>> iterator = new NonReusingMergeInnerJoinIterator<Tuple2<Integer, String>, Tuple2<Integer, String>, Tuple2<Integer, String>>( input1, input2, this.serializer1, this.comparator1, this.serializer2, this.comparator2, this.pairComparator, this.memoryManager, this.ioManager, PAGES_FOR_BNLJN, this.parentTask); iterator.open(); while (iterator.callWithNextKey(joinFunction, collector)); iterator.close(); // assert that each expected match was seen for (Entry<Integer, Collection<Match>> entry : expectedMatchesMap.entrySet()) { Assert.assertTrue("Collection for key " + entry.getKey() + " is not empty", entry.getValue().isEmpty()); } } catch (Exception e) { e.printStackTrace(); Assert.fail("An exception occurred during the test: " + e.getMessage()); } } @Test public void testMergeWithHighNumberOfCommonKeys() { // the size of the left and right inputs final int INPUT_1_SIZE = 200; final int INPUT_2_SIZE = 100; final int INPUT_1_DUPLICATES = 10; final int INPUT_2_DUPLICATES = 4000; final int DUPLICATE_KEY = 13; try { final TupleGenerator generator1 = new TupleGenerator(SEED1, 500, 4096, KeyMode.SORTED, ValueMode.RANDOM_LENGTH); final TupleGenerator generator2 = new TupleGenerator(SEED2, 500, 2048, KeyMode.SORTED, ValueMode.RANDOM_LENGTH); final TestData.TupleGeneratorIterator gen1Iter = new TestData.TupleGeneratorIterator(generator1, INPUT_1_SIZE); final TestData.TupleGeneratorIterator gen2Iter = new TestData.TupleGeneratorIterator(generator2, INPUT_2_SIZE); final TestData.TupleConstantValueIterator const1Iter = new TestData.TupleConstantValueIterator(DUPLICATE_KEY, "LEFT String for Duplicate Keys", INPUT_1_DUPLICATES); final TestData.TupleConstantValueIterator const2Iter = new TestData.TupleConstantValueIterator(DUPLICATE_KEY, "RIGHT String for Duplicate Keys", INPUT_2_DUPLICATES); final List<MutableObjectIterator<Tuple2<Integer, String>>> inList1 = new ArrayList<MutableObjectIterator<Tuple2<Integer, String>>>(); inList1.add(gen1Iter); inList1.add(const1Iter); final List<MutableObjectIterator<Tuple2<Integer, String>>> inList2 = new ArrayList<MutableObjectIterator<Tuple2<Integer, String>>>(); inList2.add(gen2Iter); inList2.add(const2Iter); MutableObjectIterator<Tuple2<Integer, String>> input1 = new MergeIterator<Tuple2<Integer, String>>(inList1, comparator1.duplicate()); MutableObjectIterator<Tuple2<Integer, String>> input2 = new MergeIterator<Tuple2<Integer, String>>(inList2, comparator2.duplicate()); // collect expected data final Map<Integer, Collection<Match>> expectedMatchesMap = matchValues( collectData(input1), collectData(input2)); // re-create the whole thing for actual processing // reset the generators and iterators generator1.reset(); generator2.reset(); const1Iter.reset(); const2Iter.reset(); gen1Iter.reset(); gen2Iter.reset(); inList1.clear(); inList1.add(gen1Iter); inList1.add(const1Iter); inList2.clear(); inList2.add(gen2Iter); inList2.add(const2Iter); input1 = new MergeIterator<Tuple2<Integer, String>>(inList1, comparator1.duplicate()); input2 = new MergeIterator<Tuple2<Integer, String>>(inList2, comparator2.duplicate()); final FlatJoinFunction<Tuple2<Integer, String>, Tuple2<Integer, String>, Tuple2<Integer, String>> joinFunction = new MatchRemovingJoiner(expectedMatchesMap); final Collector<Tuple2<Integer, String>> collector = new DiscardingOutputCollector<Tuple2<Integer, String>>(); // we create this sort-merge iterator with little memory for the block-nested-loops fall-back to make sure it // needs to spill for the duplicate keys NonReusingMergeInnerJoinIterator<Tuple2<Integer, String>, Tuple2<Integer, String>, Tuple2<Integer, String>> iterator = new NonReusingMergeInnerJoinIterator<Tuple2<Integer, String>, Tuple2<Integer, String>, Tuple2<Integer, String>>( input1, input2, this.serializer1, this.comparator1, this.serializer2, this.comparator2, this.pairComparator, this.memoryManager, this.ioManager, PAGES_FOR_BNLJN, this.parentTask); iterator.open(); while (iterator.callWithNextKey(joinFunction, collector)); iterator.close(); // assert that each expected match was seen for (Entry<Integer, Collection<Match>> entry : expectedMatchesMap.entrySet()) { if (!entry.getValue().isEmpty()) { Assert.fail("Collection for key " + entry.getKey() + " is not empty"); } } } catch (Exception e) { e.printStackTrace(); Assert.fail("An exception occurred during the test: " + e.getMessage()); } } // -------------------------------------------------------------------------------------------- // Utilities // -------------------------------------------------------------------------------------------- private Map<Integer, Collection<Match>> matchValues( Map<Integer, Collection<String>> leftMap, Map<Integer, Collection<String>> rightMap) { Map<Integer, Collection<Match>> map = new HashMap<Integer, Collection<Match>>(); for (Integer key : leftMap.keySet()) { Collection<String> leftValues = leftMap.get(key); Collection<String> rightValues = rightMap.get(key); if (rightValues == null) { continue; } if (!map.containsKey(key)) { map.put(key, new ArrayList<Match>()); } Collection<Match> matchedValues = map.get(key); for (String leftValue : leftValues) { for (String rightValue : rightValues) { matchedValues.add(new Match(leftValue, rightValue)); } } } return map; } private Map<Integer, Collection<String>> collectData(MutableObjectIterator<Tuple2<Integer, String>> iter) throws Exception { Map<Integer, Collection<String>> map = new HashMap<Integer, Collection<String>>(); Tuple2<Integer, String> pair = new Tuple2<Integer, String>(); while ((pair = iter.next(pair)) != null) { final Integer key = pair.getField(0); if (!map.containsKey(key)) { map.put(key, new ArrayList<String>()); } Collection<String> values = map.get(key); final String value = pair.getField(1); values.add(value); } return map; } }
/* * Copyright 2010 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.drools.serialization.protobuf; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import com.google.protobuf.ByteString; import com.google.protobuf.ByteString.Output; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.Message; import org.drools.core.beliefsystem.simple.BeliefSystemLogicalCallback; import org.drools.core.common.DroolsObjectInputStream; import org.drools.core.common.DroolsObjectOutputStream; import org.drools.core.common.WorkingMemoryAction; import org.drools.core.factmodel.traits.TraitFactory; import org.drools.core.impl.InternalKnowledgeBase; import org.drools.core.impl.StatefulKnowledgeSessionImpl.WorkingMemoryReteAssertAction; import org.drools.core.impl.StatefulKnowledgeSessionImpl.WorkingMemoryReteExpireAction; import org.drools.core.marshalling.impl.ActivationKey; import org.drools.core.marshalling.impl.MarshallerReaderContext; import org.drools.core.marshalling.impl.MarshallerWriteContext; import org.drools.core.marshalling.impl.MarshallingHelper; import org.drools.core.marshalling.impl.ProcessMarshaller; import org.drools.core.marshalling.impl.TupleKey; import org.drools.core.rule.SlidingTimeWindow.BehaviorExpireWMAction; import org.drools.core.spi.Tuple; import org.drools.core.util.Drools; import org.drools.core.util.KeyStoreHelper; import org.drools.reflective.classloader.ProjectClassLoader; import org.drools.serialization.protobuf.ProtobufMessages.Header; import org.drools.serialization.protobuf.ProtobufMessages.Header.StrategyIndex.Builder; import org.drools.serialization.protobuf.actions.ProtobufBehaviorExpireWMAction; import org.drools.serialization.protobuf.actions.ProtobufBeliefSystemLogicalCallback; import org.drools.serialization.protobuf.actions.ProtobufWorkingMemoryReteAssertAction; import org.drools.serialization.protobuf.actions.ProtobufWorkingMemoryReteExpireAction; import org.kie.api.marshalling.ObjectMarshallingStrategy; import org.kie.api.marshalling.ObjectMarshallingStrategy.Context; public class PersisterHelper extends MarshallingHelper { public static WorkingMemoryAction readWorkingMemoryAction( MarshallerReaderContext context) throws IOException { int type = context.readShort(); switch ( type ) { case WorkingMemoryAction.WorkingMemoryReteAssertAction : { return new WorkingMemoryReteAssertAction( context ); } case WorkingMemoryAction.LogicalRetractCallback : { return new BeliefSystemLogicalCallback( context ); } case WorkingMemoryAction.WorkingMemoryReteExpireAction : { return new WorkingMemoryReteExpireAction( context ); } case WorkingMemoryAction.WorkingMemoryBehahviourRetract : { return new BehaviorExpireWMAction( context ); } } return null; } public static WorkingMemoryAction deserializeWorkingMemoryAction( MarshallerReaderContext context, ProtobufMessages.ActionQueue.Action _action) throws IOException { switch ( _action.getType() ) { case ASSERT : { return new ProtobufWorkingMemoryReteAssertAction( context, _action ); } case LOGICAL_RETRACT : { return new ProtobufBeliefSystemLogicalCallback(context, _action ); } case EXPIRE : { return new ProtobufWorkingMemoryReteExpireAction(context, _action ); } case BEHAVIOR_EXPIRE : { return new ProtobufBehaviorExpireWMAction( context, _action ); } case SIGNAL : { // need to fix this } case SIGNAL_PROCESS_INSTANCE : { // need to fix this } } return null; } public void write( ProtobufMarshallerWriteContext context) throws IOException { } public static ActivationKey createActivationKey( String pkgName, String ruleName, ProtobufMessages.Tuple _tuple) { return createActivationKey( pkgName, ruleName, toArrayOfObject(createTupleArray( _tuple )) ); } public static ProtobufMessages.Tuple createTuple( final Tuple leftTuple ) { ProtobufMessages.Tuple.Builder _tuple = ProtobufMessages.Tuple.newBuilder(); for( Tuple entry = leftTuple.skipEmptyHandles(); entry != null ; entry = entry.getParent() ) { _tuple.addHandleId( entry.getFactHandle().getId() ); } return _tuple.build(); } public static long[] createTupleArray(final ProtobufMessages.Tuple _tuple) { long[] tuple = new long[_tuple.getHandleIdCount()]; for ( int i = 0; i < tuple.length; i++ ) { // needs to reverse the tuple elements tuple[i] = _tuple.getHandleId( tuple.length - i - 1 ); } return tuple; } public static TupleKey createTupleKey( final ProtobufMessages.Tuple _tuple) { return new TupleKey( createTupleArray( _tuple )); } public static ProtobufMessages.Activation createActivation(final String packageName, final String ruleName, final Tuple tuple) { return ProtobufMessages.Activation.newBuilder() .setPackageName( packageName ) .setRuleName( ruleName ) .setTuple( createTuple( tuple ) ) .build(); } public static void writeToStreamWithHeader( MarshallerWriteContext context, Message payload ) throws IOException { ProtobufMessages.Header.Builder _header = ProtobufMessages.Header.newBuilder(); _header.setVersion( ProtobufMessages.Version.newBuilder() .setVersionMajor( Drools.getMajorVersion() ) .setVersionMinor( Drools.getMinorVersion() ) .setVersionRevision( Drools.getRevisionVersion() ) .build() ); writeStrategiesIndex( context, _header ); InternalKnowledgeBase kBase = context.getKnowledgeBase(); if (kBase != null) { TraitFactory traitFactory = kBase.getConfiguration().getComponentFactory().getTraitFactory(); if (traitFactory != null) { writeRuntimeDefinedClasses(traitFactory, context, _header); } } byte[] buff = payload.toByteArray(); sign( _header, buff ); _header.setPayload( ByteString.copyFrom( buff ) ); context.write( _header.build().toByteArray() ); } private static void writeRuntimeDefinedClasses( TraitFactory traitFactory, MarshallerWriteContext context, ProtobufMessages.Header.Builder _header) { if (context.getKnowledgeBase() == null) { return; } ProjectClassLoader pcl = (ProjectClassLoader) (context.getKnowledgeBase()).getRootClassLoader(); if (pcl.getStore() == null || pcl.getStore().isEmpty()) { return; } List<String> runtimeClassNames = new ArrayList(pcl.getStore().keySet()); Collections.sort(runtimeClassNames); ProtobufMessages.RuntimeClassDef.Builder _classDef = ProtobufMessages.RuntimeClassDef.newBuilder(); for (String resourceName : runtimeClassNames) { if (traitFactory.isRuntimeClass(resourceName)) { _classDef.clear(); _classDef.setClassFqName(resourceName); _classDef.setClassDef(ByteString.copyFrom(pcl.getStore().get(resourceName))); _header.addRuntimeClassDefinitions(_classDef.build()); } } } private static void writeStrategiesIndex( MarshallerWriteContext context, ProtobufMessages.Header.Builder _header) throws IOException { for( Entry<ObjectMarshallingStrategy,Integer> entry : context.getUsedStrategies().entrySet() ) { Builder _strat = ProtobufMessages.Header.StrategyIndex.newBuilder() .setId( entry.getValue().intValue() ) .setName( entry.getKey().getName() ); Context ctx = context.getStrategyContext().get( entry.getKey() ); if( ctx != null ) { Output os = ByteString.newOutput(); ctx.write( new DroolsObjectOutputStream( os ) ); _strat.setData( os.toByteString() ); os.close(); } _header.addStrategy( _strat.build() ); } } private static void sign(ProtobufMessages.Header.Builder _header, byte[] buff ) { KeyStoreHelper helper = new KeyStoreHelper(); if (helper.isSigned()) { try { _header.setSignature( ProtobufMessages.Signature.newBuilder() .setKeyAlias( helper.getPvtKeyAlias() ) .setSignature( ByteString.copyFrom( helper.signDataWithPrivateKey( buff ) ) ) .build() ); } catch (Exception e) { throw new RuntimeException( "Error signing session: " + e.getMessage(), e ); } } } private static ProtobufMessages.Header loadStrategiesCheckSignature( MarshallerReaderContext context, ProtobufMessages.Header _header) throws ClassNotFoundException, IOException { loadStrategiesIndex( context, _header ); byte[] sessionbuff = _header.getPayload().toByteArray(); // should we check version as well here? checkSignature( _header, sessionbuff ); return _header; } public static ProtobufMessages.Header readFromStreamWithHeaderPreloaded( MarshallerReaderContext context, ExtensionRegistry registry ) throws IOException, ClassNotFoundException { // we preload the stream into a byte[] to overcome a message size limit // imposed by protobuf as per https://issues.jboss.org/browse/DROOLS-25 byte[] preloaded = preload((InputStream) context); ProtobufMessages.Header _header = ProtobufMessages.Header.parseFrom( preloaded, registry ); return loadStrategiesCheckSignature(context, _header); } /* Method that preloads the source stream into a byte array to bypass the message size limitations in Protobuf unmarshalling. (Protobuf does not enforce a message size limit when unmarshalling from a byte array) */ private static byte[] preload(InputStream stream) throws IOException { byte[] buf = new byte[4096]; ByteArrayOutputStream preloaded = new ByteArrayOutputStream(); int read; while((read = stream.read(buf)) != -1) { preloaded.write(buf, 0, read); } return preloaded.toByteArray(); } private static void loadStrategiesIndex( MarshallerReaderContext context, ProtobufMessages.Header _header) throws IOException, ClassNotFoundException { for ( ProtobufMessages.Header.StrategyIndex _entry : _header.getStrategyList() ) { ObjectMarshallingStrategy strategyObject = context.getResolverStrategyFactory().getStrategyObject( _entry.getName() ); if ( strategyObject == null ) { throw new IllegalStateException( "No strategy of type " + _entry.getName() + " available." ); } context.getUsedStrategies().put( _entry.getId(), strategyObject ); Context ctx = strategyObject.createContext(); context.getStrategyContexts().put( strategyObject, ctx ); if( _entry.hasData() && ctx != null ) { ClassLoader classLoader = null; if (context.getClassLoader() != null ){ classLoader = context.getClassLoader(); } else if(context.getKnowledgeBase() != null){ classLoader = context.getKnowledgeBase().getRootClassLoader(); } if ( classLoader instanceof ProjectClassLoader ) { readRuntimeDefinedClasses( _header, (ProjectClassLoader) classLoader ); } ctx.read( new DroolsObjectInputStream( _entry.getData().newInput(), classLoader) ); } } } public static void readRuntimeDefinedClasses( Header _header, ProjectClassLoader pcl ) throws IOException, ClassNotFoundException { if ( _header.getRuntimeClassDefinitionsCount() > 0 ) { for ( ProtobufMessages.RuntimeClassDef def : _header.getRuntimeClassDefinitionsList() ) { String resourceName = def.getClassFqName(); byte[] byteCode = def.getClassDef().toByteArray(); if ( ! pcl.getStore().containsKey( resourceName ) ) { pcl.getStore().put(resourceName, byteCode); } } } } private static void checkSignature(Header _header, byte[] sessionbuff) { KeyStoreHelper helper = new KeyStoreHelper(); boolean signed = _header.hasSignature(); if ( helper.isSigned() != signed ) { throw new RuntimeException( "This environment is configured to work with " + (helper.isSigned() ? "signed" : "unsigned") + " serialized objects, but the given object is " + (signed ? "signed" : "unsigned") + ". Deserialization aborted." ); } if ( signed ) { if ( helper.getPubKeyStore() == null ) { throw new RuntimeException( "The session was serialized with a signature. Please configure a public keystore with the public key to check the signature. Deserialization aborted." ); } try { if ( !helper.checkDataWithPublicKey( _header.getSignature().getKeyAlias(), sessionbuff, _header.getSignature().getSignature().toByteArray() ) ) { throw new RuntimeException( "Signature does not match serialized package. This is a security violation. Deserialisation aborted." ); } } catch ( InvalidKeyException e ) { throw new RuntimeException( "Invalid key checking signature: " + e.getMessage(), e ); } catch ( KeyStoreException e ) { throw new RuntimeException( "Error accessing Key Store: " + e.getMessage(), e ); } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException( "No algorithm available: " + e.getMessage(), e ); } catch ( SignatureException e ) { throw new RuntimeException( "Signature Exception: " + e.getMessage(), e ); } } } public static ExtensionRegistry buildRegistry( MarshallerReaderContext context, ProcessMarshaller processMarshaller ) { ExtensionRegistry registry = ExtensionRegistry.newInstance(); if( processMarshaller != null ) { context.setParameterObject( registry ); processMarshaller.init( context ); } return registry; } }
/* * 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.table.runtime.operators.rank; import org.apache.flink.api.common.ExecutionConfig; import org.apache.flink.api.common.state.MapState; import org.apache.flink.api.common.state.MapStateDescriptor; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.api.java.typeutils.ListTypeInfo; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.dataformat.BaseRow; import org.apache.flink.table.runtime.generated.GeneratedRecordComparator; import org.apache.flink.table.runtime.keyselector.BaseRowKeySelector; import org.apache.flink.table.runtime.typeutils.BaseRowTypeInfo; import org.apache.flink.table.runtime.util.LRUMap; import org.apache.flink.util.Collector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * The function could and only could handle append input stream. */ public class AppendOnlyTopNFunction extends AbstractTopNFunction { private static final long serialVersionUID = -4708453213104128010L; private static final Logger LOG = LoggerFactory.getLogger(AppendOnlyTopNFunction.class); private final BaseRowTypeInfo sortKeyType; private final TypeSerializer<BaseRow> inputRowSer; private final long cacheSize; // a map state stores mapping from sort key to records list which is in topN private transient MapState<BaseRow, List<BaseRow>> dataState; // the buffer stores mapping from sort key to records list, a heap mirror to dataState private transient TopNBuffer buffer; // the kvSortedMap stores mapping from partition key to it's buffer private transient Map<BaseRow, TopNBuffer> kvSortedMap; public AppendOnlyTopNFunction( long minRetentionTime, long maxRetentionTime, BaseRowTypeInfo inputRowType, GeneratedRecordComparator sortKeyGeneratedRecordComparator, BaseRowKeySelector sortKeySelector, RankType rankType, RankRange rankRange, boolean generateUpdateBefore, boolean outputRankNumber, long cacheSize) { super(minRetentionTime, maxRetentionTime, inputRowType, sortKeyGeneratedRecordComparator, sortKeySelector, rankType, rankRange, generateUpdateBefore, outputRankNumber); this.sortKeyType = sortKeySelector.getProducedType(); this.inputRowSer = inputRowType.createSerializer(new ExecutionConfig()); this.cacheSize = cacheSize; } public void open(Configuration parameters) throws Exception { super.open(parameters); int lruCacheSize = Math.max(1, (int) (cacheSize / getDefaultTopNSize())); kvSortedMap = new LRUMap<>(lruCacheSize); LOG.info("Top{} operator is using LRU caches key-size: {}", getDefaultTopNSize(), lruCacheSize); ListTypeInfo<BaseRow> valueTypeInfo = new ListTypeInfo<>(inputRowType); MapStateDescriptor<BaseRow, List<BaseRow>> mapStateDescriptor = new MapStateDescriptor<>( "data-state-with-append", sortKeyType, valueTypeInfo); dataState = getRuntimeContext().getMapState(mapStateDescriptor); // metrics registerMetric(kvSortedMap.size() * getDefaultTopNSize()); } @Override public void processElement(BaseRow input, Context context, Collector<BaseRow> out) throws Exception { long currentTime = context.timerService().currentProcessingTime(); // register state-cleanup timer registerProcessingCleanupTimer(context, currentTime); initHeapStates(); initRankEnd(input); BaseRow sortKey = sortKeySelector.getKey(input); // check whether the sortKey is in the topN range if (checkSortKeyInBufferRange(sortKey, buffer)) { // insert sort key into buffer buffer.put(sortKey, inputRowSer.copy(input)); Collection<BaseRow> inputs = buffer.get(sortKey); // update data state dataState.put(sortKey, (List<BaseRow>) inputs); if (outputRankNumber || hasOffset()) { // the without-number-algorithm can't handle topN with offset, // so use the with-number-algorithm to handle offset processElementWithRowNumber(sortKey, input, out); } else { processElementWithoutRowNumber(input, out); } } } @Override public void onTimer( long timestamp, OnTimerContext ctx, Collector<BaseRow> out) throws Exception { if (stateCleaningEnabled) { // cleanup cache kvSortedMap.remove(keyContext.getCurrentKey()); cleanupState(dataState); } } private void initHeapStates() throws Exception { requestCount += 1; BaseRow currentKey = (BaseRow) keyContext.getCurrentKey(); buffer = kvSortedMap.get(currentKey); if (buffer == null) { buffer = new TopNBuffer(sortKeyComparator, ArrayList::new); kvSortedMap.put(currentKey, buffer); // restore buffer Iterator<Map.Entry<BaseRow, List<BaseRow>>> iter = dataState.iterator(); if (iter != null) { while (iter.hasNext()) { Map.Entry<BaseRow, List<BaseRow>> entry = iter.next(); BaseRow sortKey = entry.getKey(); List<BaseRow> values = entry.getValue(); // the order is preserved buffer.putAll(sortKey, values); } } } else { hitCount += 1; } } private void processElementWithRowNumber(BaseRow sortKey, BaseRow input, Collector<BaseRow> out) throws Exception { Iterator<Map.Entry<BaseRow, Collection<BaseRow>>> iterator = buffer.entrySet().iterator(); long curRank = 0L; boolean findsSortKey = false; while (iterator.hasNext() && isInRankEnd(curRank)) { Map.Entry<BaseRow, Collection<BaseRow>> entry = iterator.next(); Collection<BaseRow> records = entry.getValue(); // meet its own sort key if (!findsSortKey && entry.getKey().equals(sortKey)) { curRank += records.size(); collect(out, input, curRank); findsSortKey = true; } else if (findsSortKey) { Iterator<BaseRow> recordsIter = records.iterator(); while (recordsIter.hasNext() && isInRankEnd(curRank)) { curRank += 1; BaseRow prevRow = recordsIter.next(); retract(out, prevRow, curRank - 1); collect(out, prevRow, curRank); } } else { curRank += records.size(); } } // remove the records associated to the sort key which is out of topN List<BaseRow> toDeleteSortKeys = new ArrayList<>(); while (iterator.hasNext()) { Map.Entry<BaseRow, Collection<BaseRow>> entry = iterator.next(); BaseRow key = entry.getKey(); dataState.remove(key); toDeleteSortKeys.add(key); } for (BaseRow toDeleteKey : toDeleteSortKeys) { buffer.removeAll(toDeleteKey); } } private void processElementWithoutRowNumber(BaseRow input, Collector<BaseRow> out) throws Exception { // remove retired element if (buffer.getCurrentTopNum() > rankEnd) { Map.Entry<BaseRow, Collection<BaseRow>> lastEntry = buffer.lastEntry(); BaseRow lastKey = lastEntry.getKey(); List<BaseRow> lastList = (List<BaseRow>) lastEntry.getValue(); // remove last one BaseRow lastElement = lastList.remove(lastList.size() - 1); if (lastList.isEmpty()) { buffer.removeAll(lastKey); dataState.remove(lastKey); } else { dataState.put(lastKey, lastList); } if (input.equals(lastElement)) { return; } else { // lastElement shouldn't be null delete(out, lastElement); } } collect(out, input); } }
/* * Copyright 1999-2012 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.orient.test.internal; import java.io.IOException; import java.util.ConcurrentModificationException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.orientechnologies.common.exception.OException; import com.orientechnologies.orient.client.db.ODatabaseHelper; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.db.record.ODatabaseRecord; import com.orientechnologies.orient.core.exception.OConcurrentModificationException; import com.orientechnologies.orient.core.exception.ORecordNotFoundException; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocumentHelper; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; @Test public class FreezeMultiThreadingTestNonTX { private static final int TRANSACTIONAL_CREATOR_THREAD_COUNT = 2; private static final int TRANSACTIONAL_UPDATER_THREAD_COUNT = 2; private static final int TRANSACTIONAL_DELETER_THREAD_COUNT = 2; private static final int CREATOR_THREAD_COUNT = 10; private static final int UPDATER_THREAD_COUNT = 10; private static final int DELETER_THREAD_COUNT = 10; private static final int DOCUMENT_COUNT = 1000; private static final int TRANSACTIONAL_DOCUMENT_COUNT = 1000; private static final String URL = "remote:localhost/FreezeMultiThreadingTestNonTX"; private static final String STUDENT_CLASS_NAME = "Student"; private static final String TRANSACTIONAL_WORD = "Transactional"; private AtomicInteger createCounter = new AtomicInteger(0); private AtomicInteger deleteCounter = new AtomicInteger(0); private AtomicInteger transactionalCreateCounter = new AtomicInteger(0); private AtomicInteger transactionalDeleteCounter = new AtomicInteger(0); private final ExecutorService executorService = Executors.newFixedThreadPool(CREATOR_THREAD_COUNT + UPDATER_THREAD_COUNT + DELETER_THREAD_COUNT + 1); private ConcurrentSkipListSet<Integer> deleted = new ConcurrentSkipListSet<Integer>(); private ConcurrentSkipListSet<Integer> deletedInTransaction = new ConcurrentSkipListSet<Integer>(); private CountDownLatch countDownLatch = new CountDownLatch(1); private class NonTransactionalAdder implements Callable<Void> { public Void call() throws Exception { Thread.currentThread().setName("Adder - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); try { ODatabaseRecordThreadLocal.INSTANCE.set(database); countDownLatch.await(); long value = createCounter.getAndIncrement(); while (value < DOCUMENT_COUNT) { Thread.sleep(200); ODocument document = new ODocument(STUDENT_CLASS_NAME); document.field("counter", value); document.save(); if (value % 10 == 0) System.out.println(Thread.currentThread() + " : document " + value + " added"); value = createCounter.getAndIncrement(); } return null; } catch (Exception e) { e.printStackTrace(); throw e; } catch (Throwable e) { e.printStackTrace(); return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); database.close(); } } } private class TransactionalAdder implements Callable<Void> { public Void call() throws Exception { Thread.currentThread().setName("TransactionalAdder - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); try { ODatabaseRecordThreadLocal.INSTANCE.set(database); countDownLatch.await(); long value = transactionalCreateCounter.getAndIncrement(); while (value < TRANSACTIONAL_DOCUMENT_COUNT) { Thread.sleep(200); database.begin(); ODocument document = new ODocument(TRANSACTIONAL_WORD + STUDENT_CLASS_NAME); document.field("counter", value); document.save(); database.commit(); if (value % 10 == 0) System.out.println(Thread.currentThread() + " : document " + value + " added"); value = transactionalCreateCounter.getAndIncrement(); } return null; } catch (Exception e) { e.printStackTrace(); throw e; } catch (Throwable e) { e.printStackTrace(); return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); database.close(); } } } private class NonTransactionalUpdater implements Callable<Void> { private int updateCounter = 0; public Void call() throws Exception { Thread.currentThread().setName("Updater - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); try { ODatabaseRecordThreadLocal.INSTANCE.set(database); countDownLatch.await(); while (updateCounter < DOCUMENT_COUNT) { if (updateCounter > createCounter.get()) { continue; } List<ODocument> execute = null; if (updateCounter % 10 == 0) System.out.println(Thread.currentThread() + " : before search cycle(update)" + updateCounter); do { try { execute = database.command(new OSQLSynchQuery<Object>("select * from " + STUDENT_CLASS_NAME + " where counter = ?")) .execute(updateCounter); } catch (ORecordNotFoundException onfe) { System.out.println("Record not found for doc " + updateCounter); } catch (OException e) { if (e.getMessage().contains("Error during loading record with id")) { // ignore this because record deleted System.out.println(Thread.currentThread() + "exception record already deleted"); continue; } if (e.getCause() instanceof ConcurrentModificationException) { System.out.println(Thread.currentThread() + "exception concurrent modification"); // ignore this because record deleted continue; } throw e; } } while (!deleted.contains(updateCounter) && (execute == null || execute.isEmpty())); if (!deleted.contains(updateCounter)) { if (updateCounter % 10 == 0) System.out.println(Thread.currentThread() + " : after search cycle(update) " + updateCounter); ODocument document = execute.get(0); document.field("counter2", document.field("counter")); try { document.save(); if (updateCounter % 10 == 0) System.out.println(Thread.currentThread() + " : document " + updateCounter + " updated"); updateCounter++; } catch (ORecordNotFoundException ornfe) { System.out.println(Thread.currentThread() + " exception record already deleted"); } catch (OConcurrentModificationException e) { System.out.println(Thread.currentThread() + " : concurrent modification exception while updating! " + updateCounter); } catch (Exception e) { e.printStackTrace(); throw e; } } else { System.out.println(Thread.currentThread() + " : document " + updateCounter + " already deleted couldn't update!"); updateCounter++; } } return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); database.close(); } } } private class TransactionalUpdater implements Callable<Void> { private int updateCounter = 0; public Void call() throws Exception { Thread.currentThread().setName("TransactionalUpdater - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); try { ODatabaseRecordThreadLocal.INSTANCE.set(database); countDownLatch.await(); while (updateCounter < TRANSACTIONAL_DOCUMENT_COUNT) { if (updateCounter > transactionalCreateCounter.get()) { continue; } List<ODocument> execute = null; if (updateCounter % 10 == 0) System.out.println(Thread.currentThread() + " : before search cycle(update)" + updateCounter); do { try { execute = database.command( new OSQLSynchQuery<Object>("select * from " + TRANSACTIONAL_WORD + STUDENT_CLASS_NAME + " where counter = ?")) .execute(updateCounter); } catch (ORecordNotFoundException onfe) { // ignore has been deleted } catch (OException e) { if (e.getMessage().contains("Error during loading record with id")) { // ignore this because record deleted System.out.println(Thread.currentThread() + "exception record already deleted"); continue; } if (e.getCause() instanceof ConcurrentModificationException) { System.out.println(Thread.currentThread() + "exception concurrent modification"); // ignore this because record deleted continue; } throw e; } } while (!deletedInTransaction.contains(updateCounter) && (execute == null || execute.isEmpty())); if (!deletedInTransaction.contains(updateCounter)) { if (updateCounter % 10 == 0) System.out.println(Thread.currentThread() + " : after search cycle(update) " + updateCounter); database.begin(); ODocument document = execute.get(0); document.field("counter2", document.field("counter")); try { document.save(); database.commit(); if (updateCounter % 10 == 0) System.out.println(Thread.currentThread() + " : document " + updateCounter + " updated"); updateCounter++; } catch (ORecordNotFoundException ornfe) { System.out.println(Thread.currentThread() + " exception record already deleted"); } catch (OConcurrentModificationException e) { System.out.println(Thread.currentThread() + " : concurrent modification exception while updating! " + updateCounter); } catch (Exception e) { e.printStackTrace(); throw e; } } else { System.out.println(Thread.currentThread() + " : document " + updateCounter + " already deleted couldn't update!"); updateCounter++; } } return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); database.close(); } } } private class NonTransactionalDeleter implements Callable<Void> { public Void call() throws Exception { Thread.currentThread().setName("Deleter - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); try { ODatabaseRecordThreadLocal.INSTANCE.set(database); countDownLatch.await(); int number = deleteCounter.getAndIncrement(); while (number < DOCUMENT_COUNT) { // wait while necessary document will be created while (number > createCounter.get()) ; try { List<ODocument> execute; if (number % 10 == 0) System.out.println(Thread.currentThread() + " : before search cycle (delete) " + number); do { execute = database.command(new OSQLSynchQuery<Object>("select * from " + STUDENT_CLASS_NAME + " where counter2 = ?")) .execute(number); } while (execute == null || execute.isEmpty()); if (number % 10 == 0) System.out.println(Thread.currentThread() + " : after search cycle (delete)" + number); ODocument document = execute.get(0); document.delete(); deleted.add(number); if (number % 10 == 0) System.out.println(Thread.currentThread() + " : document deleted " + number); number = deleteCounter.getAndIncrement(); } catch (OConcurrentModificationException e) { System.out.println(Thread.currentThread() + " : exception while deleted " + number); } } return null; } catch (Exception e) { e.printStackTrace(); throw e; } catch (Throwable e) { e.printStackTrace(); return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); database.close(); } } } private class TransactionalDeleter implements Callable<Void> { public Void call() throws Exception { Thread.currentThread().setName("TransactionalDeleterDeleter - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); try { ODatabaseRecordThreadLocal.INSTANCE.set(database); countDownLatch.await(); int number = transactionalDeleteCounter.getAndIncrement(); while (number < TRANSACTIONAL_DOCUMENT_COUNT) { // wait while necessary document will be created while (number > transactionalCreateCounter.get()) ; try { List<ODocument> execute; if (number % 10 == 0) System.out.println(Thread.currentThread() + " : before search cycle (delete) " + number); do { execute = database.command( new OSQLSynchQuery<Object>("select * from " + TRANSACTIONAL_WORD + STUDENT_CLASS_NAME + " where counter2 = ?")) .execute(number); } while (execute == null || execute.isEmpty()); if (number % 10 == 0) System.out.println(Thread.currentThread() + " : after search cycle (delete)" + number); database.begin(); ODocument document = execute.get(0); document.delete(); database.commit(); deletedInTransaction.add(number); if (number % 10 == 0) System.out.println(Thread.currentThread() + " : document deleted " + number); number = transactionalDeleteCounter.getAndIncrement(); } catch (OConcurrentModificationException e) { System.out.println(Thread.currentThread() + " : exception while deleted " + number); } } return null; } catch (Exception e) { e.printStackTrace(); throw e; } catch (Throwable e) { e.printStackTrace(); return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); database.close(); } } } private class Locker implements Callable<Void> { public Void call() throws Exception { Thread.currentThread().setName("Locker - " + Thread.currentThread().getId()); ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); try { countDownLatch.await(); while (createCounter.get() < DOCUMENT_COUNT) { ODatabaseHelper.freezeDatabase(database); database.open("admin", "admin"); final List<ODocument> beforeNonTxDocuments = database.query(new OSQLSynchQuery<Object>("select from " + STUDENT_CLASS_NAME)); final List<ODocument> beforeTxDocuments = database.query(new OSQLSynchQuery<Object>("select from " + TRANSACTIONAL_WORD + STUDENT_CLASS_NAME)); database.close(); System.out.println("Freeze DB - nonTx : " + beforeNonTxDocuments.size() + " Tx : " + beforeTxDocuments.size()); try { Thread.sleep(10000); } finally { database.open("admin", "admin"); final List<ODocument> afterNonTxDocuments = database.query(new OSQLSynchQuery<Object>("select from " + STUDENT_CLASS_NAME)); final List<ODocument> afterTxDocuments = database.query(new OSQLSynchQuery<Object>("select from " + TRANSACTIONAL_WORD + STUDENT_CLASS_NAME)); assertDocumentAreEquals(beforeNonTxDocuments, afterNonTxDocuments); assertDocumentAreEquals(beforeTxDocuments, afterTxDocuments); database.close(); System.out.println("Release DB - nonTx : " + afterNonTxDocuments.size() + " Tx : " + afterTxDocuments.size()); ODatabaseHelper.releaseDatabase(database); } Thread.sleep(10000); } return null; } catch (Exception e) { e.printStackTrace(); throw e; } catch (Throwable e) { e.printStackTrace(); return null; } finally { System.out.println(Thread.currentThread() + "************************CLOSE************************************"); } } } @BeforeMethod public void setUp() throws Exception { OGlobalConfiguration.CACHE_LEVEL1_ENABLED.setValue(false); OGlobalConfiguration.CACHE_LEVEL2_ENABLED.setValue(false); OGlobalConfiguration.CACHE_LEVEL1_SIZE.setValue(0); OGlobalConfiguration.CACHE_LEVEL2_SIZE.setValue(0); OGlobalConfiguration.CLIENT_DB_RELEASE_WAIT_TIMEOUT.setValue(1000); // OGlobalConfiguration.CLIENT_CHANNEL_MAX_POOL.setValue(50); System.out.println("Create db"); // SETUP DB try { ODatabaseDocumentTx db = new ODatabaseDocumentTx(URL); System.out.println("Recreating database"); if (ODatabaseHelper.existsDatabase(db)) { db.setProperty("security", Boolean.FALSE); ODatabaseHelper.dropDatabase(db, URL); } ODatabaseHelper.createDatabase(db, URL); db.close(); } catch (IOException ex) { System.out.println("Exception: " + ex); throw ex; } ODatabaseDocumentTx database = new ODatabaseDocumentTx(URL); database.open("admin", "admin"); OClass student = database.getMetadata().getSchema().createClass(STUDENT_CLASS_NAME); student.createProperty("counter", OType.INTEGER); student.createProperty("counter2", OType.INTEGER); student.createIndex("index1", OClass.INDEX_TYPE.UNIQUE, "counter"); student.createIndex("index2", OClass.INDEX_TYPE.NOTUNIQUE, "counter2"); student.createIndex("index3", OClass.INDEX_TYPE.NOTUNIQUE, "counter", "counter2"); OClass transactionalStudent = database.getMetadata().getSchema().createClass(TRANSACTIONAL_WORD + STUDENT_CLASS_NAME); transactionalStudent.createProperty("counter", OType.INTEGER); transactionalStudent.createProperty("counter2", OType.INTEGER); transactionalStudent.createIndex("index4", OClass.INDEX_TYPE.UNIQUE, "counter"); transactionalStudent.createIndex("index5", OClass.INDEX_TYPE.NOTUNIQUE, "counter2"); transactionalStudent.createIndex("index6", OClass.INDEX_TYPE.NOTUNIQUE, "counter", "counter2"); database.getMetadata().getSchema().save(); System.out.println("*in before***********CLOSE************************************"); database.close(); } @Test public void test() throws Exception { Set<Future<Void>> threads = new HashSet<Future<Void>>(CREATOR_THREAD_COUNT + DELETER_THREAD_COUNT + UPDATER_THREAD_COUNT + 1); for (int i = 0; i < CREATOR_THREAD_COUNT; ++i) { NonTransactionalAdder thread = new NonTransactionalAdder(); threads.add(executorService.submit(thread)); } for (int i = 0; i < UPDATER_THREAD_COUNT; ++i) { NonTransactionalUpdater thread = new NonTransactionalUpdater(); threads.add(executorService.submit(thread)); } for (int i = 0; i < DELETER_THREAD_COUNT; ++i) { NonTransactionalDeleter thread = new NonTransactionalDeleter(); threads.add(executorService.submit(thread)); } // for (int i = 0; i < TRANSACTIONAL_CREATOR_THREAD_COUNT; ++i) { // TransactionalAdder thread = new TransactionalAdder(); // threads.add(executorService.submit(thread)); // } // for (int i = 0; i < TRANSACTIONAL_UPDATER_THREAD_COUNT; ++i) { // TransactionalUpdater thread = new TransactionalUpdater(); // threads.add(executorService.submit(thread)); // } // // for (int i = 0; i < TRANSACTIONAL_DELETER_THREAD_COUNT; ++i) { // TransactionalDeleter thread = new TransactionalDeleter(); // threads.add(executorService.submit(thread)); // } threads.add(executorService.submit(new Locker())); countDownLatch.countDown(); for (Future<Void> future : threads) future.get(); System.out.println("finish"); } private void assertDocumentAreEquals(List<ODocument> firstDocs, List<ODocument> secondDocs) { if (firstDocs.size() != secondDocs.size()) Assert.fail(); outer: for (final ODocument firstDoc : firstDocs) { for (final ODocument secondDoc : secondDocs) { if (firstDoc.equals(secondDoc)) { final ODatabaseRecord databaseRecord = ODatabaseRecordThreadLocal.INSTANCE.get(); Assert.assertTrue(ODocumentHelper.hasSameContentOf(firstDoc, databaseRecord, secondDoc, databaseRecord)); continue outer; } } Assert.fail("Document " + firstDoc + " was changed during DB freeze"); } } }
/* --------------------------------------------------------------------- * This file is part of the program EscherConverter. * * Copyright (C) 2013-2017 by the University of California, San Diego. * * 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. A copy of the license * agreement is provided in the file named "LICENSE.txt" included with * this software distribution and also available online as * <http://www.gnu.org/licenses/lgpl-3.0-standalone.html>. * --------------------------------------------------------------------- */ package edu.ucsd.sbrg.escher.converter; import de.zbit.graph.io.def.SBGNProperties; import de.zbit.graph.io.def.SBGNProperties.ArcType; import de.zbit.graph.io.def.SBGNProperties.GlyphType; import de.zbit.sbml.util.SBMLtools; import edu.ucsd.sbrg.escher.model.*; import edu.ucsd.sbrg.escher.model.Point; import edu.ucsd.sbrg.sbgn.SBGNbuilder; import org.sbgn.bindings.*; import org.sbgn.bindings.Arc.End; import org.sbgn.bindings.Arc.Next; import org.sbgn.bindings.Glyph.Callout; import org.sbml.jsbml.util.ResourceManager; import org.sbml.jsbml.util.StringTools; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.text.MessageFormat; import java.util.*; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; /** * @author Andreas Dr&auml;ger * @since 1.0 */ public class Escher2SBGN extends Escher2Standard<Sbgn> { /** * A {@link java.util.logging.Logger} for this class. */ private static final Logger logger = Logger.getLogger(Escher2SBGN.class.getName()); /** * Localization support. */ public static final ResourceBundle bundle = ResourceManager.getBundle("edu.ucsd.sbrg.escher.Messages"); /** * The SBGN map builder. */ private SBGNbuilder builder; /** * Default constructor. */ public Escher2SBGN() { super(); builder = new SBGNbuilder(); } /* (non-Javadoc) * @see edu.ucsd.sbrg.escher.converters.Escher2Standard#convert(edu.ucsd.sbrg.escher.model.EscherMap) */ @Override public Sbgn convert(EscherMap escherMap) { preprocessDataStructure(escherMap); Canvas canvas = escherMap.getCanvas(); double xOffset = canvas.isSetX() ? canvas.getX().doubleValue() : 0d; double yOffset = canvas.isSetY() ? canvas.getY().doubleValue() : 0d; Sbgn sbgn = builder.createSbgn(); org.sbgn.bindings.Map map = builder.createMap(SBGNbuilder.Language.process_description, 0d, 0d, canvas.isSetHeight() ? canvas.getHeight().doubleValue() : getCanvasDefaultHeight(), canvas.isSetWidth() ? canvas.getWidth().doubleValue() : getCanvasDefaultWidth()); sbgn.setMap(map); if (escherMap.isSetDescription()) { try { // TODO: also insert map's name here if there is any, maybe Escher Homepage map.setNotes(builder.createNotes(escherMap.getDescription())); } catch (ParserConfigurationException | SAXException | IOException exc) { // TODO logger.warning(exc.getMessage()); } } Map<String, SBGNBase> node2glyph = new HashMap<String, SBGNBase>(); Map<String, Node> multimarkers = new HashMap<String, Node>(); if (getInferCompartmentBoundaries()) { int i = 0; for (Map.Entry<String, EscherCompartment> entry : escherMap .compartments()) { String id = entry.getKey(); if (!(id.equalsIgnoreCase("n") || id.equalsIgnoreCase("e"))) { EscherCompartment compartment = entry.getValue(); Glyph compGlyph = builder.createGlyph(id, compartment.getName(), SBGNProperties.GlyphType.compartment, compartment.getX() - xOffset, compartment.getY() - yOffset, compartment.getWidth(), compartment.getHeight()); node2glyph.put(compGlyph.getId(), compGlyph); map.getGlyph().add(compGlyph); // TODO: arrange compartments according to their size. compGlyph.setCompartmentOrder((float) --i); } } } for (Map.Entry<String, Node> entry : escherMap.nodes()) { convertNode(entry.getValue(), escherMap, node2glyph, multimarkers, map, xOffset, yOffset); } for (Map.Entry<String, EscherReaction> entry : escherMap.reactions()) { convertProcess(entry.getValue(), escherMap, map, node2glyph, xOffset, yOffset); } for (Map.Entry<String, TextLabel> entry : escherMap.textLabels()) { createTextLabel(entry.getValue(), map, xOffset, yOffset); } return sbgn; } /** * @param node * @param escherMap * @param node2glyph * @param multimarkers * @param xOffset * @param yOffset */ private void convertNode(Node node, EscherMap escherMap, Map<String, SBGNBase> node2glyph, Map<String, Node> multimarkers, org.sbgn.bindings.Map map, double xOffset, double yOffset) { Glyph glyph = null; if (node.isSetType()) { switch (node.getType()) { case metabolite: glyph = convertMetabolite(node, escherMap, multimarkers, xOffset, yOffset); node2glyph.put(node.getId(), glyph); map.getGlyph().add(glyph); break; case midmarker: glyph = convertMidmarker(node, node2glyph, map, xOffset, yOffset); break; case exchange: // TODO: Exchange! glyph = convertExchange(node, node2glyph, map, xOffset, yOffset); break; case multimarker: // This is done when converting reaction arcs. //convertMultimarker(node, multimarkers, xOffset, yOffset); break; default: // This is also done at a different time. // convertTextLabel(node, map, xOffset, yOffset); break; } } if ((glyph != null) && getInferCompartmentBoundaries() && node .isSetCompartment()) { String id = node.getCompartment(); if (!(id.equalsIgnoreCase("n") || id.equalsIgnoreCase("e"))) { glyph.setCompartmentRef(builder.getSBGNBase(id)); } } } /** * @param node * @param node2glyph * @param map * @param xOffset * @param yOffset */ private Glyph convertExchange(Node node, Map<String, SBGNBase> node2glyph, org.sbgn.bindings.Map map, double xOffset, double yOffset) { // TODO: implement support for exchange reactions! logger.warning(MessageFormat .format(bundle.getString("Escher2SBGN.cannotConvertExchange"), node.getId())); return null; } /** * @param midmarker * @param node2glyph * @param map * @param xOffset * @param yOffset * @return */ private Glyph convertMidmarker(Node midmarker, Map<String, SBGNBase> node2glyph, org.sbgn.bindings.Map map, double xOffset, double yOffset) { String rId = midmarker .getId(); //extractReactionId(midmarker.getConnectedSegments()); if (rId != null) { if (!node2glyph.containsValue(rId)) { double width = getPrimaryNodeWidth() * getReactionNodeRatio(); double height = getPrimaryNodeHeight() * getReactionNodeRatio(); // Also shift node because again the center of the node would be used as coordinate instead of upper-left corner Glyph rGlyph = builder.createGlyph(SBMLtools.toSId(rId), midmarker.isSetName() ? midmarker.getName() : midmarker.getBiggId(), GlyphType.process, convertCoordinate(midmarker.getX(), xOffset) - width / 2d, convertCoordinate(midmarker.getY(), yOffset) - height / 2d, width, height); //Do that later... createTextGlyph(midmarker, layout, xOffset, yOffset, rGlyph); (when the actual reaction is treated) map.getGlyph().add(rGlyph); node2glyph.put(rId, rGlyph); return rGlyph; } } return null; } /** * @param textLabel * @param map * @param xOffset * @param yOffset */ private void createTextLabel(TextLabel textLabel, org.sbgn.bindings.Map map, double xOffset, double yOffset) { try { // This is important in order to skip cardinality labels. These are treated directly in the reaction conversion. Double.parseDouble(textLabel.getText()); } catch (NumberFormatException exc) { if (!textLabel.isSetId()) { // Actually, the id should always be defined! textLabel.setId("" + textLabel.hashCode()); } String id = SBMLtools.toSId(textLabel.getId()); if (builder.getSBGNBase(id) != null) { int i = 0; do { i++; } while (builder.getSBGNBase(id + "_" + i) != null); id += "_" + i; } Glyph glyph = builder.createGlyph(id, textLabel.getText(), GlyphType.annotation, convertCoordinate(textLabel.getX(), xOffset), convertCoordinate(textLabel.getY(), yOffset), textLabel.isSetWidth() ? SBGNbuilder.toDouble(textLabel.getWidth()) : getLabelWidth(), textLabel.isSetHeight() ? SBGNbuilder.toDouble(textLabel.getHeight()) : getLabelHeight()); Callout callout = builder .createGlyphCallout(convertCoordinate(textLabel.getX(), xOffset), convertCoordinate(textLabel.getY(), yOffset)); glyph.setCallout(callout); map.getGlyph().add(glyph); } } /** * @param reaction * @param escherMap * @param map * @param node2glyph * @param xOffset * @param yOffset */ private void convertProcess(EscherReaction reaction, EscherMap escherMap, org.sbgn.bindings.Map map, Map<String, SBGNBase> node2glyph, double xOffset, double yOffset) { Node midmarker = reaction.getMidmarker(); if (midmarker == null) { logger.warning(MessageFormat .format(bundle.getString("Escher2SBGN.midmarkerMissing"), reaction)); return; } Glyph processGlyph = (Glyph) node2glyph.get(midmarker.getId()); if (processGlyph == null) { // We should never get here actually... This is just in case. processGlyph = convertMidmarker(midmarker, node2glyph, map, xOffset, yOffset); } List<String> list = midmarker.getConnectedSegments(reaction.getId()); if (list != null) { for (String segmentId : list) { Segment segment = reaction.getSegment(segmentId); Node node = escherMap.getNode( segment.getFromNodeId().equals(midmarker.getId()) ? segment.getToNodeId() : segment.getFromNodeId()); if (node.isMultimarker()) { Port port = createPort(node, processGlyph, xOffset, yOffset); node2glyph.put(port.getId(), port); processGlyph.getPort().add(port); } else { logger.info(MessageFormat.format( bundle.getString("Escher2SBGN.midmarkerWithoutMultimarker"), midmarker.getId(), reaction.isSetBiggId() ? reaction.getBiggId() : reaction.getId(), node.getType(), node.isSetBiggId() ? node.getBiggId() : node.getId())); } } } else { logger.warning(MessageFormat .format(bundle.getString("Escher2SBGN.reactionNodeWithoutSegments"), reaction.getId())); } for (Entry<String, Metabolite> entry : reaction.getMetabolites() .entrySet()) { Metabolite metabolite = entry.getValue(); Node srGlyph = escherMap.getNode(metabolite.getNodeRefId()); if (srGlyph != null) { // TODO: First do primary nodes.. map.getArc().add( convertSegments(metabolite, reaction, escherMap, map, node2glyph, xOffset, yOffset)); } } } /** * @param node * @param reaction * @param xOffset * @param yOffset * @return */ private Port createPort(Node node, Glyph reaction, double xOffset, double yOffset) { return builder.createPort(createPortId(reaction, node.getId()), convertCoordinate(node.getX(), xOffset), convertCoordinate(node.getY(), yOffset)); } /** * @param escherMap * @param map * @param xOffset * @param yOffset * @return */ private Arc convertSegments(Metabolite metabolite, EscherReaction reaction, EscherMap escherMap, org.sbgn.bindings.Map map, Map<String, SBGNBase> node2glyph, double xOffset, double yOffset) { double coeff = SBGNbuilder.toDouble(metabolite.getCoefficient()); Node metaboliteNode = escherMap.getNode(metabolite.getNodeRefId()); boolean isProduct = coeff > 0d; Glyph processGlyph = (Glyph) node2glyph.get(reaction.getMidmarker().getId()); List<String> connectedSegments = metaboliteNode.getConnectedSegments(reaction.getId()); Segment segment = reaction.getSegment(connectedSegments.get(0)); Node source, target; SBGNBase sourceBase, targetBase; double x1, y1, x2, y2; // Connect to ports if (isProduct) { // -x-->|=|-->x- if (connectedSegments.size() > 1) { source = escherMap.getNode(segment.getToNodeId()); // port sourceBase = node2glyph.get(createPortId(processGlyph, source.getId())); } else { source = escherMap.getNode(segment.getFromNodeId()); sourceBase = node2glyph.get(source.getId()); } target = escherMap.getNode(metabolite.getNodeRefId()); targetBase = node2glyph.get(target.getId()); x1 = source.getX(); y1 = source.getY(); // TODO /*Segment lastSegment = reaction.getSegment(target.getConnectedSegments(reaction.getId()).get(0)); Node fromNode = escherMap.getNode(lastSegment.getFromNodeId()); Point bp1 = lastSegment.getBasePoint1(); Point bp2 = lastSegment.getBasePoint2(); Shape shape = new Ellipse2D.Double(target.getX() - target.getWidth()/2d, target.getY() - target.getHeight()/2d, target.getWidth(), target.getHeight()); CubicCurve2D curve = new CubicCurve2D.Double(fromNode.getX(), fromNode.getY(), bp1 != null ? bp1.getX() : Double.NaN, bp1 != null ? bp1.getY() : Double.NaN, bp2 != null ? bp2.getX() : Double.NaN, bp2 != null ? bp2.getY() : Double.NaN, target.getX(), target.getY()); Point2D point = Geometry.findIntersection(shape, curve); if (point == null) {*/ x2 = target.getX(); y2 = target.getY(); /*} else { x2 = point.getX(); y2 = point.getY(); }*/ } else { source = escherMap.getNode(segment.getFromNodeId()); // metabolite Segment lastSegment = reaction .getSegment(connectedSegments.get(connectedSegments.size() - 1)); if (connectedSegments.size() > 1) { target = escherMap.getNode(lastSegment.getFromNodeId()); targetBase = node2glyph.get(createPortId(processGlyph, target.getId())); } else { target = escherMap.getNode(lastSegment.getToNodeId()); targetBase = node2glyph.get(target.getId()); } sourceBase = node2glyph.get(source.getId()); // TODO /*Node toNode = escherMap.getNode(segment.getToNodeId()); Point bp1 = segment.getBasePoint1(); Point bp2 = segment.getBasePoint2(); Shape shape = new Ellipse2D.Double(source.getX() - source.getWidth()/2d, source.getY() - source.getHeight()/2d, source.getWidth(), source.getHeight()); CubicCurve2D curve = new CubicCurve2D.Double(source.getX(), source.getY(), bp1 != null ? bp1.getX() : Double.NaN, bp1 != null ? bp1.getY() : Double.NaN, bp2 != null ? bp2.getX() : Double.NaN, bp2 != null ? bp2.getY() : Double.NaN, toNode.getX(), toNode.getY()); Point2D point = Geometry.findIntersection(shape, curve); if (point == null) {*/ x1 = source.getX(); y1 = source.getY(); /*} else { x1 = point.getX(); y1 = point.getY(); }*/ x2 = target.getX(); y2 = target.getY(); } Arc arc = builder.createArc(SBMLtools .toSId("r" + reaction.getId() + "_n" + metabolite.getNodeRefId()), sourceBase, targetBase, isProduct ? ArcType.production : ArcType.consumption); arc.setStart(builder.createArcStart(convertCoordinate(x1, xOffset), convertCoordinate(y1, yOffset))); coeff = Math.abs(coeff); if (coeff != 1d) { // Create cardinality labels for the edges if necessary. Glyph cardinalityGlyph = builder.createGlyph( SBMLtools.toSId("cardinality_" + metabolite.getNodeRefId()), StringTools.toString(Locale.ENGLISH, coeff), GlyphType.cardinality); double width = getPrimaryNodeWidth() * getReactionNodeRatio(); double height = getPrimaryNodeHeight() * getReactionNodeRatio(); Segment targetSegment; double x, y, ratio = 1d; if (isProduct) { targetSegment = reaction.getSegment( connectedSegments.get(connectedSegments.size() - 1)); Node end = escherMap.getNode(targetSegment.getToNodeId()); ratio = end.isMetabolite() && end.isPrimary() ? 1d : getSecondaryNodeRatio(); x = convertCoordinate(end.getX(), xOffset) - getPrimaryNodeWidth() * ratio; y = convertCoordinate(end.getY(), yOffset) - getPrimaryNodeHeight() * ratio; } else { targetSegment = reaction.getSegment(connectedSegments.get(0)); Node start = escherMap.getNode(targetSegment.getFromNodeId()); ratio = start.isMetabolite() && start.isPrimary() ? 1d : getSecondaryNodeRatio(); x = convertCoordinate(start.getX(), xOffset) - getPrimaryNodeWidth() * ratio; y = convertCoordinate(start.getY(), yOffset) - getPrimaryNodeHeight() * ratio; } cardinalityGlyph.setBbox(builder.createBbox(x, y, width, height)); arc.getGlyph().add(cardinalityGlyph); } // add individual segments for (int i = 1; i < connectedSegments.size(); i++) { Segment nextSeg = reaction.getSegment(connectedSegments.get(i)); Node nextNode = escherMap.getNode(nextSeg.getToNodeId()); if (nextNode != target) { Next next = builder.createArcNext(convertCoordinate(nextNode.getX(), xOffset), convertCoordinate(nextNode.getY(), yOffset)); if (segment.isSetBasePoint1()) { next.getPoint() .add(convertPoint(segment.getBasePoint1(), xOffset, yOffset)); } if (segment.isSetBasePoint2()) { next.getPoint() .add(convertPoint(segment.getBasePoint2(), xOffset, yOffset)); } arc.getNext().add(next); } segment = nextSeg; } End end = builder.createArcEnd(convertCoordinate(x2, xOffset), convertCoordinate(y2, yOffset)); if (connectedSegments.size() < 2) { segment = reaction .getSegment(connectedSegments.get(connectedSegments.size() - 1)); } if (segment.isSetBasePoint1()) { end.getPoint() .add(convertPoint(segment.getBasePoint1(), xOffset, yOffset)); } if (segment.isSetBasePoint2()) { end.getPoint() .add(convertPoint(segment.getBasePoint2(), xOffset, yOffset)); } arc.setEnd(end); return arc; } /** * @param reaction * @param nodeId * @return */ private String createPortId(Glyph reaction, String nodeId) { return SBMLtools.toSId(reaction.getId() + "_" + nodeId); } /** * @param p * @param yOffset * @param xOffset * @return */ private org.sbgn.bindings.Point convertPoint(Point p, double xOffset, double yOffset) { return builder.createPoint(convertCoordinate(p.getX(), xOffset), convertCoordinate(p.getY(), yOffset)); } /** * @param coordinate * @param offset * @return */ private float convertCoordinate(Double coordinate, double offset) { return (float) (SBGNbuilder.toDouble(coordinate) - offset); } /** * @param node * @param escherMap * @param multimarkers * @param xOffset * @param yOffset * @return */ private Glyph convertMetabolite(Node node, EscherMap escherMap, Map<String, Node> multimarkers, double xOffset, double yOffset) { double width = 0d, height = 0d; if (node.isSetHeight()) { height = node.getHeight().doubleValue(); } else if (node.isSetPrimary()) { height = (node.isPrimary() ? getPrimaryNodeHeight() : getPrimaryNodeHeight() * getSecondaryNodeRatio()); } if (node.isSetWidth()) { width = node.getWidth().doubleValue(); } else if (node.isSetPrimary()) { width = (node.isPrimary() ? getPrimaryNodeWidth() : getPrimaryNodeWidth() * getSecondaryNodeRatio()); } // TODO: Node size should be set elsewhere. if (!node.isSetWidth()) { node.setWidth(width); } if (!node.isSetHeight()) { node.setHeight(height); } double x = node.isSetX() ? convertCoordinate(node.getX(), xOffset) - width / 2d : 0d; double y = node.isSetY() ? convertCoordinate(node.getY(), yOffset) - height / 2d : 0d; // name the glyph and add the id globally Glyph glyph = builder.createGlyph(SBMLtools.toSId(node.getId()), GlyphType.simple_chemical, x, y, height, width, node.isSetBiggId() && (escherMap.getNodes(node.getBiggId()).size() > 1)); if (node.isSetLabelX() && node.isSetLabelY()) { glyph.setLabel(builder .createLabel(node.isSetName() ? node.getName() : node.getBiggId(), convertCoordinate(node.getLabelX(), xOffset), convertCoordinate(node.getLabelY(), yOffset), Double.valueOf(getLabelWidth()), Double.valueOf(getLabelHeight()))); } return glyph; } }
package framework; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import framework.annotation.Route; /** * request scoped object */ @SuppressWarnings("serial") public abstract class Request implements Attributes<Object> { /** * current request */ transient static final ThreadLocal<Request> CURRENT = new ThreadLocal<>(); /** * @return current request */ public static Optional<Request> current() { return Tool.of(CURRENT.get()); } /** * @return path */ public abstract String getPath(); /** * @return Folder name(with end separator) */ public String getFolder() { return Tool.getFolder(getPath()); } /** * @return file name(without extension) */ public String getName() { return Tool.getName(getPath()); } /** * @return extension(with period) */ public String getExtension() { return Tool.getExtension(getPath()); } /** * @return file name(with extension) */ public String getFile() { return getName() + getExtension(); } /** * @return Query string */ public abstract String getQuery(); /** * @return path */ public String getURL() { return Application.current().map(Application::getContextPath).orElse("/") + Tool.trim("/", getPath(), null) + Tool.string(getQuery()).map(s -> '?' + s).orElse(""); } /** * @return http method */ public abstract Route.Method getMethod(); @Override public String toString() { return "<- " + getMethod() + " " + getURL(); } /** * @param args URL(https) * @throws NoSuchAlgorithmException algorithm error * @throws KeyManagementException key error * @throws IOException IO error * @throws MalformedURLException url error */ public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException { String url = args.length > 0 ? args[0] : "https://localhost:8443"; SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }, null); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("POST"); try (InputStream in = connection.getInputStream()) { byte[] bytes = new byte[256]; for (;;) { int n = in.read(bytes); if (n <= 0) { break; } Log.info(new String(bytes, 0, n, StandardCharsets.UTF_8)); } } } /** * @return files */ public abstract Map<String, Tuple<byte[], File>> getFiles(); /** * @return headers */ public abstract Map<String, List<String>> getHeaders(); /** * @return parameters */ public abstract Map<String, List<String>> getParameters(); /** * @return Remote IP address */ protected abstract String getRemoteAddr(); /** * @return Remote IP address */ public String getRemoteIp() { return Tool.val(getHeaders(), map -> Tool.or(Tool.getFirst(map, "X-FORWARDED-FOR") .filter(i -> i.length() >= 4 && !"unknown".equalsIgnoreCase(i)), () -> Tool.getFirst(map, "INTEL_SOURCE_IP") .filter(i -> !"unknown".equalsIgnoreCase(i)), () -> Tool.getFirst(map, "PROXY-CLIENT-IP") .filter(i -> !"unknown".equalsIgnoreCase(i)), () -> Tool.getFirst(map, "WL-PROXY-CLIENT-IP") .filter(i -> !"unknown".equalsIgnoreCase(i)), () -> Tool.getFirst(map, "HTTP_CLIENT_IP") .filter(i -> !"unknown".equalsIgnoreCase(i)), () -> Tool.getFirst(map, "HTTP_X_FORWARDED_FOR") .filter(i -> !"unknown".equalsIgnoreCase(i)), () -> Tool.of(getRemoteAddr())) .orElse("unknwon")); } /** * @return parameters */ public Map<String, String> getFirstParameters() { Map<String, List<String>> map = getParameters(); return new Map<String, String>() { @Override public int size() { return map.size(); } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return Stream.of(map.values()) .anyMatch(i -> Objects.equals(i, value)); } @Override public String get(Object key) { return Tool.getFirst(map, (String) key) .orElse(null); } @Override public String put(String key, String value) { return Tool.setValue(map, key, value, ArrayList::new); } @Override public String remove(Object key) { return map.remove(key) .get(0); } @Override public void putAll(Map<? extends String, ? extends String> m) { m.forEach((key, value) -> Tool.setValue(map, key, value, ArrayList::new)); } @Override public void clear() { map.clear(); } @Override public Set<String> keySet() { return map.keySet(); } @Override public Collection<String> values() { return map.values() .stream() .flatMap(List::stream) .collect(Collectors.toList()); } @Override public Set<java.util.Map.Entry<String, String>> entrySet() { return map.entrySet() .stream() .map(entry -> Tuple.of(entry.getKey(), Tool.of(entry.getValue()) .filter(list -> !list.isEmpty()) .map(list -> list.get(0)) .orElse(null))) .collect(Collectors.toSet()); } }; } }
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2022 DBeaver Corp and others * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jkiss.dbeaver.runtime.properties; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBPContextProvider; import org.jkiss.dbeaver.model.exec.DBCExecutionContext; import org.jkiss.dbeaver.model.impl.PropertyDescriptor; import org.jkiss.dbeaver.model.preferences.DBPPropertyDescriptor; import org.jkiss.dbeaver.model.preferences.DBPPropertyManager; import org.jkiss.dbeaver.model.preferences.DBPPropertySource; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.load.AbstractLoadService; import org.jkiss.dbeaver.model.runtime.load.ILoadVisualizer; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.runtime.DBWorkbench; import org.jkiss.utils.ArrayUtils; import java.lang.reflect.InvocationTargetException; import java.util.*; /** * PropertyCollector */ public abstract class PropertySourceAbstract implements DBPPropertyManager, IPropertySourceMulti { private static final Log log = Log.getLog(PropertySourceAbstract.class); private Object sourceObject; private Object object; private boolean loadLazyProps; private final List<DBPPropertyDescriptor> props = new ArrayList<>(); private final Map<Object, Object> propValues = new HashMap<>(); private final Map<Object, Object> lazyValues = new HashMap<>(); private final List<ObjectPropertyDescriptor> lazyProps = new ArrayList<>(); private Job lazyLoadJob; private String locale; private boolean enableFilters = true; /** * constructs property source * @param object object */ public PropertySourceAbstract(Object sourceObject, Object object, boolean loadLazyProps) { this.sourceObject = sourceObject; this.object = object; this.loadLazyProps = loadLazyProps; } public synchronized void addProperty(DBPPropertyDescriptor prop) { if (prop instanceof ObjectPropertyDescriptor && ((ObjectPropertyDescriptor) prop).isHidden()) { // Do not add it to property list } else { props.add(prop); } propValues.put(prop.getId(), prop); } public synchronized void addProperty(@Nullable String category, String id, String name, Object value) { props.add(new PropertyDescriptor(category, id, name, null, value == null ? null : value.getClass(), false, null, null, false)); propValues.put(id, value); } public synchronized void removeProperty(DBPPropertyDescriptor prop) { propValues.remove(prop.getId()); lazyValues.remove(prop.getId()); props.remove(prop); } public synchronized void clearProperties() { props.clear(); propValues.clear(); lazyValues.clear(); } public synchronized boolean hasProperty(ObjectPropertyDescriptor prop) { return props.contains(prop); } public synchronized boolean isEmpty() { return props.isEmpty(); } public DBPPropertyDescriptor getProperty(String id) { for (DBPPropertyDescriptor prop : props) { if (prop.getId().equals(id)) { return prop; } } return null; } public Object getSourceObject() { return sourceObject; } @Override public Object getEditableValue() { return object; } @Override public DBPPropertyDescriptor[] getProperties() { return props.toArray(new DBPPropertyDescriptor[0]); } /* public IPropertyDescriptor getPropertyDescriptor(final Object id) { for (IPropertyDescriptor prop : props) { if (CommonUtils.equalObjects(prop.getId(), id)) { return prop; } } return null; } */ @Override public boolean isPropertySet(String id) { Object value = propValues.get(id); if (value instanceof ObjectPropertyDescriptor) { return isPropertySet(getEditableValue(), (ObjectPropertyDescriptor) value); } else { return value != null; } } @Override public boolean isPropertySet(Object object, ObjectPropertyDescriptor prop) { try { return !prop.isLazy(object, true) && prop.readValue(object, null, false) != null; } catch (Exception e) { log.error("Error reading property '" + prop.getId() + "' from " + object, e); return false; } } @Override public final Object getPropertyValue(@Nullable DBRProgressMonitor monitor, final String id) { Object value = propValues.get(id); if (value instanceof ObjectPropertyDescriptor) { value = getPropertyValue(monitor, getEditableValue(), (ObjectPropertyDescriptor) value, true); } return value; } @Override public Object getPropertyValue(@Nullable DBRProgressMonitor monitor, final Object object, final ObjectPropertyDescriptor prop, boolean formatValue) { try { if (monitor == null && prop.isLazy(object, true) && !prop.supportsPreview()) { final Object value = lazyValues.get(prop.getId()); if (value != null) { return value; } if (lazyValues.containsKey(prop.getId())) { // Some lazy props has null value return null; } if (!loadLazyProps) { return null; } else { synchronized (lazyProps) { lazyProps.add(prop); if (lazyLoadJob == null) { // We assume that it can be called ONLY by properties viewer // So, start lazy loading job to update it after value will be loaded lazyLoadJob = DBWorkbench.getPlatformUI().createLoadingService( new PropertyValueLoadService(), new PropertyValueLoadVisualizer()); lazyLoadJob.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { synchronized (lazyProps) { if (!lazyProps.isEmpty()) { lazyLoadJob.schedule(100); } else { lazyLoadJob = null; } } } }); lazyLoadJob.schedule(100); } } // Return dummy string for now lazyValues.put(prop.getId(), null); return null; } } else { return prop.readValue(object, monitor, formatValue); } } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getTargetException(); } log.error("Error reading property '" + prop.getId() + "' from " + object, e); return e.getMessage(); } } @Override public boolean isPropertyResettable(String id) { Object value = propValues.get(id); if (value instanceof ObjectPropertyDescriptor) { return isPropertyResettable(getEditableValue(), (ObjectPropertyDescriptor) value); } else { // No by default return false; } } @Override public boolean isPropertyResettable(Object object, ObjectPropertyDescriptor prop) { return false; } @Override public final void resetPropertyValue(@Nullable DBRProgressMonitor monitor, String id) { Object value = propValues.get(id); if (value instanceof ObjectPropertyDescriptor) { resetPropertyValue(monitor, getEditableValue(), (ObjectPropertyDescriptor) value); } else { throw new UnsupportedOperationException("Direct property reset not implemented"); } } @Override public void resetPropertyValue(@Nullable DBRProgressMonitor monitor, Object object, ObjectPropertyDescriptor id) { throw new UnsupportedOperationException("Cannot reset property in non-editable property source"); } @Override public void resetPropertyValueToDefault(String id) { throw new UnsupportedOperationException("Cannot reset property in non-editable property source"); } @Override public final void setPropertyValue(@Nullable DBRProgressMonitor monitor, String id, Object value) { Object prop = propValues.get(id); if (prop instanceof ObjectPropertyDescriptor) { setPropertyValue(monitor, getEditableValue(), (ObjectPropertyDescriptor) prop, value); lazyValues.put(((ObjectPropertyDescriptor) prop).getId(), value); } else { propValues.put(id, value); } } @Override public void setPropertyValue(@Nullable DBRProgressMonitor monitor, Object object, ObjectPropertyDescriptor prop, Object value) { throw new UnsupportedOperationException("Cannot update property in non-editable property source"); } public boolean collectProperties() { lazyValues.clear(); props.clear(); propValues.clear(); final Object editableValue = getEditableValue(); if (editableValue != null) { IPropertyFilter filter; if (isEnableFilters()) { if (editableValue instanceof DBSObject) { filter = new DataSourcePropertyFilter(((DBSObject) editableValue).getDataSource()); } else if (editableValue instanceof DBPContextProvider) { DBCExecutionContext context = ((DBPContextProvider) editableValue).getExecutionContext(); filter = context == null ? new DataSourcePropertyFilter() : new DataSourcePropertyFilter(context.getDataSource()); } else { filter = new DataSourcePropertyFilter(); } } else { filter = null; } List<ObjectPropertyDescriptor> annoProps = ObjectAttributeDescriptor.extractAnnotations(this, editableValue.getClass(), filter, locale); for (final ObjectPropertyDescriptor desc : annoProps) { if (desc.isPropertyVisible(editableValue, editableValue)) { addProperty(desc); } } if (editableValue instanceof DBPPropertySource) { DBPPropertySource ownPropSource = (DBPPropertySource) editableValue; DBPPropertyDescriptor[] ownProperties = ownPropSource.getProperties(); if (!ArrayUtils.isEmpty(ownProperties)) { for (DBPPropertyDescriptor prop : ownProperties) { props.add(prop); propValues.put(prop.getId(), ownPropSource.getPropertyValue(null, prop.getId())); } } } } return !props.isEmpty(); } public void setLocale(String locale) { this.locale = locale; } public boolean isEnableFilters() { return enableFilters; } public void setEnableFilters(boolean enableFilters) { this.enableFilters = enableFilters; } public boolean getEnableFilters() { return enableFilters; } private class PropertyValueLoadService extends AbstractLoadService<Map<ObjectPropertyDescriptor, Object>> { public static final String TEXT_LOADING = "..."; public PropertyValueLoadService() { super(TEXT_LOADING); } @Override public Map<ObjectPropertyDescriptor, Object> evaluate(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { Map<ObjectPropertyDescriptor, Object> result = new IdentityHashMap<>(); for (ObjectPropertyDescriptor prop : obtainLazyProperties()) { if (monitor.isCanceled()) { break; } result.put(prop, prop.readValue(getEditableValue(), monitor, true)); } return result; } catch (Throwable ex) { if (ex instanceof InvocationTargetException) { throw (InvocationTargetException)ex; } else { throw new InvocationTargetException(ex); } } } @Override public Object getFamily() { final Object editableValue = getEditableValue(); return editableValue instanceof DBSObject ? ((DBSObject) editableValue).getDataSource() : editableValue; } } private List<ObjectPropertyDescriptor> obtainLazyProperties() { synchronized (lazyProps) { if (lazyProps.isEmpty()) { return Collections.emptyList(); } else { List<ObjectPropertyDescriptor> result = new ArrayList<>(lazyProps); lazyProps.clear(); return result; } } } private class PropertyValueLoadVisualizer implements ILoadVisualizer<Map<ObjectPropertyDescriptor, Object>> { //private Object propertyId; //private int callCount = 0; private boolean completed = false; private PropertyValueLoadVisualizer() { } @Override public DBRProgressMonitor overwriteMonitor(DBRProgressMonitor monitor) { return monitor; } @Override public boolean isCompleted() { return completed; } @Override public void visualizeLoading() { /* String dots; switch (callCount++ % 4) { case 0: dots = ""; break; case 1: dots = "."; break; case 2: dots = ".."; break; case 3: default: dots = "..."; break; } propValues.put(propertyId, PropertyValueLoadService.TEXT_LOADING + dots); refreshProperties(false); */ } @Override public void completeLoading(Map<ObjectPropertyDescriptor, Object> result) { completed = true; if (result != null) { for (Map.Entry<ObjectPropertyDescriptor, Object> entry : result.entrySet()) { lazyValues.put(entry.getKey().getId(), entry.getValue()); PropertiesContributor.getInstance().notifyPropertyLoad(getEditableValue(), entry.getKey(), entry.getValue(), true); } } } } }
/* * Copyright (c) 2015. * Johannes Bauer, Fabian Buske, Matthias Fisch, * Michael Mitterer, Maximilian Witzelsperger * * 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 sep.gaia.util; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import sep.gaia.renderer.Mode2D; import sep.gaia.state.AbstractStateManager.StateType; import sep.gaia.state.GLState; import sep.gaia.state.GeoState; import sep.gaia.state.StateManager; import sep.gaia.state.TileState; /** * * Utility class that provides converting methods between different States (such * as GLState, TileState, GeoState). * * @author Johannes Bauer, Matthias Fisch * */ public final class AlgoUtil { /** * A half of the length of the whole map (i.e. the world) in GL coordinates. * MAYBE TO REMOVE TODO */ private static final int HALF_MAP_LENGTH_GL = (int) Math.pow(2, TileState.MAX_ZOOM - 1); /** * Amount of pixels a tile should have in window-coordinate-space. */ public static final float TILE_LENGTH_IN_PIXELS = 256; public static final float[][] IDENTITY = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; private AlgoUtil() { } // utility class constructor /* * CONVERTING VECTOR METHODS */ /** * Converts a given vector of which the first two coordinates represent * a position and the third one a zoom level in geographic coordinates into * a vector of which the first two coordinates represent a matching * position and zoom in GL-coordinates. * * @param geoVector the vector to be converted * * @return the converted vector in GL-coordinates which is of the form * (x-position, y-position, zoom) */ public static FloatVector3D geoToGL(FloatVector3D geoVector) { /*float lat = (geoVector.getX() * ((float) Math.pow(2, Mode2D.MAX_2D_LEVEL))) / 180.0f; float lon = (geoVector.getY() * ((float) Math.pow(2, Mode2D.MAX_2D_LEVEL))) / 180.0f; float z = geoVector.getZ(); return new FloatVector3D(lat, lon, z); */ FloatVector3D floatTile = geoToFloatTile(geoVector); FloatVector3D glVector = floatTileToGL(floatTile); glVector.setY(-glVector.getY()); return glVector; } /** * Converts a <code>IntegerVector3D</code> object which represents a * position * on the map and a zoom level in tile coordinates into a * <code>FloatVector3D</code> object that represents the same position and * the same zoom level in GL-coordinates. The position is represented in * the first two coordinates and the zoom level in the third one. Because a * zoom level is always greater than or equal to 0 in tile coordinates, * in the case of the given zoom level being smaller than 0 * <code>null</code> will be returned. * * @param tileVector * the vector in tile coordinates that represents a * position on the map in the first two coordinates and a * zoom level in the third one * * @return a vector in GL-coordinates that matches <code>tileVector</code> * and <code>null</code> if and only if <code>tileVector</code> is * <code>null</code> or the third coordinate of it is smaller * than 0 */ public static FloatVector3D tileToGL(IntegerVector3D tileVector) { int tileZoom = tileVector.getZ(); int tilesPerDirection = (int) Math.pow(2, tileZoom); float sideLength = (float) Math.pow(2, Mode2D.MAX_2D_LEVEL - tileZoom); float x = (tileVector.getX() - tilesPerDirection / 2.0f) * (sideLength); float y = (tileVector.getY() - tilesPerDirection / 2.0f) * sideLength; float z = tileToGLZoom(tileZoom); return new FloatVector3D(x, -y, z); } /** * Converts a <code>FloatVector3D</code> object which represents a position * on the map and a zoom level in GL-coordinates into an * <code>IntegerVector3D</code> object that represents the same position and * the same zoom level in tile coordinates. The position is represented in * the first two coordinates and the zoom level in the third one. Because a * zoom level is always strictly greater than 0 in the GL-representation, * in the case of the given zoom level being smaller or equal to 0 * <code>null</code> will be returned. * * @param glVector * the vector in GL-coordinates that represents a position on the * map in the first two coordinates and a zoom level in the third * one * * @return a vector in tile coordinates that matches <code>glVector</code> * and <code>null</code> if and only if <code>glVector</code> is * <code>null</code> or the third coordinate of it is smaller or * equal to 0 */ public static IntegerVector3D glToTile(FloatVector3D glVector) { // Fetch gl coordinates. float glX = glVector.getX(); float glY = glVector.getY(); float glZ = glVector.getZ(); // Initialize tile coordinates. int tileX = 0; int tileY = 0; int tileZ = glToTileZoom(glZ); // The gl zoom is equal to the side length of a tile in gl coords. float tileLengthGL = glZ; // The side length of the "whole earth map" in gl coords. float glSideLength = (int) Math.pow(2, Mode2D.MAX_2D_LEVEL); // Translate gl coords: eliminate negative values. glX += glSideLength / 2.0f; glY -= glSideLength / 2.0f; glY *= -1; // Prepare deltas for rounding. dX/dY is the difference to the next // higher tileLengthGL multiple. float dX = (glX % tileLengthGL) % tileLengthGL; float dY = (glY % tileLengthGL) % tileLengthGL; // Floor to next multiple if positive, else ceiling. glX -= dX; glY -= dY; tileX = (int) (glX / tileLengthGL); tileY = (int) (glY / tileLengthGL); // return new created tileVector return new IntegerVector3D(tileX, tileY, tileZ); } /** * Converts a <code>FloatVector3D</code> object which represents a position * on the map and a zoom level in geographic coordinates into an * <code>IntegerVector3D</code> object that represents the same position and * the same zoom level in tile coordinates. The position is represented in * the first two coordinates and the zoom level in the third one. Because a * zoom level is always strictly greater than 0 in geographic coordinates, * in the case of the given zoom level being smaller or equal to 0 * <code>null</code> will be returned. * * @param geoVector * the vector in geographic coordinates that represents a * position on the map in the first two coordinates and a * zoom level in the third one * * @return a vector in tile coordinates that matches <code>geoVector</code> * and <code>null</code> if and only if <code>geoVector</code> is * <code>null</code> or the third coordinate of it is smaller or * equal to 0 */ public static IntegerVector3D geoToTile(FloatVector3D geoVector) { float lat = geoVector.getX(); float lon = geoVector.getY(); // Lat in radians. float latRAD = (float) Math.toRadians(lat); // Tile zoom. int tileZ = glToTileZoom(geoVector.getZ()); int tileX = (int) Math.floor((lon + 180.0f) / 360 * (1 << tileZ)); int tileY = (int) Math.floor((1 - Math.log(Math.tan(latRAD) + 1 / Math.cos(latRAD)) / Math.PI) / 2.0f * (1 << tileZ)); return new IntegerVector3D(tileX, tileY, tileZ); } /** * Converts a given vector of which the first two coordinates represent * a position and the third one a zoom level in GL-coordinates into a * vector of which the first two coordinates represent a matching position * and zoom in geographic coordinates. * * @param glVector the vector in GL-coordinates to be converted * * @return a converted vector in geographic coordinates, which has the form * (longitude, latitude, zoom) */ public static FloatVector3D glToGeo(FloatVector3D glVector) { FloatVector3D floatTileVec = glToFloatTile(glVector); float x = floatTileVec.getX(); float y = floatTileVec.getY(); float z = floatTileVec.getZ(); float lat = (float) Math.toDegrees(Math.atan(Math.sinh(Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, z)))); float lon = (float) ((x / Math.pow(2, z)) * 360.0 - 180.0); float zoom = glVector.getZ(); return (new FloatVector3D(lat, lon, zoom)); } /** * Converts a <code>IntegerVector3D</code> object which represents a position * on the map and a zoom level in tile coordinates into a * <code>FloatVector3D</code> object that represents the same position and * the same zoom level in geographic coordinates. The position is represented in * the first two coordinates and the zoom level in the third one. Because a * zoom level is always greater than or equal to 0 in tile coordinates, * in the case of the given zoom level being smaller than 0 * <code>null</code> will be returned. * * @param tileVector * the vector in tile coordinates that represents a * position on the map in the first two coordinates and a * zoom level in the third one * * @return a vector in geographic coordinates that matches <code>tileVector</code> * and <code>null</code> if and only if <code>tileVector</code> is * <code>null</code> or the third coordinate of it is smaller * than 0 */ public static FloatVector3D tileToGeo(IntegerVector3D tileVector) { int x = tileVector.getX(); int y = tileVector.getY(); int zoom = tileVector.getZ(); double n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2.0, zoom); float lon = (float) (x / Math.pow(2.0, zoom) * 360.0 - 180.0); float lat = (float) (Math.toDegrees(Math.atan(Math.sinh(n)))); return new FloatVector3D(lat, lon, zoom); } // HELPER METHODS FOR CONVERTING: // A "float tile" is a tile coordinate with floating point amount. // This is needed for converting between tile and gl/geo easier. // The zoom of a "float tile" is equal to the "normal" tile zoom. public static FloatVector3D glToFloatTile(FloatVector3D glVector) { float glX = glVector.getX(); float glY = glVector.getY(); float tileLengthGL = glVector.getZ(); // Convert the glVector in a "regular", integer tileVector. IntegerVector3D tileVector = glToTile(glVector); float x = tileVector.getX(); float y = tileVector.getY(); float z = tileVector.getZ(); // Now make the tileVector "floating": means, add fraction amount to it. float dX = (Math.abs(glX) % tileLengthGL) / tileLengthGL; float dY = (Math.abs(glY) % tileLengthGL) / tileLengthGL; // Add the deltas. x += dX; y += dY; return (new FloatVector3D(x, y, z)); } public static FloatVector3D glToFloatTile(FloatBoundingBox glBox) { FloatVector3D upperLeftGL = glBox.getUpperLeft(); FloatVector3D lowerRightGL = glBox.getLowerRight(); IntegerVector3D upperLeftTile = glToTile(upperLeftGL); IntegerVector3D lowerRightTile = glToTile(lowerRightGL); float centerX = upperLeftTile.getX() + Math.abs(upperLeftTile.getX() - lowerRightTile.getX()) / 2.0f; float centerY = upperLeftTile.getY() + Math.abs(upperLeftTile.getY() - lowerRightTile.getY()) / 2.0f; float centerZ = glToTileZoom(upperLeftGL.getZ()); return new FloatVector3D(centerX, centerY, centerZ); } public static FloatVector3D floatTileToGL(FloatVector3D floatTile) { float x = floatTile.getX(); float y = floatTile.getY(); float z = floatTile.getZ(); float glTileLength = tileToGLZoom(z); float glX = x * glTileLength - HALF_MAP_LENGTH_GL; float glY = y * glTileLength - HALF_MAP_LENGTH_GL; float glZ = tileToGLZoom(z); return (new FloatVector3D(glX, glY, glZ)); } public static FloatVector3D geoToFloatTile(FloatVector3D geoVector) { float lat = geoVector.getX(); float lon = geoVector.getY(); float glZoom = geoVector.getZ(); int zoom = glToTileZoom(geoVector.getZ()); float xTile = (float) ((lon + 180.0f) / 360.0f * (1 << zoom)); float yTile = (float) ((1 - Math.log(Math.tan(Math.toRadians(lat)) + 1.0f / Math.cos(Math.toRadians(lat))) / Math.PI) / 2.0f * (1 << zoom)); if (xTile < 0) xTile = 0; if (xTile >= (1 << zoom)) xTile = (float) ((1 << zoom) - 1); if (yTile < 0) yTile = 0; if (yTile >= (1 << zoom)) yTile = (float) ((1 << zoom) - 1); return new FloatVector3D(xTile, yTile, zoom); } /* * CONVERTING BOUNDINGBOX METHODS */ /** * Converts a bounding box in geographic coordinates where the first two * coordinates of each corner vectors represent a position and the third * one a zoom level into a matching bounding box in GL-coordinates. * * @param geoBox the geographic bounding box to be converted, it is * assumed to form a valid rectangle * * @return a bounding box in GL-coordinates that matches <code>geoBox</code> * or <code>null</code> if <code>geoBox</code> is <code>null</code> */ public static FloatBoundingBox geoToGL(FloatBoundingBox geoBox) { FloatVector3D upperLeft = geoToGL(geoBox.getUpperLeft()); FloatVector3D upperRight = geoToGL(geoBox.getUpperRight()); FloatVector3D lowerLeft = geoToGL(geoBox.getLowerLeft()); FloatVector3D lowerRight = geoToGL(geoBox.getLowerRight()); return (new FloatBoundingBox(upperLeft, upperRight, lowerLeft, lowerRight)); } /** * Converts a given bounding box in geographic coordinates (degree) into an * equivalent bounding box in tile coordinates. * * @param geoBox * the bounding box in geographic coordinates, which is expected * to form a valid rectangle * * @return a bounding box in tile coordinates that matches * <code>geoBox</code>, or <code>null</code> if and only if * <code>geoBox</code> is <code>null</code> */ public static IntegerBoundingBox geoToTile(FloatBoundingBox geoBox) { IntegerVector3D upperLeft = geoToTile(geoBox.getUpperLeft()); IntegerVector3D lowerRight = geoToTile(geoBox.getLowerRight()); return (new IntegerBoundingBox(upperLeft, lowerRight)); } /** * Converts a bounding box in GL-coordinates where the first two * coordinates of each corner vectors represent a position and the third * one a zoom level into a matching bounding box in geographic coordinates. * * @param glBox the GL-bounding box to be converted, it is * assumed to form a valid rectangle * * @return a bounding box in geographic coordinates that matches * <code>geoBox</code> of <code>null</code> if <code>glBox</code> is * <code>null</code> */ public static FloatBoundingBox glToGeo(FloatBoundingBox glBox) { FloatVector3D upperLeft = glToGeo(glBox.getLowerRight()); FloatVector3D lowerRight = glToGeo(glBox.getUpperLeft()); return new FloatBoundingBox(upperLeft, lowerRight); } /** * Converts a given bounding box in GL-coordinates into an equivalent * bounding box in tile coordinates. * * @param glBox * the bounding box in GL-coordinates, which is expected to be a * valid rectangle * * @param glZoom * the current zoom level which is needed for the conversion * * @return a bounding box in tile-coordinates that matches <code>glBox</code>, * or <code>null</code> if and only if the given bounding box is * <code>null</code> */ public static IntegerBoundingBox glToTile(FloatBoundingBox glBox, float glZoom) { float minX = Float.POSITIVE_INFINITY, maxX = Float.NEGATIVE_INFINITY; float minY = Float.POSITIVE_INFINITY, maxY = Float.NEGATIVE_INFINITY; FloatVector3D[] corners = glBox.getCornersClockwise(); // Calculate new tile bounding box. for(FloatVector3D coords : corners) { minX = (float) Math.min(minX, coords.getX()); minY = (float) Math.min(minY, coords.getY()); maxX = (float) Math.max(maxX, coords.getX()); maxY = (float) Math.max(maxY, coords.getY()); } //float z = corners[0].getZ(); // HACK!!! Zoom level must be fetched by the boundingbox! TODO GLState glState = (GLState) StateManager.getInstance().getState(StateType.GLState); float z = glState.getZoom(); int tileZoom = glToTileZoom(z); FloatVector3D upperLeft = new FloatVector3D(minX, maxY, z); FloatVector3D lowerRight = new FloatVector3D(maxX, minY, z); // Now set corners of new tile bounding box and dont't let it overflow. int maxXTile = (int) Math.pow(2, tileZoom) - 1; int maxYTile = (int) Math.pow(2, tileZoom) - 1; IntegerVector3D upperLeftTile = glToTile(upperLeft); IntegerVector3D lowerRightTile = glToTile(lowerRight); // Watch for overflow. for (IntegerVector3D current : Arrays.asList(upperLeftTile, lowerRightTile)) { if (current.getX() > maxXTile) { current.setX(maxXTile); } else if (current.getX() < 0) { current.setX(0); } if (current.getX() > maxXTile) { current.setY(maxYTile); } else if (current.getY() < 0) { current.setY(0); } } return new IntegerBoundingBox(upperLeftTile, lowerRightTile); } /** * Converts a given bounding box in tile coordinates into an equivalent * bounding box in geographic coordinates (degree). * * @param tileBox * a bounding box in tile coordinates, which is expected to be a * valid rectangle * * @return a matching bounding box in geographic coordinates, or * <code>null</code> if and only if the passed bounding box is * <code>null</code> */ public static FloatBoundingBox tileToGeo(IntegerBoundingBox tileBox) { FloatVector3D upperLeft = tileToGeo(tileBox.getUpperLeft()); FloatVector3D lowerRight = tileToGeo(tileBox.getLowerRight()); return (new FloatBoundingBox(upperLeft, lowerRight)); } /** * Converts a bounding box given in tile coordinates into an equivalent * bounding box in GL-coordinates. * * @param tileBox * the bounding box in tile coordinates which is expected to be a * valid rectangle * * @return the converted bounding box in GL-coordinates, or * <code>null</code> if and only if <code>null</code> is given as * bounding box */ public static FloatBoundingBox tileToGL(IntegerBoundingBox tileBox) { FloatVector3D upperLeft = tileToGL(tileBox.getUpperLeft()); FloatVector3D lowerRight = tileToGL(tileBox.getLowerRight()); return (new FloatBoundingBox(upperLeft, lowerRight)); } /** * Converts a given 3d-integer-vector of which the first two coordinates * represent a position in tile coordinates and the third one a zoom level * in tile coordinates, into a bounding box in GL-coordinates of which the * upper left corner matches the given vector. * * @param tileCoords * a vector in tile coordinates, representing position and a zoom * level * * @return a rectangle in GL-coordinates of which <code>tileCoords</code> * matches the upper left corner */ public static FloatBoundingBox tileToGLBox(IntegerVector3D tileVector) { float zoomGL = AlgoUtil.tileToGLZoom(tileVector.getZ()); float zoom = tileVector.getZ(); FloatVector3D upperLeft = tileToGL(tileVector); float sideLength = (float) Math.pow(2, TileState.MAX_ZOOM - zoom); FloatVector3D lowerRight = new FloatVector3D(upperLeft.getX() + sideLength, upperLeft.getY() - sideLength, zoomGL); return (new FloatBoundingBox(upperLeft, lowerRight)); } /* * CONVERTING STATES */ /** * Converts the coordinates from <code>geoState</code> into GL-coordinates * and saves them in <code>glState</code> * * @param geoState the state from which the data is taken * @param glState the state to be updated */ public static void geoToGL(GeoState geoState, GLState glState) { if (geoState != null && glState != null) { // Convert bounding boxes: FloatBoundingBox bBoxGeo = geoState.getBoundingBox(); FloatVector3D upperLeftGeo = bBoxGeo.getUpperLeft(); FloatVector3D lowerRightGeo = bBoxGeo.getLowerRight(); FloatVector3D upperLeftGL = geoToGL(upperLeftGeo); FloatVector3D lowerRightGL = geoToGL(lowerRightGeo); FloatBoundingBox bBoxGl = new FloatBoundingBox(upperLeftGL, lowerRightGL); glState.setBoundingBox(bBoxGl, false); // Calculate center: FloatVector3D centerGeo = geoState.getPosition(); FloatVector3D centerGL = geoToGL(centerGeo); glState.setPosition(centerGL, false); // Convert zoom: float zoomGeo = geoState.getZoom(); glState.setZoom(zoomGeo, false);// Geo-zoom identical to // GL-zoom } } /** * Converts the available coordinates from <code>glState</code> into * tile coordinates and updates <code>tileState</code> with those new * values. * * @param glState the state from which the information is taken * @param tileState the state to be updated */ public static void glToTile(GLState glState, TileState tileState) { if (glState != null && tileState != null) { FloatBoundingBox bBoxGl = glState.getBoundingBox(); // Convert bounding box flipping corners. FloatVector3D lowerRightGl = bBoxGl.getUpperLeft(); FloatVector3D upperLeftGl = bBoxGl.getLowerRight(); upperLeftGl.setZ(glState.getZoom()); lowerRightGl.setZ(glState.getZoom()); // Flip coordinates to fit slippy-map convention: IntegerVector3D upperLeftTile = glToTile(lowerRightGl); IntegerVector3D lowerRightTile = glToTile(upperLeftGl); upperLeftTile.setZ(glToTileZoom(upperLeftGl.getZ())); lowerRightTile.setZ(glToTileZoom(lowerRightGl.getZ())); IntegerBoundingBox bBoxTile = new IntegerBoundingBox(upperLeftTile, lowerRightTile); tileState.setBoundingBox(bBoxTile, false); // Calculate center: FloatVector3D centerGl = glState.getPosition(); IntegerVector3D centerTile = glToTile(centerGl); tileState.setCenter(centerTile, false); // Convert zoom: float zoomGl = glState.getZoom(); int zoomTile = glToTileZoom(zoomGl); tileState.setZoom(zoomTile, false); } } /** * Converts the coordinates from <code>geoState</code> into tile coordinates * and updates <code>tileState</code> with them. * * @param geoState the state from which the data is taken * @param tileState the state to be updated */ public static void geoToTile(GeoState geoState, TileState tileState) { if (geoState != null && tileState != null) { // Convert bounding boxes: FloatBoundingBox bBoxGeo = geoState.getBoundingBox(); FloatVector3D upperLeftGeo = bBoxGeo.getUpperLeft(); FloatVector3D lowerRightGeo = bBoxGeo.getLowerRight(); IntegerVector3D upperLeftTile = geoToTile(upperLeftGeo); IntegerVector3D lowerRightTile = geoToTile(lowerRightGeo); IntegerBoundingBox bBoxTile = new IntegerBoundingBox(upperLeftTile, lowerRightTile); tileState.setBoundingBox(bBoxTile); // Calculate center: FloatVector3D centerGeo = geoState.getPosition(); IntegerVector3D centerTile = geoToTile(centerGeo); tileState.setCenter(centerTile, false); // Convert zoom: float zoomGeo = geoState.getZoom(); int zoomTile = glToTileZoom(zoomGeo); // Geo-zoom identical to // GL-zoom tileState.setZoom(zoomTile, false); } } /** * Updates the given <code>GeoState</code> object by converting all the * available information from <code>GLState</code> into geographic * coordinates. * * @param glState the state from which the data is used * @param geoState the state to be updated */ public static void glToGeo(GLState glState, GeoState geoState) { if (glState != null && geoState != null) { // Convert bounding boxes: FloatBoundingBox bBoxGL = glState.getBoundingBox(); FloatVector3D upperLeftGL = bBoxGL.getUpperLeft(); FloatVector3D upperRightGL = bBoxGL.getUpperRight(); FloatVector3D lowerLeftGL = bBoxGL.getLowerLeft(); FloatVector3D lowerRightGL = bBoxGL.getLowerRight(); FloatVector3D upperLeftGeo = glToGeo(upperLeftGL); FloatVector3D upperRightGeo = glToGeo(upperRightGL); FloatVector3D lowerLeftGeo = glToGeo(lowerLeftGL); FloatVector3D lowerRightGeo = glToGeo(lowerRightGL); FloatBoundingBox bBoxGeo = new FloatBoundingBox(upperLeftGeo, upperRightGeo, lowerLeftGeo, lowerRightGeo); geoState.setBoundingBox(bBoxGeo, false); // Calculate center: FloatVector3D centerGL = glState.getPosition(); FloatVector3D centerGeo = glToGeo(centerGL); geoState.setCenter(centerGeo, false); // Adopt zoom. geoState.setZoom(glState.getZoom(), false); } } /** * Converts a given positive number representing a zoom level in * GL-coordinates into a zoom level for tile coordinates. * * @param glZoom * the zoom level to be converted * * @return a value in the range of 1-<code>TileState.MAX_ZOOM</code> * representing a zoom level in tile coordinates */ public static int glToTileZoom(float glZoom) { return (int) (Mode2D.MAX_2D_LEVEL - (Math.log(glZoom) / Math.log(2))); } /** * Converts a given non-negative number representing a zoom level in * tile coordinates into a zoom level in GL-coordinates. * * @param tileZoom * the zoom level to be converted * * @return a zoom level in GL-coordinates */ public static float tileToGLZoom(float tileZoom) { return (float) (Math.pow(2, Mode2D.MAX_2D_LEVEL - tileZoom)); } public static boolean isTileBBoxSuperposed(IntegerBoundingBox a, IntegerBoundingBox b) { boolean inXRange = a.getUpperLeft().getX() >= b.getUpperLeft().getX() && a.getUpperRight().getX() <= b.getUpperRight().getX(); boolean inYRange = a.getUpperLeft().getY() >= b.getUpperLeft().getY() && a.getLowerLeft().getY() <= b.getLowerLeft().getY(); return inXRange && inYRange; } /** * Returns the length of a vertical or horizontal range in * window-coordinate-space in GL-coordinates. * * @param pixels * The length of the range in pixels (window-space). * @param tileZoom * The zoom-level to calculate the length for. * @return The length of the range in GL-coordinates. */ public static float glCoordsPerPixelRange(int pixels, int tileZoom) { return (((float)pixels) / TILE_LENGTH_IN_PIXELS) * (float) Math.pow(2, Mode2D.MAX_2D_LEVEL - tileZoom); } public static float glCoordsPerPixelRange(int pixels, float canvasPixelRange, float canvasRange) { return ((float) pixels * (float) canvasRange / (float) canvasPixelRange); } /* * ROTATING METHODS */ /* * public static FloatVector3D rotateAroundX(FloatVector3D vec, float angle) * { // MAYBE TODO return null; } * * public static FloatVector3D rotateAroundY(FloatVector3D vec, float angle) * { // MAYBE TODO return null; } */ /** * Rotates the passed Vector around the Z-Axis. * * @param vec * The Vector to be rotated. It won't be changed. * @param angle * The angle around which the FloatVector3D <code>vec</code>will * be rotated. * @return A vector rotated around <code>angle</code> which origin * coordinates where specified by <code>vec</code>. */ public static FloatVector3D rotateAroundZ(FloatVector3D vec, float angle) { float x = vec.getX(); float y = vec.getY(); float z = vec.getZ(); float angleRAD = (float) Math.toRadians(angle); float newX = (float) (x * Math.cos(angleRAD) - y * Math.sin(angleRAD)); float newY = (float) (x * Math.sin(angleRAD) + y * Math.cos(angleRAD)); return (new FloatVector3D(newX, newY, z)); } /** * Takes a GL-bounding-box and returns the tile-coordinates of all those * tiles that are contained fully or partially in the bounding-box. * * @param bbox * The bounding-box to get tile-coordinates for. * @param step * The distance checked for tiles in. This should be less or * equal to the side-length of a tile to get all tiles contained * in the box. * @param tileZoom * The tile-zoom of the tiles to check for. * @return The tile-coordinates of all those tiles that are contained fully * or partially in the bounding-box. */ public static Collection<IntegerVector3D> getTileCoordsInGLBBox( FloatBoundingBox bbox, float step, int tileZoom) { // Get the corners of the Bounding-box: FloatVector3D[] corners = bbox.getCornersClockwise(); // Get the maximum and minimum tile-coordinates of the corners: int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE; int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE; for (FloatVector3D corner : corners) { IntegerVector3D tileCoords = AlgoUtil.glToTile(corner); maxX = Math.max(tileCoords.getX(), maxX); minX = Math.min(tileCoords.getX(), minX); maxY = Math.max(tileCoords.getY(), maxY); minY = Math.min(tileCoords.getY(), minY); } /* * Now a matrix is used where the entry at [x][y] is true if and only if * a border of the bbox is on the tile with coordinates (minX + x, minY * + y). */ boolean[][] borders = new boolean[maxX - minX][maxY - minY]; for (int i = 0; i < corners.length; i++) { // Select the next corner clockwise: FloatVector3D from = new FloatVector3D(corners[i]); FloatVector3D to = new FloatVector3D(corners[(i + 1) % corners.length]); // Ignore z-coordinate: from.setZ(0); to.setZ(0); // Calculate the vector between the corners: FloatVector3D totalDiff = new FloatVector3D(to); totalDiff.sub(from); // For scaling a vector of length one is required: FloatVector3D unit = totalDiff.toUnitVector(); // Now view all linear-combinations shorter than the vector between // corners: for (int j = 0; j < totalDiff.length(); j += step) { // Get the linear-combination with current length: FloatVector3D currentDiff = new FloatVector3D(unit); currentDiff.mul(j); // The stretched vector is relative to from. Undo that: FloatVector3D pos = new FloatVector3D(from); pos.add(currentDiff); // Conversion-algorithm requires z-coordinate to be Gl-Zoom: pos.setZ(tileToGLZoom(tileZoom)); // Get coordinates of the tile where the current position is on: IntegerVector3D tilePos = glToTile(pos); // Mark the current position as border coordinates: borders[tilePos.getX() - minX][tilePos.getY() - minY] = true; } } Collection<IntegerVector3D> tileCoords = new LinkedList<>(); boolean rotated = !borders[0][0] || !borders[maxX - minX][maxY - minY]; // If the box is not rotated, all coordinates are contained in the box: for (int x = 0; x < borders.length && !rotated; x++) { for (int y = 0; y < borders[x].length; y++) { // Add the coordinate to those in the bbox: IntegerVector3D tilePos = new IntegerVector3D(minX + x, minY + y, tileZoom); tileCoords.add(tilePos); } } /* * Now we have the all tile-coordinates where the borders are. Iterate * the matrix and add those border-tiles and all tile-coordinates * between them: */ for (int x = 0; x < borders.length && rotated; x++) { Collection<IntegerVector3D> columnTileCoords = new LinkedList<>(); // Flag whether we are between two borders in this column: boolean inRange = false; for (int y = 0; y < borders[x].length; y++) { // If we are not in range yet, but just hit a border: if (!inRange && borders[x][y]) { inRange = true; // Remember that } // If we are on a border or between them: if (inRange) { // Did we hit another border? inRange = !borders[x][y]; // Add the coordinate to those in the bbox: IntegerVector3D tilePos = new IntegerVector3D(minX + x, minY + y, tileZoom); columnTileCoords.add(tilePos); } } // Add all found coordinates to total collection: tileCoords.addAll(columnTileCoords); } return tileCoords; } /** * Calculates the distance between two geo-positions. * @param from The position to start from. * @param to The destination. * @return The distance between <code>from</code> and <code>to</code> in kilometers. */ public static float calculateGeoDistance(FloatVector3D from, FloatVector3D to) { float radius = 6371f; // The earth radius in kilometers // Get differences in radians float dLat = (float) Math.toRadians(to.getX() - from.getX()); float dLon = (float) Math.toRadians(to.getY() - from.getY()); // Get latitudes in radians: float latFrom = (float) Math.toRadians(from.getX()); float latTo = (float) Math.toRadians(to.getX()); float a = (float) (Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(latFrom) * Math.cos(latTo)); float c = 2 * (float)Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); float distance = radius * c; return distance; } public static float[][] multMatrix(float[][] m, float[][] n) { float[][] result = null; if (m[0].length == n.length) { int rowsInM = m.length; int colsInM = m[0].length; int colsInN = n[0].length; result = new float[rowsInM][colsInN]; for (int i = 0; i < rowsInM; i++) { for (int j = 0; j < colsInN; j++) { result[i][j] = 0; for (int k = 0; k < colsInM; k++) { result[i][j] += m[i][k] * n[k][j]; } } } } else { int rows = m.length; int cols = m[0].length; result = new float[rows][cols]; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[0].length; j++) { result[i][j] = 0; } } } return result; } public static float[][] getRotationMatrix(float deg, FloatVector3D axis, float[][] oldMatrix) { FloatVector3D n = axis.toUnitVector(); float[][] matrix = new float[3][3]; float cos = (float) Math.cos(Math.toRadians(deg)); float sin = (float) Math.sin(Math.toRadians(deg)); matrix[0][0] = (n.getX()*n.getX()) * (1 - cos) + cos; matrix[0][1] = (n.getX()*n.getY()) * (1 - cos) - (n.getZ() * sin); matrix[0][2] = (n.getX()*n.getZ()) * (1 - cos) + (n.getY() * sin); matrix[1][0] = (n.getY()*n.getX()) * (1 - cos) + (n.getZ() * sin); matrix[1][1] = (n.getY()*n.getY()) * (1 - cos) + cos; matrix[1][2] = (n.getY()*n.getZ()) * (1 - cos) - (n.getX() * sin); matrix[2][0] = (n.getX()*n.getZ()) * (1 - cos) - (n.getY() * sin); matrix[2][1] = (n.getY()*n.getZ()) * (1 - cos) + (n.getX() * sin); matrix[2][2] = (n.getZ()*n.getZ()) * (1 - cos) + cos; matrix = AlgoUtil.multMatrix(oldMatrix, matrix); return matrix; } }
/* * Copyright 2018 Lithium Technologies Pvt Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package lithium.community.android.sdk.queryutil; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; /** * Created by kunal.shrivastava on 10/18/16. * Model represents setting for API provider query */ public class LiQuerySetting { private static final String WHERE_CONDITION = "where-condition"; private static final String ORDER = "order"; private static final String LIMIT = "limit"; private ArrayList<WhereClause> whereClauses; private Ordering ordering; private int limit; public LiQuerySetting(ArrayList<WhereClause> whereClauses, Ordering ordering, int limit) { this.whereClauses = whereClauses; this.ordering = ordering; this.limit = limit; } public ArrayList<WhereClause> getWhereClauses() { return (ArrayList<WhereClause>) whereClauses.clone(); } public Ordering getOrdering() { return ordering; } public int getLimit() { return limit; } @Override public String toString() { return "LiQuerySetting{" + ", whereClauses=" + whereClauses + ", orderObject=" + ordering + ", limit=" + limit + '}'; } /** * All allowed conditions in where clause. */ public enum LiWhereClause { @SerializedName("equals") EQUALS("="), @SerializedName("not-equals") NOT_EQUALS("!="), @SerializedName("greater-than") GREATER_THAN(">"), @SerializedName("greater-than-equals") GREATER_THAN_EQUALS(">="), @SerializedName("less-than") LESS_THAN("<"), @SerializedName("less-than-equal") LESS_THAN_EQUAL("<="), @SerializedName("in") IN("in"), @SerializedName("matches") MATCHES("matches"); private final String value; private LiWhereClause(String str) { value = str; } public String getValue() { return value; } public boolean equals(String value) { return (value == null) ? false : this.value.equals(value); } public String toString() { return this.value.toString(); } } /** * Allowed cluses on LIQL. */ protected enum LiClauses { @SerializedName("where") WHERE("where"), @SerializedName("order") ORDER("order"), @SerializedName("limit") LIMIT("limit"); private final String value; private LiClauses(String str) { value = str; } public boolean equals(String value) { return (value == null) ? false : this.value.equals(value); } public String toString() { return this.value.toString(); } } /** * Class for adding where clause. */ protected static class WhereClause { private LiWhereClause clause; private String key; private String value; private String operator; public LiWhereClause getClause() { return clause; } public void setClause(LiWhereClause clause) { this.clause = clause; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } @Override public String toString() { return "LiQueryWhereClause{" + "clause=" + clause + ", key='" + key + '\'' + ", value='" + value + '\'' + ", operator='" + operator + '\'' + '}'; } } /** * Class for adding ordering clause. */ protected static class Ordering { private String key; private String type; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "LiQueryOrdering{" + "key='" + key + '\'' + ", type='" + type + '\'' + '}'; } } }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.compute.model; /** * Model definition for FutureReservationsScopedList. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class FutureReservationsScopedList extends com.google.api.client.json.GenericJson { /** * A list of future reservations contained in this scope. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<FutureReservation> futureReservations; static { // hack to force ProGuard to consider FutureReservation used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(FutureReservation.class); } /** * Informational warning which replaces the list of future reservations when the list is empty. * The value may be {@code null}. */ @com.google.api.client.util.Key private Warning warning; /** * A list of future reservations contained in this scope. * @return value or {@code null} for none */ public java.util.List<FutureReservation> getFutureReservations() { return futureReservations; } /** * A list of future reservations contained in this scope. * @param futureReservations futureReservations or {@code null} for none */ public FutureReservationsScopedList setFutureReservations(java.util.List<FutureReservation> futureReservations) { this.futureReservations = futureReservations; return this; } /** * Informational warning which replaces the list of future reservations when the list is empty. * @return value or {@code null} for none */ public Warning getWarning() { return warning; } /** * Informational warning which replaces the list of future reservations when the list is empty. * @param warning warning or {@code null} for none */ public FutureReservationsScopedList setWarning(Warning warning) { this.warning = warning; return this; } @Override public FutureReservationsScopedList set(String fieldName, Object value) { return (FutureReservationsScopedList) super.set(fieldName, value); } @Override public FutureReservationsScopedList clone() { return (FutureReservationsScopedList) super.clone(); } /** * Informational warning which replaces the list of future reservations when the list is empty. */ public static final class Warning extends com.google.api.client.json.GenericJson { /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String code; /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<Data> data; static { // hack to force ProGuard to consider Data used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(Data.class); } /** * [Output Only] A human-readable description of the warning code. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String message; /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @return value or {@code null} for none */ public java.lang.String getCode() { return code; } /** * [Output Only] A warning code, if applicable. For example, Compute Engine returns * NO_RESULTS_ON_PAGE if there are no results in the response. * @param code code or {@code null} for none */ public Warning setCode(java.lang.String code) { this.code = code; return this; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @return value or {@code null} for none */ public java.util.List<Data> getData() { return data; } /** * [Output Only] Metadata about this warning in key: value format. For example: "data": [ { "key": * "scope", "value": "zones/us-east1-d" } * @param data data or {@code null} for none */ public Warning setData(java.util.List<Data> data) { this.data = data; return this; } /** * [Output Only] A human-readable description of the warning code. * @return value or {@code null} for none */ public java.lang.String getMessage() { return message; } /** * [Output Only] A human-readable description of the warning code. * @param message message or {@code null} for none */ public Warning setMessage(java.lang.String message) { this.message = message; return this; } @Override public Warning set(String fieldName, Object value) { return (Warning) super.set(fieldName, value); } @Override public Warning clone() { return (Warning) super.clone(); } /** * Model definition for FutureReservationsScopedListWarningData. */ public static final class Data extends com.google.api.client.json.GenericJson { /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String key; /** * [Output Only] A warning data value corresponding to the key. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String value; /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @return value or {@code null} for none */ public java.lang.String getKey() { return key; } /** * [Output Only] A key that provides more detail on the warning being returned. For example, for * warnings where there are no results in a list request for a particular zone, this key might be * scope and the key value might be the zone name. Other examples might be a key indicating a * deprecated resource and a suggested replacement, or a warning about invalid network settings * (for example, if an instance attempts to perform IP forwarding but is not enabled for IP * forwarding). * @param key key or {@code null} for none */ public Data setKey(java.lang.String key) { this.key = key; return this; } /** * [Output Only] A warning data value corresponding to the key. * @return value or {@code null} for none */ public java.lang.String getValue() { return value; } /** * [Output Only] A warning data value corresponding to the key. * @param value value or {@code null} for none */ public Data setValue(java.lang.String value) { this.value = value; return this; } @Override public Data set(String fieldName, Object value) { return (Data) super.set(fieldName, value); } @Override public Data clone() { return (Data) super.clone(); } } } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.fetch; import org.apache.lucene.index.PostingsEnum; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.util.BytesRef; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.termvectors.TermVectorsRequest; import org.elasticsearch.action.termvectors.TermVectorsResponse; import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.termvectors.TermVectorsService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.SearchPlugin; import org.elasticsearch.search.SearchExtBuilder; import org.elasticsearch.search.SearchExtParser; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.internal.InternalSearchHitField; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static java.util.Collections.singletonList; import static org.elasticsearch.client.Requests.indexRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.CoreMatchers.equalTo; @ClusterScope(scope = Scope.SUITE, supportsDedicatedMasters = false, numDataNodes = 2) public class FetchSubPhasePluginIT extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singletonList(FetchTermVectorsPlugin.class); } @Override protected Collection<Class<? extends Plugin>> transportClientPlugins() { return nodePlugins(); } @SuppressWarnings("unchecked") public void testPlugin() throws Exception { client().admin() .indices() .prepareCreate("test") .addMapping( "type1", jsonBuilder() .startObject().startObject("type1") .startObject("properties") .startObject("test") .field("type", "text").field("term_vector", "yes") .endObject() .endObject() .endObject().endObject()).execute().actionGet(); client().index( indexRequest("test").type("type1").id("1") .source(jsonBuilder().startObject().field("test", "I am sam i am").endObject())).actionGet(); client().admin().indices().prepareRefresh().execute().actionGet(); SearchResponse response = client().prepareSearch().setSource(new SearchSourceBuilder() .ext(Collections.singletonList(new TermVectorsFetchBuilder("test")))).get(); assertSearchResponse(response); assertThat(((Map<String, Integer>) response.getHits().getAt(0).field("term_vectors_fetch").getValues().get(0)).get("i"), equalTo(2)); assertThat(((Map<String, Integer>) response.getHits().getAt(0).field("term_vectors_fetch").getValues().get(0)).get("am"), equalTo(2)); assertThat(((Map<String, Integer>) response.getHits().getAt(0).field("term_vectors_fetch").getValues().get(0)).get("sam"), equalTo(1)); } public static class FetchTermVectorsPlugin extends Plugin implements SearchPlugin { @Override public List<FetchSubPhase> getFetchSubPhases(FetchPhaseConstructionContext context) { return singletonList(new TermVectorsFetchSubPhase()); } @Override public List<SearchExtSpec<?>> getSearchExts() { return Collections.singletonList(new SearchExtSpec<>(TermVectorsFetchSubPhase.NAME, TermVectorsFetchBuilder::new, TermVectorsFetchParser.INSTANCE)); } } private static final class TermVectorsFetchSubPhase implements FetchSubPhase { private static final String NAME = "term_vectors_fetch"; @Override public void hitExecute(SearchContext context, HitContext hitContext) { TermVectorsFetchBuilder fetchSubPhaseBuilder = (TermVectorsFetchBuilder)context.getSearchExt(NAME); if (fetchSubPhaseBuilder == null) { return; } String field = fetchSubPhaseBuilder.getField(); if (hitContext.hit().fieldsOrNull() == null) { hitContext.hit().fields(new HashMap<>()); } SearchHitField hitField = hitContext.hit().fields().get(NAME); if (hitField == null) { hitField = new InternalSearchHitField(NAME, new ArrayList<>(1)); hitContext.hit().fields().put(NAME, hitField); } TermVectorsRequest termVectorsRequest = new TermVectorsRequest(context.indexShard().shardId().getIndex().getName(), hitContext.hit().type(), hitContext.hit().id()); TermVectorsResponse termVector = TermVectorsService.getTermVectors(context.indexShard(), termVectorsRequest); try { Map<String, Integer> tv = new HashMap<>(); TermsEnum terms = termVector.getFields().terms(field).iterator(); BytesRef term; while ((term = terms.next()) != null) { tv.put(term.utf8ToString(), terms.postings(null, PostingsEnum.ALL).freq()); } hitField.values().add(tv); } catch (IOException e) { ESLoggerFactory.getLogger(FetchSubPhasePluginIT.class.getName()).info("Swallowed exception", e); } } } private static final class TermVectorsFetchParser implements SearchExtParser<TermVectorsFetchBuilder> { private static final TermVectorsFetchParser INSTANCE = new TermVectorsFetchParser(); private TermVectorsFetchParser() { } @Override public TermVectorsFetchBuilder fromXContent(XContentParser parser) throws IOException { String field; XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_STRING) { field = parser.text(); } else { throw new ParsingException(parser.getTokenLocation(), "Expected a VALUE_STRING but got " + token); } if (field == null) { throw new ParsingException(parser.getTokenLocation(), "no fields specified for " + TermVectorsFetchSubPhase.NAME); } return new TermVectorsFetchBuilder(field); } } private static final class TermVectorsFetchBuilder extends SearchExtBuilder { private final String field; private TermVectorsFetchBuilder(String field) { this.field = field; } private TermVectorsFetchBuilder(StreamInput in) throws IOException { this.field = in.readString(); } private String getField() { return field; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TermVectorsFetchBuilder that = (TermVectorsFetchBuilder) o; return Objects.equals(field, that.field); } @Override public int hashCode() { return Objects.hash(field); } @Override public String getWriteableName() { return TermVectorsFetchSubPhase.NAME; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(field); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.field(TermVectorsFetchSubPhase.NAME, field); } } }
/* * The Plaid API * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * The version of the OpenAPI document: 2020-09-14_1.79.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.plaid.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.plaid.client.model.PaymentInitiationConsentConstraints; import com.plaid.client.model.PaymentInitiationConsentScope; import com.plaid.client.model.PaymentInitiationConsentStatus; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; /** * PaymentInitiationConsent defines a payment initiation consent. */ @ApiModel(description = "PaymentInitiationConsent defines a payment initiation consent.") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-03-01T23:05:06.764Z[GMT]") public class PaymentInitiationConsent { public static final String SERIALIZED_NAME_CONSENT_ID = "consent_id"; @SerializedName(SERIALIZED_NAME_CONSENT_ID) private String consentId; public static final String SERIALIZED_NAME_STATUS = "status"; @SerializedName(SERIALIZED_NAME_STATUS) private PaymentInitiationConsentStatus status; public static final String SERIALIZED_NAME_CREATED_AT = "created_at"; @SerializedName(SERIALIZED_NAME_CREATED_AT) private OffsetDateTime createdAt; public static final String SERIALIZED_NAME_RECIPIENT_ID = "recipient_id"; @SerializedName(SERIALIZED_NAME_RECIPIENT_ID) private String recipientId; public static final String SERIALIZED_NAME_REFERENCE = "reference"; @SerializedName(SERIALIZED_NAME_REFERENCE) private String reference; public static final String SERIALIZED_NAME_CONSTRAINTS = "constraints"; @SerializedName(SERIALIZED_NAME_CONSTRAINTS) private PaymentInitiationConsentConstraints constraints; public static final String SERIALIZED_NAME_SCOPES = "scopes"; @SerializedName(SERIALIZED_NAME_SCOPES) private List<PaymentInitiationConsentScope> scopes = new ArrayList<>(); public PaymentInitiationConsent consentId(String consentId) { this.consentId = consentId; return this; } /** * The consent ID. * @return consentId **/ @ApiModelProperty(required = true, value = "The consent ID.") public String getConsentId() { return consentId; } public void setConsentId(String consentId) { this.consentId = consentId; } public PaymentInitiationConsent status(PaymentInitiationConsentStatus status) { this.status = status; return this; } /** * Get status * @return status **/ @ApiModelProperty(required = true, value = "") public PaymentInitiationConsentStatus getStatus() { return status; } public void setStatus(PaymentInitiationConsentStatus status) { this.status = status; } public PaymentInitiationConsent createdAt(OffsetDateTime createdAt) { this.createdAt = createdAt; return this; } /** * Consent creation timestamp, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format. * @return createdAt **/ @ApiModelProperty(required = true, value = "Consent creation timestamp, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format.") public OffsetDateTime getCreatedAt() { return createdAt; } public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; } public PaymentInitiationConsent recipientId(String recipientId) { this.recipientId = recipientId; return this; } /** * The ID of the recipient the payment consent is for. * @return recipientId **/ @ApiModelProperty(required = true, value = "The ID of the recipient the payment consent is for.") public String getRecipientId() { return recipientId; } public void setRecipientId(String recipientId) { this.recipientId = recipientId; } public PaymentInitiationConsent reference(String reference) { this.reference = reference; return this; } /** * A reference for the payment consent. * @return reference **/ @ApiModelProperty(required = true, value = "A reference for the payment consent.") public String getReference() { return reference; } public void setReference(String reference) { this.reference = reference; } public PaymentInitiationConsent constraints(PaymentInitiationConsentConstraints constraints) { this.constraints = constraints; return this; } /** * Get constraints * @return constraints **/ @ApiModelProperty(required = true, value = "") public PaymentInitiationConsentConstraints getConstraints() { return constraints; } public void setConstraints(PaymentInitiationConsentConstraints constraints) { this.constraints = constraints; } public PaymentInitiationConsent scopes(List<PaymentInitiationConsentScope> scopes) { this.scopes = scopes; return this; } public PaymentInitiationConsent addScopesItem(PaymentInitiationConsentScope scopesItem) { this.scopes.add(scopesItem); return this; } /** * An array of payment consent scopes. * @return scopes **/ @ApiModelProperty(required = true, value = "An array of payment consent scopes.") public List<PaymentInitiationConsentScope> getScopes() { return scopes; } public void setScopes(List<PaymentInitiationConsentScope> scopes) { this.scopes = scopes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentInitiationConsent paymentInitiationConsent = (PaymentInitiationConsent) o; return Objects.equals(this.consentId, paymentInitiationConsent.consentId) && Objects.equals(this.status, paymentInitiationConsent.status) && Objects.equals(this.createdAt, paymentInitiationConsent.createdAt) && Objects.equals(this.recipientId, paymentInitiationConsent.recipientId) && Objects.equals(this.reference, paymentInitiationConsent.reference) && Objects.equals(this.constraints, paymentInitiationConsent.constraints) && Objects.equals(this.scopes, paymentInitiationConsent.scopes); } @Override public int hashCode() { return Objects.hash(consentId, status, createdAt, recipientId, reference, constraints, scopes); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentInitiationConsent {\n"); sb.append(" consentId: ").append(toIndentedString(consentId)).append("\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n"); sb.append(" recipientId: ").append(toIndentedString(recipientId)).append("\n"); sb.append(" reference: ").append(toIndentedString(reference)).append("\n"); sb.append(" constraints: ").append(toIndentedString(constraints)).append("\n"); sb.append(" scopes: ").append(toIndentedString(scopes)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.vzome.core.commands; import java.io.InputStream; import java.util.HashSet; import java.util.Set; import java.util.logging.Logger; import org.w3c.dom.Element; import com.vzome.core.algebra.AlgebraicField; import com.vzome.core.algebra.AlgebraicVector; import com.vzome.core.construction.Construction; import com.vzome.core.construction.ConstructionChanges; import com.vzome.core.construction.ConstructionList; import com.vzome.core.construction.FreePoint; import com.vzome.core.construction.Point; import com.vzome.core.construction.Segment; import com.vzome.core.construction.SegmentJoiningPoints; import com.vzome.core.construction.VefToModel; import com.vzome.core.math.DomUtils; /** * @author Scott Vorthmann */ public class CommandImportVEFData extends AbstractCommand { public static final int X = 0, Y = 1, Z = 2, W = 3; public static final String VEF_STRING_ATTR_NAME = "org.vorthmann.zome.commands.CommandImportVEFData" + ".vef.string"; public static final String FIELD_ATTR_NAME = "org.vorthmann.zome.commands.CommandImportVEFData" + ".field"; public static final String NO_INVERSION_ATTR_NAME = "org.vorthmann.zome.commands.CommandImportVEFData" + ".no.inversion"; private static final Object[][] PARAM_SIGNATURE = new Object[][]{ { GENERIC_PARAM_NAME, Construction.class } }; private static final Object[][] ATTR_SIGNATURE = new Object[][]{ { VEF_STRING_ATTR_NAME, String.class }, { Command.FIELD_ATTR_NAME, InputStream.class }, { NO_INVERSION_ATTR_NAME, InputStream.class } }; private static final Logger logger = Logger .getLogger( "com.vzome.core.commands.importVEF" ); @Override public Object[][] getParameterSignature() { return PARAM_SIGNATURE; } @Override public Object[][] getAttributeSignature() { return ATTR_SIGNATURE; } @Override public boolean attributeIs3D( String attrName ) { if ( "symmetry.axis.segment" .equals( attrName ) ) return false; else return true; } /* * Currently, there is no way to set this via the UI... only reading it from XML */ private AlgebraicVector quaternionVector = null; /** * Only called when migrating a 2.0 model file. */ @Override public void setQuaternion( AlgebraicVector offset ) { quaternionVector = offset; } /* * Adding this to support a 4D quaternion. */ @Override public AttributeMap setXml( Element xml, XmlSaveFormat format ) { AttributeMap attrs = super .setXml( xml, format ); quaternionVector = format .parseRationalVector( xml, "quaternion" ); return attrs; } @Override public void getXml( Element result, AttributeMap attributes ) { if ( quaternionVector != null ) DomUtils .addAttribute( result, "quaternion", quaternionVector .toString() ); super .getXml( result, attributes ); } @Override public void setFixedAttributes( AttributeMap attributes, XmlSaveFormat format ) { if ( ! attributes .containsKey( CommandImportVEFData .FIELD_ATTR_NAME ) ) attributes .put( CommandImportVEFData .FIELD_ATTR_NAME, format .getField() ); super .setFixedAttributes( attributes, format ); } @Override public ConstructionList apply( ConstructionList parameters, AttributeMap attributes, ConstructionChanges effects ) throws Failure { ConstructionList result = new ConstructionList(); AlgebraicField field = (AlgebraicField) attributes .get( CommandImportVEFData .FIELD_ATTR_NAME ); if ( field == null ) field = (AlgebraicField) attributes .get( Command.FIELD_ATTR_NAME ); Segment symmAxis = (Segment) attributes .get( CommandTransform.SYMMETRY_AXIS_ATTR_NAME ); String vefData = (String) attributes .get( VEF_STRING_ATTR_NAME ); Boolean noInversion = (Boolean) attributes .get( NO_INVERSION_ATTR_NAME ); AlgebraicVector quaternion = quaternionVector; if ( quaternion == null ) quaternion = (symmAxis==null)? null : symmAxis .getOffset(); // will get inflated to 4D when we know wFirst() if ( quaternion != null ) quaternion = quaternion .scale( field .createPower( -5 ) ); if ( noInversion != null && noInversion ) new VefToModelNoInversion( quaternion, field, effects ) .parseVEF( vefData, field ); else new VefToModel( quaternion, effects, field .createPower( 5 ), null ) .parseVEF( vefData, field ); return result; } private class VefToModelNoInversion extends VefToModel { protected AlgebraicVector[][] mProjected; protected final Set<Point> mUsedPoints = new HashSet<>(); public VefToModelNoInversion( AlgebraicVector quaternion, AlgebraicField field, ConstructionChanges effects ) { super( quaternion, effects, field .createPower( 5 ), null ); } @Override protected void addVertex( int index, AlgebraicVector location ) { if ( scale != null && ! usesActualScale() ) { location = location .scale( scale ); } if ( mProjection != null ) location = mProjection .projectImage( location, wFirst() ); mVertices[ index ] = new FreePoint( location ); // mEffects .constructionAdded( mVertices[ index ] ); } @Override protected void startEdges( int numEdges ) { mProjected = new AlgebraicVector[ numEdges ][ 2 ]; } @Override protected void addEdge( int index, int v1, int v2 ) { Point p1 = mVertices[ v1 ], p2 = mVertices[ v2 ]; if ( p1 == null || p2 == null ) return; Segment seg = new SegmentJoiningPoints( p1, p2 ); AlgebraicVector pr1 = p1 .getLocation() .projectTo3d( wFirst() ) .negate(); AlgebraicVector pr2 = p2 .getLocation() .projectTo3d( wFirst() ) .negate(); for ( int i = 0; i < index; i++ ) { if ( pr1 .equals( mProjected[ i ][ 0 ] ) && pr2 .equals( mProjected[ i ][ 1 ] ) ) return; if ( pr2 .equals( mProjected[ i ][ 0 ] ) && pr1 .equals( mProjected[ i ][ 1 ] ) ) return; } mProjected[ index ][ 0 ] = pr1 .negate(); mProjected[ index ][ 1 ] = pr2 .negate(); mEffects .constructionAdded( seg ); mUsedPoints .add( p1 ); mUsedPoints .add( p2 ); } @Override protected void endEdges() { for (Point point : mUsedPoints) { mEffects .constructionAdded( point ); } } } }
/* * 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.gateway; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.nodes.BaseNodeResponse; import org.elasticsearch.action.support.nodes.BaseNodesResponse; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.RerouteService; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.allocation.AllocateUnassignedDecision; import org.elasticsearch.cluster.routing.allocation.ExistingShardsAllocator; import org.elasticsearch.cluster.routing.allocation.FailedShard; import org.elasticsearch.cluster.routing.allocation.RoutingAllocation; import org.elasticsearch.common.Priority; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lease.Releasables; import org.elasticsearch.common.util.concurrent.ConcurrentCollections; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.gateway.AsyncShardFetch.Lister; import org.elasticsearch.gateway.TransportNodesListGatewayStartedShards.NodeGatewayStartedShards; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.indices.store.TransportNodesListShardStoreMetadata; import org.elasticsearch.indices.store.TransportNodesListShardStoreMetadata.NodeStoreFilesMetadata; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class GatewayAllocator implements ExistingShardsAllocator { public static final String ALLOCATOR_NAME = "gateway_allocator"; private static final Logger logger = LogManager.getLogger(GatewayAllocator.class); private final RerouteService rerouteService; private final PrimaryShardAllocator primaryShardAllocator; private final ReplicaShardAllocator replicaShardAllocator; private final ConcurrentMap<ShardId, AsyncShardFetch<NodeGatewayStartedShards>> asyncFetchStarted = ConcurrentCollections.newConcurrentMap(); private final ConcurrentMap<ShardId, AsyncShardFetch<NodeStoreFilesMetadata>> asyncFetchStore = ConcurrentCollections.newConcurrentMap(); private Set<String> lastSeenEphemeralIds = Collections.emptySet(); @Inject public GatewayAllocator(RerouteService rerouteService, NodeClient client) { this.rerouteService = rerouteService; this.primaryShardAllocator = new InternalPrimaryShardAllocator(client); this.replicaShardAllocator = new InternalReplicaShardAllocator(client); } @Override public void cleanCaches() { Releasables.close(asyncFetchStarted.values()); asyncFetchStarted.clear(); Releasables.close(asyncFetchStore.values()); asyncFetchStore.clear(); } // for tests protected GatewayAllocator() { this.rerouteService = null; this.primaryShardAllocator = null; this.replicaShardAllocator = null; } @Override public int getNumberOfInFlightFetches() { int count = 0; for (AsyncShardFetch<NodeGatewayStartedShards> fetch : asyncFetchStarted.values()) { count += fetch.getNumberOfInFlightFetches(); } for (AsyncShardFetch<NodeStoreFilesMetadata> fetch : asyncFetchStore.values()) { count += fetch.getNumberOfInFlightFetches(); } return count; } @Override public void applyStartedShards(final List<ShardRouting> startedShards, final RoutingAllocation allocation) { for (ShardRouting startedShard : startedShards) { Releasables.close(asyncFetchStarted.remove(startedShard.shardId())); Releasables.close(asyncFetchStore.remove(startedShard.shardId())); } } @Override public void applyFailedShards(final List<FailedShard> failedShards, final RoutingAllocation allocation) { for (FailedShard failedShard : failedShards) { Releasables.close(asyncFetchStarted.remove(failedShard.getRoutingEntry().shardId())); Releasables.close(asyncFetchStore.remove(failedShard.getRoutingEntry().shardId())); } } @Override public void beforeAllocation(final RoutingAllocation allocation) { assert primaryShardAllocator != null; assert replicaShardAllocator != null; ensureAsyncFetchStorePrimaryRecency(allocation); } @Override public void afterPrimariesBeforeReplicas(RoutingAllocation allocation) { assert replicaShardAllocator != null; if (allocation.routingNodes().hasInactiveShards()) { // cancel existing recoveries if we have a better match replicaShardAllocator.processExistingRecoveries(allocation); } } @Override public void allocateUnassigned(ShardRouting shardRouting, final RoutingAllocation allocation, UnassignedAllocationHandler unassignedAllocationHandler) { assert primaryShardAllocator != null; assert replicaShardAllocator != null; innerAllocatedUnassigned(allocation, primaryShardAllocator, replicaShardAllocator, shardRouting, unassignedAllocationHandler); } // allow for testing infra to change shard allocators implementation protected static void innerAllocatedUnassigned(RoutingAllocation allocation, PrimaryShardAllocator primaryShardAllocator, ReplicaShardAllocator replicaShardAllocator, ShardRouting shardRouting, ExistingShardsAllocator.UnassignedAllocationHandler unassignedAllocationHandler) { assert shardRouting.unassigned(); if (shardRouting.primary()) { primaryShardAllocator.allocateUnassigned(shardRouting, allocation, unassignedAllocationHandler); } else { replicaShardAllocator.allocateUnassigned(shardRouting, allocation, unassignedAllocationHandler); } } @Override public AllocateUnassignedDecision explainUnassignedShardAllocation(ShardRouting unassignedShard, RoutingAllocation routingAllocation) { assert unassignedShard.unassigned(); assert routingAllocation.debugDecision(); if (unassignedShard.primary()) { assert primaryShardAllocator != null; return primaryShardAllocator.makeAllocationDecision(unassignedShard, routingAllocation, logger); } else { assert replicaShardAllocator != null; return replicaShardAllocator.makeAllocationDecision(unassignedShard, routingAllocation, logger); } } /** * Clear the fetched data for the primary to ensure we do not cancel recoveries based on excessively stale data. */ private void ensureAsyncFetchStorePrimaryRecency(RoutingAllocation allocation) { DiscoveryNodes nodes = allocation.nodes(); if (hasNewNodes(nodes)) { final Set<String> newEphemeralIds = StreamSupport.stream(nodes.getDataNodes().spliterator(), false) .map(node -> node.value.getEphemeralId()).collect(Collectors.toSet()); // Invalidate the cache if a data node has been added to the cluster. This ensures that we do not cancel a recovery if a node // drops out, we fetch the shard data, then some indexing happens and then the node rejoins the cluster again. There are other // ways we could decide to cancel a recovery based on stale data (e.g. changing allocation filters or a primary failure) but // making the wrong decision here is not catastrophic so we only need to cover the common case. logger.trace(() -> new ParameterizedMessage( "new nodes {} found, clearing primary async-fetch-store cache", Sets.difference(newEphemeralIds, lastSeenEphemeralIds))); asyncFetchStore.values().forEach(fetch -> clearCacheForPrimary(fetch, allocation)); // recalc to also (lazily) clear out old nodes. this.lastSeenEphemeralIds = newEphemeralIds; } } private static void clearCacheForPrimary(AsyncShardFetch<TransportNodesListShardStoreMetadata.NodeStoreFilesMetadata> fetch, RoutingAllocation allocation) { ShardRouting primary = allocation.routingNodes().activePrimary(fetch.shardId); if (primary != null) { fetch.clearCacheForNode(primary.currentNodeId()); } } private boolean hasNewNodes(DiscoveryNodes nodes) { for (ObjectObjectCursor<String, DiscoveryNode> node : nodes.getDataNodes()) { if (lastSeenEphemeralIds.contains(node.value.getEphemeralId()) == false) { return true; } } return false; } class InternalAsyncFetch<T extends BaseNodeResponse> extends AsyncShardFetch<T> { InternalAsyncFetch(Logger logger, String type, ShardId shardId, String customDataPath, Lister<? extends BaseNodesResponse<T>, T> action) { super(logger, type, shardId, customDataPath, action); } @Override protected void reroute(ShardId shardId, String reason) { logger.trace("{} scheduling reroute for {}", shardId, reason); assert rerouteService != null; rerouteService.reroute("async_shard_fetch", Priority.HIGH, ActionListener.wrap( r -> logger.trace("{} scheduled reroute completed for {}", shardId, reason), e -> logger.debug(new ParameterizedMessage("{} scheduled reroute failed for {}", shardId, reason), e))); } } class InternalPrimaryShardAllocator extends PrimaryShardAllocator { private final NodeClient client; InternalPrimaryShardAllocator(NodeClient client) { this.client = client; } @Override protected AsyncShardFetch.FetchResult<NodeGatewayStartedShards> fetchData(ShardRouting shard, RoutingAllocation allocation) { // explicitely type lister, some IDEs (Eclipse) are not able to correctly infer the function type Lister<BaseNodesResponse<NodeGatewayStartedShards>, NodeGatewayStartedShards> lister = this::listStartedShards; AsyncShardFetch<NodeGatewayStartedShards> fetch = asyncFetchStarted.computeIfAbsent(shard.shardId(), shardId -> new InternalAsyncFetch<>(logger, "shard_started", shardId, IndexMetadata.INDEX_DATA_PATH_SETTING.get(allocation.metadata().index(shard.index()).getSettings()), lister)); AsyncShardFetch.FetchResult<NodeGatewayStartedShards> shardState = fetch.fetchData(allocation.nodes(), allocation.getIgnoreNodes(shard.shardId())); if (shardState.hasData()) { shardState.processAllocation(allocation); } return shardState; } private void listStartedShards(ShardId shardId, String customDataPath, DiscoveryNode[] nodes, ActionListener<BaseNodesResponse<NodeGatewayStartedShards>> listener) { var request = new TransportNodesListGatewayStartedShards.Request(shardId, customDataPath, nodes); client.executeLocally(TransportNodesListGatewayStartedShards.TYPE, request, ActionListener.wrap(listener::onResponse, listener::onFailure)); } } class InternalReplicaShardAllocator extends ReplicaShardAllocator { private final NodeClient client; InternalReplicaShardAllocator(NodeClient client) { this.client = client; } @Override protected AsyncShardFetch.FetchResult<NodeStoreFilesMetadata> fetchData(ShardRouting shard, RoutingAllocation allocation) { // explicitely type lister, some IDEs (Eclipse) are not able to correctly infer the function type Lister<BaseNodesResponse<NodeStoreFilesMetadata>, NodeStoreFilesMetadata> lister = this::listStoreFilesMetadata; AsyncShardFetch<NodeStoreFilesMetadata> fetch = asyncFetchStore.computeIfAbsent(shard.shardId(), shardId -> new InternalAsyncFetch<>(logger, "shard_store", shard.shardId(), IndexMetadata.INDEX_DATA_PATH_SETTING.get(allocation.metadata().index(shard.index()).getSettings()), lister)); AsyncShardFetch.FetchResult<NodeStoreFilesMetadata> shardStores = fetch.fetchData(allocation.nodes(), allocation.getIgnoreNodes(shard.shardId())); if (shardStores.hasData()) { shardStores.processAllocation(allocation); } return shardStores; } private void listStoreFilesMetadata(ShardId shardId, String customDataPath, DiscoveryNode[] nodes, ActionListener<BaseNodesResponse<NodeStoreFilesMetadata>> listener) { var request = new TransportNodesListShardStoreMetadata.Request(shardId, customDataPath, nodes); client.executeLocally(TransportNodesListShardStoreMetadata.TYPE, request, ActionListener.wrap(listener::onResponse, listener::onFailure)); } @Override protected boolean hasInitiatedFetching(ShardRouting shard) { return asyncFetchStore.get(shard.shardId()) != null; } } }
package qub; public interface SwingUIVerticalLayoutTests { static AWTUIBase createUIBase(Test test) { final Display display = new Display(1000, 1000, 100, 100); return AWTUIBase.create(display, test.getMainAsyncRunner(), test.getParallelAsyncRunner()); } static SwingUIBuilder createUIBuilder(Test test) { final AWTUIBase uiBase = SwingUIVerticalLayoutTests.createUIBase(test); return SwingUIBuilder.create(uiBase); } static SwingUIVerticalLayout createUIVerticalLayout(Test test) { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); return uiBuilder.create(SwingUIVerticalLayout.class).await(); } static void test(TestRunner runner) { runner.testGroup(SwingUIVerticalLayout.class, () -> { UIVerticalLayoutTests.test(runner, SwingUIVerticalLayoutTests::createUIVerticalLayout); SwingUIElementTests.test(runner, SwingUIVerticalLayoutTests::createUIVerticalLayout); runner.testGroup("create(SwingUIBase)", () -> { runner.test("with null", (Test test) -> { test.assertThrows(() -> SwingUIVerticalLayout.create(null), new PreConditionFailure("uiBase cannot be null.")); }); runner.test("with non-null", (Test test) -> { final AWTUIBase uiBase = SwingUIVerticalLayoutTests.createUIBase(test); final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayout.create(uiBase); test.assertNotNull(verticalLayout); test.assertEqual(Distance.zero, verticalLayout.getWidth()); test.assertEqual(Distance.zero, verticalLayout.getHeight()); test.assertEqual(UIPaddingInPixels.create(), verticalLayout.getPaddingInPixels()); final javax.swing.JPanel component = verticalLayout.getComponent(); test.assertNotNull(component); final javax.swing.JPanel jComponent = verticalLayout.getJComponent(); test.assertNotNull(jComponent); test.assertSame(component, jComponent); }); }); runner.testGroup("setWidth(Distance)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setWidthResult = verticalLayout.setWidth(Distance.inches(1)); test.assertSame(verticalLayout, setWidthResult); }); }); runner.testGroup("setWidthInPixels(int)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setWidthInPixelsResult = verticalLayout.setWidthInPixels(1); test.assertSame(verticalLayout, setWidthInPixelsResult); }); }); runner.testGroup("setHeight(Distance)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setHeightResult = verticalLayout.setHeight(Distance.inches(1)); test.assertSame(verticalLayout, setHeightResult); }); }); runner.testGroup("setHeightInPixels(Distance)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setHeightInPixelsResult = verticalLayout.setHeightInPixels(1); test.assertSame(verticalLayout, setHeightInPixelsResult); }); }); runner.testGroup("setSize(Size2D)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setSizeResult = verticalLayout.setSize(Size2D.create(Distance.inches(2), Distance.inches(3))); test.assertSame(verticalLayout, setSizeResult); }); }); runner.testGroup("setSize(Distance,Distance)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setSizeResult = verticalLayout.setSize(Distance.inches(2), Distance.inches(3)); test.assertSame(verticalLayout, setSizeResult); }); }); runner.testGroup("setSizeInPixels(int,int)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setSizeInPixelsResult = verticalLayout.setSizeInPixels(2, 3); test.assertSame(verticalLayout, setSizeInPixelsResult); }); }); runner.testGroup("add(UIElement)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout element = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout addResult = verticalLayout.add(element); test.assertSame(verticalLayout, addResult); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(element, Point2D.zero), verticalLayout.getElementPositions()); test.assertEqual(Point2D.zero, verticalLayout.getElementPosition(element).await()); test.assertEqual(Size2D.zero, verticalLayout.getSize()); test.assertEqual(Size2D.zero, element.getSize()); }); runner.test("with one non-empty sized element with left horizontal alignment", (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setElementHorizontalAlignment(HorizontalAlignment.Left); final SwingUIButton uiButton = uiBuilder.create(SwingUIButton.class).await() .setText("Hello!"); verticalLayout.add(uiButton); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), verticalLayout.getSize()); test.assertEqual(Point2D.zero, verticalLayout.getElementPosition(uiButton).await()); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(uiButton, Point2D.zero), verticalLayout.getElementPositions()); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), uiButton.getSize()); }); runner.test("with one non-empty sized element with center horizontal alignment", (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setElementHorizontalAlignment(HorizontalAlignment.Center); final SwingUIButton uiButton = uiBuilder.create(SwingUIButton.class).await() .setText("Hello!"); verticalLayout.add(uiButton); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), verticalLayout.getSize()); test.assertEqual(Point2D.zero, verticalLayout.getElementPosition(uiButton).await()); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(uiButton, Point2D.zero), verticalLayout.getElementPositions()); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), uiButton.getSize()); }); runner.test("with one non-empty sized element with right horizontal alignment", (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setElementHorizontalAlignment(HorizontalAlignment.Right); final SwingUIButton uiButton = uiBuilder.create(SwingUIButton.class).await() .setText("Hello!"); verticalLayout.add(uiButton); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), verticalLayout.getSize()); test.assertEqual(Point2D.zero, verticalLayout.getElementPosition(uiButton).await()); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(uiButton, Point2D.zero), verticalLayout.getElementPositions()); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), uiButton.getSize()); }); runner.test("with two non-empty sized elements with left horizontal alignment", (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setElementHorizontalAlignment(HorizontalAlignment.Left); final SwingUIButton uiButton1 = uiBuilder.create(SwingUIButton.class).await() .setText("Hello!"); verticalLayout.add(uiButton1); final SwingUIButton uiButton2 = uiBuilder.create(SwingUIButton.class).await() .setText("I'm a button!"); verticalLayout.add(uiButton2); test.assertEqual(Size2D.create(Distance.inches(1.03), Distance.inches(0.52)), verticalLayout.getSize()); test.assertEqual(Point2D.zero, verticalLayout.getElementPosition(uiButton1).await()); test.assertEqual(Point2D.create(Distance.zero, Distance.inches(0.26)), verticalLayout.getElementPosition(uiButton2).await()); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(uiButton1, Point2D.zero) .set(uiButton2, Point2D.create(Distance.zero, Distance.inches(0.26))), verticalLayout.getElementPositions()); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), uiButton1.getSize()); test.assertEqual(Size2D.create(Distance.inches(1.03), Distance.inches(0.26)), uiButton2.getSize()); }); runner.test("with one non-empty sized element with center horizontal alignment", (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setElementHorizontalAlignment(HorizontalAlignment.Center); final SwingUIButton uiButton1 = uiBuilder.create(SwingUIButton.class).await() .setText("Hello!"); verticalLayout.add(uiButton1); final SwingUIButton uiButton2 = uiBuilder.create(SwingUIButton.class).await() .setText("I'm a button!"); verticalLayout.add(uiButton2); test.assertEqual(Size2D.create(Distance.inches(1.03), Distance.inches(0.52)), verticalLayout.getSize()); test.assertEqual(Point2D.create(Distance.inches(0.19), Distance.zero), verticalLayout.getElementPosition(uiButton1).await()); test.assertEqual(Point2D.create(Distance.zero, Distance.inches(0.26)), verticalLayout.getElementPosition(uiButton2).await()); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(uiButton1, Point2D.create(Distance.inches(0.19), Distance.zero)) .set(uiButton2, Point2D.create(Distance.zero, Distance.inches(0.26))), verticalLayout.getElementPositions()); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), uiButton1.getSize()); test.assertEqual(Size2D.create(Distance.inches(1.03), Distance.inches(0.26)), uiButton2.getSize()); }); runner.test("with one non-empty sized element with right horizontal alignment", (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIVerticalLayoutTests.createUIBuilder(test); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setElementHorizontalAlignment(HorizontalAlignment.Right); final SwingUIButton uiButton1 = uiBuilder.create(SwingUIButton.class).await() .setText("Hello!"); verticalLayout.add(uiButton1); final SwingUIButton uiButton2 = uiBuilder.create(SwingUIButton.class).await() .setText("I'm a button!"); verticalLayout.add(uiButton2); test.assertEqual(Size2D.create(Distance.inches(1.03), Distance.inches(0.52)), verticalLayout.getSize()); test.assertEqual(Point2D.create(Distance.inches(0.38), Distance.zero), verticalLayout.getElementPosition(uiButton1).await()); test.assertEqual(Point2D.create(Distance.zero, Distance.inches(0.26)), verticalLayout.getElementPosition(uiButton2).await()); test.assertEqual( Map.<AWTUIElement,Point2D>create() .set(uiButton1, Point2D.create(Distance.inches(0.38), Distance.zero)) .set(uiButton2, Point2D.create(Distance.zero, Distance.inches(0.26))), verticalLayout.getElementPositions()); test.assertEqual(Size2D.create(Distance.inches(0.65), Distance.inches(0.26)), uiButton1.getSize()); test.assertEqual(Size2D.create(Distance.inches(1.03), Distance.inches(0.26)), uiButton2.getSize()); }); }); runner.testGroup("addAll(UIElement...)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout addAllResult = verticalLayout.addAll(); test.assertSame(verticalLayout, addAllResult); }); }); runner.testGroup("addAll(Iterable<? extends UIElement>)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout addResult = verticalLayout.addAll(Iterable.create()); test.assertSame(verticalLayout, addResult); test.assertEqual(Map.create(), verticalLayout.getElementPositions()); }); }); runner.testGroup("getElementPosition(AWTUIElement)", () -> { runner.test("with null", (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); test.assertThrows(() -> verticalLayout.getElementPosition(null), new PreConditionFailure("awtUiElement cannot be null.")); }); runner.test("with not found UIElement", (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); test.assertThrows(() -> verticalLayout.getElementPosition(verticalLayout).await(), new NotFoundException(verticalLayout + " doesn't contain " + verticalLayout + ", so it can't get it's relative position.")); }); }); runner.testGroup("setElementHorizontalAlignment(HorizontalAlignment)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setElementHorizontalAlignmentResult = verticalLayout.setElementHorizontalAlignment(HorizontalAlignment.Center); test.assertSame(verticalLayout, setElementHorizontalAlignmentResult); test.assertEqual(HorizontalAlignment.Center, verticalLayout.getElementHorizontalAlignment()); }); }); runner.testGroup("setElementVerticalAlignment(VerticalAlignment)", () -> { runner.test("should return " + Types.getTypeName(SwingUIVerticalLayout.class), (Test test) -> { final SwingUIVerticalLayout verticalLayout = SwingUIVerticalLayoutTests.createUIVerticalLayout(test); final SwingUIVerticalLayout setElementVerticalAlignmentResult = verticalLayout.setElementVerticalAlignment(VerticalAlignment.Center); test.assertSame(verticalLayout, setElementVerticalAlignmentResult); test.assertEqual(VerticalAlignment.Center, verticalLayout.getElementVerticalAlignment()); }); }); runner.testGroup("in window", () -> { runner.test("with labels", runner.skip(), (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIBuilder.create(test.getProcess()); try (final SwingUIWindow window = uiBuilder.createSwingUIWindow().await()) { window.setTitle(test.getFullName()); window.setContentSpaceSize(Distance.inches(1), Distance.inches(3)); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await(); for (int i = 1; i <= 3; ++i) { verticalLayout.add(uiBuilder.createUIText().await() .setFontSize(Distance.inches(0.5)) .setText(Integers.toString(i)) .setSize(Distance.inches(1), Distance.inches(1))); } window.setContent(verticalLayout); window.setVisible(true); window.await(); } test.fail(); }); runner.test("with alignment", runner.skip(), (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIBuilder.create(test.getProcess()); try (final SwingUIWindow window = uiBuilder.createSwingUIWindow().await()) { window.setTitle(test.getFullName()); window.setContentSpaceSize(Distance.inches(3), Distance.inches(3)); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await(); final SwingUIHorizontalLayout horizontalAlignmentLayout = uiBuilder.create(SwingUIHorizontalLayout.class).await(); for (final HorizontalAlignment horizontalAlignment : HorizontalAlignment.values()) { final SwingUIButton button = uiBuilder.create(SwingUIButton.class).await() .setText(horizontalAlignment.toString()) .setWidth(Distance.inches(1)); button.onClick(() -> { verticalLayout.setElementHorizontalAlignment(horizontalAlignment); }); horizontalAlignmentLayout.add(button); } verticalLayout.add(horizontalAlignmentLayout); final SwingUIHorizontalLayout verticalAlignmentLayout = uiBuilder.create(SwingUIHorizontalLayout.class).await(); for (final VerticalAlignment verticalAlignment : VerticalAlignment.values()) { final SwingUIButton button = uiBuilder.create(SwingUIButton.class).await() .setText(verticalAlignment.toString()) .setWidth(Distance.inches(1)); button.onClick(() -> { verticalLayout.setElementVerticalAlignment(verticalAlignment); }); verticalAlignmentLayout.add(button); } verticalLayout.add(verticalAlignmentLayout); for (int i = 1; i <= 3; ++i) { verticalLayout.add(uiBuilder.createUIText().await() .setFontSize(Distance.inches(0.5)) .setText(Integers.toString(i)) .setSize(Distance.inches(1), Distance.inches(1))); } window.setContent(verticalLayout); window.setVisible(true); window.await(); } test.fail(); }); runner.test("with dynamic width", runner.skip(), (Test test) -> { final SwingUIBuilder uiBuilder = SwingUIBuilder.create(test.getProcess()); try (final SwingUIWindow window = uiBuilder.createSwingUIWindow().await()) { window.setTitle(test.getFullName()); window.setContentSpaceSize(Distance.inches(5), Distance.inches(3)); final SwingUIVerticalLayout verticalLayout = uiBuilder.create(SwingUIVerticalLayout.class).await() .setPadding(UIPadding.create(Distance.inches(0.25))) .setWidth(Distance.inches(4)) .setHeight(Distance.inches(2)) .setBackgroundColor(Color.create(20, 120, 220)); verticalLayout.add(uiBuilder.createUIText().await() .setText("2 Inches") .setWidth(Distance.inches(2)) .setHeight(Distance.inches(0.5)) .setBackgroundColor(Color.red)); verticalLayout.add(uiBuilder.createUIText().await() .setText("Dynamic Width") .setDynamicWidth(verticalLayout.getDynamicWidth()) .setHeight(Distance.inches(0.5)) .setBackgroundColor(Color.blue)); verticalLayout.add(uiBuilder.createUIText().await() .setText("Dynamic Content Space Width") .setDynamicWidth(verticalLayout.getDynamicContentSpaceWidth()) .setHeight(Distance.inches(0.5)) .setBackgroundColor(Color.green)); window.setContent(verticalLayout); window.setVisible(true); window.await(); } test.fail(); }); }); }); } }
package org.jactors.junit; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.hamcrest.BaseMatcher; import org.hamcrest.CoreMatchers; import org.hamcrest.Factory; import org.hamcrest.StringDescription; import org.jactors.junit.rule.BaseRule; import org.junit.Assert; import org.junit.Test; import org.junit.matchers.JUnitMatchers; /** * Expected exception failure annotation used by rules and theories to express custom exception * failure expectations. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.FIELD }) public @interface Expect { /** * Default null message result. */ public static final String NULL = "<%null%>"; /** * Default empty message result. */ public static final String UNAVAILABLE = "<%message not available%>"; /** * Failure message matcher type. */ public static enum Matcher { /** * Matcher operation type for equals. */ EQUALS, /** * Matcher operation type for contains. */ CONTAINS, /** * Matcher operation type for starts with. */ STARTS_WITH, /** * Matcher operation type for ends with. */ ENDS_WITH, /** * MAtcher operation type for regular expression patterns. */ PATTERN; /** * Check whether given compare expression pattern matches using given actual message string. * * @param pattern compare expression pattern. * @param message actual message string. * * @return whether given compare expression pattern matches given actual message string. */ public boolean match(String pattern, String message) { return Matcher.match(this, pattern, message); } /** * Check whether given matcher operation type with given compare expression pattern matches * given actual message string. * * @param matcher matcher operation type. * @param pattern compare expression pattern. * @param message actual message string. * * @return whether given compare expression pattern matches given actual message string. */ private static boolean match(Matcher matcher, String pattern, String message) { if (Expect.NULL.equals(pattern)) { pattern = null; } if ((message == null) && (pattern == null)) { return true; } else if (message == null) { return false; } else if (pattern == null) { return false; } switch (matcher) { case EQUALS: return message.equals(pattern); case CONTAINS: return message.contains(pattern); case STARTS_WITH: return message.startsWith(pattern); case ENDS_WITH: return message.endsWith(pattern); case PATTERN: return message.matches(pattern); default: throw new IllegalArgumentException("matcher not supported [" + matcher + "]"); } } } /** * Failure exception class type. */ public Class<? extends Throwable> type() default Test.None.class; /** * Failure message. */ public String message() default UNAVAILABLE; /** * Failure message matcher type. */ public Matcher matcher() default Matcher.EQUALS; /** * Failure message. */ public Cause[] cause() default {}; /** * Abstract expected exception rule. */ public static class Rule extends BaseRule { /** * Message constant to introduce expectation. */ private static final String EXPECTED_MESSAGE = "expected test to throw "; /** * List of expectations matchers. */ private final List<org.hamcrest.Matcher<?>> matchers = new ArrayList<org.hamcrest.Matcher<?>>(); /** * Insert given expectation matchers defined by {@link Expect} and return expected exception * rule for further setup. Use {@link Expect.Builder} to create new expected exception * failure. * * @param expect expected exception failure. * * @return expected exception rule for further setup. */ public final Rule expect(Expect expect) { if ((expect != null) && Helper.matches(expect)) { return this.expect(Helper.expect(expect)); } return this; } /** * Insert expectation matchers defined by given expected exception failure ({@link Expect}) * as well as JUnit test annotation ({@link Test}) and return expected exception rule for * further setup. * * @param test JUnit test annotation. * @param expect expected exception failure. * * @return expected exception rule for further setup. */ public final Rule expect(Test test, Expect expect) { if ((test != null) && (test.expected() != Test.None.class)) { if (expect == null) { return this.expect(CoreMatchers.instanceOf(test.expected())); } else if (expect.type() == Test.None.class) { return this.expect(Builder.join(test, expect)); } } return this.expect(expect); } /** * Insert given expectation matcher to list of expectations and return expected exception * rule for further setup. * * @param matcher expectation matcher. * * @return expected exception rule for further setup. */ private final Rule expect(org.hamcrest.Matcher<?> matcher) { this.matchers.add(matcher); return this; } /** * Handle expectation in response to given exception after execution, and return whether * original exception should be re-thrown. * * @param <Type> exception type. * @param except exception instance. * * @throws Type assertion error or original exception (if re-thrown). */ protected <Type extends Throwable> void failure(Type except) throws Type { if (this.matchers.isEmpty()) { throw except; } Assert.assertThat(except, this.throwing()); } /** * Handle expectation in response to successful execution. If an exception was expected, an * assertion error is thrown. */ protected void success() { if (!this.matchers.isEmpty()) { throw new AssertionError(EXPECTED_MESSAGE + StringDescription.toString(this.throwing())); } } /** * Return list of expectation matchers. * * @return list of expectation matchers. */ public List<org.hamcrest.Matcher<?>> matchers() { return this.matchers; } /** * Return expected exception defined by match builder. * * @return expected exception defined by match builder. */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected org.hamcrest.Matcher<Throwable> throwing() { if (this.matchers.size() == 1) { return JUnitMatchers.isThrowable((org.hamcrest.Matcher<Throwable>) this.matchers.get(0)); } return JUnitMatchers.isThrowable(CoreMatchers.allOf( new ArrayList<org.hamcrest.Matcher<? super Throwable>>((List) this.matchers))); } /** * {@inheritDoc} */ public String toString() { return "Expect.Rule[message=" + StringDescription.toString(this.throwing()) + "]"; } } /** * Expectation helper. */ public static final class Helper { /** * Create failure message matcher with given matcher operation type and compare expression * pattern. * * @param pattern compare expression pattern. * @param matcher matcher operation type. * * @return string matcher. */ protected static org.hamcrest.Matcher<String> message(String pattern, Matcher matcher) { return ToStringMatcher.create(pattern, matcher); } /** * Create general expectation based exception matcher with given expected exception failure. * * @param <Type> exception type. * @param expect expected exception failure. * * @return general expectation based exception matcher. */ protected static <Type extends Throwable> org.hamcrest.Matcher<Type> expect(Expect expect) { return ExpectMatcher.create(expect); } /** * Check whether given expected exception failure matches any exception. * * @param expect expected exception failure. * * @return whether given expected exception failure matches any exception. */ protected static boolean matches(Expect expect) { if (Helper.matches(expect.type(), expect.message())) { return true; } for (Cause cause : expect.cause()) { if (Helper.matches(cause.type(), cause.message())) { return true; } } return false; } /** * Check whether given expected failure exception class type and given expected failure * message matches any distinct exception. * * @param type expected failure exception class type. * @param message expected failure message. * * @return whether any distinct exception is matched. */ protected static boolean matches(Class<? extends Throwable> type, String message) { return (type != Test.None.class) || !UNAVAILABLE.equals(message); } /** * Check whether given expected failure exception class type and given expected failure * message using given failure message matcher type matches the given distinct exception. * * @param except distinct exception. * @param type expected failure exception class type. * @param message expected failure message. * @param matcher failure message matcher type. * * @return whether given distinct exception is matched. */ protected static boolean matches(Throwable except, Class<? extends Throwable> type, String message, Matcher matcher) { if ((type == null) || ((type != Test.None.class) && !type.isAssignableFrom(except.getClass()))) { return false; } else if (!Expect.UNAVAILABLE.equals(message) && !matcher.match((!Expect.NULL.equals(message)) ? message : null, except.getMessage())) { return false; } return true; } /** * Append given expected failure message pattern using given failure message matcher type to * given matcher description. * * @param description matcher description. * @param pattern expected failure message pattern. * @param matcher failure message matcher type. */ protected static void describe(org.hamcrest.Description description, String pattern, Expect.Matcher matcher) { if ((pattern == null) || Expect.NULL.equals(pattern)) { description.appendText("null"); return; } switch (matcher) { case EQUALS: description.appendValue(pattern); break; case CONTAINS: description.appendText("<^.*").appendText(pattern).appendText(".*$>"); break; case STARTS_WITH: description.appendText("<^").appendText(pattern).appendText(".*>"); break; case ENDS_WITH: description.appendText("<.*").appendText(pattern).appendText("$>"); break; case PATTERN: description.appendText("<").appendText(pattern).appendText(">"); break; default: throw new IllegalArgumentException("matcher not supported [" + matcher + "]"); } } /** * String matcher that allows to define use different dynamic matching strategies including * equals, contains, starts with, ends with, and regular expressions. */ private static final class ToStringMatcher extends BaseMatcher<String> { /** * String matcher type. */ private final Expect.Matcher matcher; /** * Compare string pattern. */ private final String pattern; /** * Create string matcher with given matcher operation type and compare expression * pattern. * * @param matcher matcher operation type. * @param pattern compare expression pattern. */ private ToStringMatcher(Expect.Matcher matcher, String pattern) { this.matcher = matcher; this.pattern = pattern; } /** * Create string matcher with given matcher operation type and compare expression * pattern. * * @param matcher matcher operation type. * @param pattern compare expression pattern. * * @return string matcher. */ @Factory public static ToStringMatcher create(String pattern, Expect.Matcher matcher) { return new ToStringMatcher(matcher, pattern); } /** * {@inheritDoc} */ public boolean matches(Object item) { return this.matcher.match(this.pattern, (item == null) ? null : item.toString()); } /** * {@inheritDoc} */ public void describeTo(org.hamcrest.Description description) { Helper.describe(description, this.pattern, this.matcher); } /** * {@inheritDoc} */ public String toString() { return "StringMatcher[matcher=" + this.matcher + ", pattern=" + this.pattern + "]"; } } /** * General expect based exception matcher supporting detailed exception root causes. * * @param <Type> exception type. */ private static final class ExpectMatcher<Type extends Throwable> extends BaseMatcher<Type> { /** * Expected exception failure. */ private final Expect expect; /** * Actual mismatch position. */ private Throwable except; /** * Create general expectation based exception matcher with given expected exception * failure. * * @param expect expected exception failure. */ private ExpectMatcher(Expect expect) { this.expect = expect; } /** * Create general expectation based exception matcher with given expected exception * failure. * * @param <Type> type exception to throw. * @param expect expected exception failure. * * @return general expectation based exception matcher. */ @Factory public static <Type extends Throwable> org.hamcrest.Matcher<Type> create(Expect expect) { return new ExpectMatcher<Type>(expect); } /** * {@inheritDoc} */ public boolean matches(Object item) { if (!(item instanceof Throwable)) { return false; } Throwable except = (Throwable) item; if (!Helper.matches(except, this.expect.type(), this.expect.message(), this.expect.matcher())) { this.except = except; return false; } for (Cause cause : this.expect.cause()) { except = except.getCause(); if (!Helper.matches(except, cause.type(), cause.message(), cause.matcher())) { this.except = except; return false; } } return true; } /** * {@inheritDoc} */ public void describeMismatch(Object item, org.hamcrest.Description description) { if (item == null) { description.appendText("was null"); return; } else if (!(item instanceof Throwable)) { description.appendText("was instance-of <").appendText(item.getClass().getName()).appendText("> ") .appendValue(item); return; } Throwable except = (Throwable) item; description.appendText("was exception <").appendText(item.getClass().getName()).appendText( "> with message ").appendValue(except.getMessage()); for (Throwable cause = except.getCause(); cause != null; cause = cause.getCause()) { description.appendText("\n caused by <").appendText(cause.getClass().getName()).appendText( "> with message ").appendValue(cause.getMessage()); } } /** * Append given expected failure message pattern using given failure message matcher * type to given matcher description. * * @param description matcher description. * @param pattern expected failure message pattern. * @param matcher failure message matcher type. */ private void describeTo(org.hamcrest.Description description, String pattern, Expect.Matcher matcher) { if (Expect.UNAVAILABLE.equals(pattern)) { return; } description.appendText(" with message "); Helper.describe(description, pattern, matcher); } /** * {@inheritDoc} */ public void describeTo(org.hamcrest.Description description) { if (this.expect.type() != Test.None.class) { description.appendText("exception <").appendText(this.expect.type().getName()).appendText(">"); } else { description.appendText("any exception"); } this.describeTo(description, this.expect.message(), this.expect.matcher()); for (Cause cause : this.expect.cause()) { description.appendText("\n caused by <").appendText(cause.type().getName()).appendText(">"); this.describeTo(description, cause.message(), cause.matcher()); } if (this.except != null) { description.appendText("\n mismatch in (").appendValue(this.except).appendText(")"); } } /** * {@inheritDoc} */ public String toString() { return "ExpectMatcher[expect=" + this.expect + "]"; } } } /** * Expected exception configuration builder. */ public static final class Builder { /** * Expected exception. */ private Expect expect = new Expected(Test.None.class, UNAVAILABLE, Matcher.EQUALS, new Cause[] {}); /** * List of expected exception cause. */ private final List<Cause> causes = new ArrayList<Cause>(); /** * Join JUnit test annotation with given expected exception annotation into new expected * exception annotation value. * * @param test JUnit test annotation value. * @param expect expected exception annotation value. * * @return joined expected exception annotation value. */ protected static Expect join(Test test, Expect expect) { return new Expected(test.expected(), expect.message(), expect.matcher(), expect.cause()); } /** * Create expected exception builder with default settings. * * @return expected exception builder. */ public static Builder create() { return new Builder(); } /** * Create expected exception builder with given expected failure exception class type * without checking for failure message pattern. Note: missing expectations will set to * defaults. * * @param type expected failure exception class type. * * @return expected exception builder. */ public static Builder create(Class<? extends Throwable> type) { return new Builder().expect(type); } /** * Create expected exception builder with given expected failure exception class type and * expected failure message pattern. Note: missing expectations will set to defaults. * * @param type expected failure exception class type. * @param message expected failure message pattern. * * @return expected exception builder. */ public static Builder create(Class<? extends Throwable> type, String message) { return new Builder().expect(type, message); } /** * Create expected exception builder with given expected failure exception class type and * expected failure message pattern using failure message matcher type. Note: missing * expectations will set to defaults. * * @param type expected failure exception class type. * @param message expected failure message pattern. * @param matcher failure message matcher type. * * @return expected exception builder. */ public static Builder create(Class<? extends Throwable> type, String message, Matcher matcher) { return new Builder().expect(type, message, matcher); } /** * Create expected exception builder with given expected failure message pattern. Note: * missing expectations will set to defaults. * * @param message expected failure message pattern. * * @return expected exception builder. */ public static Builder create(String message) { return new Builder().expect(message); } /** * Create expected exception builder with given expected failure message pattern using * failure message matcher type. Note: missing expectations will set to defaults. * * @param message expected failure message pattern. * @param matcher failure message matcher type. * * @return expected exception builder. */ public static Builder create(String message, Matcher matcher) { return new Builder().expect(message, matcher); } /** * Expect exception with given failure exception class type without checking for failure * message. Note: missing expectations stay unchanged. * * @param type expected failure exception class type. * * @return same expected exception builder for further setup. */ public Builder expect(Class<? extends Throwable> type) { this.expect = new Expected(type, this.expect.message(), this.expect.matcher(), this.expect.cause()); return this; } /** * Expect exception with given failure exception class type and failure message pattern. * Note: missing expectations stay unchanged. * * @param type expected failure exception class type. * @param message expected failure message pattern. * * @return same expected exception builder for further setup. */ public Builder expect(Class<? extends Throwable> type, String message) { this.expect = new Expected(type, message, this.expect.matcher(), this.expect.cause()); return this; } /** * Expect exception with given failure exception class type and failure message pattern * using given failure message matcher type. Note: missing expectations stay unchanged. * * @param type expected failure exception class type. * @param message expected failure message pattern. * @param matcher failure message matcher type. * * @return same expected exception builder for further setup. */ public Builder expect(Class<? extends Throwable> type, String message, Matcher matcher) { this.expect = new Expected(type, message, matcher, this.expect.cause()); return this; } /** * Expect exception with given failure message pattern. Note: missing expectations stay * unchanged. * * @param message expected failure message pattern. * * @return same expected exception builder for further setup. */ public Builder expect(String message) { this.expect = new Expected(this.expect.type(), message, this.expect.matcher(), this.expect.cause()); return this; } /** * Expect exception with given failure message pattern using given failure message matcher * type. Note: missing expectations stay unchanged. * * @param message expected failure message pattern. * @param matcher failure message matcher type. * * @return same expected exception builder for further setup. */ public Builder expect(String message, Matcher matcher) { this.expect = new Expected(this.expect.type(), message, matcher, this.expect.cause()); return this; } /** * Expect exception cause with given failure exception class type without checking for * failure message. Note: declaring a cause this way always appends a new cause to the list * of causes. * * @param type expected failure exception class type. * * @return same expected exception builder for further setup. */ public Builder cause(Class<? extends Throwable> type) { this.causes.add(new Caused(type, UNAVAILABLE, Matcher.EQUALS)); return this; } /** * Expect exception cause with given failure exception class type and failure message * pattern. Note: declaring a cause this way always appends a new cause to the list of * causes. * * @param type expected failure exception class type. * @param message expected failure message pattern. * * @return same expected exception builder for further setup. */ public Builder cause(Class<? extends Throwable> type, String message) { this.causes.add(new Caused(type, message, Matcher.EQUALS)); return this; } /** * Expect exception cause with given failure exception class type and failure message * pattern using given failure message matcher type. Note: declaring a cause this way always * appends a new cause to the list of causes. * * @param type expected failure exception class type. * @param message expected failure message pattern. * @param matcher failure message matcher type. * * @return same expected exception builder for further setup. */ public Builder cause(Class<? extends Throwable> type, String message, Matcher matcher) { this.causes.add(new Caused(type, message, matcher)); return this; } /** * Expect exception cause with given failure message pattern. Note: declaring a cause this * way always appends a new cause to the list of causes. * * @param message expected failure message pattern. * * @return same expected exception builder for further setup. */ public Builder cause(String message) { this.causes.add(new Caused(Test.None.class, message, Matcher.EQUALS)); return this; } /** * Expect exception cause with given failure message pattern using given failure message * matcher type. Note: declaring a cause this way always appends a new cause to the list of * causes. * * @param message expected failure message pattern. * @param matcher failure message matcher type. * * @return same expected exception builder for further setup. */ public Builder cause(String message, Matcher matcher) { this.causes.add(new Caused(Test.None.class, message, matcher)); return this; } /** * Clear expected exception builder. Removes all expectations, i.e. list of expected * exception causes as well as expected exception itself. * * @return same expected exception builder for further setup. */ public Builder clear() { this.expect = new Expected(Test.None.class, UNAVAILABLE, Matcher.EQUALS, new Cause[] {}); this.causes.clear(); return this; } /** * Return expected exception configuration. * * @return expected exception configuration. */ public Expect build() { Cause[] causes = this.causes.toArray(new Cause[this.causes.size()]); return new Expected(this.expect, causes); } /** * {@inheritDoc} */ public String toString() { return "Builder[expect=" + this.expect + ", causes=" + this.causes + "]"; } /** * Base expected exception information. */ private static abstract class Config implements Cause { /** * Expected failure exception class type. */ private final Class<? extends Throwable> type; /** * Expected failure message pattern. */ private final String message; /** * Failure message matcher type. */ private final Matcher matcher; /** * Create base expected exception information with given expected exception class type, * expected failure message, and failure message matcher type. * * @param type expected exception class type. * @param message expected failure message pattern. * @param matcher failure message matcher type. */ public Config(Class<? extends Throwable> type, String message, Matcher matcher) { this.type = (type == null) ? Test.None.class : type; this.message = (Expect.NULL.equals(message)) ? null : message; this.matcher = ((matcher == null) || (this.message == null)) ? Matcher.EQUALS : matcher; } /** * {@inheritDoc} */ public Class<? extends Throwable> type() { return this.type; } /** * {@inheritDoc} */ public String message() { return this.message; } /** * {@inheritDoc} */ public Expect.Matcher matcher() { return this.matcher; } /** * {@inheritDoc} */ public String toString() { return "type=" + this.type.getName() + ", message=" + this.message + ", matcher=" + this.matcher; } } /** * Expected exception information. */ private static final class Expected extends Config implements Expect { /** * List of expected exception causes. */ private final Cause[] causes; /** * Create expected exception information based on given expected exception information * and given list of expected exception causes. * * @param expect expected exception class type. * @param causes list of expected exception causes. */ public Expected(Expect expect, Cause[] causes) { super(expect.type(), expect.message(), expect.matcher()); this.causes = causes; } /** * Create expected exception information with given expected exception class type, * expected failure message pattern, and failure message matcher type, and list of * expected exception causes. * * @param type expected exception class type. * @param message expected failure message pattern. * @param matcher failure message matcher type. * @param causes list of expected exception causes. */ public Expected(Class<? extends Throwable> type, String message, Matcher matcher, Cause[] causes) { super(type, message, matcher); this.causes = causes; } /** * {@inheritDoc} */ public Class<Expect> annotationType() { return Expect.class; } /** * {@inheritDoc} */ public Cause[] cause() { return this.causes; } /** * {@inheritDoc} */ public String toString() { return "Expect[" + super.toString() + ", causes=" + Arrays.toString(this.causes) + "]"; } } /** * Expected exception cause information. */ private static final class Caused extends Config implements Cause { /** * Create expected exception cause information with given expected exception class type, * expected failure message pattern, and failure message matcher type. * * @param type expected exception class type. * @param message expected failure message pattern. * @param matcher failure message matcher type. */ public Caused(Class<? extends Throwable> type, String message, Matcher matcher) { super(type, message, matcher); } /** * {@inheritDoc} */ public Class<Cause> annotationType() { return Cause.class; } /** * {@inheritDoc} */ public String toString() { return "Cause[" + super.toString() + "]"; } } } /** * Expected exception cause annotation. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.METHOD, ElementType.FIELD }) public @interface Cause { /** * Failure exception class type. */ public Class<? extends Throwable> type() default Test.None.class; /** * Failure message. */ public String message() default UNAVAILABLE; /** * Failure message matcher type. */ public Matcher matcher() default Matcher.EQUALS; } }
/* * Copyright 2020 The gRPC 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 io.grpc.xds; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableMap; import io.grpc.CallOptions; import io.grpc.ConnectivityState; import io.grpc.EquivalentAddressGroup; import io.grpc.LoadBalancer; import io.grpc.LoadBalancer.Helper; import io.grpc.LoadBalancer.PickResult; import io.grpc.LoadBalancer.PickSubchannelArgs; import io.grpc.LoadBalancer.ResolvedAddresses; import io.grpc.LoadBalancer.Subchannel; import io.grpc.LoadBalancer.SubchannelPicker; import io.grpc.LoadBalancerProvider; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.MethodDescriptor.MethodType; import io.grpc.Status; import io.grpc.Status.Code; import io.grpc.SynchronizationContext; import io.grpc.internal.FakeClock; import io.grpc.internal.PickSubchannelArgsImpl; import io.grpc.internal.ServiceConfigUtil.PolicySelection; import io.grpc.testing.TestMethodDescriptors; import io.grpc.xds.ClusterManagerLoadBalancerProvider.ClusterManagerConfig; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; /** Tests for {@link ClusterManagerLoadBalancer}. */ @RunWith(JUnit4.class) public class ClusterManagerLoadBalancerTest { private final SynchronizationContext syncContext = new SynchronizationContext( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { throw new AssertionError(e); } }); private final FakeClock fakeClock = new FakeClock(); @Captor ArgumentCaptor<SubchannelPicker> pickerCaptor; @Mock private LoadBalancer.Helper helper; private final Map<String, Object> lbConfigInventory = new HashMap<>(); private final List<FakeLoadBalancer> childBalancers = new ArrayList<>(); private LoadBalancer clusterManagerLoadBalancer; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(helper.getSynchronizationContext()).thenReturn(syncContext); when(helper.getScheduledExecutorService()).thenReturn(fakeClock.getScheduledExecutorService()); lbConfigInventory.put("childA", new Object()); lbConfigInventory.put("childB", new Object()); lbConfigInventory.put("childC", null); clusterManagerLoadBalancer = new ClusterManagerLoadBalancer(helper); clearInvocations(helper); } @After public void tearDown() { clusterManagerLoadBalancer.shutdown(); for (FakeLoadBalancer childLb : childBalancers) { assertThat(childLb.shutdown).isTrue(); } } @Test public void handleResolvedAddressesUpdatesChannelPicker() { deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); verify(helper, atLeastOnce()).updateBalancingState( eq(ConnectivityState.CONNECTING), pickerCaptor.capture()); SubchannelPicker picker = pickerCaptor.getValue(); assertThat(pickSubchannel(picker, "childA")).isEqualTo(PickResult.withNoResult()); assertThat(pickSubchannel(picker, "childB")).isEqualTo(PickResult.withNoResult()); assertThat(childBalancers).hasSize(2); FakeLoadBalancer childBalancer1 = childBalancers.get(0); FakeLoadBalancer childBalancer2 = childBalancers.get(1); assertThat(childBalancer1.name).isEqualTo("policy_a"); assertThat(childBalancer2.name).isEqualTo("policy_b"); assertThat(childBalancer1.config).isEqualTo(lbConfigInventory.get("childA")); assertThat(childBalancer2.config).isEqualTo(lbConfigInventory.get("childB")); // Receive an updated config. deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childC", "policy_c")); verify(helper, atLeast(2)) .updateBalancingState(eq(ConnectivityState.CONNECTING), pickerCaptor.capture()); picker = pickerCaptor.getValue(); assertThat(pickSubchannel(picker, "childA")).isEqualTo(PickResult.withNoResult()); assertThat(pickSubchannel(picker, "childC")).isEqualTo(PickResult.withNoResult()); Status status = pickSubchannel(picker, "childB").getStatus(); assertThat(status.getCode()).isEqualTo(Code.UNAVAILABLE); assertThat(status.getDescription()).isEqualTo("Unable to find cluster childB"); assertThat(fakeClock.numPendingTasks()) .isEqualTo(1); // (delayed) shutdown because "childB" is removed assertThat(childBalancer1.shutdown).isFalse(); assertThat(childBalancer2.shutdown).isFalse(); assertThat(childBalancers).hasSize(3); FakeLoadBalancer childBalancer3 = childBalancers.get(2); assertThat(childBalancer3.name).isEqualTo("policy_c"); assertThat(childBalancer3.config).isEqualTo(lbConfigInventory.get("childC")); // delayed policy_b deletion fakeClock.forwardTime( ClusterManagerLoadBalancer.DELAYED_CHILD_DELETION_TIME_MINUTES, TimeUnit.MINUTES); assertThat(childBalancer2.shutdown).isTrue(); } @Test public void updateBalancingStateFromChildBalancers() { deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); assertThat(childBalancers).hasSize(2); FakeLoadBalancer childBalancer1 = childBalancers.get(0); FakeLoadBalancer childBalancer2 = childBalancers.get(1); Subchannel subchannel1 = mock(Subchannel.class); Subchannel subchannel2 = mock(Subchannel.class); childBalancer1.deliverSubchannelState(subchannel1, ConnectivityState.READY); verify(helper).updateBalancingState(eq(ConnectivityState.READY), pickerCaptor.capture()); SubchannelPicker picker = pickerCaptor.getValue(); assertThat(pickSubchannel(picker, "childA").getSubchannel()).isEqualTo(subchannel1); assertThat(pickSubchannel(picker, "childB")).isEqualTo(PickResult.withNoResult()); childBalancer2.deliverSubchannelState(subchannel2, ConnectivityState.READY); verify(helper, times(2)) .updateBalancingState(eq(ConnectivityState.READY), pickerCaptor.capture()); assertThat(pickSubchannel(pickerCaptor.getValue(), "childB").getSubchannel()) .isEqualTo(subchannel2); } @Test public void ignoreBalancingStateUpdateForDeactivatedChildLbs() { deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); deliverResolvedAddresses(ImmutableMap.of("childB", "policy_b")); FakeLoadBalancer childBalancer1 = childBalancers.get(0); // policy_a (deactivated) Subchannel subchannel = mock(Subchannel.class); childBalancer1.deliverSubchannelState(subchannel, ConnectivityState.READY); verify(helper, never()).updateBalancingState( eq(ConnectivityState.READY), any(SubchannelPicker.class)); // Reactivate policy_a, balancing state update reflects the latest connectivity state and // picker. deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); verify(helper).updateBalancingState(eq(ConnectivityState.READY), pickerCaptor.capture()); assertThat(pickSubchannel(pickerCaptor.getValue(), "childA").getSubchannel()) .isEqualTo(subchannel); } @Test public void raceBetweenShutdownAndChildLbBalancingStateUpdate() { deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); verify(helper).updateBalancingState( eq(ConnectivityState.CONNECTING), any(SubchannelPicker.class)); FakeLoadBalancer childBalancer = childBalancers.iterator().next(); // LB shutdown and subchannel state change can happen simultaneously. If shutdown runs first, // any further balancing state update should be ignored. clusterManagerLoadBalancer.shutdown(); childBalancer.deliverSubchannelState(mock(Subchannel.class), ConnectivityState.READY); verifyNoMoreInteractions(helper); } @Test public void handleNameResolutionError_beforeChildLbsInstantiated_returnErrorPicker() { clusterManagerLoadBalancer.handleNameResolutionError( Status.UNAVAILABLE.withDescription("resolver error")); verify(helper).updateBalancingState( eq(ConnectivityState.TRANSIENT_FAILURE), pickerCaptor.capture()); PickResult result = pickerCaptor.getValue().pickSubchannel(mock(PickSubchannelArgs.class)); assertThat(result.getStatus().getCode()).isEqualTo(Code.UNAVAILABLE); assertThat(result.getStatus().getDescription()).isEqualTo("resolver error"); } @Test public void handleNameResolutionError_afterChildLbsInstantiated_propagateToChildLbs() { deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); assertThat(childBalancers).hasSize(2); FakeLoadBalancer childBalancer1 = childBalancers.get(0); FakeLoadBalancer childBalancer2 = childBalancers.get(1); clusterManagerLoadBalancer.handleNameResolutionError( Status.UNAVAILABLE.withDescription("resolver error")); assertThat(childBalancer1.upstreamError.getCode()).isEqualTo(Code.UNAVAILABLE); assertThat(childBalancer1.upstreamError.getDescription()).isEqualTo("resolver error"); assertThat(childBalancer2.upstreamError.getCode()).isEqualTo(Code.UNAVAILABLE); assertThat(childBalancer2.upstreamError.getDescription()).isEqualTo("resolver error"); } @Test public void handleNameResolutionError_notPropagateToDeactivatedChildLbs() { deliverResolvedAddresses(ImmutableMap.of("childA", "policy_a", "childB", "policy_b")); deliverResolvedAddresses(ImmutableMap.of("childB", "policy_b")); FakeLoadBalancer childBalancer1 = childBalancers.get(0); // policy_a (deactivated) FakeLoadBalancer childBalancer2 = childBalancers.get(1); // policy_b clusterManagerLoadBalancer.handleNameResolutionError( Status.UNKNOWN.withDescription("unknown error")); assertThat(childBalancer1.upstreamError).isNull(); assertThat(childBalancer2.upstreamError.getCode()).isEqualTo(Code.UNKNOWN); assertThat(childBalancer2.upstreamError.getDescription()).isEqualTo("unknown error"); } private void deliverResolvedAddresses(final Map<String, String> childPolicies) { clusterManagerLoadBalancer.handleResolvedAddresses( ResolvedAddresses.newBuilder() .setAddresses(Collections.<EquivalentAddressGroup>emptyList()) .setLoadBalancingPolicyConfig(buildConfig(childPolicies)) .build()); } private ClusterManagerConfig buildConfig(Map<String, String> childPolicies) { Map<String, PolicySelection> childPolicySelections = new LinkedHashMap<>(); for (String name : childPolicies.keySet()) { String childPolicyName = childPolicies.get(name); Object childConfig = lbConfigInventory.get(name); PolicySelection policy = new PolicySelection(new FakeLoadBalancerProvider(childPolicyName), childConfig); childPolicySelections.put(name, policy); } return new ClusterManagerConfig(childPolicySelections); } private static PickResult pickSubchannel(SubchannelPicker picker, String clusterName) { PickSubchannelArgs args = new PickSubchannelArgsImpl( MethodDescriptor.<Void, Void>newBuilder() .setType(MethodType.UNARY) .setFullMethodName("/service/method") .setRequestMarshaller(TestMethodDescriptors.voidMarshaller()) .setResponseMarshaller(TestMethodDescriptors.voidMarshaller()) .build(), new Metadata(), CallOptions.DEFAULT.withOption( XdsNameResolver.CLUSTER_SELECTION_KEY, clusterName)); return picker.pickSubchannel(args); } private final class FakeLoadBalancerProvider extends LoadBalancerProvider { private final String policyName; FakeLoadBalancerProvider(String policyName) { this.policyName = policyName; } @Override public LoadBalancer newLoadBalancer(Helper helper) { FakeLoadBalancer balancer = new FakeLoadBalancer(policyName, helper); childBalancers.add(balancer); return balancer; } @Override public boolean isAvailable() { return true; } @Override public int getPriority() { return 0; // doesn't matter } @Override public String getPolicyName() { return policyName; } } private final class FakeLoadBalancer extends LoadBalancer { private final String name; private final Helper helper; private Object config; private Status upstreamError; private boolean shutdown; FakeLoadBalancer(String name, Helper helper) { this.name = name; this.helper = helper; } @Override public void handleResolvedAddresses(ResolvedAddresses resolvedAddresses) { config = resolvedAddresses.getLoadBalancingPolicyConfig(); } @Override public void handleNameResolutionError(Status error) { upstreamError = error; } @Override public void shutdown() { shutdown = true; childBalancers.remove(this); } void deliverSubchannelState(final Subchannel subchannel, ConnectivityState state) { SubchannelPicker picker = new SubchannelPicker() { @Override public PickResult pickSubchannel(PickSubchannelArgs args) { return PickResult.withSubchannel(subchannel); } }; helper.updateBalancingState(state, picker); } } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation 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.unitime.timetable.reports; import java.awt.Color; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.unitime.timetable.reports.AbstractReport.Alignment; import org.unitime.timetable.reports.AbstractReport.Line; import com.lowagie.text.DocumentException; /** * @author Tomas Muller */ public class XlsReportWriter implements ReportWriter { private Workbook iWorkbook; private OutputStream iOutput; private Sheet iSheet; private int iPageNo = -1; private int iLineNo = 0; private int iNrColumns = 0, iMaxColumns = 0; private boolean iHeaderPrinted = false; private boolean iEmpty = true; private String iFooter = null, iPageName = null; private Map<String, CellStyle> iStyles = new HashMap<String, CellStyle>(); private Map<String, Font> iFonts = new HashMap<String, Font>(); private Map<String, Short> iColors = new HashMap<String, Short>(); private Line iHeaderLine[] = null; public XlsReportWriter(OutputStream out, String title, String title2, String subject, String session) throws DocumentException, IOException { if (out != null) open(out); } @Override public void setFooter(String footer) { iFooter = footer; if (iWorkbook != null) try { iWorkbook.setSheetName(iPageNo, footer.replaceAll("/", "-").replaceAll(":", "")); } catch (IllegalArgumentException e) {} } @Override public void setHeader(Line... line) { if (iHeaderPrinted) { try { printSeparator(null); } catch (DocumentException e) {} } iHeaderLine = line; iNrColumns = 0; if (line != null) { for (Line l: line) { if (l.isEmpty()) continue; int cols = countColumns(l); if (cols > iNrColumns) iNrColumns = cols; } } if (iMaxColumns < iNrColumns) iMaxColumns = iNrColumns; iHeaderPrinted = false; } @Override public Line[] getHeader() { return iHeaderLine; } @Override public void printLine(Line line) throws DocumentException { render(line, iSheet.createRow(iLineNo++), false, 0); iEmpty = false; } @Override public void close() throws IOException, DocumentException { lastPage(); iWorkbook.write(iOutput); iWorkbook.close(); } @Override public void open(OutputStream out) throws DocumentException, IOException { iOutput = out; iWorkbook = new HSSFWorkbook(); createSheet(); } protected void createSheet() { iSheet = iWorkbook.createSheet(); // iSheet.setDisplayGridlines(false); iSheet.setPrintGridlines(false); iSheet.setFitToPage(true); iSheet.setHorizontallyCenter(true); PrintSetup printSetup = iSheet.getPrintSetup(); printSetup.setLandscape(true); iSheet.setAutobreaks(true); printSetup.setFitHeight((short)1); printSetup.setFitWidth((short)1); iPageNo ++; iLineNo = 0; iMaxColumns = 0; iEmpty = true; iFooter = null; iPageName = null; if (iHeaderLine != null && iHeaderLine.length > 0) { try { printHeader(false); } catch (DocumentException e) {} iMaxColumns = iNrColumns; } } protected Font getFont(boolean bold, boolean italic, boolean underline, Color c) { Short color = null; if (c == null) c = Color.BLACK; if (c != null) { String colorId = Integer.toHexString(c.getRGB()); color = iColors.get(colorId); if (color == null) { HSSFPalette palette = ((HSSFWorkbook)iWorkbook).getCustomPalette(); HSSFColor clr = palette.findSimilarColor(c.getRed(), c.getGreen(), c.getBlue()); color = (clr == null ? IndexedColors.BLACK.getIndex() : clr.getIndex()); iColors.put(colorId, color); } } String fontId = (bold ? "b" : "") + (italic ? "i" : "") + (underline ? "u" : "") + (color == null ? "" : color); Font font = iFonts.get(fontId); if (font == null) { font = iWorkbook.createFont(); font.setBold(bold); font.setItalic(italic); font.setUnderline(underline ? Font.U_SINGLE : Font.U_NONE); font.setColor(color); font.setFontHeightInPoints((short)10); font.setFontName("Arial"); iFonts.put(fontId, font); } return font; } protected CellStyle getStyle(boolean header, Alignment a) { String styleId = (header ? "H" : "") + (a.name().charAt(0)); CellStyle style = iStyles.get(styleId); if (style == null) { style = iWorkbook.createCellStyle(); style.setAlignment(a == Alignment.Left ? HorizontalAlignment.LEFT : a == Alignment.Right ? HorizontalAlignment.RIGHT : HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.TOP); style.setFont(getFont(header, false, false, Color.BLACK)); style.setWrapText(true); if (header) { style.setFillForegroundColor(org.apache.poi.ss.usermodel.IndexedColors.GREY_25_PERCENT.getIndex()); style.setFillPattern(org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND); } iStyles.put(styleId, style); } return style; } protected CellStyle cloneStyle(CellStyle style, String name) { CellStyle clone = iStyles.get(name); if (clone != null) return clone; clone = iWorkbook.createCellStyle(); clone.setFont(iWorkbook.getFontAt(style.getFontIndex())); clone.setVerticalAlignment(VerticalAlignment.TOP); clone.setAlignment(style.getAlignmentEnum()); clone.setBorderBottom(style.getBorderBottomEnum()); clone.setBorderTop(style.getBorderTopEnum()); clone.setBorderLeft(style.getBorderLeftEnum()); clone.setBorderRight(style.getBorderRightEnum()); clone.setBottomBorderColor(style.getBottomBorderColor()); clone.setTopBorderColor(style.getTopBorderColor()); clone.setLeftBorderColor(style.getLeftBorderColor()); clone.setRightBorderColor(style.getRightBorderColor()); clone.setWrapText(true); clone.setFillForegroundColor(style.getFillForegroundColor()); clone.setFillPattern(style.getFillPatternEnum()); iStyles.put(name, clone); return clone; } protected String getStyleName(CellStyle style) { for (Map.Entry<String, CellStyle> e: iStyles.entrySet()) { if (e.getValue().getIndex() == style.getIndex()) return e.getKey(); } return null; } protected CellStyle addBottomRow(CellStyle style) { if (style.getBorderBottomEnum() == BorderStyle.THIN) return style; String name = getStyleName(style); if (name == null) return style; CellStyle clone = cloneStyle(style, name + "|B"); clone.setBottomBorderColor(IndexedColors.BLACK.getIndex()); clone.setBorderBottom(BorderStyle.THIN); return clone; } protected CellStyle addTopRow(CellStyle style) { if (style.getBorderTopEnum() == BorderStyle.THIN) return style; String name = getStyleName(style); if (name == null) return style; CellStyle clone = cloneStyle(style, name + "|T"); clone.setTopBorderColor(IndexedColors.BLACK.getIndex()); clone.setBorderTop(BorderStyle.THIN); return clone; } protected CellStyle addLeftRow(CellStyle style) { if (style.getBorderLeftEnum() == BorderStyle.THIN) return style; String name = getStyleName(style); if (name == null) return style; CellStyle clone = cloneStyle(style, name + "|L"); clone.setLeftBorderColor(IndexedColors.BLACK.getIndex()); clone.setBorderLeft(BorderStyle.THIN); return clone; } protected CellStyle addRightRow(CellStyle style) { if (style.getBorderRightEnum() == BorderStyle.THIN) return style; String name = getStyleName(style); if (name == null) return style; CellStyle clone = cloneStyle(style, name + "|R"); clone.setRightBorderColor(IndexedColors.BLACK.getIndex()); clone.setBorderRight(BorderStyle.THIN); return clone; } @Override public void setPageName(String pageName) { iPageName = pageName; } @Override public void setCont(String cont) {} @Override public void printHeader(boolean newPage) throws DocumentException { if (!iEmpty && newPage) newPage(); if (iHeaderLine != null) { iHeaderPrinted = true; boolean first = true; for (Line line: iHeaderLine) { if (line.isEmpty()) continue; Row row = iSheet.createRow(iLineNo++); render(line, row, true, 0); iEmpty = false; if (first) { for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) row.getCell(c).setCellStyle(addTopRow(row.getCell(c).getCellStyle())); first = false; } } printSeparator(null); } } @Override public void newPage() throws DocumentException { lastPage(); createSheet(); } @Override public void lastPage() throws DocumentException { for (short col = 0; col < iMaxColumns; col++) if (iSheet.getColumnWidth(col) == 256 * iSheet.getDefaultColumnWidth()) iSheet.autoSizeColumn(col); if (iPageName != null && iFooter == null) { try { iWorkbook.setSheetName(iPageNo, iPageName.replaceAll("/", "-").replaceAll(":", "")); } catch (IllegalArgumentException e) {} } printSeparator(null); } @Override public int getLineNumber() { return iLineNo; } @Override public int getNrLinesPerPage() { return 0; } @Override public int getNrCharsPerLine() { return 1000; } @Override public void printSeparator(Line line) throws DocumentException { if (iLineNo > 0) { Row row = iSheet.getRow(iLineNo - 1); if (row != null) for (int c = 0; c < iNrColumns; c++) { Cell cell = row.getCell(c); if (cell != null) { if (cell.getCellStyle() != null) cell.setCellStyle(addBottomRow(cell.getCellStyle())); else cell.setCellStyle(addBottomRow(getStyle(false, Alignment.Left))); } else { cell = row.createCell(c); cell.setCellStyle(addBottomRow(getStyle(false, Alignment.Left))); } } } } @Override public int getSeparatorNrLines() { return 0; } private String render(AbstractReport.Cell cell) { StringBuffer ret = new StringBuffer(); if (cell.getText() != null) { if (cell.getPadding() != ' ' && cell.getText().length() < cell.getLength()) ret.append(cell.render()); else ret.append(cell.getText()); } if (cell.getCells() != null) { if (cell.getText() != null) { if (cell.getCellSeparator().isEmpty()) ret.append(" "); else ret.append(cell.getCellSeparator()); } for (int i = 0; i < cell.getCells().length; i++) { if (i > 0) { if (cell.getCells()[i-1].getCellSeparator().isEmpty()) ret.append(" "); else ret.append(cell.getCells()[i-1].getCellSeparator()); } ret.append(render(cell.getCells()[i])); } } return ret.toString(); } private int render(Line line, Row row, boolean header, int col) { if (line == null) return col; if (line.getLines() != null) { for (int i = 0; i < line.getLines().length; i++) { col = render(line.getLines()[i], row, header, col); } } if (line.getCells() != null) { String leftOver = null; for (AbstractReport.Cell cell: line.getCells()) { if (cell.getColSpan() == 0) { leftOver = ((leftOver == null || leftOver.isEmpty() ? "" : leftOver + " ") + render(cell)).trim(); continue; } Cell c = row.createCell(col); CellStyle style = getStyle(header, cell.getAlignment()); c.setCellStyle(style); c.setCellValue((leftOver == null || leftOver.isEmpty() ? "" : leftOver + " ") + render(cell)); Cell last = c; if (cell.getColSpan() > 1) { for (int x = 1; x < cell.getColSpan(); x++) { Cell d = row.createCell(col + x); d.setCellStyle(style); last = d; } iSheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), col, col + cell.getColSpan() - 1)); } if (cell.getCellSeparator().trim().equals("|")) last.setCellStyle(addRightRow(style)); col += cell.getColSpan(); leftOver = null; } if (row.getLastCellNum() < 0 && iNrColumns > 0) { for (int i = 0; i < iNrColumns; i++) { Cell c = row.createCell(i); c.setCellStyle(getStyle(header, Alignment.Left)); } iSheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), 0, iNrColumns - 1)); } if (iHeaderPrinted) { row.getCell(row.getFirstCellNum()).setCellStyle(addLeftRow(row.getCell(0).getCellStyle())); row.getCell(row.getLastCellNum() - 1).setCellStyle(addRightRow(row.getCell(row.getLastCellNum() - 1).getCellStyle())); } } return col; } private int countColumns(Line line) { if (line == null) return 0; int cols = 0; if (line.getLines() != null) { for (Line l: line.getLines()) cols += countColumns(l); } if (line.getCells() != null) { for (AbstractReport.Cell cell: line.getCells()) cols += cell.getColSpan(); } return cols; } @Override public void setListener(Listener listener) {} @Override public boolean isSkipRepeating() { return true; } }
package com.sectong.domain; import com.google.gson.JsonObject; import org.springframework.data.annotation.Id; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * Created by admin on 2016/11/19. */ public class UserMessages { @Id private String id; private String fromplatform; private String targetname; private String msgtype; private String version; private String targetid; private String fromappkey; private String fromname; private String fromid; private String createtime; private String fromtype; private String targetappkey; private String targettype; private String msgid; private String msgctime; private String msglevel; private String msgbody; private String msgdata; public UserMessages() { } public UserMessages(String fromplatform, String targetname, String msgtype, String version, String targetid, String fromappkey, String fromname, String fromid, String createtime, String fromtype, String targetappkey, String targettype, String msgid, String msgctime, String msglevel, String msgbody, String msgdata) { this.fromplatform = fromplatform; this.targetname = targetname; this.msgtype = msgtype; this.version = version; this.targetid = targetid; this.fromappkey = fromappkey; this.fromname = fromname; this.fromid = fromid; this.createtime = createtime; this.fromtype = fromtype; this.targetappkey = targetappkey; this.targettype = targettype; this.msgid = msgid; this.msgctime = msgctime; this.msglevel = msglevel; this.msgbody = msgbody; this.msgdata = msgdata; } public UserMessages(Map asdf) { this.fromplatform = asdf.get("from_platform").toString(); this.targetname = asdf.get("target_name").toString(); this.msgtype = asdf.get("msg_type").toString(); this.version = asdf.get("version").toString(); this.targetid = asdf.get("target_id").toString(); this.fromappkey = asdf.get("from_appkey").toString(); this.fromname = asdf.get("from_name").toString(); this.fromid = asdf.get("from_id").toString(); this.createtime = stampToDate(asdf.get("create_time").toString()); this.fromtype = asdf.get("from_type").toString(); // this.targetappkey = asdf.get("target_appkey").toString(); this.targettype = asdf.get("target_type").toString(); this.msgid = asdf.get("msgid").toString(); this.msgctime = stampToDate(asdf.get("msg_ctime").toString()); this.msglevel = asdf.get("msg_level").toString(); this.msgbody = asdf.get("msg_body").toString(); } public static String stampToDate(String s) { String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long lt = new Long(s); Date date = new Date(lt); res = simpleDateFormat.format(date); return res; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFromplatform() { return fromplatform; } public void setFromplatform(String fromplatform) { this.fromplatform = fromplatform; } public String getTargetname() { return targetname; } public void setTargetname(String targetname) { this.targetname = targetname; } public String getMsgtype() { return msgtype; } public void setMsgtype(String msgtype) { this.msgtype = msgtype; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getTargetid() { return targetid; } public void setTargetid(String targetid) { this.targetid = targetid; } public String getFromappkey() { return fromappkey; } public void setFromappkey(String fromappkey) { this.fromappkey = fromappkey; } public String getFromname() { return fromname; } public void setFromname(String fromname) { this.fromname = fromname; } public String getFromid() { return fromid; } public void setFromid(String fromid) { this.fromid = fromid; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public String getFromtype() { return fromtype; } public void setFromtype(String fromtype) { this.fromtype = fromtype; } public String getTargetappkey() { return targetappkey; } public void setTargetappkey(String targetappkey) { this.targetappkey = targetappkey; } public String getTargettype() { return targettype; } public void setTargettype(String targettype) { this.targettype = targettype; } public String getMsgid() { return msgid; } public void setMsgid(String msgid) { this.msgid = msgid; } public String getMsgctime() { return msgctime; } public void setMsgctime(String msgctime) { this.msgctime = msgctime; } public String getMsglevel() { return msglevel; } public void setMsglevel(String msglevel) { this.msglevel = msglevel; } public String getMsgbody() { return msgbody; } public void setMsgbody(String msgbody) { this.msgbody = msgbody; } public String getMsgdata() { return msgdata; } public void setMsgdata(String msgdata) { this.msgdata = msgdata; } }
/* * 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.index.translog; import org.apache.lucene.codecs.CodecUtil; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.IndexFormatTooNewException; import org.apache.lucene.index.IndexFormatTooOldException; import org.apache.lucene.store.DataInput; import org.apache.lucene.store.DataOutput; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.OutputStreamIndexOutput; import org.apache.lucene.store.SimpleFSDirectory; import org.elasticsearch.common.io.Channels; import org.elasticsearch.index.seqno.SequenceNumbers; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; final class Checkpoint { final long offset; final int numOps; final long generation; final long minSeqNo; final long maxSeqNo; final long globalCheckpoint; final long minTranslogGeneration; final long trimmedAboveSeqNo; private static final int CURRENT_VERSION = 3; private static final String CHECKPOINT_CODEC = "ckp"; static final int V3_FILE_SIZE = CodecUtil.headerLength(CHECKPOINT_CODEC) + Integer.BYTES // ops + Long.BYTES // offset + Long.BYTES // generation + Long.BYTES // minimum sequence number + Long.BYTES // maximum sequence number + Long.BYTES // global checkpoint + Long.BYTES // minimum translog generation in the translog + Long.BYTES // maximum reachable (trimmed) sequence number + CodecUtil.footerLength(); /** * Create a new translog checkpoint. * * @param offset the current offset in the translog * @param numOps the current number of operations in the translog * @param generation the current translog generation * @param minSeqNo the current minimum sequence number of all operations in the translog * @param maxSeqNo the current maximum sequence number of all operations in the translog * @param globalCheckpoint the last-known global checkpoint * @param minTranslogGeneration the minimum generation referenced by the translog at this moment. * @param trimmedAboveSeqNo all operations with seq# above trimmedAboveSeqNo should be ignored and not read from the * corresponding translog file. {@link SequenceNumbers#UNASSIGNED_SEQ_NO} is used to disable trimming. */ Checkpoint(long offset, int numOps, long generation, long minSeqNo, long maxSeqNo, long globalCheckpoint, long minTranslogGeneration, long trimmedAboveSeqNo) { assert minSeqNo <= maxSeqNo : "minSeqNo [" + minSeqNo + "] is higher than maxSeqNo [" + maxSeqNo + "]"; assert trimmedAboveSeqNo <= maxSeqNo : "trimmedAboveSeqNo [" + trimmedAboveSeqNo + "] is higher than maxSeqNo [" + maxSeqNo + "]"; assert minTranslogGeneration <= generation : "minTranslogGen [" + minTranslogGeneration + "] is higher than generation [" + generation + "]"; this.offset = offset; this.numOps = numOps; this.generation = generation; this.minSeqNo = minSeqNo; this.maxSeqNo = maxSeqNo; this.globalCheckpoint = globalCheckpoint; this.minTranslogGeneration = minTranslogGeneration; this.trimmedAboveSeqNo = trimmedAboveSeqNo; } private void write(DataOutput out) throws IOException { out.writeLong(offset); out.writeInt(numOps); out.writeLong(generation); out.writeLong(minSeqNo); out.writeLong(maxSeqNo); out.writeLong(globalCheckpoint); out.writeLong(minTranslogGeneration); out.writeLong(trimmedAboveSeqNo); } /** * Returns the maximum sequence number of operations in this checkpoint after applying {@link #trimmedAboveSeqNo}. */ long maxEffectiveSeqNo() { if (trimmedAboveSeqNo == SequenceNumbers.UNASSIGNED_SEQ_NO) { return maxSeqNo; } else { return Math.min(trimmedAboveSeqNo, maxSeqNo); } } static Checkpoint emptyTranslogCheckpoint(final long offset, final long generation, final long globalCheckpoint, long minTranslogGeneration) { final long minSeqNo = SequenceNumbers.NO_OPS_PERFORMED; final long maxSeqNo = SequenceNumbers.NO_OPS_PERFORMED; final long trimmedAboveSeqNo = SequenceNumbers.UNASSIGNED_SEQ_NO; return new Checkpoint(offset, 0, generation, minSeqNo, maxSeqNo, globalCheckpoint, minTranslogGeneration, trimmedAboveSeqNo); } static Checkpoint readCheckpointV3(final DataInput in) throws IOException { final long offset = in.readLong(); final int numOps = in.readInt(); final long generation = in.readLong(); final long minSeqNo = in.readLong(); final long maxSeqNo = in.readLong(); final long globalCheckpoint = in.readLong(); final long minTranslogGeneration = in.readLong(); final long trimmedAboveSeqNo = in.readLong(); return new Checkpoint(offset, numOps, generation, minSeqNo, maxSeqNo, globalCheckpoint, minTranslogGeneration, trimmedAboveSeqNo); } @Override public String toString() { return "Checkpoint{" + "offset=" + offset + ", numOps=" + numOps + ", generation=" + generation + ", minSeqNo=" + minSeqNo + ", maxSeqNo=" + maxSeqNo + ", globalCheckpoint=" + globalCheckpoint + ", minTranslogGeneration=" + minTranslogGeneration + ", trimmedAboveSeqNo=" + trimmedAboveSeqNo + '}'; } public static Checkpoint read(Path path) throws IOException { try (Directory dir = new SimpleFSDirectory(path.getParent())) { try (IndexInput indexInput = dir.openInput(path.getFileName().toString(), IOContext.DEFAULT)) { // We checksum the entire file before we even go and parse it. If it's corrupted we barf right here. CodecUtil.checksumEntireFile(indexInput); final int fileVersion = CodecUtil.checkHeader(indexInput, CHECKPOINT_CODEC, CURRENT_VERSION, CURRENT_VERSION); assert fileVersion == CURRENT_VERSION : fileVersion; assert indexInput.length() == V3_FILE_SIZE : indexInput.length(); return Checkpoint.readCheckpointV3(indexInput); } catch (CorruptIndexException | NoSuchFileException | IndexFormatTooOldException | IndexFormatTooNewException e) { throw new TranslogCorruptedException(path.toString(), e); } } } public static void write(ChannelFactory factory, Path checkpointFile, Checkpoint checkpoint, OpenOption... options) throws IOException { byte[] bytes = createCheckpointBytes(checkpointFile, checkpoint); // now go and write to the channel, in one go. try (FileChannel channel = factory.open(checkpointFile, options)) { Channels.writeToChannel(bytes, channel); // fsync with metadata as we use this method when creating the file channel.force(true); } } public static void write(FileChannel fileChannel, Path checkpointFile, Checkpoint checkpoint) throws IOException { byte[] bytes = createCheckpointBytes(checkpointFile, checkpoint); Channels.writeToChannel(bytes, fileChannel, 0); // no need to force metadata, file size stays the same and we did the full fsync // when we first created the file, so the directory entry doesn't change as well fileChannel.force(false); } private static byte[] createCheckpointBytes(Path checkpointFile, Checkpoint checkpoint) throws IOException { final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(V3_FILE_SIZE) { @Override public synchronized byte[] toByteArray() { // don't clone return buf; } }; final String resourceDesc = "checkpoint(path=\"" + checkpointFile + "\", gen=" + checkpoint + ")"; try (OutputStreamIndexOutput indexOutput = new OutputStreamIndexOutput(resourceDesc, checkpointFile.toString(), byteOutputStream, V3_FILE_SIZE)) { CodecUtil.writeHeader(indexOutput, CHECKPOINT_CODEC, CURRENT_VERSION); checkpoint.write(indexOutput); CodecUtil.writeFooter(indexOutput); assert indexOutput.getFilePointer() == V3_FILE_SIZE : "get you numbers straight; bytes written: " + indexOutput.getFilePointer() + ", buffer size: " + V3_FILE_SIZE; assert indexOutput.getFilePointer() < 512 : "checkpoint files have to be smaller than 512 bytes for atomic writes; size: " + indexOutput.getFilePointer(); } return byteOutputStream.toByteArray(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Checkpoint that = (Checkpoint) o; if (offset != that.offset) return false; if (numOps != that.numOps) return false; if (generation != that.generation) return false; if (minSeqNo != that.minSeqNo) return false; if (maxSeqNo != that.maxSeqNo) return false; if (globalCheckpoint != that.globalCheckpoint) return false; return trimmedAboveSeqNo == that.trimmedAboveSeqNo; } @Override public int hashCode() { int result = Long.hashCode(offset); result = 31 * result + numOps; result = 31 * result + Long.hashCode(generation); result = 31 * result + Long.hashCode(minSeqNo); result = 31 * result + Long.hashCode(maxSeqNo); result = 31 * result + Long.hashCode(globalCheckpoint); result = 31 * result + Long.hashCode(trimmedAboveSeqNo); return result; } }
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.siyeh.ig.junit; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.TestFrameworks; import com.intellij.codeInsight.intention.impl.AddOnDemandStaticImportAction; import com.intellij.codeInspection.*; import com.intellij.codeInspection.actions.CleanupInspectionUtil; import com.intellij.codeInspection.ex.LocalInspectionToolWrapper; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.JavaVersionService; import com.intellij.openapi.util.EmptyRunnable; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.searches.ClassInheritorsSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.refactoring.RefactoringManager; import com.intellij.refactoring.migration.MigrationManager; import com.intellij.refactoring.migration.MigrationMap; import com.intellij.refactoring.migration.MigrationProcessor; import com.intellij.refactoring.util.RefactoringUIUtil; import com.intellij.testIntegration.TestFramework; import com.intellij.usageView.UsageInfo; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import com.siyeh.InspectionGadgetsBundle; import com.siyeh.ig.BaseInspection; import com.siyeh.ig.BaseInspectionVisitor; import com.siyeh.ig.InspectionGadgetsFix; import com.siyeh.ig.psiutils.TestUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.intellij.codeInsight.AnnotationUtil.CHECK_HIERARCHY; public class JUnit5ConverterInspection extends BaseInspection { private static final List<String> ruleAnnotations = Arrays.asList(JUnitCommonClassNames.ORG_JUNIT_RULE, JUnitCommonClassNames.ORG_JUNIT_CLASS_RULE); @Nls @NotNull @Override public String getDisplayName() { return InspectionGadgetsBundle.message("junit5.converter.display.name"); } @NotNull @Override protected String buildErrorString(Object... infos) { return "#ref can be JUnit 5 test"; } @Override public boolean shouldInspect(PsiFile file) { if (!JavaVersionService.getInstance().isAtLeast(file, JavaSdkVersion.JDK_1_8)) return false; if (JavaPsiFacade.getInstance(file.getProject()).findClass(JUnitCommonClassNames.ORG_JUNIT_JUPITER_API_ASSERTIONS, file.getResolveScope()) == null) { return false; } return super.shouldInspect(file); } @Nullable @Override protected InspectionGadgetsFix buildFix(Object... infos) { return new MigrateToJUnit5(); } @Override public BaseInspectionVisitor buildVisitor() { return new BaseInspectionVisitor() { @Override public void visitClass(PsiClass aClass) { TestFramework framework = TestFrameworks.detectFramework(aClass); if (framework == null || !"JUnit4".equals(framework.getName())) { return; } if (!canBeConvertedToJUnit5(aClass)) return; registerClassError(aClass); } }; } protected static boolean canBeConvertedToJUnit5(PsiClass aClass) { if (AnnotationUtil.isAnnotated(aClass, TestUtils.RUN_WITH, CHECK_HIERARCHY)) { return false; } for (PsiField field : aClass.getAllFields()) { if (AnnotationUtil.isAnnotated(field, ruleAnnotations, 0)) { return false; } } for (PsiMethod method : aClass.getMethods()) { if (AnnotationUtil.isAnnotated(method, ruleAnnotations, 0)) { return false; } PsiAnnotation testAnnotation = AnnotationUtil.findAnnotation(method, true, JUnitCommonClassNames.ORG_JUNIT_TEST); if (testAnnotation != null && testAnnotation.getParameterList().getAttributes().length > 0) { return false; } } return true; } private static class MigrateToJUnit5 extends InspectionGadgetsFix implements BatchQuickFix { @Nls @NotNull @Override public String getFamilyName() { return InspectionGadgetsBundle.message("junit5.converter.fix.name"); } @Override protected void doFix(Project project, ProblemDescriptor descriptor) { PsiClass psiClass = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiClass.class); if (psiClass != null) { MigrationManager manager = RefactoringManager.getInstance(project).getMigrateManager(); MigrationMap migrationMap = manager.findMigrationMap("JUnit (4.x -> 5.0)"); if (migrationMap != null) { new MyJUnit5MigrationProcessor(project, migrationMap, Collections.singleton(psiClass.getContainingFile())).run(); } } } @Override public boolean startInWriteAction() { return false; } @Override public void applyFix(@NotNull Project project, @NotNull CommonProblemDescriptor[] descriptors, @NotNull List psiElementsToIgnore, @Nullable Runnable refreshViews) { Set<PsiFile> files = Arrays.stream(descriptors).map(descriptor -> ((ProblemDescriptor)descriptor).getPsiElement()) .filter(Objects::nonNull) .map(element -> element.getContainingFile()).collect(Collectors.toSet()); if (!files.isEmpty()) { MigrationManager manager = RefactoringManager.getInstance(project).getMigrateManager(); MigrationMap migrationMap = manager.findMigrationMap("JUnit (4.x -> 5.0)"); if (migrationMap != null) { new MyJUnit5MigrationProcessor(project, migrationMap, files).run(); if (refreshViews != null) { refreshViews.run(); } } } } private static class MyJUnit5MigrationProcessor extends MigrationProcessor { private final Project myProject; private final Set<? extends PsiFile> myFiles; MyJUnit5MigrationProcessor(Project project, MigrationMap migrationMap, Set<? extends PsiFile> files) { super(project, migrationMap, GlobalSearchScope.filesWithoutLibrariesScope(project, ContainerUtil.map(files, file -> file.getVirtualFile()))); setPrepareSuccessfulSwingThreadCallback(EmptyRunnable.INSTANCE); myProject = project; myFiles = files; } @Override protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) { final MultiMap<PsiElement, String> conflicts = new MultiMap<>(); for (PsiFile file : myFiles) { for (PsiClass psiClass : ((PsiClassOwner)file).getClasses()) { Set<PsiClass> inheritors = new HashSet<>(); ClassInheritorsSearch.search(psiClass).forEach(inheritor -> { if (!canBeConvertedToJUnit5(inheritor)) { inheritors.add(inheritor); return false; } return true; }); if (!inheritors.isEmpty()) { conflicts.putValue(psiClass, "Class " + RefactoringUIUtil.getDescription(psiClass, true) + " can't be converted to JUnit 5, cause there are incompatible inheritor(s): " + StringUtil.join(inheritors, aClass -> aClass.getQualifiedName(), ", ")); } } } setPreviewUsages(true); return showConflicts(conflicts, refUsages.get()); } @NotNull @Override protected UsageInfo[] findUsages() { UsageInfo[] usages = super.findUsages(); InspectionManager inspectionManager = InspectionManager.getInstance(myProject); GlobalInspectionContext globalContext = inspectionManager.createNewGlobalContext(); LocalInspectionToolWrapper assertionsConverter = new LocalInspectionToolWrapper(new JUnit5AssertionsConverterInspection("JUnit4")); Stream<ProblemDescriptor> stream = myFiles.stream().flatMap(file -> InspectionEngine.runInspectionOnFile(file, assertionsConverter, globalContext).stream()); UsageInfo[] descriptors = stream.map(descriptor -> new MyDescriptionBasedUsageInfo(descriptor)).toArray(UsageInfo[]::new); return ArrayUtil.mergeArrays(usages, descriptors); } List<SmartPsiElementPointer<PsiElement>> myReplacedRefs = new ArrayList<>(); @Override protected void performRefactoring(@NotNull UsageInfo[] usages) { List<UsageInfo> migrateUsages = new ArrayList<>(); List<ProblemDescriptor> descriptions = new ArrayList<>(); SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(myProject); for (UsageInfo usage : usages) { if (usage instanceof MyDescriptionBasedUsageInfo) { ProblemDescriptor descriptor = ((MyDescriptionBasedUsageInfo)usage).myDescriptor; descriptions.add (descriptor); markUsagesImportedThroughStaticImport(smartPointerManager, descriptor); } else { migrateUsages.add(usage); } } super.performRefactoring(migrateUsages.toArray(UsageInfo.EMPTY_ARRAY)); CleanupInspectionUtil.getInstance().applyFixes(myProject, "Convert Assertions", descriptions, JUnit5AssertionsConverterInspection.ReplaceObsoleteAssertsFix.class, false); } @Override protected void performPsiSpoilingRefactoring() { super.performPsiSpoilingRefactoring(); tryToRestoreStaticImportsOnNewAssertions(); } private void markUsagesImportedThroughStaticImport(SmartPointerManager smartPointerManager, ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); PsiMethodCallExpression callExpression = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class); if (callExpression != null) { PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); PsiElement scope = methodExpression.getQualifierExpression() == null ? methodExpression.advancedResolve(false).getCurrentFileResolveScope() : null; if (scope instanceof PsiImportStaticStatement && ((PsiImportStaticStatement)scope).isOnDemand()) { myReplacedRefs.add(smartPointerManager.createSmartPsiElementPointer(callExpression)); } } } private void tryToRestoreStaticImportsOnNewAssertions() { for (SmartPsiElementPointer<PsiElement> ref : myReplacedRefs) { PsiElement element = ref.getElement(); if (element instanceof PsiMethodCallExpression) { PsiExpression qualifierExpression = ((PsiMethodCallExpression)element).getMethodExpression().getQualifierExpression(); if (qualifierExpression != null) { PsiElement referenceNameElement = ((PsiReferenceExpression)qualifierExpression).getReferenceNameElement(); PsiClass aClass = referenceNameElement != null ? AddOnDemandStaticImportAction .getClassToPerformStaticImport(referenceNameElement) : null; PsiFile containingFile = element.getContainingFile(); if (aClass != null && !AddOnDemandStaticImportAction.invoke(myProject, containingFile, null, referenceNameElement)) { PsiImportStatementBase importReferenceTo = PsiTreeUtil .getParentOfType(((PsiJavaFile)containingFile).findImportReferenceTo(aClass), PsiImportStatementBase.class); if (importReferenceTo != null) importReferenceTo.delete(); } } } } } } } private static class MyDescriptionBasedUsageInfo extends UsageInfo { private final ProblemDescriptor myDescriptor; MyDescriptionBasedUsageInfo(ProblemDescriptor descriptor) { super(descriptor.getPsiElement()); myDescriptor = descriptor; } } }
package org.wso2.carbon.identity.application.authentication.framework.handler.provisioning.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonException; import org.wso2.carbon.core.util.AnonymousSessionUtil; import org.wso2.carbon.core.util.PermissionUpdateUtil; import org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException; import org.wso2.carbon.identity.application.authentication.framework.handler.provisioning.ProvisioningHandler; import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceComponent; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.UserRealm; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.math.BigInteger; import java.security.SecureRandom; import java.util.*; public class DefaultProvisioningHandler implements ProvisioningHandler { private static Log log = LogFactory.getLog(DefaultProvisioningHandler.class); private static volatile DefaultProvisioningHandler instance; private SecureRandom random = new SecureRandom(); public static DefaultProvisioningHandler getInstance() { if (instance == null) { synchronized (DefaultProvisioningHandler.class) { if (instance == null) { instance = new DefaultProvisioningHandler(); } } } return instance; } public void handle(List<String> roles, String subject, Map<String, String> attributes, String provisioningUserStoreId, String tenantDomain) throws FrameworkException { RegistryService registryService = FrameworkServiceComponent.getRegistryService(); RealmService realmService = FrameworkServiceComponent.getRealmService(); try { int tenantId = realmService.getTenantManager().getTenantId(tenantDomain); UserRealm realm = AnonymousSessionUtil.getRealmByTenantDomain(registryService, realmService, tenantDomain); String userstoreDomain = getUserStoreDomain(provisioningUserStoreId, realm); String username = MultitenantUtils.getTenantAwareUsername(subject); UserStoreManager userstore = null; if (userstoreDomain != null && !userstoreDomain.isEmpty()) { userstore = realm.getUserStoreManager().getSecondaryUserStoreManager( userstoreDomain); } else { userstore = realm.getUserStoreManager(); } if (userstore == null) { throw new FrameworkException("Specified user store is invalid"); } // Remove userstore domain from username if the userstoreDomain is not primary if (realm.getUserStoreManager().getRealmConfiguration().isPrimary()) { username = UserCoreUtil.removeDomainFromName(username); } String[] newRoles = new String[]{}; if (roles != null) { newRoles = roles.toArray(new String[roles.size()]); } if (log.isDebugEnabled()) { log.debug("User " + username + " contains roles : " + Arrays.toString(newRoles) + " going to be provisioned"); } // addingRoles = newRoles AND allExistingRoles Collection<String> addingRoles = new ArrayList<String>(); Collections.addAll(addingRoles, newRoles); Collection<String> allExistingRoles = Arrays.asList(userstore.getRoleNames()); addingRoles.retainAll(allExistingRoles); if (userstore.isExistingUser(username)) { if (roles != null && roles.size() > 0) { // Update user Collection<String> currentRolesList = Arrays.asList(userstore .getRoleListOfUser(username)); // addingRoles = (newRoles AND existingRoles) - currentRolesList) addingRoles.removeAll(currentRolesList); Collection<String> deletingRoles = new ArrayList<String>(); deletingRoles.addAll(currentRolesList); // deletingRoles = currentRolesList - newRoles deletingRoles.removeAll(Arrays.asList(newRoles)); // Exclude Internal/everyonerole from deleting role since its cannot be deleted deletingRoles.remove(realm.getRealmConfiguration().getEveryOneRoleName()); // TODO : Does it need to check this? // Check for case whether superadmin login if (userstore.getRealmConfiguration().isPrimary() && username.equals(realm.getRealmConfiguration().getAdminUserName())) { if (log.isDebugEnabled()) { log.debug("Federated user's username is equal to super admin's username of local IdP."); } // Whether superadmin login without superadmin role is permitted if (deletingRoles .contains(realm.getRealmConfiguration().getAdminRoleName())) { if (log.isDebugEnabled()) { log.debug("Federated user doesn't have super admin role. Unable to sync roles, since super admin role cannot be unassingned from super admin user"); } throw new FrameworkException( "Federated user which having same username to super admin username of local IdP, trying login without having superadmin role assigned"); } } if (log.isDebugEnabled()) { log.debug("Deleting roles : " + Arrays.toString(deletingRoles.toArray(new String[0])) + " and Adding roles : " + Arrays.toString(addingRoles.toArray(new String[0]))); } userstore.updateRoleListOfUser(username, deletingRoles.toArray(new String[0]), addingRoles.toArray(new String[0])); if (log.isDebugEnabled()) { log.debug("Federated user: " + username + " is updated by authentication framework with roles : " + Arrays.toString(newRoles)); } } if (attributes != null && attributes.size() > 0) { userstore.setUserClaimValues(username, attributes, null); } } else { Map<String, String> userClaim = new HashMap<String, String>(); if (attributes != null && attributes.size() > 0) { // Provision user for (Map.Entry<String, String> entry : attributes.entrySet()) { if (entry.getValue() != null && !entry.getValue().isEmpty()) { userClaim.put(entry.getKey(), entry.getValue()); } } userstore.addUser(username, generatePassword(username), addingRoles.toArray(new String[0]), userClaim, null); } else { userstore.addUser(username, generatePassword(username), addingRoles.toArray(new String[0]), userClaim, null); } if (log.isDebugEnabled()) { log.debug("Federated user: " + username + " is provisioned by authentication framework with roles : " + Arrays.toString(addingRoles.toArray(new String[0]))); } } PermissionUpdateUtil.updatePermissionTree(tenantId); } catch (UserStoreException e) { throw new FrameworkException("Error while provisioning user : " + subject, e); } catch (org.wso2.carbon.user.api.UserStoreException e) { throw new FrameworkException("Error while provisioning user : " + subject, e); } catch (CarbonException e) { throw new FrameworkException("Error while provisioning user : " + subject, e); } } /** * Compute the user store which user to be provisioned * * @return * @throws UserStoreException */ private String getUserStoreDomain(String userStoreDomain, UserRealm realm) throws FrameworkException, UserStoreException { // If the any of above value is invalid, keep it empty to use primary userstore if (userStoreDomain != null && realm.getUserStoreManager().getSecondaryUserStoreManager(userStoreDomain) == null) { throw new FrameworkException("Specified user store domain " + userStoreDomain + " is not valid."); } return userStoreDomain; } /** * Generates (random) password for user to be provisioned * * @param username * @return */ protected String generatePassword(String username) { return new BigInteger(130, random).toString(32); } private String getUserStoreClaimValueFromMap(Map<ClaimMapping, String> claimMappingStringMap, String userStoreClaimURI) { for (Map.Entry<ClaimMapping, String> entry : claimMappingStringMap.entrySet()) { if (entry.getKey().getRemoteClaim().getClaimUri().equals(userStoreClaimURI)) { return entry.getValue(); } } return null; } }
/*************************************************************************** * Copyright 2015 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.tools.logReplayer; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import kieker.common.logging.Log; import kieker.common.logging.LogFactory; import kieker.tools.AbstractCommandLineTool; /** * Command-line tool for replaying a filesystem monitoring log using the {@link FilesystemLogReplayer}. * * @author Andre van Hoorn, Nils Christian Ehmke * * @since 0.95a */ @SuppressWarnings("static-access") public final class FilesystemLogReplayerStarter extends AbstractCommandLineTool { private static final Log LOG = LogFactory.getLog(FilesystemLogReplayerStarter.class); private static final String CMD_OPT_NAME_MONITORING_CONFIGURATION = "monitoring.configuration"; private static final String CMD_OPT_NAME_INPUTDIRS = "inputdirs"; private static final String CMD_OPT_NAME_KEEPORIGINALLOGGINGTIMESTAMPS = "keep-logging-timestamps"; private static final String CMD_OPT_NAME_REALTIME = "realtime"; private static final String CMD_OPT_NAME_NUM_REALTIME_WORKERS = "realtime-worker-threads"; private static final String CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR = "realtime-acceleration-factor"; private static final String CMD_OPT_NAME_IGNORERECORDSBEFOREDATE = "ignore-records-before-date"; private static final String CMD_OPT_NAME_IGNORERECORDSAFTERDATE = "ignore-records-after-date"; private static final String DATE_FORMAT_PATTERN = "yyyyMMdd'-'HHmmss"; private static final String DATE_FORMAT_PATTERN_CMD_USAGE_HELP = DATE_FORMAT_PATTERN.replaceAll("'", ""); // only for usage info private static final String OPTION_EXAMPLE_FILE_MONITORING_PROPERTIES = File.separator + "path" + File.separator + "to" + File.separator + "monitoring.properties"; private String monitoringConfigurationFile; private String[] inputDirs; private boolean keepOriginalLoggingTimestamps; private boolean realtimeMode; private double realtimeAccelerationFactor; private int numRealtimeWorkerThreads = -1; private long ignoreRecordsBeforeTimestamp = FilesystemLogReplayer.MIN_TIMESTAMP; private long ignoreRecordsAfterTimestamp = FilesystemLogReplayer.MAX_TIMESTAMP; private FilesystemLogReplayerStarter() { super(true); } public static void main(final String[] args) { new FilesystemLogReplayerStarter().start(args); } @Override protected void addAdditionalOptions(final Options options) { Option option; option = new Option("c", CMD_OPT_NAME_MONITORING_CONFIGURATION, true, "Configuration to use for the Kieker monitoring instance"); option.setArgName(OPTION_EXAMPLE_FILE_MONITORING_PROPERTIES); option.setRequired(false); option.setValueSeparator('='); options.addOption(option); option = new Option("i", CMD_OPT_NAME_INPUTDIRS, true, "Log directories to read data from"); option.setArgName("dir1 ... dirN"); option.setRequired(false); option.setArgs(Option.UNLIMITED_VALUES); options.addOption(option); option = new Option("k", CMD_OPT_NAME_KEEPORIGINALLOGGINGTIMESTAMPS, true, "Replay the original logging timestamps (defaults to true)?"); option.setArgName("true|false"); option.setRequired(false); option.setValueSeparator('='); options.addOption(option); option = new Option("r", CMD_OPT_NAME_REALTIME, true, "Replay log data in realtime?"); option.setArgName("true|false"); option.setRequired(false); option.setValueSeparator('='); options.addOption(option); option = new Option("n", CMD_OPT_NAME_NUM_REALTIME_WORKERS, true, "Number of worker threads used in realtime mode (defaults to 1)."); option.setArgName("num"); option.setRequired(false); options.addOption(option); option = new Option("a", CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR, true, "Factor by which to accelerate (>1.0) or slow down (<1.0) the replay in realtime mode (defaults to 1.0, i.e., no acceleration/slow down)."); option.setArgName("factor"); option.setRequired(false); option.setValueSeparator('='); options.addOption(option); option = new Option(null, CMD_OPT_NAME_IGNORERECORDSBEFOREDATE, true, "Records logged before this date (UTC timezone) are ignored (disabled by default)."); option.setArgName(DATE_FORMAT_PATTERN_CMD_USAGE_HELP); option.setRequired(false); options.addOption(option); option = new Option(null, CMD_OPT_NAME_IGNORERECORDSAFTERDATE, true, "Records logged after this date (UTC timezone) are ignored (disabled by default)."); option.setArgName(DATE_FORMAT_PATTERN_CMD_USAGE_HELP); option.setRequired(false); options.addOption(option); } @Override protected boolean readPropertiesFromCommandLine(final CommandLine commandLine) { boolean retVal = true; // 0.) monitoring properties this.monitoringConfigurationFile = commandLine.getOptionValue(CMD_OPT_NAME_MONITORING_CONFIGURATION); // 1.) init inputDirs this.inputDirs = commandLine.getOptionValues(CMD_OPT_NAME_INPUTDIRS); if (this.inputDirs == null) { LOG.error("No input directory configured"); retVal = false; } // 2.) init keepOriginalLoggingTimestamps final String keepOriginalLoggingTimestampsOptValStr = commandLine.getOptionValue( CMD_OPT_NAME_KEEPORIGINALLOGGINGTIMESTAMPS, "true"); if (!("true".equals(keepOriginalLoggingTimestampsOptValStr) || "false".equals(keepOriginalLoggingTimestampsOptValStr))) { LOG.error("Invalid value for option " + CMD_OPT_NAME_KEEPORIGINALLOGGINGTIMESTAMPS + ": '" + keepOriginalLoggingTimestampsOptValStr + "'"); retVal = false; } this.keepOriginalLoggingTimestamps = "true".equals(keepOriginalLoggingTimestampsOptValStr); if (LOG.isDebugEnabled()) { LOG.debug("Keeping original logging timestamps: " + (this.keepOriginalLoggingTimestamps ? "true" : "false")); // NOCS } // 3.) init realtimeMode final String realtimeOptValStr = commandLine.getOptionValue(CMD_OPT_NAME_REALTIME, "false"); if (!("true".equals(realtimeOptValStr) || "false".equals(realtimeOptValStr))) { LOG.error("Invalid value for option " + CMD_OPT_NAME_REALTIME + ": '" + realtimeOptValStr + "'"); retVal = false; } this.realtimeMode = "true".equals(realtimeOptValStr); // 4.) init numRealtimeWorkerThreads final String numRealtimeWorkerThreadsStr = commandLine.getOptionValue(CMD_OPT_NAME_NUM_REALTIME_WORKERS, "1"); try { this.numRealtimeWorkerThreads = Integer.parseInt(numRealtimeWorkerThreadsStr); } catch (final NumberFormatException ex) { LOG.error("Invalid value for option " + CMD_OPT_NAME_NUM_REALTIME_WORKERS + ": '" + numRealtimeWorkerThreadsStr + "'"); LOG.error("NumberFormatException: ", ex); retVal = false; } if (this.numRealtimeWorkerThreads < 1) { LOG.error("Option value for " + CMD_OPT_NAME_NUM_REALTIME_WORKERS + " must be >= 1; found " + this.numRealtimeWorkerThreads); LOG.error("Invalid specification of " + CMD_OPT_NAME_NUM_REALTIME_WORKERS + ":" + this.numRealtimeWorkerThreads); retVal = false; } // 5.) init realtimeAccelerationFactor final String realtimeAccelerationFactorStr = commandLine.getOptionValue(CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR, "1"); try { this.realtimeAccelerationFactor = Double.parseDouble(realtimeAccelerationFactorStr); } catch (final NumberFormatException ex) { LOG.error("Invalid value for option " + CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR + ": '" + numRealtimeWorkerThreadsStr + "'"); LOG.error("NumberFormatException: ", ex); retVal = false; } if (this.numRealtimeWorkerThreads <= 0) { LOG.error("Option value for " + CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR + " must be > 0; found " + this.realtimeAccelerationFactor); LOG.error("Invalid specification of " + CMD_OPT_NAME_REALTIME_ACCELERATION_FACTOR + ":" + this.realtimeAccelerationFactor); retVal = false; } // 6.) init ignoreRecordsBefore/After final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PATTERN, Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { final String ignoreRecordsBeforeTimestampString = commandLine.getOptionValue( CMD_OPT_NAME_IGNORERECORDSBEFOREDATE, null); final String ignoreRecordsAfterTimestampString = commandLine.getOptionValue( CMD_OPT_NAME_IGNORERECORDSAFTERDATE, null); if (ignoreRecordsBeforeTimestampString != null) { final Date ignoreBeforeDate = dateFormat.parse(ignoreRecordsBeforeTimestampString); this.ignoreRecordsBeforeTimestamp = ignoreBeforeDate.getTime() * (1000 * 1000); if (LOG.isDebugEnabled()) { LOG.debug("Ignoring records before " + dateFormat.format(ignoreBeforeDate) + " (" + this.ignoreRecordsBeforeTimestamp + ")"); } } if (ignoreRecordsAfterTimestampString != null) { final Date ignoreAfterDate = dateFormat.parse(ignoreRecordsAfterTimestampString); this.ignoreRecordsAfterTimestamp = ignoreAfterDate.getTime() * (1000 * 1000); if (LOG.isDebugEnabled()) { LOG.debug("Ignoring records after " + dateFormat.format(ignoreAfterDate) + " (" + this.ignoreRecordsAfterTimestamp + ")"); } } } catch (final java.text.ParseException ex) { final String erorMsg = "Error parsing date/time string. Please use the following pattern: " + DATE_FORMAT_PATTERN_CMD_USAGE_HELP; LOG.error(erorMsg, ex); return false; } // log configuration if (retVal && LOG.isDebugEnabled()) { LOG.debug("inputDirs: " + FilesystemLogReplayerStarter.fromStringArrayToDeliminedString(this.inputDirs, ';')); LOG.debug("Replaying in " + (this.realtimeMode ? "" : "non-") + "realtime mode"); // NOCS if (this.realtimeMode) { LOG.debug("Using " + this.numRealtimeWorkerThreads + " realtime worker thread" + (this.numRealtimeWorkerThreads > 1 ? "s" : "")); // NOCS } } return retVal; } @Override protected boolean performTask() { if (LOG.isDebugEnabled()) { if (this.realtimeMode) { LOG.debug("Replaying log data in real time"); } else { LOG.debug("Replaying log data in non-real time"); } } final FilesystemLogReplayer player = new FilesystemLogReplayer(this.monitoringConfigurationFile, this.realtimeMode, this.realtimeAccelerationFactor, this.keepOriginalLoggingTimestamps, this.numRealtimeWorkerThreads, this.ignoreRecordsBeforeTimestamp, this.ignoreRecordsAfterTimestamp, this.inputDirs); if (player.replay()) { return true; } else { LOG.error("An error occured"); return false; } } private static String fromStringArrayToDeliminedString(final String[] array, final char delimiter) { Arrays.toString(array); final StringBuilder arTostr = new StringBuilder(); if (array.length > 0) { arTostr.append(array[0]); for (int i = 1; i < array.length; i++) { arTostr.append(delimiter); arTostr.append(array[i]); } } return arTostr.toString(); } }
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.job.entries.msaccessbulkload; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.DirectoryDialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.Props; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entries.msaccessbulkload.JobEntryMSAccessBulkLoad; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.WindowProperty; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.job.dialog.JobDialog; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; /** * This dialog allows you to edit the Microsoft Access Bulk Load job entry settings. * * @author Samatar Hassan * @since 24-07-2008 */ public class JobEntryMSAccessBulkLoadDialog extends JobEntryDialog implements JobEntryDialogInterface { private static Class<?> PKG = JobEntryMSAccessBulkLoad.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private static final String[] FILETYPES = new String[] { BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Filetype.All") }; private Label wlName; private Text wName; private FormData fdlName, fdName; private Label WSourceFileFoldername; private Button wbFileFoldername,wbaEntry,wbSourceFolder; private TextVar wSourceFileFoldername; private FormData fdlSourceFileFoldername, fdbSourceFileFoldername, fdbaEntry,fdSourceFileFoldername,fdbSourceFolder; private Label wlTargetDbname; private Button wbTargetDbname; private TextVar wTargetDbname; private FormData fdlTargetDbname, fdbTargetDbname, fdTargetDbname; private Label wlTablename; private TextVar wTablename; private FormData fdlTablename; private FormData fdTablename; private Label wlWildcard; private TextVar wWildcard; private FormData fdlWildcard; private FormData fdWildcard; private Label wlDelimiter; private TextVar wDelimiter; private FormData fdlDelimiter; private FormData fdDelimiter; private Button wOK, wCancel; private Listener lsOK, lsCancel; private Label wlFields; private TableView wFields; private FormData fdlFields, fdFields; private Button wbDelete; // Delete private FormData fdbdDelete; private Button wbEdit; // Edit private CTabFolder wTabFolder; private Composite wGeneralComp,wAdvancedComp; private CTabItem wGeneralTab,wAdvancedTab; private FormData fdGeneralComp,fdAdvancedComp; private FormData fdTabFolder; private Group wSourceGroup; private FormData fdSourceGroup; private Group wTargetGroup; private FormData fdTargetGroup; private FormData fdbeSourceFileFolder; private Group wFileResult; private FormData fdFileResult; private Label wlSuccessCondition; private CCombo wSuccessCondition; private FormData fdlSuccessCondition, fdSuccessCondition; private Group wSuccessOn; private FormData fdSuccessOn; private Label wlNrErrorsLessThan; private TextVar wNrErrorsLessThan; private FormData fdlNrErrorsLessThan, fdNrErrorsLessThan; private Label wlAddFileToResult,wlincludeSubFolders; private Button wAddFileToResult,wincludeSubFolders; private FormData fdlAddFileToResult, fdAddFileToResult,fdlincludeSubFolders,fdincludeSubFolders; private JobEntryMSAccessBulkLoad jobEntry; private Shell shell; private Label wlPrevious; private Button wPrevious; private FormData fdlPrevious, fdPrevious; private SelectionAdapter lsDef; private boolean changed; public JobEntryMSAccessBulkLoadDialog(Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta) { super(parent, jobEntryInt, rep, jobMeta); jobEntry = (JobEntryMSAccessBulkLoad) jobEntryInt; if (this.jobEntry.getName() == null) this.jobEntry.setName(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Name.Default")); } public JobEntryInterface open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, props.getJobsDialogStyle()); props.setLook(shell); JobDialog.setShellImage(shell, jobEntry); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { jobEntry.setChanged(); } }; changed = jobEntry.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Title")); int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Name line wlName=new Label(shell, SWT.RIGHT); wlName.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Name.Label")); props.setLook(wlName); fdlName=new FormData(); fdlName.left = new FormAttachment(0, 0); fdlName.right= new FormAttachment(middle, -margin); fdlName.top = new FormAttachment(0, margin); wlName.setLayoutData(fdlName); wName=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wName); wName.addModifyListener(lsMod); fdName=new FormData(); fdName.left = new FormAttachment(middle, 0); fdName.top = new FormAttachment(0, margin); fdName.right= new FormAttachment(100, 0); wName.setLayoutData(fdName); wTabFolder = new CTabFolder(shell, SWT.BORDER); props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB); ////////////////////////// // START OF GENERAL TAB /// ////////////////////////// wGeneralTab=new CTabItem(wTabFolder, SWT.NONE); wGeneralTab.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Tab.General.Label")); wGeneralComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wGeneralComp); FormLayout generalLayout = new FormLayout(); generalLayout.marginWidth = 3; generalLayout.marginHeight = 3; wGeneralComp.setLayout(generalLayout); // //////////////////////// // START OF Source GROUP/// // / wSourceGroup = new Group(wGeneralComp, SWT.SHADOW_NONE); props.setLook(wSourceGroup); wSourceGroup.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.SourceGroup.Group.Label")); FormLayout SourceGroupgroupLayout = new FormLayout(); SourceGroupgroupLayout.marginWidth = 10; SourceGroupgroupLayout.marginHeight = 10; wSourceGroup.setLayout(SourceGroupgroupLayout); // previous wlPrevious = new Label(wSourceGroup, SWT.RIGHT); wlPrevious.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Previous.Label")); props.setLook(wlPrevious); fdlPrevious = new FormData(); fdlPrevious.left = new FormAttachment(0, 0); fdlPrevious.top = new FormAttachment(wName, margin ); fdlPrevious.right = new FormAttachment(middle, -margin); wlPrevious.setLayoutData(fdlPrevious); wPrevious = new Button(wSourceGroup, SWT.CHECK); props.setLook(wPrevious); wPrevious.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Previous.Tooltip")); fdPrevious = new FormData(); fdPrevious.left = new FormAttachment(middle, 0); fdPrevious.top = new FormAttachment(wName, margin ); fdPrevious.right = new FormAttachment(100, 0); wPrevious.setLayoutData(fdPrevious); wPrevious.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { RefreshArgFromPrevious(); } }); // FileFoldername line WSourceFileFoldername=new Label(wSourceGroup, SWT.RIGHT); WSourceFileFoldername.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FileFoldername.Label")); props.setLook(WSourceFileFoldername); fdlSourceFileFoldername=new FormData(); fdlSourceFileFoldername.left = new FormAttachment(0, 0); fdlSourceFileFoldername.top = new FormAttachment(wPrevious, margin); fdlSourceFileFoldername.right= new FormAttachment(middle, -margin); WSourceFileFoldername.setLayoutData(fdlSourceFileFoldername); // Browse Destination folders button ... wbSourceFolder=new Button(wSourceGroup, SWT.PUSH| SWT.CENTER); props.setLook(wbSourceFolder); wbSourceFolder.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.BrowseFolders.Label")); fdbSourceFolder=new FormData(); fdbSourceFolder.right= new FormAttachment(100, 0); fdbSourceFolder.top = new FormAttachment(wPrevious, margin); wbSourceFolder.setLayoutData(fdbSourceFolder); wbSourceFolder.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { DirectoryDialog ddialog = new DirectoryDialog(shell, SWT.OPEN); if (wSourceFileFoldername.getText()!=null) { ddialog.setFilterPath(jobMeta.environmentSubstitute(wSourceFileFoldername.getText()) ); } // Calling open() will open and run the dialog. // It will return the selected directory, or // null if user cancels String dir = ddialog.open(); if (dir != null) { // Set the text box to the new selection wSourceFileFoldername.setText(dir); } } } ); // Browse source file button ... wbFileFoldername=new Button(wSourceGroup, SWT.PUSH| SWT.CENTER); props.setLook(wbFileFoldername); wbFileFoldername.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.BrowseFiles.Label")); fdbSourceFileFoldername=new FormData(); fdbSourceFileFoldername.right= new FormAttachment(wbSourceFolder, -margin); fdbSourceFileFoldername.top = new FormAttachment(wPrevious, margin); wbFileFoldername.setLayoutData(fdbSourceFileFoldername); wSourceFileFoldername=new TextVar(jobMeta,wSourceGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wSourceFileFoldername); wSourceFileFoldername.addModifyListener(lsMod); fdSourceFileFoldername=new FormData(); fdSourceFileFoldername.left = new FormAttachment(middle, 0); fdSourceFileFoldername.top = new FormAttachment(wPrevious, margin); fdSourceFileFoldername.right= new FormAttachment(wbFileFoldername, -margin); wSourceFileFoldername.setLayoutData(fdSourceFileFoldername); // Whenever something changes, set the tooltip to the expanded version: wSourceFileFoldername.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wSourceFileFoldername.setToolTipText(jobMeta.environmentSubstitute( wSourceFileFoldername.getText() ) ); } } ); wbFileFoldername.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*"}); if (wSourceFileFoldername.getText()!=null) { dialog.setFileName(jobMeta.environmentSubstitute(wSourceFileFoldername.getText()) ); } dialog.setFilterNames(FILETYPES); if (dialog.open()!=null) { wSourceFileFoldername.setText(dialog.getFilterPath()+Const.FILE_SEPARATOR+dialog.getFileName()); } } } ); //Include sub folders wlincludeSubFolders = new Label(wSourceGroup, SWT.RIGHT); wlincludeSubFolders.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.includeSubFolders.Label")); props.setLook(wlincludeSubFolders); fdlincludeSubFolders = new FormData(); fdlincludeSubFolders.left = new FormAttachment(0, 0); fdlincludeSubFolders.top = new FormAttachment(wSourceFileFoldername, margin); fdlincludeSubFolders.right = new FormAttachment(middle, -margin); wlincludeSubFolders.setLayoutData(fdlincludeSubFolders); wincludeSubFolders = new Button(wSourceGroup, SWT.CHECK); props.setLook(wincludeSubFolders); wincludeSubFolders.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.includeSubFolders.Tooltip")); fdincludeSubFolders = new FormData(); fdincludeSubFolders.left = new FormAttachment(middle, 0); fdincludeSubFolders.top = new FormAttachment(wSourceFileFoldername, margin); fdincludeSubFolders.right = new FormAttachment(100, 0); wincludeSubFolders.setLayoutData(fdincludeSubFolders); wincludeSubFolders.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); // Wildcard wlWildcard=new Label(wSourceGroup, SWT.RIGHT); wlWildcard.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Wildcard.Label")); props.setLook(wlWildcard); fdlWildcard=new FormData(); fdlWildcard.left = new FormAttachment(0, 0); fdlWildcard.top = new FormAttachment(wincludeSubFolders, margin); fdlWildcard.right= new FormAttachment(middle, -margin); wlWildcard.setLayoutData(fdlWildcard); wWildcard=new TextVar(jobMeta,wSourceGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wWildcard); wWildcard.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Wildcard.Tooltip")); wWildcard.addModifyListener(lsMod); fdWildcard=new FormData(); fdWildcard.left = new FormAttachment(middle, 0); fdWildcard.top = new FormAttachment(wincludeSubFolders, margin); fdWildcard.right= new FormAttachment(wbFileFoldername, -margin); wWildcard.setLayoutData(fdWildcard); // Whenever something changes, set the tooltip to the expanded version: wWildcard.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wWildcard.setToolTipText(jobMeta.environmentSubstitute( wWildcard.getText() ) ); } } ); // Delimiter wlDelimiter=new Label(wSourceGroup, SWT.RIGHT); wlDelimiter.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Delimiter.Label")); props.setLook(wlDelimiter); fdlDelimiter=new FormData(); fdlDelimiter.left = new FormAttachment(0, 0); fdlDelimiter.top = new FormAttachment(wWildcard, margin); fdlDelimiter.right= new FormAttachment(middle, -margin); wlDelimiter.setLayoutData(fdlDelimiter); wDelimiter=new TextVar(jobMeta,wSourceGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wDelimiter); wDelimiter.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Delimiter.Tooltip")); wDelimiter.addModifyListener(lsMod); fdDelimiter=new FormData(); fdDelimiter.left = new FormAttachment(middle, 0); fdDelimiter.top = new FormAttachment(wWildcard, margin); fdDelimiter.right= new FormAttachment(wbFileFoldername, -margin); wDelimiter.setLayoutData(fdDelimiter); // Whenever something changes, set the tooltip to the expanded version: wDelimiter.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wDelimiter.setToolTipText(jobMeta.environmentSubstitute( wDelimiter.getText() ) ); } } ); fdSourceGroup = new FormData(); fdSourceGroup.left = new FormAttachment(0, margin); fdSourceGroup.top = new FormAttachment(wName, margin); fdSourceGroup.right = new FormAttachment(100, -margin); wSourceGroup.setLayoutData(fdSourceGroup); // /////////////////////////////////////////////////////////// // / END OF Source GROUP // /////////////////////////////////////////////////////////// // //////////////////////// // START OF Target GROUP/// // / wTargetGroup = new Group(wGeneralComp, SWT.SHADOW_NONE); props.setLook(wTargetGroup); wTargetGroup.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.TargetGroup.Group.Label")); FormLayout TargetGroupgroupLayout = new FormLayout(); TargetGroupgroupLayout.marginWidth = 10; TargetGroupgroupLayout.marginHeight = 10; wTargetGroup.setLayout(TargetGroupgroupLayout); // Target Db name line wlTargetDbname=new Label(wTargetGroup, SWT.RIGHT); wlTargetDbname.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.TargetDbname.Label")); props.setLook(wlTargetDbname); fdlTargetDbname=new FormData(); fdlTargetDbname.left = new FormAttachment(0, 0); fdlTargetDbname.top = new FormAttachment(wSourceGroup, margin); fdlTargetDbname.right= new FormAttachment(middle, -margin); wlTargetDbname.setLayoutData(fdlTargetDbname); wbTargetDbname=new Button(wTargetGroup, SWT.PUSH| SWT.CENTER); props.setLook(wbTargetDbname); wbTargetDbname.setText(BaseMessages.getString(PKG, "System.Button.Browse")); fdbTargetDbname=new FormData(); fdbTargetDbname.right= new FormAttachment(100, 0); fdbTargetDbname.top = new FormAttachment(wSourceGroup, margin); wbTargetDbname.setLayoutData(fdbTargetDbname); wTargetDbname=new TextVar(jobMeta,wTargetGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wTargetDbname); wTargetDbname.addModifyListener(lsMod); fdTargetDbname=new FormData(); fdTargetDbname.left = new FormAttachment(middle, 0); fdTargetDbname.top = new FormAttachment(wSourceGroup, margin); fdTargetDbname.right= new FormAttachment(wbTargetDbname, -margin); wTargetDbname.setLayoutData(fdTargetDbname); // Whenever something changes, set the tooltip to the expanded version: wTargetDbname.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wTargetDbname.setToolTipText(jobMeta.environmentSubstitute( wTargetDbname.getText() ) ); } } ); wbTargetDbname.addSelectionListener ( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*"}); if (wTargetDbname.getText()!=null) { dialog.setFileName(jobMeta.environmentSubstitute(wTargetDbname.getText()) ); } dialog.setFilterNames(FILETYPES); if (dialog.open()!=null) { wTargetDbname.setText(dialog.getFilterPath()+Const.FILE_SEPARATOR+dialog.getFileName()); } } } ); // Tablename wlTablename=new Label(wTargetGroup, SWT.RIGHT); wlTablename.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Tablename.Label")); props.setLook(wlTablename); fdlTablename=new FormData(); fdlTablename.left = new FormAttachment(0, 0); fdlTablename.top = new FormAttachment(wTargetDbname, margin); fdlTablename.right= new FormAttachment(middle, -margin); wlTablename.setLayoutData(fdlTablename); wTablename=new TextVar(jobMeta,wTargetGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wTablename); wTablename.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Tablename.Tooltip")); wTablename.addModifyListener(lsMod); fdTablename=new FormData(); fdTablename.left = new FormAttachment(middle, 0); fdTablename.top = new FormAttachment(wTargetDbname, margin); fdTablename.right= new FormAttachment(wbTargetDbname, -margin); wTablename.setLayoutData(fdTablename); // Whenever something changes, set the tooltip to the expanded version: wTablename.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { wTablename.setToolTipText(jobMeta.environmentSubstitute( wTablename.getText() ) ); } } ); fdTargetGroup = new FormData(); fdTargetGroup.left = new FormAttachment(0, margin); fdTargetGroup.top = new FormAttachment(wSourceGroup, margin); fdTargetGroup.right = new FormAttachment(100, -margin); wTargetGroup.setLayoutData(fdTargetGroup); // /////////////////////////////////////////////////////////// // / END OF Target GROUP // /////////////////////////////////////////////////////////// // add button ... wbaEntry=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER); props.setLook(wbaEntry); wbaEntry.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FilenameAdd.Button")); wbaEntry.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FilenameAdd.Button.Tooltip")); fdbaEntry=new FormData(); fdbaEntry.left= new FormAttachment(0, 0); fdbaEntry.right= new FormAttachment(100, -margin); fdbaEntry.top = new FormAttachment(wTargetGroup, margin); wbaEntry.setLayoutData(fdbaEntry); // Buttons to the right of the screen... wbDelete=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER); props.setLook(wbDelete); wbDelete.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FilenameDelete.Button")); wbDelete.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FilenameDelete.Tooltip")); fdbdDelete=new FormData(); fdbdDelete.right = new FormAttachment(100, 0); fdbdDelete.top = new FormAttachment (wbaEntry, 10*margin); wbDelete.setLayoutData(fdbdDelete); wbEdit=new Button(wGeneralComp, SWT.PUSH| SWT.CENTER); props.setLook(wbEdit); wbEdit.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FilenameEdit.Button")); fdbeSourceFileFolder=new FormData(); fdbeSourceFileFolder.right = new FormAttachment(100, 0); fdbeSourceFileFolder.left = new FormAttachment(wbDelete, 0, SWT.LEFT); fdbeSourceFileFolder.top = new FormAttachment (wbDelete, margin); wbEdit.setLayoutData(fdbeSourceFileFolder); wlFields = new Label(wGeneralComp, SWT.NONE); wlFields.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.Label")); props.setLook(wlFields); fdlFields = new FormData(); fdlFields.left = new FormAttachment(0, 0); fdlFields.right= new FormAttachment(middle, -margin); fdlFields.top = new FormAttachment(wbaEntry,margin); wlFields.setLayoutData(fdlFields); int rows = jobEntry.source_filefolder == null ? 1 : (jobEntry.source_filefolder.length == 0 ? 0 : jobEntry.source_filefolder.length); final int FieldsRows = rows; ColumnInfo[] colinf=new ColumnInfo[] { new ColumnInfo(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.SourceFileFolder.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.Wildcard.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.FieldsDelimiter.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false ), new ColumnInfo(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.TargetDb.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.TargetTable.Label"), ColumnInfo.COLUMN_TYPE_TEXT, false ), }; colinf[0].setUsingVariables(true); colinf[0].setToolTip(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.SourceFileFolder.Tooltip")); colinf[1].setUsingVariables(true); colinf[1].setToolTip(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Fields.Wildcard.Tooltip")); colinf[2].setUsingVariables(true); colinf[2].setToolTip(BaseMessages.getString(PKG, "JobCopyFiles.Fields.FieldsDelimiter.Tooltip")); colinf[3].setUsingVariables(true); colinf[3].setToolTip(BaseMessages.getString(PKG, "JobCopyFiles.Fields.TargetDb.Tooltip")); colinf[4].setUsingVariables(true); colinf[4].setToolTip(BaseMessages.getString(PKG, "JobCopyFiles.Fields.TargetTable.Tooltip")); wFields = new TableView(jobMeta, wGeneralComp, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props); fdFields = new FormData(); fdFields.left = new FormAttachment(0, 0); fdFields.top = new FormAttachment(wlFields, margin); fdFields.right = new FormAttachment(wbDelete, -margin); fdFields.bottom = new FormAttachment(100, -margin); wFields.setLayoutData(fdFields); fdGeneralComp=new FormData(); fdGeneralComp.left = new FormAttachment(0, 0); fdGeneralComp.top = new FormAttachment(0, 0); fdGeneralComp.right = new FormAttachment(100, 0); fdGeneralComp.bottom= new FormAttachment(100, 0); wGeneralComp.setLayoutData(fdGeneralComp); wGeneralComp.layout(); wGeneralTab.setControl(wGeneralComp); props.setLook(wGeneralComp); ///////////////////////////////////////////////////////////// /// END OF GENERAL TAB ///////////////////////////////////////////////////////////// ////////////////////////// // START OF ADVANCED TAB /// ////////////////////////// wAdvancedTab=new CTabItem(wTabFolder, SWT.NONE); wAdvancedTab.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.Tab.Advanced.Label")); wAdvancedComp = new Composite(wTabFolder, SWT.NONE); props.setLook(wAdvancedComp); FormLayout advancedLayout = new FormLayout(); advancedLayout.marginWidth = 3; advancedLayout.marginHeight = 3; wAdvancedComp.setLayout(generalLayout); // SuccessOngrouping? // //////////////////////// // START OF SUCCESS ON GROUP/// // / wSuccessOn= new Group(wAdvancedComp, SWT.SHADOW_NONE); props.setLook(wSuccessOn); wSuccessOn.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.SuccessOn.Group.Label")); FormLayout successongroupLayout = new FormLayout(); successongroupLayout.marginWidth = 10; successongroupLayout.marginHeight = 10; wSuccessOn.setLayout(successongroupLayout); //Success Condition wlSuccessCondition = new Label(wSuccessOn, SWT.RIGHT); wlSuccessCondition.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.SuccessCondition.Label")); props.setLook(wlSuccessCondition); fdlSuccessCondition = new FormData(); fdlSuccessCondition.left = new FormAttachment(0, 0); fdlSuccessCondition.right = new FormAttachment(middle, 0); fdlSuccessCondition.top = new FormAttachment(0, margin); wlSuccessCondition.setLayoutData(fdlSuccessCondition); wSuccessCondition = new CCombo(wSuccessOn, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); wSuccessCondition.add(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.SuccessWhenAllWorksFine.Label")); wSuccessCondition.add(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.SuccessWhenAtLeat.Label")); wSuccessCondition.add(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.SuccessWhenErrorsLessThan.Label")); wSuccessCondition.select(0); // +1: starts at -1 props.setLook(wSuccessCondition); fdSuccessCondition= new FormData(); fdSuccessCondition.left = new FormAttachment(middle, 0); fdSuccessCondition.top = new FormAttachment(0, margin); fdSuccessCondition.right = new FormAttachment(100, 0); wSuccessCondition.setLayoutData(fdSuccessCondition); wSuccessCondition.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { activeSuccessCondition(); } }); // Success when number of errors less than wlNrErrorsLessThan= new Label(wSuccessOn, SWT.RIGHT); wlNrErrorsLessThan.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.NrErrorsLessThan.Label")); props.setLook(wlNrErrorsLessThan); fdlNrErrorsLessThan= new FormData(); fdlNrErrorsLessThan.left = new FormAttachment(0, 0); fdlNrErrorsLessThan.top = new FormAttachment(wSuccessCondition, margin); fdlNrErrorsLessThan.right = new FormAttachment(middle, -margin); wlNrErrorsLessThan.setLayoutData(fdlNrErrorsLessThan); wNrErrorsLessThan= new TextVar(jobMeta,wSuccessOn, SWT.SINGLE | SWT.LEFT | SWT.BORDER, BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.NrErrorsLessThan.Tooltip")); props.setLook(wNrErrorsLessThan); wNrErrorsLessThan.addModifyListener(lsMod); fdNrErrorsLessThan= new FormData(); fdNrErrorsLessThan.left = new FormAttachment(middle, 0); fdNrErrorsLessThan.top = new FormAttachment(wSuccessCondition, margin); fdNrErrorsLessThan.right = new FormAttachment(100, -margin); wNrErrorsLessThan.setLayoutData(fdNrErrorsLessThan); fdSuccessOn= new FormData(); fdSuccessOn.left = new FormAttachment(0, margin); fdSuccessOn.top = new FormAttachment(0, margin); fdSuccessOn.right = new FormAttachment(100, -margin); wSuccessOn.setLayoutData(fdSuccessOn); // /////////////////////////////////////////////////////////// // / END OF Success ON GROUP // /////////////////////////////////////////////////////////// // fileresult grouping? // //////////////////////// // START OF LOGGING GROUP/// // / wFileResult = new Group(wAdvancedComp, SWT.SHADOW_NONE); props.setLook(wFileResult); wFileResult.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.FileResult.Group.Label")); FormLayout fileresultgroupLayout = new FormLayout(); fileresultgroupLayout.marginWidth = 10; fileresultgroupLayout.marginHeight = 10; wFileResult.setLayout(fileresultgroupLayout); //Add file to result wlAddFileToResult = new Label(wFileResult, SWT.RIGHT); wlAddFileToResult.setText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.AddFileToResult.Label")); props.setLook(wlAddFileToResult); fdlAddFileToResult = new FormData(); fdlAddFileToResult.left = new FormAttachment(0, 0); fdlAddFileToResult.top = new FormAttachment(wSuccessOn, margin); fdlAddFileToResult.right = new FormAttachment(middle, -margin); wlAddFileToResult.setLayoutData(fdlAddFileToResult); wAddFileToResult = new Button(wFileResult, SWT.CHECK); props.setLook(wAddFileToResult); wAddFileToResult.setToolTipText(BaseMessages.getString(PKG, "JobEntryMSAccessBulkLoad.AddFileToResult.Tooltip")); fdAddFileToResult = new FormData(); fdAddFileToResult.left = new FormAttachment(middle, 0); fdAddFileToResult.top = new FormAttachment(wSuccessOn, margin); fdAddFileToResult.right = new FormAttachment(100, 0); wAddFileToResult.setLayoutData(fdAddFileToResult); wAddFileToResult.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { jobEntry.setChanged(); } }); fdFileResult = new FormData(); fdFileResult.left = new FormAttachment(0, margin); fdFileResult.top = new FormAttachment(wSuccessOn, margin); fdFileResult.right = new FormAttachment(100, -margin); wFileResult.setLayoutData(fdFileResult); // /////////////////////////////////////////////////////////// // / END OF FilesRsult GROUP // /////////////////////////////////////////////////////////// fdAdvancedComp=new FormData(); fdAdvancedComp.left = new FormAttachment(0, 0); fdAdvancedComp.top = new FormAttachment(0, 0); fdAdvancedComp.right = new FormAttachment(100, 0); fdAdvancedComp.bottom= new FormAttachment(100, 0); wAdvancedComp.setLayoutData(fdGeneralComp); wAdvancedComp.layout(); wAdvancedTab.setControl(wAdvancedComp); props.setLook(wAdvancedComp); ///////////////////////////////////////////////////////////// /// END OF ADVANCED TAB ///////////////////////////////////////////////////////////// fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.top = new FormAttachment(wName, margin); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.bottom= new FormAttachment(100, -50); wTabFolder.setLayoutData(fdTabFolder); // Add the file to the list of files... SelectionAdapter selA = new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { wFields.add(new String[] { wSourceFileFoldername.getText(), wWildcard.getText(), wDelimiter.getText(), wTargetDbname.getText(),wTablename.getText() } ); wSourceFileFoldername.setText(""); wWildcard.setText(""); wDelimiter.setText(""); wTargetDbname.setText(""); wTablename.setText(""); wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); } }; wbaEntry.addSelectionListener(selA); wSourceFileFoldername.addSelectionListener(selA); // Delete files from the list of files... wbDelete.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { int idx[] = wFields.getSelectionIndices(); wFields.remove(idx); wFields.removeEmptyRows(); wFields.setRowNums(); } }); // Edit the selected file & remove from the list... wbEdit.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { int idx = wFields.getSelectionIndex(); if (idx>=0) { String string[] = wFields.getItem(idx); wSourceFileFoldername.setText(string[0]); wWildcard.setText(string[1]); wDelimiter.setText(string[2]); wTargetDbname.setText(string[3]); wTablename.setText(string[4]); wFields.remove(idx); } wFields.removeEmptyRows(); wFields.setRowNums(); } }); wOK = new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); wCancel = new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, wTabFolder); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; wCancel.addListener(SWT.Selection, lsCancel); wOK.addListener (SWT.Selection, lsOK ); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wName.addSelectionListener( lsDef ); wSourceFileFoldername.addSelectionListener( lsDef ); wTargetDbname.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); getData(); activeSuccessCondition(); RefreshArgFromPrevious(); wTabFolder.setSelection(0); BaseStepDialog.setSize(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return jobEntry; } private void RefreshArgFromPrevious() { wlFields.setEnabled(!wPrevious.getSelection()); wFields.setEnabled(!wPrevious.getSelection()); wbSourceFolder.setEnabled(!wPrevious.getSelection()); wSourceFileFoldername.setEnabled(!wPrevious.getSelection()); wlTargetDbname.setEnabled(!wPrevious.getSelection()); wTargetDbname.setEnabled(!wPrevious.getSelection()); wTablename.setEnabled(!wPrevious.getSelection()); wlTablename.setEnabled(!wPrevious.getSelection()); wbTargetDbname.setEnabled(!wPrevious.getSelection()); wbEdit.setEnabled(!wPrevious.getSelection()); wincludeSubFolders.setEnabled(!wPrevious.getSelection()); wlincludeSubFolders.setEnabled(!wPrevious.getSelection()); wbDelete.setEnabled(!wPrevious.getSelection()); wbaEntry.setEnabled(!wPrevious.getSelection()); wbFileFoldername.setEnabled(!wPrevious.getSelection()); wlWildcard.setEnabled(!wPrevious.getSelection()); wWildcard.setEnabled(!wPrevious.getSelection()); wlDelimiter.setEnabled(!wPrevious.getSelection()); wDelimiter.setEnabled(!wPrevious.getSelection()); WSourceFileFoldername.setEnabled(!wPrevious.getSelection()); } public void dispose() { WindowProperty winprop = new WindowProperty(shell); props.setScreen(winprop); shell.dispose(); } private void activeSuccessCondition() { wlNrErrorsLessThan.setEnabled(wSuccessCondition.getSelectionIndex()!=0); wNrErrorsLessThan.setEnabled(wSuccessCondition.getSelectionIndex()!=0); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { if (jobEntry.getName() != null) wName.setText( jobEntry.getName() ); wName.selectAll(); wAddFileToResult.setSelection(jobEntry.isAddResultFilename()); wincludeSubFolders.setSelection(jobEntry.isIncludeSubFoders()); wPrevious.setSelection(jobEntry.isArgsFromPrevious()); if (jobEntry.source_filefolder != null) { for (int i = 0; i < jobEntry.source_filefolder.length; i++) { TableItem ti = wFields.table.getItem(i); if (jobEntry.source_filefolder[i] != null) ti.setText(1, jobEntry.source_filefolder[i]); if (jobEntry.source_wildcard[i] != null) ti.setText(2, jobEntry.source_wildcard[i]); if (jobEntry.delimiter[i] != null) ti.setText(3, jobEntry.delimiter[i]); if (jobEntry.target_Db[i] != null) ti.setText(4, jobEntry.target_Db[i]); if (jobEntry.target_table[i] != null) ti.setText(5, jobEntry.target_table[i]); } wFields.setRowNums(); wFields.optWidth(true); } if (jobEntry.getLimit()!= null) wNrErrorsLessThan.setText( jobEntry.getLimit() ); else wNrErrorsLessThan.setText("10"); if(jobEntry.getSuccessCondition()!=null) { if(jobEntry.getSuccessCondition().equals(jobEntry.SUCCESS_IF_AT_LEAST)) wSuccessCondition.select(1); else if(jobEntry.getSuccessCondition().equals(jobEntry.SUCCESS_IF_ERRORS_LESS)) wSuccessCondition.select(2); else wSuccessCondition.select(0); }else wSuccessCondition.select(0); } private void cancel() { jobEntry.setChanged(changed); jobEntry=null; dispose(); } private void ok() { if(Const.isEmpty(wName.getText())) { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR ); mb.setText(BaseMessages.getString(PKG, "System.StepJobEntryNameMissing.Title")); mb.setMessage(BaseMessages.getString(PKG, "System.JobEntryNameMissing.Msg")); mb.open(); return; } jobEntry.setName(wName.getText()); jobEntry.setAddResultFilenames(wAddFileToResult.getSelection()); jobEntry.setIncludeSubFoders(wincludeSubFolders.getSelection()); jobEntry.setArgsFromPrevious(wPrevious.getSelection()); int nritems = wFields.nrNonEmpty(); int nr = 0; for (int i = 0; i < nritems; i++) { String arg = wFields.getNonEmpty(i).getText(1); if (arg != null && arg.length() != 0) nr++; } jobEntry.source_filefolder = new String[nr]; jobEntry.source_wildcard = new String[nr]; jobEntry.delimiter = new String[nr]; jobEntry.target_Db= new String[nr]; jobEntry.target_table = new String[nr]; nr = 0; for (int i = 0; i < nritems; i++) { String source = wFields.getNonEmpty(i).getText(1); String wild = wFields.getNonEmpty(i).getText(2); String delimiter = wFields.getNonEmpty(i).getText(3); String destdb = wFields.getNonEmpty(i).getText(4); String desttable = wFields.getNonEmpty(i).getText(5); if (source != null && source.length() != 0) { jobEntry.source_filefolder[nr] = source; jobEntry.source_wildcard[nr] = wild; jobEntry.delimiter[nr] = delimiter; jobEntry.target_Db[nr] = destdb; jobEntry.target_table[nr] = desttable; nr++; } } jobEntry.setLimit(wNrErrorsLessThan.getText()); if(wSuccessCondition.getSelectionIndex()==1) jobEntry.setSuccessCondition(jobEntry.SUCCESS_IF_AT_LEAST); else if(wSuccessCondition.getSelectionIndex()==2) jobEntry.setSuccessCondition(jobEntry.SUCCESS_IF_ERRORS_LESS); else jobEntry.setSuccessCondition(jobEntry.SUCCESS_IF_NO_ERRORS); dispose(); } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } }
// Copyright 2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.util; import com.google.common.base.Preconditions; import com.google.devtools.build.lib.vfs.FileSystemUtils; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.IOException; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Representation of a set of file dependencies for a given output file. There * are generally one input dependency and a bunch of include dependencies. The * files are stored as {@code PathFragment}s and may be relative or absolute. * <p> * The serialized format read and written is equivalent and compatible with the * ".d" file produced by the -MM for a given out (.o) file. * <p> * The file format looks like: * * <pre> * {outfile}: \ * {infile} \ * {include} \ * ... \ * {include} * </pre> * * @see "http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Preprocessor-Options.html#Preprocessor-Options" */ public final class DependencySet { private static final Pattern DOTD_MERGED_LINE_SEPARATOR = Pattern.compile("\\\\[\n\r]+"); private static final Pattern DOTD_LINE_SEPARATOR = Pattern.compile("[\n\r]+"); private static final Pattern DOTD_DEP = Pattern.compile("(?:[^\\s\\\\]++|\\\\ |\\\\)+"); /** * The set of dependent files that this DependencySet embodies. May be * relative or absolute PathFragments. A tree set is used to ensure that we * write them out in a consistent order. */ private final Collection<PathFragment> dependencies = new ArrayList<>(); private final Path root; private String outputFileName; /** * Get output file name for which dependencies are included in this DependencySet. */ public String getOutputFileName() { return outputFileName; } public void setOutputFileName(String outputFileName) { this.outputFileName = outputFileName; } /** * Constructs a new empty DependencySet instance. */ public DependencySet(Path root) { this.root = root; } /** * Gets an unmodifiable view of the set of dependencies in PathFragment form * from this DependencySet instance. */ public Collection<PathFragment> getDependencies() { return Collections.unmodifiableCollection(dependencies); } /** * Adds a given collection of dependencies in Path form to this DependencySet * instance. Paths are converted to root-relative */ public void addDependencies(Collection<Path> deps) { for (Path d : deps) { addDependency(d.relativeTo(root)); } } /** * Adds a given dependency in PathFragment form to this DependencySet * instance. */ public void addDependency(PathFragment dep) { dependencies.add(Preconditions.checkNotNull(dep)); } /** * Reads a dotd file into this DependencySet instance. */ public DependencySet read(Path dotdFile) throws IOException { return process(FileSystemUtils.readContent(dotdFile)); } /** * Parses a .d file. * * <p>Performance-critical! In large C++ builds there are lots of .d files to read, and some of * them reach into hundreds of kilobytes. */ public DependencySet process(byte[] content) { // true if there is a CR in the input. boolean cr = content.length > 0 && content[0] == '\r'; // true if there is more than one line in the input, not counting \-wrapped lines. boolean multiline = false; byte prevByte = ' '; for (int i = 1; i < content.length; i++) { byte b = content[i]; if (cr || b == '\r') { // CR found, abort since our little loop here does not deal with CR/LFs. cr = true; break; } if (b == '\n') { // Merge lines wrapped using backslashes. if (prevByte == '\\') { content[i] = ' '; content[i - 1] = ' '; } else { multiline = true; } } prevByte = b; } if (!cr && content.length > 0 && content[content.length - 1] == '\n') { content[content.length - 1] = ' '; } String s = new String(content, StandardCharsets.UTF_8); if (cr) { s = DOTD_MERGED_LINE_SEPARATOR.matcher(s).replaceAll(" ").trim(); multiline = true; } return process(s, multiline); } private DependencySet process(String contents, boolean multiline) { String[] lines; if (!multiline) { // Microoptimization: skip the usually unnecessary expensive-ish splitting step if there is // only one target. This saves about 20% of CPU time. lines = new String[] { contents }; } else { lines = DOTD_LINE_SEPARATOR.split(contents); } for (String line : lines) { // Split off output file name. int pos = line.indexOf(':'); if (pos == -1) { continue; } outputFileName = line.substring(0, pos); String deps = line.substring(pos + 1); Matcher m = DOTD_DEP.matcher(deps); while (m.find()) { String token = m.group(); // Process escaped spaces. if (token.contains("\\ ")) { token = token.replace("\\ ", " "); } dependencies.add(new PathFragment(token).normalize()); } } return this; } /** * Writes this DependencySet object for a specified output file under the root * dir, and with a given suffix. */ public void write(Path outFile, String suffix) throws IOException { Path dotdFile = outFile.getRelative(FileSystemUtils.replaceExtension(outFile.asFragment(), suffix)); PrintStream out = new PrintStream(dotdFile.getOutputStream()); try { out.print(outFile.relativeTo(root) + ": "); for (PathFragment d : dependencies) { out.print(" \\\n " + d.getPathString()); // should already be root relative } out.println(); } finally { out.close(); } } @Override public boolean equals(Object other) { return other instanceof DependencySet && ((DependencySet) other).dependencies.equals(dependencies); } @Override public int hashCode() { return dependencies.hashCode(); } }
package algs.model.tests.kdtree; import java.util.Iterator; import junit.framework.TestCase; import org.junit.Test; import algs.model.IMultiPoint; import algs.model.kdtree.*; import algs.model.nd.Hypercube; import algs.model.problems.nearestNeighbor.BruteForceNearestNeighbor; import algs.model.twod.*; /** These are nothing more than the TwoDTests converted to using KD trees. */ public class KDTest extends TestCase { // use for all max dimensions. int maxDimension = 2; /** * Validate RectangularRegion. */ @Test public void testRectangularRegion () { TwoDRectangle rr = new TwoDRectangle(10, 10, 300, 153); assertEquals ("[10.0,10.0 : 300.0,153.0]", rr.toString()); assertFalse (rr.equals("slkdjlds")); assertTrue (rr.equals (rr)); assertFalse (rr.equals(null)); } /** * Validate the structure of KDNode trees, with alternating levels. */ @Test public void testStructure () { DimensionalNode hn = new DimensionalNode (1, new TwoDPoint (100, 100)); DimensionalNode hn2 = new DimensionalNode(1,new TwoDPoint (100, 253)); DimensionalNode vn = new DimensionalNode (2,new TwoDPoint (90, 120)); DimensionalNode vn2 = new DimensionalNode(2,new TwoDPoint (110, 230)); try { hn.setBelow(hn2); fail ("Structure of KDTree can be compromised."); } catch (IllegalArgumentException iae) { } try { hn.setAbove(hn2); fail ("Structure of KDTree can be compromised."); } catch (IllegalArgumentException iae) { } try { vn.setBelow(vn2); fail ("Structure of KDTree can be compromised."); } catch (IllegalArgumentException iae) { } try { vn.setAbove(vn2); fail ("Structure of KDTree can be compromised."); } catch (IllegalArgumentException iae) { } // allowed [These only check the proper types are allowed. This actually // produces a cyclic tree...] hn.setBelow (vn); vn.setBelow (hn2); hn.setAbove (vn2); vn2.setAbove (hn); } @Test public void testKDPoint() { TwoDPoint pt = new TwoDPoint(10,30); assertEquals (10.0, pt.getX()); assertEquals (30.0, pt.getY()); // probe equals TwoDPoint pt2 = new TwoDPoint(10,30); assertEquals (pt, pt2); assertEquals (pt2, pt); assertFalse (pt.equals("SDS")); assertFalse (pt.equals(null)); } @Test public void testHorizontalNode() { DimensionalNode n = new DimensionalNode(2, new TwoDPoint (200, 153)); assertEquals (2, n.dimension); assertTrue (n.isBelow(new TwoDPoint(10,10))); assertFalse (n.isBelow(new TwoDPoint(10,330))); } @Test public void testRootSetter() { // just here for closure. KDTree tt = new KDTree(2); DimensionalNode n = new DimensionalNode(1, new TwoDPoint (90, 120)); tt.setRoot(n); assertEquals (new TwoDPoint (90,120), tt.getRoot().point); // allow for null. tt.setRoot(null); assertTrue (null == tt.getRoot()); assertEquals (0, tt.count()); } @Test public void testVerticalNode() { DimensionalNode n2, n3; DimensionalNode n = new DimensionalNode(1, new TwoDPoint (90, 120)); assertEquals (n.dimension, 1); assertTrue (n.isBelow(new TwoDPoint(10,10))); // means to the left assertFalse (n.isBelow(new TwoDPoint(210,330))); // to the right //IHypercube space = new Hypercube (10, 300, 10, 300); // split vertical node 'below' (i.e., to the left) n = new DimensionalNode(1, new TwoDPoint (90, 120)); n2 = new DimensionalNode(2, new TwoDPoint (10, 300)); n.setBelow(n2); assertEquals (new Hypercube (Double.NEGATIVE_INFINITY, 90, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), n2.region()); // split vertical node 'above' (i.e., to the right) n = new DimensionalNode(1, new TwoDPoint (90, 120)); n2 = new DimensionalNode(2, new TwoDPoint (300, 300)); n.setAbove(n2); assertEquals (new Hypercube (90, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), n2.region()); n = new DimensionalNode(1, new TwoDPoint (90, 120)); n2 = new DimensionalNode(2, new TwoDPoint (300, 300)); n.setAbove(n2); n3 = new DimensionalNode(1, new TwoDPoint (120, 400)); n2.setAbove(n3); assertEquals (new Hypercube (90, Double.POSITIVE_INFINITY, 300.0, Double.POSITIVE_INFINITY), n3.region()); n = new DimensionalNode(1, new TwoDPoint (90, 120)); n2 = new DimensionalNode(2, new TwoDPoint (300, 300)); n.setAbove(n2); n3 = new DimensionalNode(1, new TwoDPoint (120, 200)); n2.setBelow(n3); assertEquals (new Hypercube (90, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 300.0), n3.region()); } @Test public void testExceptions () { try { new KDTree(-2); fail ("KDTree constructor fails to check for proper parameters."); } catch (IllegalArgumentException iae) { } try { new KDTree(0); fail ("KDTree constructor fails to check for proper parameters."); } catch (IllegalArgumentException iae) { } KDTree tt = new KDTree(2); try { tt.insert(null); fail ("KDTree insert fails to detect null"); } catch (IllegalArgumentException iae) { } } @Test public void testVariety() { KDTree tt = new KDTree(2); assertEquals (2, tt.maxDimension); tt.insert(new TwoDPoint (200, 153)); DimensionalNode root = tt.getRoot(); assertEquals (1, root.dimension); assertEquals (2, tt.nextDimension(root)); assertEquals (2, tt.nextDimension(1)); assertEquals (1, tt.nextDimension(2)); final StringBuilder empRecord = new StringBuilder(); Hypercube hc = new Hypercube (Integer.MIN_VALUE,Integer.MAX_VALUE,Integer.MIN_VALUE,Integer.MAX_VALUE); IVisitKDNode visitor = new IVisitKDNode() { public void visit(DimensionalNode node) { empRecord.append ("*"); } public void drain(DimensionalNode node) { empRecord.append ("+"); } }; tt.range(hc, visitor); assertEquals ("*", empRecord.toString()); tt.removeAll(); // ensure none left. empRecord.delete(0, empRecord.length()); tt.range(hc, visitor); assertEquals ("", empRecord.toString()); } @Test public void testNearest() { KDTree tt = new KDTree(2); IMultiPoint p1, p2, p3, p4; tt.insert(p1 = new TwoDPoint (100, 100)); tt.insert(p2 = new TwoDPoint (-100, 100)); tt.insert(p3 = new TwoDPoint (100, -100)); tt.insert(p4 = new TwoDPoint (-100, -100)); BruteForceNearestNeighbor bfnn = new BruteForceNearestNeighbor (new IMultiPoint[]{p1,p2,p3,p4}); // right in the middle! All four are the same distance. IMultiPoint p0 = new TwoDPoint (0,0); IMultiPoint near = tt.nearest(p0); assertTrue (near == p1 || near == p2 || near == p3 || near == p4); // no point checking whether result of bfnn is same as tt since // any of the above four could be the closest... // clearly one. assertEquals (p1, tt.nearest (p1)); assertEquals (p2, tt.nearest (p2)); assertEquals (p3, tt.nearest (p3)); assertEquals (p4, tt.nearest (p4)); assertEquals (p1, bfnn.nearest (p1)); assertEquals (p2, bfnn.nearest (p2)); assertEquals (p3, bfnn.nearest (p3)); assertEquals (p4, bfnn.nearest (p4)); assertEquals (p1, tt.nearest (new TwoDPoint(1,1))); assertEquals (p3, tt.nearest (new TwoDPoint(1,-1))); assertEquals (p4, tt.nearest (new TwoDPoint(-1,-1))); assertEquals (p2, tt.nearest (new TwoDPoint(-1,1))); assertEquals (p1, bfnn.nearest (new TwoDPoint(1,1))); assertEquals (p3, bfnn.nearest (new TwoDPoint(1,-1))); assertEquals (p4, bfnn.nearest (new TwoDPoint(-1,-1))); assertEquals (p2, bfnn.nearest (new TwoDPoint(-1,1))); } @Test public void testNearestExceptions() { try { new BruteForceNearestNeighbor (null); fail ("must disallow brute force on null"); } catch (IllegalArgumentException npe) { } try { new BruteForceNearestNeighbor (new IMultiPoint[]{}); fail ("must disallow brute force on empty points"); } catch (IllegalArgumentException npe) { } } @Test public void testParent() { KDTree tt = new KDTree(2); try { tt.parent(null); fail ("KDTree fails to prevent parent of null"); } catch (IllegalArgumentException e) { } assertNull (tt.parent(new TwoDPoint (200, 153))); IMultiPoint p1 = new TwoDPoint (100, 100); IMultiPoint p2 = new TwoDPoint (80, 90); IMultiPoint p3 = new TwoDPoint (120, 180); IMultiPoint p4 = new TwoDPoint (70, 110); IMultiPoint p5 = new TwoDPoint (220, 110); IMultiPoint p6 = new TwoDPoint (20, 20); // not inserted IMultiPoint p7 = new TwoDPoint (300, 160); // not inserted tt.insert(p1); assertEquals (p1, tt.parent(p2).point); assertEquals (p1, tt.parent(p3).point); tt.insert(p2); tt.insert(p3); assertEquals (p2, tt.parent (p4).point); assertEquals (p3, tt.parent (p5).point); assertEquals (p2, tt.parent (p6).point); assertEquals (p3, tt.parent (p7).point); tt.insert(p4); tt.insert(p5); assertEquals (p5, tt.parent (p7).point); // show working count. CounterKDTree cdt = new CounterKDTree(); assertEquals (0, cdt.getCount()); Hypercube space = new Hypercube (Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY); tt.range(space, cdt); assertEquals (5, cdt.getCount()); cdt.reset(); assertEquals (0, cdt.getCount()); tt.range(new Hypercube (60,80, 100,120), cdt); assertEquals (1, cdt.getCount()); // deal with traversal. final StringBuffer sb = new StringBuffer(); KDTraversal kdt = new KDTraversal(tt) { public void visit(DimensionalNode node) { sb.append("*"); } }; kdt.traverse(); assertEquals ("*****", sb.toString()); // validate drain does NOTHING. kdt.drain(null); // grab one intermediate node DimensionalNode inter = tt.getRoot().getAbove(); sb.setLength(0); kdt = new KDTraversal(tt, inter) { public void visit(DimensionalNode node) { sb.append("*"); } }; kdt.traverse(); assertEquals ("**", sb.toString()); // bad test sb.setLength(0); kdt = new KDTraversal(tt, null) { public void visit(DimensionalNode node) { sb.append("*"); } }; kdt.traverse(); assertEquals (0, sb.length()); } @Test public void testSample () { KDTree tt = new KDTree(2); // quick simple boundary cases... assertEquals (0, tt.count()); assertEquals (0, tt.height()); assertEquals ("", tt.toString()); // perform null search on empty tree Iterator<IMultiPoint> empResults = tt.range(new Hypercube (0,2,0,2)); int count = 0; while (empResults.hasNext()) { count++; empResults.next(); } assertEquals (0, count); final StringBuilder empRecord = new StringBuilder(); tt.range(new Hypercube (79,81,143,145), new IVisitKDNode() { public void visit(DimensionalNode node) { empRecord.append ("*"); } public void drain(DimensionalNode node) { empRecord.append ("+"); } }); assertEquals ("", empRecord.toString()); // construct tree in top-down fashion tt.insert(new TwoDPoint (200, 153)); assertNotNull(tt.getRoot()); assertEquals (new TwoDPoint (200, 153), tt.getRoot().point); tt.insert(new TwoDPoint (180, 133)); tt.insert(new TwoDPoint (245, 120)); tt.insert(new TwoDPoint (120, 80)); tt.insert(new TwoDPoint (80, 144)); tt.insert(new TwoDPoint (210, 40)); tt.insert(new TwoDPoint (238, 150)); tt.insert(new TwoDPoint (195, 30)); tt.insert(new TwoDPoint (190, 140)); tt.insert(new TwoDPoint (230, 90)); tt.insert(new TwoDPoint (250, 148)); assertEquals ("1:<120.0,80.0>2:<195.0,30.0>2:<180.0,133.0>1:<80.0,144.0>2:<190.0,140.0>1:<200.0,153.0>1:<210.0,40.0>2:<230.0,90.0>2:<245.0,120.0>1:<238.0,150.0>2:<250.0,148.0>", tt.toString()); // check count and heights assertEquals (11, tt.count()); assertEquals (4, tt.height()); // do empty query Iterator<IMultiPoint> results = tt.range(new Hypercube (0,2,0,2)); assertEquals (false, results.hasNext()); // try one by itself results = tt.range(new Hypercube (79,81,143,145)); count = 0; while (results.hasNext()) { count++; results.next(); } assertEquals (1, count); // try all by itself results = tt.range(new Hypercube (Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); count = 0; while (results.hasNext()) { count++; results.next(); } assertEquals (11, count); // validate catch attempts to modify iterator. results = tt.range(new Hypercube (Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)); KDSearchResults sr = (KDSearchResults) results; count = 0; while (sr.hasNext()) { count++; // must fail try { sr.add(new TwoDPoint(0,0)); fail ("Shouldn't be able to add points once iteration starts."); } catch (java.util.ConcurrentModificationException cme) { } // must fail try { sr.remove(); fail ("Shouldn't be able to remove points once iteration starts."); } catch (UnsupportedOperationException uoe) { } // must fail try { DimensionalNode tdn = new DimensionalNode(1, new TwoDPoint(0,0)); sr.add(tdn); fail ("Shouldn't be able to remove points once iteration starts."); } catch (java.util.ConcurrentModificationException cme) { } sr.next(); } assertEquals (11, count); // try more complex search. final StringBuilder record = new StringBuilder(""); tt.range(new Hypercube (79,81,143,145), new IVisitKDNode() { public void visit(DimensionalNode node) { record.append ("*"); } public void drain(DimensionalNode node) { record.append ("+"); } }); assertEquals ("*", record.toString()); // this will DRAIN all of the nodes... record.setLength(0); tt.range(new Hypercube (Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY), new IVisitKDNode() { public void visit(DimensionalNode node) { record.append ("*"); } public void drain(DimensionalNode node) { record.append ("+"); } }); assertEquals ("+++++++++++", record.toString()); } @Test public void testInspections () { KDTree tt = new KDTree(2); // construct tree in top-down fashion tt.insert(new TwoDPoint (200, 153)); tt.insert(new TwoDPoint (180, 133)); tt.insert(new TwoDPoint (245, 120)); tt.insert(new TwoDPoint (180, 133)); tt.insert(new TwoDPoint (245, 120)); tt.insert(new TwoDPoint (120, 80)); tt.insert(new TwoDPoint (80, 144)); // THE ONE found. tt.insert(new TwoDPoint (210, 40)); tt.insert(new TwoDPoint (238, 150)); tt.insert(new TwoDPoint (195, 30)); tt.insert(new TwoDPoint (190, 140)); tt.insert(new TwoDPoint (230, 90)); tt.insert(new TwoDPoint (250, 148)); // add more to get some internal nodes that are fully defined without Infinity tt.insert(new TwoDPoint (60, 80)); tt.insert(new TwoDPoint (65, 75)); tt.insert(new TwoDPoint (200, 40)); tt.insert(new TwoDPoint (200, 200)); tt.insert(new TwoDPoint (140, 80)); // place a lot of poinst in this region (120,80) -- (200,133) to ensure drain of subtrees. tt.insert(new TwoDPoint (130, 110)); tt.insert(new TwoDPoint (137, 113)); tt.insert(new TwoDPoint (197, 99)); tt.insert(new TwoDPoint (197, 91)); tt.insert(new TwoDPoint (167, 120)); // Infer node properties from region tt.range(new Hypercube (79,343,77,165), new IVisitKDNode() { public void visit(DimensionalNode node) { // find leaves if (node.isLeaf()) { assertTrue (node.getAbove() == null); assertTrue (node.getBelow() == null); } } public void drain(DimensionalNode node) {} }); } }
/* * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* @test @bug 6479820 @summary verify that after Alt+Space resizing/moving the correct event gets generated. @author Andrei Dmitriev: area=awt.event @run main/manual SpuriousExitEnter_2 */ /** * SpuriousExitEnter_2.java * There is a JFrame with a JButton in it (Lightweight) and a Frame with a Button in it (Heavyweight). * Testcases diveded into two similar activities: first with JFrame and second with Frame. */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SpuriousExitEnter_2 { static JFrame frame = new JFrame("SpuriousExitEnter_2(LW)"); static JButton jbutton = new JButton("jbutton"); static Frame frame1 = new Frame("SpuriousExitEnter_2 (HW)"); static Button button1 = new Button("button"); private static void init() { String[] instructions = { "You see a plain JFrame with JButton in it and Frame with Button in it.", " Following steps should be accomplished for both of them (for Frame and for JFrame).", " If any of the following ", " third steps fails, press Fail.", " Let A area is the area inside Button.", " Let B area is the area inside Frame but not inside Button.", " Let C area is the area outside Frame.", " Stage 1:", " 1) Put the mouse pointer into A area.", " 2) Press Alt+Space (or other sequence opening the system menu from the top-left corner) ", " and resize the Frame so the pointer remains in A.", " 3) Press Enter key. No event should be fired.", " Stage 2:", " Repeat Stage 1 with area B.", " Stage 3:", " Repeat Stage 1 with area C.", " Stage 4:", " 1) Put the mouse pointer into A area.", " 2) Press Alt+Space and resize the Frame so the pointer becomes in B.", " 3) Press Enter key. Exited event on Button and Entered event on Frame should be fired.", " Stage 5:", " 1) Put the mouse pointer into A area.", " 2) Press Alt+Space and resize the Frame so the pointer becomes in C.", " 3) Press Enter key. Exited event on Button should be fired.", " Stage 6:", " 1) Put the mouse pointer into B area.", " 2) Press Alt+Space and resize the Frame so the pointer becomes in A.", " 3) Press Enter key. Exited event on Frame and Entered event on Button should be fired.", " Stage 7:", " 1) Put the mouse pointer into B area.", " 2) Press Alt+Space and resize the Frame so the pointer becomes in C.", " 3) Press Enter key. Exited event on Frame should be fired.", " Stage 8:", " 1) Put the mouse pointer into C area.", " 2) Press Alt+Space and resize the Frame so the pointer becomes in A.", " 3) Press Enter key. Entered event on Button should be fired.", " Stage 9:", " 1) Put the mouse pointer into C area.", " 2) Press Alt+Space and resize the Frame so the pointer becomes in B.", " 3) Press Enter key. Entered event on Frame should be fired.", " Stage 10:", " Repeat Stages from 4 to 9 with using Move command rather then Resize. ", " Note, that when the pointer jumps to the titlebar when you select \"Move window\", ", " it is OK to fire Exited event. Then, if the pointer returns to component back, ", " it should fire Entered event.", }; Sysout.createDialog( ); Sysout.printInstructions( instructions ); Sysout.enableNumbering(true); MouseAdapter enterExitAdapter = new MouseAdapter() { public void mouseEntered(MouseEvent e){ Sysout.println("Entered on " + e.getSource().getClass().getName()); } public void mouseExited(MouseEvent e){ Sysout.println("Exited on " + e.getSource().getClass().getName()); } }; frame.addMouseListener(enterExitAdapter); jbutton.addMouseListener(enterExitAdapter); frame.setSize(600, 200); frame.add(jbutton, BorderLayout.NORTH); frame.setVisible(true); frame1.addMouseListener(enterExitAdapter); button1.addMouseListener(enterExitAdapter); frame1.setSize(600, 200); frame1.add(button1, BorderLayout.NORTH); frame1.setVisible(true); }//End init() /***************************************************** * Standard Test Machinery Section * DO NOT modify anything in this section -- it's a * standard chunk of code which has all of the * synchronisation necessary for the test harness. * By keeping it the same in all tests, it is easier * to read and understand someone else's test, as * well as insuring that all tests behave correctly * with the test harness. * There is a section following this for test-defined * classes ******************************************************/ private static boolean theTestPassed = false; private static boolean testGeneratedInterrupt = false; private static String failureMessage = ""; private static Thread mainThread = null; private static int sleepTime = 300000; public static void main( String args[] ) throws InterruptedException { mainThread = Thread.currentThread(); try { init(); } catch( TestPassedException e ) { //The test passed, so just return from main and harness will // interepret this return as a pass return; } //At this point, neither test passed nor test failed has been // called -- either would have thrown an exception and ended the // test, so we know we have multiple threads. //Test involves other threads, so sleep and wait for them to // called pass() or fail() try { Thread.sleep( sleepTime ); //Timed out, so fail the test throw new RuntimeException( "Timed out after " + sleepTime/1000 + " seconds" ); } catch (InterruptedException e) { if( ! testGeneratedInterrupt ) throw e; //reset flag in case hit this code more than once for some reason (just safety) testGeneratedInterrupt = false; if ( theTestPassed == false ) { throw new RuntimeException( failureMessage ); } } }//main public static synchronized void setTimeoutTo( int seconds ) { sleepTime = seconds * 1000; } public static synchronized void pass() { Sysout.println( "The test passed." ); Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); //first check if this is executing in main thread if ( mainThread == Thread.currentThread() ) { //Still in the main thread, so set the flag just for kicks, // and throw a test passed exception which will be caught // and end the test. theTestPassed = true; throw new TestPassedException(); } //pass was called from a different thread, so set the flag and interrupt // the main thead. theTestPassed = true; testGeneratedInterrupt = true; if (mainThread != null){ mainThread.interrupt(); } }//pass() public static synchronized void fail() { //test writer didn't specify why test failed, so give generic fail( "it just plain failed! :-)" ); } public static synchronized void fail( String whyFailed ) { Sysout.println( "The test failed: " + whyFailed ); Sysout.println( "The test is over, hit Ctl-C to stop Java VM" ); //check if this called from main thread if ( mainThread == Thread.currentThread() ) { //If main thread, fail now 'cause not sleeping throw new RuntimeException( whyFailed ); } theTestPassed = false; testGeneratedInterrupt = true; failureMessage = whyFailed; mainThread.interrupt(); }//fail() }// class SpuriousExitEnter_2 //This exception is used to exit from any level of call nesting // when it's determined that the test has passed, and immediately // end the test. class TestPassedException extends RuntimeException { } //*********** End Standard Test Machinery Section ********** //************ Begin classes defined for the test **************** // make listeners in a class defined here, and instantiate them in init() /* Example of a class which may be written as part of a test class NewClass implements anInterface { static int newVar = 0; public void eventDispatched(AWTEvent e) { //Counting events to see if we get enough eventCount++; if( eventCount == 20 ) { //got enough events, so pass ManualMainTest.pass(); } else if( tries == 20 ) { //tried too many times without getting enough events so fail ManualMainTest.fail(); } }// eventDispatched() }// NewClass class */ //************** End classes defined for the test ******************* /**************************************************** Standard Test Machinery DO NOT modify anything below -- it's a standard chunk of code whose purpose is to make user interaction uniform, and thereby make it simpler to read and understand someone else's test. ****************************************************/ /** This is part of the standard test machinery. It creates a dialog (with the instructions), and is the interface for sending text messages to the user. To print the instructions, send an array of strings to Sysout.createDialog WithInstructions method. Put one line of instructions per array entry. To display a message for the tester to see, simply call Sysout.println with the string to be displayed. This mimics System.out.println but works within the test harness as well as standalone. */ class Sysout { private static TestDialog dialog; private static boolean numbering = false; private static int messageNumber = 0; public static void createDialogWithInstructions( String[] instructions ) { dialog = new TestDialog( new Frame(), "Instructions" ); dialog.printInstructions( instructions ); dialog.setVisible(true); println( "Any messages for the tester will display here." ); } public static void createDialog( ) { dialog = new TestDialog( new Frame(), "Instructions" ); String[] defInstr = { "Instructions will appear here. ", "" } ; dialog.printInstructions( defInstr ); dialog.setVisible(true); println( "Any messages for the tester will display here." ); } /* Enables message counting for the tester. */ public static void enableNumbering(boolean enable){ numbering = enable; } public static void printInstructions( String[] instructions ) { dialog.printInstructions( instructions ); } public static void println( String messageIn ) { if (numbering) { messageIn = "" + messageNumber + " " + messageIn; messageNumber++; } dialog.displayMessage( messageIn ); } }// Sysout class /** This is part of the standard test machinery. It provides a place for the test instructions to be displayed, and a place for interactive messages to the user to be displayed. To have the test instructions displayed, see Sysout. To have a message to the user be displayed, see Sysout. Do not call anything in this dialog directly. */ class TestDialog extends Dialog implements ActionListener { TextArea instructionsText; TextArea messageText; int maxStringLength = 80; Panel buttonP = new Panel(); Button passB = new Button( "pass" ); Button failB = new Button( "fail" ); //DO NOT call this directly, go through Sysout public TestDialog( Frame frame, String name ) { super( frame, name ); int scrollBoth = TextArea.SCROLLBARS_BOTH; instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); add( "North", instructionsText ); messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); add("Center", messageText); passB = new Button( "pass" ); passB.setActionCommand( "pass" ); passB.addActionListener( this ); buttonP.add( "East", passB ); failB = new Button( "fail" ); failB.setActionCommand( "fail" ); failB.addActionListener( this ); buttonP.add( "West", failB ); add( "South", buttonP ); pack(); setVisible(true); }// TestDialog() //DO NOT call this directly, go through Sysout public void printInstructions( String[] instructions ) { //Clear out any current instructions instructionsText.setText( "" ); //Go down array of instruction strings String printStr, remainingStr; for( int i=0; i < instructions.length; i++ ) { //chop up each into pieces maxSringLength long remainingStr = instructions[ i ]; while( remainingStr.length() > 0 ) { //if longer than max then chop off first max chars to print if( remainingStr.length() >= maxStringLength ) { //Try to chop on a word boundary int posOfSpace = remainingStr. lastIndexOf( ' ', maxStringLength - 1 ); if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; printStr = remainingStr.substring( 0, posOfSpace + 1 ); remainingStr = remainingStr.substring( posOfSpace + 1 ); } //else just print else { printStr = remainingStr; remainingStr = ""; } instructionsText.append( printStr + "\n" ); }// while }// for }//printInstructions() //DO NOT call this directly, go through Sysout public void displayMessage( String messageIn ) { messageText.append( messageIn + "\n" ); System.out.println(messageIn); } //catch presses of the passed and failed buttons. //simply call the standard pass() or fail() static methods of //ManualMainTest public void actionPerformed( ActionEvent e ) { if( e.getActionCommand() == "pass" ) { SpuriousExitEnter_2.pass(); } else { SpuriousExitEnter_2.fail(); } } }// TestDialog class
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.util.text; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.NaturalComparator; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.LineSeparator; import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.XmlStringUtil; import org.jdom.Verifier; import org.jetbrains.annotations.NotNull; import org.junit.Test; import slowCheck.Generator; import slowCheck.PropertyChecker; import java.nio.CharBuffer; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; /** * @author Eugene Zhuravlev * @since Dec 22, 2006 */ public class StringUtilTest { @Test public void testTrimLeadingChar() throws Exception { doTestTrimLeading("", ""); doTestTrimLeading("", " "); doTestTrimLeading("", " "); doTestTrimLeading("a ", "a "); doTestTrimLeading("a ", " a "); } @Test public void testTrimTrailingChar() throws Exception { doTestTrimTrailing("", ""); doTestTrimTrailing("", " "); doTestTrimTrailing("", " "); doTestTrimTrailing(" a", " a"); doTestTrimTrailing(" a", " a "); } private static void doTestTrimLeading(@NotNull String expected, @NotNull String string) { assertEquals(expected, StringUtil.trimLeading(string)); assertEquals(expected, StringUtil.trimLeading(string, ' ')); assertEquals(expected, StringUtil.trimLeading(new StringBuilder(string), ' ').toString()); } private static void doTestTrimTrailing(@NotNull String expected, @NotNull String string) { assertEquals(expected, StringUtil.trimTrailing(string)); assertEquals(expected, StringUtil.trimTrailing(string, ' ')); assertEquals(expected, StringUtil.trimTrailing(new StringBuilder(string), ' ').toString()); } @Test public void testToUpperCase() { assertEquals('/', StringUtil.toUpperCase('/')); assertEquals(':', StringUtil.toUpperCase(':')); assertEquals('A', StringUtil.toUpperCase('a')); assertEquals('A', StringUtil.toUpperCase('A')); assertEquals('K', StringUtil.toUpperCase('k')); assertEquals('K', StringUtil.toUpperCase('K')); assertEquals('\u2567', StringUtil.toUpperCase(Character.toLowerCase('\u2567'))); } @Test public void testToLowerCase() { assertEquals('/', StringUtil.toLowerCase('/')); assertEquals(':', StringUtil.toLowerCase(':')); assertEquals('a', StringUtil.toLowerCase('a')); assertEquals('a', StringUtil.toLowerCase('A')); assertEquals('k', StringUtil.toLowerCase('k')); assertEquals('k', StringUtil.toLowerCase('K')); assertEquals('\u2567', StringUtil.toUpperCase(Character.toLowerCase('\u2567'))); } @Test public void testIsEmptyOrSpaces() throws Exception { assertTrue(StringUtil.isEmptyOrSpaces(null)); assertTrue(StringUtil.isEmptyOrSpaces("")); assertTrue(StringUtil.isEmptyOrSpaces(" ")); assertFalse(StringUtil.isEmptyOrSpaces("1")); assertFalse(StringUtil.isEmptyOrSpaces(" 12345 ")); assertFalse(StringUtil.isEmptyOrSpaces("test")); } @Test public void testSplitWithQuotes() { final List<String> strings = StringUtil.splitHonorQuotes("aaa bbb ccc \"ddd\" \"e\\\"e\\\"e\" ", ' '); assertEquals(5, strings.size()); assertEquals("aaa", strings.get(0)); assertEquals("bbb", strings.get(1)); assertEquals("ccc", strings.get(2)); assertEquals("\"ddd\"", strings.get(3)); assertEquals("\"e\\\"e\\\"e\"", strings.get(4)); } @Test public void testUnPluralize() { // synthetic assertEquals("plurals", StringUtil.unpluralize("pluralses")); assertEquals("Inherits", StringUtil.unpluralize("Inheritses")); assertEquals("s", StringUtil.unpluralize("ss")); assertEquals("I", StringUtil.unpluralize("Is")); assertEquals(null, StringUtil.unpluralize("s")); assertEquals("z", StringUtil.unpluralize("zs")); // normal assertEquals("case", StringUtil.unpluralize("cases")); assertEquals("Index", StringUtil.unpluralize("Indices")); assertEquals("fix", StringUtil.unpluralize("fixes")); assertEquals("man", StringUtil.unpluralize("men")); assertEquals("leaf", StringUtil.unpluralize("leaves")); assertEquals("cookie", StringUtil.unpluralize("cookies")); assertEquals("search", StringUtil.unpluralize("searches")); assertEquals("process", StringUtil.unpluralize("process")); assertEquals("PROPERTY", StringUtil.unpluralize("PROPERTIES")); assertEquals("THIS", StringUtil.unpluralize("THESE")); assertEquals("database", StringUtil.unpluralize("databases")); assertEquals("basis", StringUtil.unpluralize("bases")); } @Test public void testPluralize() { assertEquals("values", StringUtil.pluralize("value")); assertEquals("values", StringUtil.pluralize("values")); assertEquals("indices", StringUtil.pluralize("index")); assertEquals("matrices", StringUtil.pluralize("matrix")); assertEquals("fixes", StringUtil.pluralize("fix")); assertEquals("men", StringUtil.pluralize("man")); assertEquals("media", StringUtil.pluralize("medium")); assertEquals("stashes", StringUtil.pluralize("stash")); assertEquals("children", StringUtil.pluralize("child")); assertEquals("leaves", StringUtil.pluralize("leaf")); assertEquals("These", StringUtil.pluralize("This")); assertEquals("cookies", StringUtil.pluralize("cookie")); assertEquals("VaLuES", StringUtil.pluralize("VaLuE")); assertEquals("PLANS", StringUtil.pluralize("PLAN")); assertEquals("stackTraceLineExes", StringUtil.pluralize("stackTraceLineEx")); assertEquals("schemas", StringUtil.pluralize("schema")); // anglicized version assertEquals("PROPERTIES", StringUtil.pluralize("PROPERTY")); assertEquals("THESE", StringUtil.pluralize("THIS")); assertEquals("databases", StringUtil.pluralize("database")); assertEquals("bases", StringUtil.pluralize("base")); assertEquals("bases", StringUtil.pluralize("basis")); } @Test public void testStartsWithConcatenation() { assertTrue(StringUtil.startsWithConcatenation("something.with.dot", "something", ".")); assertTrue(StringUtil.startsWithConcatenation("something.with.dot", "", "something.")); assertTrue(StringUtil.startsWithConcatenation("something.", "something", ".")); assertTrue(StringUtil.startsWithConcatenation("something", "something", "", "", "")); assertFalse(StringUtil.startsWithConcatenation("something", "something", "", "", ".")); assertFalse(StringUtil.startsWithConcatenation("some", "something", "")); } @Test public void testNaturalCompareTransitivity() { String s1 = "#"; String s2 = "0b"; String s3 = " 0b"; assertTrue(StringUtil.naturalCompare(s1, s2) < 0); assertTrue(StringUtil.naturalCompare(s2, s3) < 0); assertTrue("non-transitive", StringUtil.naturalCompare(s1, s3) < 0); } @Test public void testNaturalCompareTransitivityProperty() { PropertyChecker.forAll(Generator.listsOf(Generator.stringsOf("ab01()_# ")), l -> { List<String> sorted = ContainerUtil.sorted(l, StringUtil::naturalCompare); for (int i = 0; i < sorted.size(); i++) { for (int j = i + 1; j < sorted.size(); j++) { if (StringUtil.naturalCompare(sorted.get(i), sorted.get(j)) > 0) return false; if (StringUtil.naturalCompare(sorted.get(j), sorted.get(i)) < 0) return false; } } return true; }); } @Test public void testNaturalCompareStability() { assertTrue(StringUtil.naturalCompare("01a1", "1a01") != StringUtil.naturalCompare("1a01", "01a1")); assertTrue(StringUtil.naturalCompare("#01A", "# 1A") != StringUtil.naturalCompare("# 1A", "#01A")); assertTrue(StringUtil.naturalCompare("aA", "aa") != StringUtil.naturalCompare("aa", "aA")); } @Test public void testNaturalCompare() { final List<String> numbers = Arrays.asList("1a000001", "000001a1", "001a0001", "0001A001" , "00001a01", "01a00001"); numbers.sort(NaturalComparator.INSTANCE); assertEquals(Arrays.asList("1a000001", "01a00001", "001a0001", "0001A001" , "00001a01", "000001a1"), numbers); final List<String> test = Arrays.asList("test011", "test10", "test10a", "test010"); test.sort(NaturalComparator.INSTANCE); assertEquals(Arrays.asList("test10", "test10a", "test010", "test011"), test); final List<String> strings = Arrays.asList("Test99", "tes0", "test0", "testing", "test", "test99", "test011", "test1", "test 3", "test2", "test10a", "test10", "1.2.10.5", "1.2.9.1"); strings.sort(NaturalComparator.INSTANCE); assertEquals(Arrays.asList("1.2.9.1", "1.2.10.5", "tes0", "test", "test0", "test1", "test2", "test 3", "test10", "test10a", "test011", "Test99", "test99", "testing"), strings); final List<String> strings2 = Arrays.asList("t1", "t001", "T2", "T002", "T1", "t2"); strings2.sort(NaturalComparator.INSTANCE); assertEquals(Arrays.asList("T1", "t1", "t001", "T2", "t2", "T002"), strings2); assertEquals(1 ,StringUtil.naturalCompare("7403515080361171695", "07403515080361171694")); assertEquals(-14, StringUtil.naturalCompare("_firstField", "myField1")); //idea-80853 final List<String> strings3 = Arrays.asList("C148A_InsomniaCure", "C148B_Escape", "C148C_TersePrincess", "C148D_BagOfMice", "C148E_Porcelain"); strings3.sort(NaturalComparator.INSTANCE); assertEquals(Arrays.asList("C148A_InsomniaCure", "C148B_Escape", "C148C_TersePrincess", "C148D_BagOfMice", "C148E_Porcelain"), strings3); final List<String> l = Arrays.asList("a0002", "a0 2", "a001"); l.sort(NaturalComparator.INSTANCE); assertEquals(Arrays.asList("a0 2", "a001", "a0002"), l); } @Test public void testFormatLinks() { assertEquals("<a href=\"http://a-b+c\">http://a-b+c</a>", StringUtil.formatLinks("http://a-b+c")); } @Test public void testCopyHeapCharBuffer() { String s = "abc.d"; CharBuffer buffer = CharBuffer.allocate(s.length()); buffer.append(s); buffer.rewind(); assertNotNull(CharArrayUtil.fromSequenceWithoutCopying(buffer)); assertNotNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(0, 5))); //assertNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(0, 4))); // end index is not checked assertNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(1, 5))); assertNull(CharArrayUtil.fromSequenceWithoutCopying(buffer.subSequence(1, 2))); } @Test public void testTitleCase() { assertEquals("Couldn't Connect to Debugger", StringUtil.wordsToBeginFromUpperCase("Couldn't connect to debugger")); assertEquals("Let's Make Abbreviations Like I18n, SQL and CSS", StringUtil.wordsToBeginFromUpperCase("Let's make abbreviations like I18n, SQL and CSS")); } @Test public void testSentenceCapitalization() { assertEquals("couldn't connect to debugger", StringUtil.wordsToBeginFromLowerCase("Couldn't Connect to Debugger")); assertEquals("let's make abbreviations like I18n, SQL and CSS s SQ sq", StringUtil.wordsToBeginFromLowerCase("Let's Make Abbreviations Like I18n, SQL and CSS S SQ Sq")); } @Test public void testEscapeStringCharacters() { assertEquals("\\\"\\n", StringUtil.escapeStringCharacters(3, "\\\"\n", "\"", false, new StringBuilder()).toString()); assertEquals("\\\"\\n", StringUtil.escapeStringCharacters(2, "\"\n", "\"", false, new StringBuilder()).toString()); assertEquals("\\\\\\\"\\n", StringUtil.escapeStringCharacters(3, "\\\"\n", "\"", true, new StringBuilder()).toString()); } @Test public void testEscapeSlashes() { assertEquals("\\/", StringUtil.escapeSlashes("/")); assertEquals("foo\\/bar\\foo\\/", StringUtil.escapeSlashes("foo/bar\\foo/")); assertEquals("\\\\\\\\server\\\\share\\\\extension.crx", StringUtil.escapeBackSlashes("\\\\server\\share\\extension.crx")); } @Test public void testEscapeQuotes() { assertEquals("\\\"", StringUtil.escapeQuotes("\"")); assertEquals("foo\\\"bar'\\\"", StringUtil.escapeQuotes("foo\"bar'\"")); } @Test public void testUnquote() { assertEquals("", StringUtil.unquoteString("")); assertEquals("\"", StringUtil.unquoteString("\"")); assertEquals("", StringUtil.unquoteString("\"\"")); assertEquals("\"", StringUtil.unquoteString("\"\"\"")); assertEquals("foo", StringUtil.unquoteString("\"foo\"")); assertEquals("\"foo", StringUtil.unquoteString("\"foo")); assertEquals("foo\"", StringUtil.unquoteString("foo\"")); assertEquals("", StringUtil.unquoteString("")); assertEquals("\'", StringUtil.unquoteString("\'")); assertEquals("", StringUtil.unquoteString("\'\'")); assertEquals("\'", StringUtil.unquoteString("\'\'\'")); assertEquals("foo", StringUtil.unquoteString("\'foo\'")); assertEquals("\'foo", StringUtil.unquoteString("\'foo")); assertEquals("foo\'", StringUtil.unquoteString("foo\'")); assertEquals("\'\"", StringUtil.unquoteString("\'\"")); assertEquals("\"\'", StringUtil.unquoteString("\"\'")); assertEquals("\"foo\'", StringUtil.unquoteString("\"foo\'")); } @SuppressWarnings("SSBasedInspection") @Test public void testStripQuotesAroundValue() { assertEquals("", StringUtil.stripQuotesAroundValue("")); assertEquals("", StringUtil.stripQuotesAroundValue("'")); assertEquals("", StringUtil.stripQuotesAroundValue("\"")); assertEquals("", StringUtil.stripQuotesAroundValue("''")); assertEquals("", StringUtil.stripQuotesAroundValue("\"\"")); assertEquals("", StringUtil.stripQuotesAroundValue("'\"")); assertEquals("foo", StringUtil.stripQuotesAroundValue("'foo'")); assertEquals("foo", StringUtil.stripQuotesAroundValue("'foo")); assertEquals("foo", StringUtil.stripQuotesAroundValue("foo'")); assertEquals("f'o'o", StringUtil.stripQuotesAroundValue("'f'o'o'")); assertEquals("f\"o'o", StringUtil.stripQuotesAroundValue("\"f\"o'o'")); assertEquals("f\"o'o", StringUtil.stripQuotesAroundValue("f\"o'o")); assertEquals("\"'f\"o'o\"", StringUtil.stripQuotesAroundValue("\"\"'f\"o'o\"\"")); assertEquals("''f\"o'o''", StringUtil.stripQuotesAroundValue("'''f\"o'o'''")); assertEquals("foo' 'bar", StringUtil.stripQuotesAroundValue("foo' 'bar")); } @Test public void testUnquoteWithQuotationChar() { assertEquals("", StringUtil.unquoteString("", '|')); assertEquals("|", StringUtil.unquoteString("|", '|')); assertEquals("", StringUtil.unquoteString("||", '|')); assertEquals("|", StringUtil.unquoteString("|||", '|')); assertEquals("foo", StringUtil.unquoteString("|foo|", '|')); assertEquals("|foo", StringUtil.unquoteString("|foo", '|')); assertEquals("foo|", StringUtil.unquoteString("foo|", '|')); } @Test public void testIsQuotedString() { assertFalse(StringUtil.isQuotedString("")); assertFalse(StringUtil.isQuotedString("'")); assertFalse(StringUtil.isQuotedString("\"")); assertTrue(StringUtil.isQuotedString("\"\"")); assertTrue(StringUtil.isQuotedString("''")); assertTrue(StringUtil.isQuotedString("'ab'")); assertTrue(StringUtil.isQuotedString("\"foo\"")); } @Test public void testJoin() { assertEquals("", StringUtil.join(Collections.emptyList(), ",")); assertEquals("qqq", StringUtil.join(Collections.singletonList("qqq"), ",")); assertEquals("", StringUtil.join(Collections.singletonList(null), ",")); assertEquals("a,b", StringUtil.join(Arrays.asList("a", "b"), ",")); assertEquals("foo,,bar", StringUtil.join(Arrays.asList("foo", "", "bar"), ",")); assertEquals("foo,,bar", StringUtil.join(new String[]{"foo", "", "bar"}, ",")); } @Test public void testSplitByLineKeepingSeparators() { assertEquals(Collections.singletonList(""), Arrays.asList(StringUtil.splitByLinesKeepSeparators(""))); assertEquals(Collections.singletonList("aa"), Arrays.asList(StringUtil.splitByLinesKeepSeparators("aa"))); assertEquals(Arrays.asList("\n", "\n", "aa\n", "\n", "bb\n", "cc\n", "\n"), Arrays.asList(StringUtil.splitByLinesKeepSeparators("\n\naa\n\nbb\ncc\n\n"))); assertEquals(Arrays.asList("\r", "\r\n", "\r"), Arrays.asList(StringUtil.splitByLinesKeepSeparators("\r\r\n\r"))); assertEquals(Arrays.asList("\r\n", "\r", "\r\n"), Arrays.asList(StringUtil.splitByLinesKeepSeparators("\r\n\r\r\n"))); assertEquals(Arrays.asList("\n", "\r\n", "\n", "\r\n", "\r", "\r", "aa\r", "bb\r\n", "cc\n", "\r", "dd\n", "\n", "\r\n", "\r"), Arrays.asList(StringUtil.splitByLinesKeepSeparators("\n\r\n\n\r\n\r\raa\rbb\r\ncc\n\rdd\n\n\r\n\r"))); } @Test public void testReplaceReturnReplacementIfTextEqualsToReplacedText() { String newS = "/tmp"; assertSame(newS, StringUtil.replace("$PROJECT_FILE$", "$PROJECT_FILE$".toLowerCase().toUpperCase() /* ensure new String instance */, newS)); } @Test public void testReplace() { assertEquals("/tmp/filename", StringUtil.replace("$PROJECT_FILE$/filename", "$PROJECT_FILE$", "/tmp")); } @Test public void testEqualsIgnoreWhitespaces() { assertTrue(StringUtil.equalsIgnoreWhitespaces(null, null)); assertFalse(StringUtil.equalsIgnoreWhitespaces("", null)); assertTrue(StringUtil.equalsIgnoreWhitespaces("", "")); assertTrue(StringUtil.equalsIgnoreWhitespaces("\n\t ", "")); assertTrue(StringUtil.equalsIgnoreWhitespaces("", "\t\n \n\t")); assertTrue(StringUtil.equalsIgnoreWhitespaces("\t", "\n")); assertTrue(StringUtil.equalsIgnoreWhitespaces("x", " x")); assertTrue(StringUtil.equalsIgnoreWhitespaces("x", "x ")); assertTrue(StringUtil.equalsIgnoreWhitespaces("x\n", "x")); assertTrue(StringUtil.equalsIgnoreWhitespaces("abc", "a\nb\nc\n")); assertTrue(StringUtil.equalsIgnoreWhitespaces("x y x", "x y x")); assertTrue(StringUtil.equalsIgnoreWhitespaces("xyx", "x y x")); assertFalse(StringUtil.equalsIgnoreWhitespaces("x", "\t\n ")); assertFalse(StringUtil.equalsIgnoreWhitespaces("", " x ")); assertFalse(StringUtil.equalsIgnoreWhitespaces("", "x ")); assertFalse(StringUtil.equalsIgnoreWhitespaces("", " x")); assertFalse(StringUtil.equalsIgnoreWhitespaces("xyx", "xxx")); assertFalse(StringUtil.equalsIgnoreWhitespaces("xyx", "xYx")); } @Test public void testStringHashCodeIgnoreWhitespaces() { assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces(""), StringUtil.stringHashCodeIgnoreWhitespaces(""))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("\n\t "), StringUtil.stringHashCodeIgnoreWhitespaces(""))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces(""), StringUtil.stringHashCodeIgnoreWhitespaces("\t\n \n\t"))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("\t"), StringUtil.stringHashCodeIgnoreWhitespaces("\n"))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("x"), StringUtil.stringHashCodeIgnoreWhitespaces(" x"))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("x"), StringUtil.stringHashCodeIgnoreWhitespaces("x "))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("x\n"), StringUtil.stringHashCodeIgnoreWhitespaces("x"))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("abc"), StringUtil.stringHashCodeIgnoreWhitespaces("a\nb\nc\n"))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("x y x"), StringUtil.stringHashCodeIgnoreWhitespaces("x y x"))); assertTrue(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("xyx"), StringUtil.stringHashCodeIgnoreWhitespaces("x y x"))); assertFalse(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("x"), StringUtil.stringHashCodeIgnoreWhitespaces("\t\n "))); assertFalse(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces(""), StringUtil.stringHashCodeIgnoreWhitespaces(" x "))); assertFalse(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces(""), StringUtil.stringHashCodeIgnoreWhitespaces("x "))); assertFalse(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces(""), StringUtil.stringHashCodeIgnoreWhitespaces(" x"))); assertFalse(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("xyx"), StringUtil.stringHashCodeIgnoreWhitespaces("xxx"))); assertFalse(Comparing.equal(StringUtil.stringHashCodeIgnoreWhitespaces("xyx"), StringUtil.stringHashCodeIgnoreWhitespaces("xYx"))); } @Test public void testContains() { assertTrue(StringUtil.contains("1", "1")); assertFalse(StringUtil.contains("1", "12")); assertTrue(StringUtil.contains("12", "1")); assertTrue(StringUtil.contains("12", "2")); } @Test public void testDetectSeparators() { assertEquals(null, StringUtil.detectSeparators("")); assertEquals(null, StringUtil.detectSeparators("asd")); assertEquals(null, StringUtil.detectSeparators("asd\t")); assertEquals(LineSeparator.LF, StringUtil.detectSeparators("asd\n")); assertEquals(LineSeparator.LF, StringUtil.detectSeparators("asd\nads\r")); assertEquals(LineSeparator.LF, StringUtil.detectSeparators("asd\nads\n")); assertEquals(LineSeparator.CR, StringUtil.detectSeparators("asd\r")); assertEquals(LineSeparator.CR, StringUtil.detectSeparators("asd\rads\r")); assertEquals(LineSeparator.CR, StringUtil.detectSeparators("asd\rads\n")); assertEquals(LineSeparator.CRLF, StringUtil.detectSeparators("asd\r\n")); assertEquals(LineSeparator.CRLF, StringUtil.detectSeparators("asd\r\nads\r")); assertEquals(LineSeparator.CRLF, StringUtil.detectSeparators("asd\r\nads\n")); } @Test public void testFindStartingLineSeparator() { assertEquals(null, StringUtil.getLineSeparatorAt("", -1)); assertEquals(null, StringUtil.getLineSeparatorAt("", 0)); assertEquals(null, StringUtil.getLineSeparatorAt("", 1)); assertEquals(null, StringUtil.getLineSeparatorAt("\nHello", -1)); assertEquals(null, StringUtil.getLineSeparatorAt("\nHello", 1)); assertEquals(null, StringUtil.getLineSeparatorAt("\nH\rel\nlo", 6)); assertEquals(LineSeparator.LF, StringUtil.getLineSeparatorAt("\nHello", 0)); assertEquals(LineSeparator.LF, StringUtil.getLineSeparatorAt("\nH\rel\nlo", 5)); assertEquals(LineSeparator.LF, StringUtil.getLineSeparatorAt("Hello\n", 5)); assertEquals(LineSeparator.CR, StringUtil.getLineSeparatorAt("\rH\r\nello", 0)); assertEquals(LineSeparator.CR, StringUtil.getLineSeparatorAt("Hello\r", 5)); assertEquals(LineSeparator.CR, StringUtil.getLineSeparatorAt("Hello\b\r", 6)); assertEquals(LineSeparator.CRLF, StringUtil.getLineSeparatorAt("\rH\r\nello", 2)); assertEquals(LineSeparator.CRLF, StringUtil.getLineSeparatorAt("\r\nH\r\nello", 0)); assertEquals(LineSeparator.CRLF, StringUtil.getLineSeparatorAt("\r\nH\r\nello\r\n", 9)); } @Test public void testFormatFileSize() { assertEquals("0B", StringUtil.formatFileSize(0)); assertEquals("1B", StringUtil.formatFileSize(1)); assertEquals("2.15G", StringUtil.formatFileSize(Integer.MAX_VALUE)); assertEquals("9.22E", StringUtil.formatFileSize(Long.MAX_VALUE)); assertEquals("60.10K", StringUtil.formatFileSize(60100)); assertEquals("1.23K", StringUtil.formatFileSize(1234)); assertEquals("12.35K", StringUtil.formatFileSize(12345)); assertEquals("123.46K", StringUtil.formatFileSize(123456)); assertEquals("1.23M", StringUtil.formatFileSize(1234567)); assertEquals("12.35M", StringUtil.formatFileSize(12345678)); assertEquals("123.46M", StringUtil.formatFileSize(123456789)); assertEquals("1.23G", StringUtil.formatFileSize(1234567890)); } @Test public void testFormatDuration() { assertEquals("0ms", StringUtil.formatDuration(0)); assertEquals("1ms", StringUtil.formatDuration(1)); assertEquals("3w 3d 20h 31m 23s 647ms", StringUtil.formatDuration(Integer.MAX_VALUE)); assertEquals("31ep 7714ml 2c 59yr 5mo 0w 3d 7h 12m 55s 807ms", StringUtil.formatDuration(Long.MAX_VALUE)); assertEquals("1m 0s 100ms", StringUtil.formatDuration(60100)); assertEquals("1s 234ms", StringUtil.formatDuration(1234)); assertEquals("12s 345ms", StringUtil.formatDuration(12345)); assertEquals("2m 3s 456ms", StringUtil.formatDuration(123456)); assertEquals("20m 34s 567ms", StringUtil.formatDuration(1234567)); assertEquals("3h 25m 45s 678ms", StringUtil.formatDuration(12345678)); assertEquals("1d 10h 17m 36s 789ms", StringUtil.formatDuration(123456789)); assertEquals("2w 0d 6h 56m 7s 890ms", StringUtil.formatDuration(1234567890)); } @Test public void testXmlWrapInCDATA() { assertEquals("<![CDATA[abc]]>", XmlStringUtil.wrapInCDATA("abc")); assertEquals("<![CDATA[abc]]]><![CDATA[]>]]>", XmlStringUtil.wrapInCDATA("abc]]>")); assertEquals("<![CDATA[abc]]]><![CDATA[]>def]]>", XmlStringUtil.wrapInCDATA("abc]]>def")); assertEquals("<![CDATA[123<![CDATA[wow<&>]]]><![CDATA[]>]]]><![CDATA[]><![CDATA[123]]>", XmlStringUtil.wrapInCDATA("123<![CDATA[wow<&>]]>]]><![CDATA[123")); } @Test public void testGetPackageName() { assertEquals("java.lang", StringUtil.getPackageName("java.lang.String")); assertEquals("java.util.Map", StringUtil.getPackageName("java.util.Map.Entry")); assertEquals("Map", StringUtil.getPackageName("Map.Entry")); assertEquals("", StringUtil.getPackageName("Number")); } @SuppressWarnings("SpellCheckingInspection") @Test public void testIndexOf_1() { char[] chars = new char[]{'a','b','c','d','a','b','c','d','A','B','C','D'}; assertEquals(2, StringUtil.indexOf(chars, 'c', 0, 12, false)); assertEquals(2, StringUtil.indexOf(chars, 'C', 0, 12, false)); assertEquals(10, StringUtil.indexOf(chars, 'C', 0, 12, true)); assertEquals(2, StringUtil.indexOf(chars, 'c', -42, 99, false)); } @SuppressWarnings("SpellCheckingInspection") @Test public void testIndexOf_2() { assertEquals(1, StringUtil.indexOf("axaxa", 'x', 0, 5)); assertEquals(2, StringUtil.indexOf("abcd", 'c', -42, 99)); } @SuppressWarnings("SpellCheckingInspection") @Test public void testIndexOf_3() { assertEquals(1, StringUtil.indexOf("axaXa", 'x', 0, 5, false)); assertEquals(3, StringUtil.indexOf("axaXa", 'X', 0, 5, true)); assertEquals(2, StringUtil.indexOf("abcd", 'c', -42, 99, false)); } @SuppressWarnings("SpellCheckingInspection") @Test public void testIndexOfAny() { assertEquals(1, StringUtil.indexOfAny("axa", "x", 0, 5)); assertEquals(1, StringUtil.indexOfAny("axa", "zx", 0, 5)); assertEquals(2, StringUtil.indexOfAny("abcd", "c", -42, 99)); } @SuppressWarnings("SpellCheckingInspection") @Test public void testLastIndexOf() { assertEquals(1, StringUtil.lastIndexOf("axaxa", 'x', 0, 2)); assertEquals(1, StringUtil.lastIndexOf("axaxa", 'x', 0, 3)); assertEquals(3, StringUtil.lastIndexOf("axaxa", 'x', 0, 5)); assertEquals(2, StringUtil.lastIndexOf("abcd", 'c', -42, 99)); // #IDEA-144968 } @Test public void testEscapingIllegalXmlChars() { for (String s : new String[]{"ab\n\0\r\tde", "\\abc\1\2\3\uFFFFdef"}) { String escapedText = XmlStringUtil.escapeIllegalXmlChars(s); assertNull(Verifier.checkCharacterData(escapedText)); assertEquals(s, XmlStringUtil.unescapeIllegalXmlChars(escapedText)); } } @Test public void testCountChars() { assertEquals(0, StringUtil.countChars("abcdefgh", 'x')); assertEquals(1, StringUtil.countChars("abcdefgh", 'd')); assertEquals(5, StringUtil.countChars("abcddddefghd", 'd')); assertEquals(4, StringUtil.countChars("abcddddefghd", 'd', 4, false)); assertEquals(3, StringUtil.countChars("abcddddefghd", 'd', 4, true)); assertEquals(2, StringUtil.countChars("abcddddefghd", 'd', 4, 6, false)); } }
package com.hearthsim; import com.hearthsim.card.Deck; import com.hearthsim.card.minion.Hero; import com.hearthsim.exception.HSException; import com.hearthsim.exception.HSInvalidParamFileException; import com.hearthsim.exception.HSParamNotFoundException; import com.hearthsim.io.ParamFile; import com.hearthsim.model.PlayerModel; import com.hearthsim.player.playercontroller.ArtificialPlayer; import com.hearthsim.results.GameResult; import com.hearthsim.results.GameResultSummary; import java.io.*; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Observable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public abstract class HearthSimBase extends Observable { private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(this .getClass()); int numSims_; int numThreads_; private String gameResultFileName_; protected Path rootPath_; protected Path aiParamFilePath0_; protected Path aiParamFilePath1_; /** * Constructor * * @param setupFilePath * @throws HSInvalidParamFileException * @throws HSParamNotFoundException * @throws IOException */ HearthSimBase(Path setupFilePath) throws HSInvalidParamFileException, HSParamNotFoundException, IOException { rootPath_ = setupFilePath.getParent(); ParamFile masterParam = new ParamFile(setupFilePath); numSims_ = masterParam.getInt("num_simulations", 40000); numThreads_ = masterParam.getInt("num_threads", 1); aiParamFilePath0_ = FileSystems.getDefault() .getPath(rootPath_.toString(), masterParam.getString("aiParamFilePath0")); aiParamFilePath1_ = FileSystems.getDefault() .getPath(rootPath_.toString(), masterParam.getString("aiParamFilePath1")); gameResultFileName_ = masterParam.getString("output_file", "gameres.txt"); } public HearthSimBase(int numSimulations, int numThreads) { numSims_ = numSimulations; numThreads_ = numThreads; } /** * Run a single game. * * Must be overridden by a concrete subclass. The subclass's job is to set * up the decks and the AIs and to call runSigleGame(ArtificialPlayer, Hero, * Deck, ArtificialPlayer, Hero, Deck). * * @return * @throws HSException * @throws IOException */ protected abstract GameResult runSingleGame(int gameId) throws HSException, IOException; protected GameResult runSingleGame(ArtificialPlayer ai0, Hero hero0, Deck deck0, ArtificialPlayer ai1, Hero hero1, Deck deck1) throws HSException { return this.runSingleGame(ai0, hero0, deck0, ai1, hero1, deck1, 0); } /** * Run a single game * * @param ai0 * AI for player 0 * @param hero0 * Hero class for player 0 * @param deck0 * Deck for player 0 * @param ai1 * AI for player 1 * @param hero1 * Hero class for player 1 * @param deck1 * Deck for player 1 * @param shufflePlayOrder * Randomizes the play order if set to true * @return * @throws HSException */ protected GameResult runSingleGame(ArtificialPlayer ai0, Hero hero0, Deck deck0, ArtificialPlayer ai1, Hero hero1, Deck deck1, boolean shufflePlayOrder) throws HSException { // Shuffle the decks! deck0.shuffle(); deck1.shuffle(); PlayerModel playerModel0 = new PlayerModel((byte) 0, "player0", hero0, deck0); PlayerModel playerModel1 = new PlayerModel((byte) 1, "player1", hero1, deck1); Game game = new Game(playerModel0, playerModel1, ai0, ai1, shufflePlayOrder); return game.runGame(); } protected GameResult runSingleGame(ArtificialPlayer ai0, Hero hero0, Deck deck0, ArtificialPlayer ai1, Hero hero1, Deck deck1, int firstPlayerId) throws HSException { // Shuffle the decks! deck0.shuffle(); deck1.shuffle(); PlayerModel playerModel0 = new PlayerModel((byte) 0, "player0", hero0, deck0); PlayerModel playerModel1 = new PlayerModel((byte) 1, "player1", hero1, deck1); Game game = new Game(playerModel0, playerModel1, ai0, ai1, firstPlayerId); return game.runGame(); } public void run() throws IOException, InterruptedException { long simStartTime = System.currentTimeMillis(); Path outputFilePath = FileSystems.getDefault().getPath( rootPath_.toString(), gameResultFileName_); Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFilePath.toString()), "utf-8")); ExecutorService taskQueue = Executors .newFixedThreadPool(this.numThreads_); for (int i = 0; i < numSims_; ++i) { GameThread gThread = new GameThread(i, writer); taskQueue.execute(gThread); } taskQueue.shutdown(); taskQueue.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); writer.close(); long simEndTime = System.currentTimeMillis(); double simDeltaTimeSeconds = (simEndTime - simStartTime) / 1000.0; String prettyDeltaTimeSeconds = String.format("%.2f", simDeltaTimeSeconds); double secondsPerGame = simDeltaTimeSeconds / numSims_; String prettySecondsPerGame = String.format("%.2f", secondsPerGame); log.info( "completed simulation of {} games in {} seconds on {} thread(s)", numSims_, prettyDeltaTimeSeconds, numThreads_); log.info("average time per game: {} seconds", prettySecondsPerGame); } @Override public synchronized void notifyObservers(Object o) { super.notifyObservers(o); } @Override public synchronized void notifyObservers() { this.notifyObservers(null); } public class GameThread implements Runnable { final int gameId_; Writer writer_; public GameThread(int gameId, Writer writer) { gameId_ = gameId; writer_ = writer; } @Override public void run() { try { GameResult res = runSingleGame(gameId_); if (writer_ != null) { synchronized (writer_) { GameResultSummary grs = new GameResultSummary(res); writer_.write(grs.toJSON().toString() + "\n"); writer_.flush(); } } setChanged(); notifyObservers(res); } catch (HSException | IOException e) { log.error("Error! " + e); } } } }
/** * 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.mapred; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.File; import java.io.PrintStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSError; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.ipc.ProtocolProxy; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.VersionedProtocol; import org.apache.hadoop.metrics.MetricsContext; import org.apache.hadoop.metrics.MetricsUtil; import org.apache.hadoop.metrics.jvm.JvmMetrics; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.StringUtils; import org.apache.log4j.LogManager; /** * The main() for child processes. */ class Child { public static final Log LOG = LogFactory.getLog(Child.class); static volatile TaskAttemptID taskid = null; static volatile boolean isCleanup; static List<VersionedProtocol> proxiesCreated = new ArrayList<VersionedProtocol>(); public static void main(String[] args) throws Throwable { LOG.debug("Child starting"); JobConf defaultConf = new JobConf(); String host = args[0]; int port = Integer.parseInt(args[1]); InetSocketAddress address = new InetSocketAddress(host, port); final TaskAttemptID firstTaskid = TaskAttemptID.forName(args[2]); final int SLEEP_LONGER_COUNT = 5; int jvmIdInt = Integer.parseInt(args[3]); JVMId jvmId = new JVMId(firstTaskid.getJobID(),firstTaskid.isMap(),jvmIdInt); UserGroupInformation ticket = UserGroupInformation.login(defaultConf); int timeout = defaultConf.getInt("mapred.socket.timeout", 60000); TaskUmbilicalProtocol umbilical = ((ProtocolProxy<TaskUmbilicalProtocol>) RPC.getProtocolProxy( TaskUmbilicalProtocol.class, TaskUmbilicalProtocol.versionID, address, ticket, defaultConf, NetUtils.getDefaultSocketFactory(defaultConf), timeout)).getProxy(); proxiesCreated.add(umbilical); int numTasksToExecute = -1; //-1 signifies "no limit" int numTasksExecuted = 0; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { if (taskid != null) { TaskLog.syncLogs(firstTaskid, taskid, isCleanup); } } catch (Throwable throwable) { } } }); Thread t = new Thread() { public void run() { //every so often wake up and syncLogs so that we can track //logs of the currently running task while (true) { try { Thread.sleep(5000); if (taskid != null) { TaskLog.syncLogs(firstTaskid, taskid, isCleanup); } } catch (InterruptedException ie) { } catch (IOException iee) { LOG.error("Error in syncLogs: " + iee); System.exit(-1); } } } }; t.setName("Thread for syncLogs"); t.setDaemon(true); t.start(); String pid = ""; if (!Shell.WINDOWS) { pid = System.getenv().get("JVM_PID"); } JvmContext context = new JvmContext(jvmId, pid); int idleLoopCount = 0; Task task = null; try { while (true) { taskid = null; JvmTask myTask = umbilical.getTask(context); if (myTask.shouldDie()) { break; } else { if (myTask.getTask() == null) { taskid = null; if (++idleLoopCount >= SLEEP_LONGER_COUNT) { //we sleep for a bigger interval when we don't receive //tasks for a while Thread.sleep(1500); } else { Thread.sleep(500); } continue; } } idleLoopCount = 0; task = myTask.getTask(); taskid = task.getTaskID(); isCleanup = task.isTaskCleanupTask(); // reset the statistics for the task FileSystem.clearStatistics(); //create the index file so that the log files //are viewable immediately TaskLog.syncLogs(firstTaskid, taskid, isCleanup); JobConf job = new JobConf(task.getJobFile()); //read from bigParam if it exists String bigParamStr = job.get("mapred.bigparam.path", ""); if ( bigParamStr != null && bigParamStr.length() > 0) { Path bigParamPath = new Path(bigParamStr); File file = new File(bigParamPath.toUri().getPath()).getAbsoluteFile(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file))); int MAX_BUFFER_SIZE = 1024; StringBuilder result = new StringBuilder(); char[] buffer = new char[MAX_BUFFER_SIZE]; int readChars = 0, totalChars = 0; while ((readChars = in.read(buffer, 0, MAX_BUFFER_SIZE)) > 0) { result.append(buffer, 0, readChars); totalChars += readChars; } job.set("mapred.input.dir", result.toString()); LOG.info("Read mapred.input.dir: " + totalChars); in.close(); } umbilical = convertToDirectUmbilicalIfNecessary(umbilical, job, task); //setupWorkDir actually sets up the symlinks for the distributed //cache. After a task exits we wipe the workdir clean, and hence //the symlinks have to be rebuilt. TaskRunner.setupWorkDir(job); numTasksToExecute = job.getNumTasksToExecutePerJvm(); assert(numTasksToExecute != 0); task.setConf(job); defaultConf.addResource(new Path(task.getJobFile())); // Initiate Java VM metrics JvmMetrics.init(task.getPhase().toString(), job.getSessionId()); // use job-specified working directory FileSystem.get(job).setWorkingDirectory(job.getWorkingDirectory()); try { task.run(job, umbilical); // run the task } finally { TaskLog.syncLogs(firstTaskid, taskid, isCleanup); } if (numTasksToExecute > 0 && ++numTasksExecuted == numTasksToExecute) { break; } } } catch (FSError e) { LOG.fatal("FSError from child", e); umbilical.fsError(taskid, e.getMessage()); } catch (Exception exception) { LOG.warn("Error running child", exception); try { if (task != null) { // do cleanup for the task task.taskCleanup(umbilical); } } catch (Exception e) { LOG.info("Error cleaning up" + e); } // Report back any failures, for diagnostic purposes ByteArrayOutputStream baos = new ByteArrayOutputStream(); exception.printStackTrace(new PrintStream(baos)); if (taskid != null) { umbilical.reportDiagnosticInfo(taskid, baos.toString()); } } catch (Throwable throwable) { LOG.fatal("Error running child : " + StringUtils.stringifyException(throwable)); if (taskid != null) { Throwable tCause = throwable.getCause(); String cause = tCause == null ? throwable.getMessage() : StringUtils.stringifyException(tCause); umbilical.fatalError(taskid, cause); } } finally { for (VersionedProtocol proxy : proxiesCreated) { RPC.stopProxy(proxy); } MetricsContext metricsContext = MetricsUtil.getContext("mapred"); metricsContext.close(); // Shutting down log4j of the child-vm... // This assumes that on return from Task.run() // there is no more logging done. LogManager.shutdown(); } } private static TaskUmbilicalProtocol convertToDirectUmbilicalIfNecessary( TaskUmbilicalProtocol umbilical, JobConf job, Task task) throws IOException { // We only need a direct umbilical for reducers. if (task.isMapTask()) { return umbilical; } String directUmbilicalAddress = job.get(DirectTaskUmbilical.MAPRED_DIRECT_TASK_UMBILICAL_ADDRESS); if (directUmbilicalAddress != null) { String hostPortPair[] = directUmbilicalAddress.split(":"); String jtHost = hostPortPair[0]; int jtPort = Integer.parseInt(hostPortPair[1]); InetSocketAddress addr = new InetSocketAddress(jtHost, jtPort); DirectTaskUmbilical d = DirectTaskUmbilical.createDirectUmbilical( umbilical, addr, job); proxiesCreated.addAll(d.getCreatedProxies()); return d; } return umbilical; } }
/* * 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.fontbox.type1; import org.apache.fontbox.encoding.BuiltInEncoding; import org.apache.fontbox.encoding.StandardEncoding; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Parses an Adobe Type 1 (.pfb) font. It is used exclusively by Type1Font. * * The Type 1 font format is a free-text format which is somewhat difficult * to parse. This is made worse by the fact that many Type 1 font files do * not conform to the specification, especially those embedded in PDFs. This * parser therefore tries to be as forgiving as possible. * * @see "Adobe Type 1 Font Format, Adobe Systems (1999)" * * @author John Hewson */ final class Type1Parser { // constants for encryption private static final int EEXEC_KEY = 55665; private static final int CHARSTRING_KEY = 4330; // state private Type1Lexer lexer; private Type1Font font; /** * Parses a Type 1 font and returns a Type1Font class which represents it. * * @param segment1 Segment 1: ASCII * @param segment2 Segment 2: Binary * @throws IOException */ public Type1Font parse(byte[] segment1, byte[] segment2) throws IOException { font = new Type1Font(segment1, segment2); parseASCII(segment1); if (segment2.length > 0) { parseBinary(segment2); } return font; } /** * Parses the ASCII portion of a Type 1 font. */ private void parseASCII(byte[] bytes) throws IOException { if (bytes.length == 0) { throw new IllegalArgumentException("byte[] is empty"); } // %!FontType1-1.0 // %!PS-AdobeFont-1.0 if (bytes.length < 2 || (bytes[0] != '%' && bytes[1] != '!')) { throw new IOException("Invalid start of ASCII segment"); } lexer = new Type1Lexer(bytes); // (corrupt?) synthetic font if (lexer.peekToken().getText().equals("FontDirectory")) { read(Token.NAME, "FontDirectory"); read(Token.LITERAL); // font name read(Token.NAME, "known"); read(Token.START_PROC); readProc(); read(Token.START_PROC); readProc(); read(Token.NAME, "ifelse"); } // font dict int length = read(Token.INTEGER).intValue(); read(Token.NAME, "dict"); readMaybe(Token.NAME, "dup"); // found in some TeX fonts read(Token.NAME, "begin"); for (int i = 0; i < length; i++) { // premature end if (lexer.peekToken().getKind() == Token.NAME && lexer.peekToken().getText().equals("currentdict")) { break; } // key/value String key = read(Token.LITERAL).getText(); if (key.equals("FontInfo")) { readFontInfo(readSimpleDict()); } else if (key.equals("Metrics")) { readSimpleDict(); } else if (key.equals("Encoding")) { readEncoding(); } else { readSimpleValue(key); } } read(Token.NAME, "currentdict"); read(Token.NAME, "end"); read(Token.NAME, "currentfile"); read(Token.NAME, "eexec"); } private void readSimpleValue(String key) throws IOException { List<Token> value = readDictValue(); if (key.equals("FontName")) { font.fontName = value.get(0).getText(); } else if (key.equals("PaintType")) { font.paintType = value.get(0).intValue(); } else if (key.equals("FontType")) { font.fontType = value.get(0).intValue(); } else if (key.equals("FontMatrix")) { font.fontMatrix = arrayToNumbers(value); } else if (key.equals("FontBBox")) { font.fontBBox = arrayToNumbers(value); } else if (key.equals("UniqueID")) { font.uniqueID = value.get(0).intValue(); } else if (key.equals("StrokeWidth")) { font.strokeWidth = value.get(0).floatValue(); } else if (key.equals("FID")) { font.fontID = value.get(0).getText(); } } private void readEncoding() throws IOException { if (lexer.peekToken().getKind() == Token.NAME) { String name = lexer.nextToken().getText(); if (name.equals("StandardEncoding")) { font.encoding = StandardEncoding.INSTANCE; } else { throw new IOException("Unknown encoding: " + name); } readMaybe(Token.NAME, "readonly"); read(Token.NAME, "def"); } else { read(Token.INTEGER).intValue(); readMaybe(Token.NAME, "array"); // 0 1 255 {1 index exch /.notdef put } for // we have to check "readonly" and "def" too // as some fonts don't provide any dup-values, see PDFBOX-2134 while (!(lexer.peekToken().getKind() == Token.NAME && (lexer.peekToken().getText().equals("dup") || lexer.peekToken().getText().equals("readonly") || lexer.peekToken().getText().equals("def")))) { lexer.nextToken(); } Map<Integer, String> codeToName = new HashMap<Integer, String>(); while (lexer.peekToken().getKind() == Token.NAME && lexer.peekToken().getText().equals("dup")) { read(Token.NAME, "dup"); int code = read(Token.INTEGER).intValue(); String name = read(Token.LITERAL).getText(); read(Token.NAME, "put"); codeToName.put(code, name); } font.encoding = new BuiltInEncoding(codeToName); readMaybe(Token.NAME, "readonly"); read(Token.NAME, "def"); } } /** * Extracts values from an array as numbers. */ private List<Number> arrayToNumbers(List<Token> value) throws IOException { List<Number> numbers = new ArrayList<Number>(); for (int i = 1, size = value.size() - 1; i < size; i++) { Token token = value.get(i); if (token.getKind() == Token.REAL) { numbers.add(token.floatValue()); } else if (token.getKind() == Token.INTEGER) { numbers.add(token.intValue()); } else { throw new IOException("Expected INTEGER or REAL but got " + token.getKind()); } } return numbers; } /** * Extracts values from the /FontInfo dictionary. */ private void readFontInfo(Map<String, List<Token>> fontInfo) { for (Map.Entry<String, List<Token>> entry : fontInfo.entrySet()) { String key = entry.getKey(); List<Token> value = entry.getValue(); if (key.equals("version")) { font.version = value.get(0).getText(); } else if (key.equals("Notice")) { font.notice = value.get(0).getText(); } else if (key.equals("FullName")) { font.fullName = value.get(0).getText(); } else if (key.equals("FamilyName")) { font.familyName = value.get(0).getText(); } else if (key.equals("Weight")) { font.weight = value.get(0).getText(); } else if (key.equals("ItalicAngle")) { font.italicAngle = value.get(0).floatValue(); } else if (key.equals("isFixedPitch")) { font.isFixedPitch = value.get(0).booleanValue(); } else if (key.equals("UnderlinePosition")) { font.underlinePosition = value.get(0).floatValue(); } else if (key.equals("UnderlineThickness")) { font.underlineThickness = value.get(0).floatValue(); } } } /** * Reads a dictionary whose values are simple, i.e., do not contain * nested dictionaries. */ private Map<String, List<Token>> readSimpleDict() throws IOException { Map<String, List<Token>> dict = new HashMap<String, List<Token>>(); int length = read(Token.INTEGER).intValue(); read(Token.NAME, "dict"); readMaybe(Token.NAME, "dup"); read(Token.NAME, "begin"); for (int i = 0; i < length; i++) { if (lexer.peekToken().getKind() == Token.NAME && !lexer.peekToken().getText().equals("end")) { read(Token.NAME); } // premature end if (lexer.peekToken().getKind() == Token.NAME && lexer.peekToken().getText().equals("end")) { break; } // simple value String key = read(Token.LITERAL).getText(); List<Token> value = readDictValue(); dict.put(key, value); } read(Token.NAME, "end"); readMaybe(Token.NAME, "readonly"); read(Token.NAME, "def"); return dict; } /** * Reads a simple value from a dictionary. */ private List<Token> readDictValue() throws IOException { List<Token> value = readValue(); readDef(); return value; } /** * Reads a simple value. This is either a number, a string, * a name, a literal name, an array, a procedure, or a charstring. * This method does not support reading nested dictionaries. */ private List<Token> readValue() throws IOException { List<Token> value = new ArrayList<Token>(); Token token = lexer.nextToken(); value.add(token); if (token.getKind() == Token.START_ARRAY) { int openArray = 1; while (true) { if (lexer.peekToken().getKind() == Token.START_ARRAY) { openArray++; } token = lexer.nextToken(); value.add(token); if (token.getKind() == Token.END_ARRAY) { openArray--; if (openArray == 0) { break; } } } } else if (token.getKind() == Token.START_PROC) { value.addAll(readProc()); } // postscript wrapper (not in the Type 1 spec) if (lexer.peekToken().getText().equals("systemdict")) { read(Token.NAME, "systemdict"); read(Token.LITERAL, "internaldict"); read(Token.NAME, "known"); read(Token.START_PROC); readProc(); read(Token.START_PROC); readProc(); read(Token.NAME, "ifelse"); // replace value read(Token.START_PROC); read(Token.NAME, "pop"); value.clear(); value.addAll(readValue()); read(Token.END_PROC); read(Token.NAME, "if"); } return value; } /** * Reads a procedure. */ private List<Token> readProc() throws IOException { List<Token> value = new ArrayList<Token>(); int openProc = 1; while (true) { if (lexer.peekToken().getKind() == Token.START_PROC) { openProc++; } Token token = lexer.nextToken(); value.add(token); if (token.getKind() == Token.END_PROC) { openProc--; if (openProc == 0) { break; } } } Token executeonly = readMaybe(Token.NAME, "executeonly"); if (executeonly != null) { value.add(executeonly); } return value; } /** * Parses the binary portion of a Type 1 font. */ private void parseBinary(byte[] bytes) throws IOException { byte[] decrypted; // Sometimes, fonts use the hex format, so this needs to be converted before decryption if (isBinary(bytes)) { decrypted = decrypt(bytes, EEXEC_KEY, 4); } else { decrypted = decrypt(hexToBinary(bytes), EEXEC_KEY, 4); } lexer = new Type1Lexer(decrypted); // find /Private dict Token peekToken = lexer.peekToken(); while (peekToken != null && !peekToken.getText().equals("Private")) { lexer.nextToken(); peekToken = lexer.peekToken(); } if (peekToken == null) { throw new IOException("/Private token not found"); } // Private dict read(Token.LITERAL, "Private"); int length = read(Token.INTEGER).intValue(); read(Token.NAME, "dict"); readMaybe(Token.NAME, "dup"); read(Token.NAME, "begin"); int lenIV = 4; // number of random bytes at start of charstring for (int i = 0; i < length; i++) { // premature end if (lexer.peekToken().getKind() != Token.LITERAL) { break; } // key/value String key = read(Token.LITERAL).getText(); if (key.equals("Subrs")) { readSubrs(lenIV); } else if (key.equals("OtherSubrs")) { readOtherSubrs(); } else if (key.equals("lenIV")) { lenIV = readDictValue().get(0).intValue(); } else if (key.equals("ND")) { read(Token.START_PROC); read(Token.NAME, "noaccess"); read(Token.NAME, "def"); read(Token.END_PROC); read(Token.NAME, "executeonly"); read(Token.NAME, "def"); } else if (key.equals("NP")) { read(Token.START_PROC); read(Token.NAME, "noaccess"); read(Token.NAME); read(Token.END_PROC); read(Token.NAME, "executeonly"); read(Token.NAME, "def"); } else if (key.equals("RD")) { // /RD {string currentfile exch readstring pop} bind executeonly def read(Token.START_PROC); readProc(); readMaybe(Token.NAME, "bind"); readMaybe(Token.NAME, "executeonly"); read(Token.NAME, "def"); } else { readPrivate(key, readDictValue()); } } // some fonts have "2 index" here, others have "end noaccess put" // sometimes followed by "put". Either way, we just skip until // the /CharStrings dict is found while (!(lexer.peekToken().getKind() == Token.LITERAL && lexer.peekToken().getText().equals("CharStrings"))) { lexer.nextToken(); } // CharStrings dict read(Token.LITERAL, "CharStrings"); readCharStrings(lenIV); } /** * Extracts values from the /Private dictionary. */ private void readPrivate(String key, List<Token> value) throws IOException { if (key.equals("BlueValues")) { font.blueValues = arrayToNumbers(value); } else if (key.equals("OtherBlues")) { font.otherBlues = arrayToNumbers(value); } else if (key.equals("FamilyBlues")) { font.familyBlues = arrayToNumbers(value); } else if (key.equals("FamilyOtherBlues")) { font.familyOtherBlues = arrayToNumbers(value); } else if (key.equals("BlueScale")) { font.blueScale = value.get(0).floatValue(); } else if (key.equals("BlueShift")) { font.blueShift = value.get(0).intValue(); } else if (key.equals("BlueFuzz")) { font.blueFuzz = value.get(0).intValue(); } else if (key.equals("StdHW")) { font.stdHW = arrayToNumbers(value); } else if (key.equals("StdVW")) { font.stdVW = arrayToNumbers(value); } else if (key.equals("StemSnapH")) { font.stemSnapH = arrayToNumbers(value); } else if (key.equals("StemSnapV")) { font.stemSnapV = arrayToNumbers(value); } else if (key.equals("ForceBold")) { font.forceBold = value.get(0).booleanValue(); } else if (key.equals("LanguageGroup")) { font.languageGroup = value.get(0).intValue(); } } /** * Reads the /Subrs array. * @param lenIV The number of random bytes used in charstring encryption. */ private void readSubrs(int lenIV) throws IOException { // allocate size (array indexes may not be in-order) int length = read(Token.INTEGER).intValue(); for (int i = 0; i < length; i++) { font.subrs.add(null); } read(Token.NAME, "array"); for (int i = 0; i < length; i++) { // premature end if (!(lexer.peekToken().getKind() == Token.NAME && lexer.peekToken().getText().equals("dup"))) { break; } read(Token.NAME, "dup"); Token index = read(Token.INTEGER); read(Token.INTEGER); // RD Token charstring = read(Token.CHARSTRING); font.subrs.set(index.intValue(), decrypt(charstring.getData(), CHARSTRING_KEY, lenIV)); readPut(); } readDef(); } // OtherSubrs are embedded PostScript procedures which we can safely ignore private void readOtherSubrs() throws IOException { if (lexer.peekToken().getKind() == Token.START_ARRAY) { readValue(); readDef(); } else { int length = read(Token.INTEGER).intValue(); read(Token.NAME, "array"); for (int i = 0; i < length; i++) { read(Token.NAME, "dup"); read(Token.INTEGER); // index readValue(); // PostScript readPut(); } readDef(); } } /** * Reads the /CharStrings dictionary. * @param lenIV The number of random bytes used in charstring encryption. */ private void readCharStrings(int lenIV) throws IOException { int length = read(Token.INTEGER).intValue(); read(Token.NAME, "dict"); read(Token.NAME, "dup"); read(Token.NAME, "begin"); for (int i = 0; i < length; i++) { // premature end if (lexer.peekToken().getKind() == Token.NAME && lexer.peekToken().getText().equals("end")) { break; } // key/value String name = read(Token.LITERAL).getText(); // RD read(Token.INTEGER); Token charstring = read(Token.CHARSTRING); font.charstrings.put(name, decrypt(charstring.getData(), CHARSTRING_KEY, lenIV)); readDef(); } // some fonts have one "end", others two read(Token.NAME, "end"); } /** * Reads the sequence "noaccess def" or equivalent. */ private void readDef() throws IOException { readMaybe(Token.NAME, "readonly"); readMaybe(Token.NAME, "noaccess"); // allows "noaccess ND" (not in the Type 1 spec) Token token = read(Token.NAME); if (token.getText().equals("ND") || token.getText().equals("|-")) { return; } else if (token.getText().equals("noaccess")) { token = read(Token.NAME); } if (token.getText().equals("def")) { return; } throw new IOException("Found " + token + " but expected ND"); } /** * Reads the sequence "noaccess put" or equivalent. */ private void readPut() throws IOException { readMaybe(Token.NAME, "readonly"); Token token = read(Token.NAME); if (token.getText().equals("NP") || token.getText().equals("|")) { return; } else if (token.getText().equals("noaccess")) { token = read(Token.NAME); } if (token.getText().equals("put")) { return; } throw new IOException("Found " + token + " but expected NP"); } /** * Reads the next token and throws an error if it is not of the given kind. */ private Token read(Token.Kind kind) throws IOException { Token token = lexer.nextToken(); if (token == null || token.getKind() != kind) { throw new IOException("Found " + token + " but expected " + kind); } return token; } /** * Reads the next token and throws an error if it is not of the given kind * and does not have the given value. */ private void read(Token.Kind kind, String name) throws IOException { Token token = read(kind); if (!token.getText().equals(name)) { throw new IOException("Found " + token + " but expected " + name); } } /** * Reads the next token if and only if it is of the given kind and * has the given value. */ private Token readMaybe(Token.Kind kind, String name) throws IOException { Token token = lexer.peekToken(); if (token.getKind() == kind && token.getText().equals(name)) { return lexer.nextToken(); } return null; } /** * Type 1 Decryption (eexec, charstring). * * @param cipherBytes cipher text * @param r key * @param n number of random bytes (lenIV) * @return plain text */ private byte[] decrypt(byte[] cipherBytes, int r, int n) { // lenIV of -1 means no encryption (not documented) if (n == -1) { return cipherBytes; } // empty charstrings and charstrings of insufficient length if (cipherBytes.length == 0 || n > cipherBytes.length) { return new byte[] {}; } // decrypt int c1 = 52845; int c2 = 22719; byte[] plainBytes = new byte[cipherBytes.length - n]; for (int i = 0; i < cipherBytes.length; i++) { int cipher = cipherBytes[i] & 0xFF; int plain = cipher ^ r >> 8; if (i >= n) { plainBytes[i - n] = (byte) plain; } r = (cipher + r) * c1 + c2 & 0xffff; } return plainBytes; } // Check whether binary or hex encoded. See Adobe Type 1 Font Format specification // 7.2 eexec encryption private boolean isBinary(byte[] bytes) { if (bytes.length < 4) { return true; } // "At least one of the first 4 ciphertext bytes must not be one of // the ASCII hexadecimal character codes (a code for 0-9, A-F, or a-f)." for (int i = 0; i < 4; ++i) { byte by = bytes[i]; if (by != 0x0a && by != 0x0d && by != 0x20 && by != '\t' && Character.digit((char) by, 16) == -1) { return true; } } return false; } private byte[] hexToBinary(byte[] bytes) { // calculate needed length int len = 0; for (int i = 0; i < bytes.length; ++i) { if (Character.digit((char) bytes[i], 16) != -1) { ++len; } } byte[] res = new byte[len / 2]; int r = 0; int prev = -1; for (int i = 0; i < bytes.length; ++i) { int digit = Character.digit((char) bytes[i], 16); if (digit != -1) { if (prev == -1) { prev = digit; } else { res[r++] = (byte) (prev * 16 + digit); prev = -1; } } } return res; } }
/*- * Copyright 2014 The American National Corpus. * * 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.anc.lapps.stanford; import edu.stanford.nlp.ie.AbstractSequenceClassifier; import edu.stanford.nlp.ie.crf.CRFClassifier; import edu.stanford.nlp.ling.CoreAnnotations; import edu.stanford.nlp.ling.CoreAnnotations.AnswerAnnotation; import edu.stanford.nlp.ling.CoreLabel; import org.anc.lapps.stanford.util.StanfordUtils; import org.anc.util.IDGenerator; import org.lappsgrid.annotations.ServiceMetadata; import org.lappsgrid.serialization.*; import org.lappsgrid.serialization.lif.Annotation; import org.lappsgrid.serialization.lif.Container; import org.lappsgrid.serialization.lif.View; import org.lappsgrid.vocabulary.Features; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import static org.lappsgrid.discriminator.Discriminators.Uri; @ServiceMetadata( description = "Stanford Named Entity Recognizer (Selectable)", requires = "token", produces = {"date", "person", "location", "organization"} ) public class SelectableNamedEntityRecognizer extends AbstractStanfordService { private static final Logger logger = LoggerFactory.getLogger(SelectableNamedEntityRecognizer.class); private static final String classifierRoot = Constants.PATH.NER_MODEL_ROOT; //protected AbstractSequenceClassifier classifier; protected Map<String, AbstractSequenceClassifier> pool; // protected BlockingQueue<AbstractSequenceClassifier> pool; protected Throwable savedException = null; protected String exceptionMessage = null; protected HashMap<String,String> nameMap = new HashMap<>(); public static final String ALL = "english.all.3class.distsim.crf.ser.gz"; public static final String CONLL = "english.conll.4class.distsim.crf.ser.gz"; public static final String MUC = "english.muc.7class.distsim.crf.ser.gz"; public static final String NOWIKI = "english.nowiki.3class.distsim.crf.ser.gz"; public static final String[] NAMES = { ALL, CONLL, MUC, NOWIKI }; public SelectableNamedEntityRecognizer() { super(SelectableNamedEntityRecognizer.class); pool = new HashMap<>(); try { // String[] names = // File root = new File(classifierRoot); // for (String name : names) // { // File file = new File(root, name); // pool.put(name, CRFClassifier.getClassifier(file)); // } mapNames(Uri.PERSON, "person", "Person", "PERSON"); mapNames(Uri.LOCATION, "location", "Location", "LOCATION"); mapNames(Uri.ORGANIZATION, "org", "organization", "ORGANIZATION"); mapNames(Uri.DATE, "data", "Date", "DATE"); logger.info("Stanford Stand-Alone Named-Entity Recognizer created."); } catch (OutOfMemoryError e) { logger.error("Ran out of memory creating the CRFClassifier.", e); savedException = e; } catch (Exception e) { logger.error("Unable to create the CRFClassifier.", e); savedException = e; } } private void mapNames(String uri, String... names) { for (String name : names) { nameMap.put(name, uri); } } @Override public String execute(String input) { logger.info("Executing the Stanford Named Entity Recognizer."); // A savedException indicates there was a problem creating the CRFClassifier // object. if (savedException != null) { if (exceptionMessage == null) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); writer.println(savedException.getMessage()); savedException.printStackTrace(writer); exceptionMessage = stringWriter.toString(); } return createError(exceptionMessage); } Data data = Serializer.parse(input, Data.class); if (data == null) { return createError("Unable to parse input."); } // String payload = map.get("payload"); // if (payload == null) // { // return createError(Messages.MISSING_PAYLOAD); // } String discriminator = data.getDiscriminator(); logger.info("Discriminator is {}", discriminator); String json = null; switch (discriminator) { case Uri.ERROR: json = input; break; case Uri.GETMETADATA: json = super.getMetadata(); logger.info("Loaded metadata"); //System.out.println(json); break; case Uri.LAPPS: // fall through case Uri.JSON: case Uri.JSON_LD: // Nothing needs to be done other than preventing the default case. break; default: json = createError(Messages.UNSUPPORTED_INPUT_TYPE + discriminator); break; } if (json != null) { return json; } Container container = new Container((Map)data.getPayload()); logger.info("Executing Configurable Stanford Named Entity Recognizer."); List<CoreLabel> labels = StanfordUtils.getListOfTaggedCoreLabels(container); if (labels == null || labels.size() == 0) { String message = "Unable to initialize a list of Stanford CoreLabels."; logger.warn(message); return createError(message); } Object param = data.getParameter("classifier"); if (param == null) { // System.out.println(data.asPrettyJson()); return createError("No classifier parameter provided."); } String classifierName = param.toString(); AbstractSequenceClassifier classifier = getClassifier(classifierName); if (classifier == null) { return createError("No such classifier: " + classifierName); } List<CoreLabel> classifiedLabels = classifier.classify(labels); if (classifiedLabels == null) { logger.warn("Classifier returned null"); } else if (classifiedLabels.size() == 0) { logger.warn("No named entities found."); } else { logger.info("There are {} labels.", classifiedLabels.size()); Set<String> types = new HashSet<String>(); IDGenerator id = new IDGenerator(); View view = new View(); String invalidNer = "O"; for (CoreLabel label : classifiedLabels) { String ner = label.get(AnswerAnnotation.class); logger.info("Label: {}", ner); if (!ner.equals(invalidNer)) { Annotation annotation = new Annotation(); String type = getUriForType(ner); types.add(type); annotation.setLabel(ner); annotation.setAtType(type); // annotation.setLabel(correctCase(ner)); annotation.setId(id.generate("ne")); long start = label.beginPosition(); long end = label.endPosition(); annotation.setStart(start); annotation.setEnd(end); Map<String,String> features = annotation.getFeatures(); add(features, Features.Token.LEMMA, label.lemma()); add(features, "category", label.category()); add(features, Features.Token.POS, label.get(CoreAnnotations.PartOfSpeechAnnotation.class)); add(features, "ner", label.ner()); add(features, "word", label.word()); view.addAnnotation(annotation); } } //ProcessingStep step = Converter.addTokens(new ProcessingStep(), labels); String producer = this.getClass().getName() + ":" + Version.getVersion(); for (String type : types) { logger.info("{} produced by {}", type, producer); view.addContains(type, producer, classifierName); } // view.addContains(Uri.NE, producer, "ner:stanford"); container.getViews().add(view); } data.setDiscriminator(Uri.LAPPS); data.setPayload(container); return data.asJson(); } private AbstractSequenceClassifier getClassifier(String name) { AbstractSequenceClassifier classifier = pool.get(name); if (classifier != null) { return classifier; } File file = new File(classifierRoot, name); if (!file.exists()) { return null; } try { classifier = CRFClassifier.getClassifier(file); } catch (IOException e) { return null; } catch (ClassNotFoundException e) { return null; } pool.put(name, classifier); return classifier; } private String getUriForType(String type) { if ("PERSON".equals(type)) return Uri.PERSON; if ("DATE".equals(type)) return Uri.DATE; if ("LOCATION".equals(type)) return Uri.LOCATION; if ("ORGANIZATION".equals(type)) return Uri.ORGANIZATION; if ("MISC".equals(type)) return Uri.NE; return type; } private String correctCase(String item) { // String head = item.substring(0, 1); // String tail = item.substring(1).toLowerCase(); // return head + tail; String uri = nameMap.get(item); if (uri == null) { return item; } return uri; } private void add(Map<String,String> features, String name, String value) { if (value != null) { features.put(name, value); } } // @Override // public Data configure(Data arg0) // { // return DataFactory.error("Unsupported operation."); // } }
/* * Copyright 2005 Joe Walker * * 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.directwebremoting.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.TreeMap; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import org.directwebremoting.Container; import org.directwebremoting.extend.ContainerConfigurationException; import org.directwebremoting.extend.UninitializingBean; import org.directwebremoting.util.LocalUtil; import org.directwebremoting.util.Loggers; /** * DefaultContainer is like a mini-IoC container for DWR. * At least it is an IoC container by interface (check: no params that have * anything to do with DWR), but it is hard coded specifically for DWR. If we * want to make more of it we can later, but this is certainly not going to * become a full blown IoC container. * @author Joe Walker [joe at getahead dot ltd dot uk] */ public class DefaultContainer extends AbstractContainer implements Container { /** * Set the class that should be used to implement the given interface * @param base The interface to implement * @param bean The new implementation * @throws ContainerConfigurationException If the specified beans could not be used */ public <T> void addBean(Class<T> base, T bean) { addParameter(LocalUtil.originalDwrClassName(base.getName()), bean); } /** * Set the class that should be used to implement the given interface * @param base The interface to implement * @param implementation The new implementation * @throws ContainerConfigurationException If the specified beans could not be used */ public <T> void addImplementation(Class<T> base, Class<? extends T> implementation) { addParameter(LocalUtil.originalDwrClassName(base.getName()), implementation.getName()); } /** * Set the class that should be used to implement the given interface * @param base The interface to implement * @param implementation The new implementation * @throws ContainerConfigurationException If the specified beans could not be used */ public <T> void addImplementationOption(Class<T> base, Class<? extends T> implementation) { Object existingOptions = beans.get(base.getName()); if (existingOptions == null) { beans.put(LocalUtil.originalDwrClassName(base.getName()), implementation.getName()); } else { beans.put(LocalUtil.originalDwrClassName(base.getName()), existingOptions + " " + implementation.getName()); } } /** * Add a parameter to the container as a possibility for injection * @param askFor The key that will be looked up * @param valueParam The value to be returned from the key lookup * @throws ContainerConfigurationException If the specified beans could not be used */ public void addParameter(String askFor, Object valueParam) throws ContainerConfigurationException { Object value = valueParam; // Maybe the value is a classname that needs instantiating if (value instanceof String) { try { Class<?> impl = LocalUtil.classForName((String) value); value = impl.newInstance(); } catch (ClassNotFoundException ex) { // it's not a classname, leave it } catch (InstantiationException ex) { throw new ContainerConfigurationException("Unable to instantiate " + value); } catch (IllegalAccessException ex) { throw new ContainerConfigurationException("Unable to access " + value); } } // If we have an instantiated value object and askFor is an interface // then we can check that one implements the other if (!(value instanceof String)) { try { Class<?> iface = LocalUtil.classForName(askFor); if (!iface.isAssignableFrom(value.getClass())) { Loggers.STARTUP.error("Can't cast: " + value + " to " + askFor); } } catch (ClassNotFoundException ex) { // it's not a classname, leave it } } if (Loggers.STARTUP.isDebugEnabled()) { if (value instanceof String) { Loggers.STARTUP.debug("- value: " + askFor + " = " + value); } else { Loggers.STARTUP.debug("- impl: " + askFor + " = " + value.getClass().getName()); } } beans.put(askFor, value); } /** * Retrieve a previously set parameter * @param name The parameter name to retrieve * @return The value of the specified parameter, or null if one is not set */ public String getParameter(String name) { Object value = beans.get(name); return (value == null) ? null : value.toString(); } /** * Called to indicate that we finished adding parameters. * The thread safety of a large part of DWR depends on this function only * being called from {@link Servlet#init(javax.servlet.ServletConfig)}, * where all the setup is done, and where we depend on the undocumented * feature of all servlet containers that they complete the init process * of a Servlet before they begin servicing requests. * @see DefaultContainer#addParameter(String, Object) * @noinspection UnnecessaryLabelOnContinueStatement */ public void setupFinished() { // We try to autowire each bean in turn for (Object bean : beans.values()) { initializeBean(bean); } callInitializingBeans(); } /* (non-Javadoc) * @see org.directwebremoting.Container#newInstance(java.lang.Class) */ public <T> T newInstance(Class<T> type) throws InstantiationException, IllegalAccessException { T t = type.newInstance(); initializeBean(t); return t; } /* (non-Javadoc) * @see org.directwebremoting.Container#initializeBean(java.lang.Object) */ public void initializeBean(Object bean) { // HACK: It wouldn't be a good idea to start injecting into objects // created by the app-server. Currently this is just ServletContext // and ServletConfig. If it is others in the future then we'll need a // better way of marking objects that should not be injected into. // It's worth remembering that the Container is itself in the container // so there is a vague risk of recursion here if we're not careful if (bean instanceof ServletContext || bean instanceof ServletConfig) { Loggers.STARTUP.debug("- skipping injecting into: " + bean.getClass().getName()); return; } if (!(bean instanceof String)) { Loggers.STARTUP.debug("- autowire: " + bean.getClass().getName()); Method[] methods = bean.getClass().getMethods(); methods: for (Method setter : methods) { if (setter.getName().startsWith("set") && setter.getName().length() > 3 && setter.getParameterTypes().length == 1) { String name = Character.toLowerCase(setter.getName().charAt(3)) + setter.getName().substring(4); Class<?> propertyType = setter.getParameterTypes()[0]; // First we try auto-wire by name Object setting = beans.get(name); if (setting != null) { if (propertyType.isAssignableFrom(setting.getClass())) { Loggers.STARTUP.debug(" - by name: " + name + " = " + setting); invoke(setter, bean, setting); continue methods; } else if (setting.getClass() == String.class) { try { Object value = LocalUtil.simpleConvert((String) setting, propertyType); Loggers.STARTUP.debug(" - by name: " + name + " = " + value); invoke(setter, bean, value); } catch (IllegalArgumentException ex) { // Ignore - this was a speculative convert anyway } continue methods; } } // Next we try autowire-by-type Object value = beans.get(LocalUtil.originalDwrClassName(propertyType.getName())); if (value != null) { Loggers.STARTUP.debug(" - by type: " + name + " = " + value.getClass().getName()); invoke(setter, bean, value); continue methods; } Loggers.STARTUP.debug(" - no properties for: " + name); } } } } /** * A helper to do the reflection. * This helper throws away all exceptions, preferring to log. * @param setter The method to invoke * @param bean The object to invoke the method on * @param value The value to assign to the property using the setter method */ private static void invoke(Method setter, Object bean, Object value) { try { setter.invoke(bean, value); } catch (InvocationTargetException ex) { Loggers.STARTUP.error(" - Exception during auto-wire: ", ex.getTargetException()); } catch (Exception ex) { Loggers.STARTUP.error(" - Error calling setter: " + setter, ex); } } /* (non-Javadoc) * @see org.directwebremoting.Container#getBean(java.lang.String) */ public Object getBean(String id) { return beans.get(id); } /* (non-Javadoc) * @see org.directwebremoting.Container#getBeanNames() */ public Collection<String> getBeanNames() { return Collections.unmodifiableCollection(beans.keySet()); } /* (non-Javadoc) * @see org.directwebremoting.Container#contextDestroyed() */ public void contextDestroyed() { contextDestroyed(getBeanNames()); } public void contextDestroyed(Collection<String> beanNames) { Loggers.STARTUP.debug("ContextDestroyed for container: " + getClass().getSimpleName()); for (String beanName : beanNames) { Object bean = getBean(beanName); if (bean instanceof UninitializingBean && !(bean instanceof Container)) { UninitializingBean scl = (UninitializingBean) bean; Loggers.STARTUP.debug("- For contained bean: " + beanName); scl.contextDestroyed(); } } } /* (non-Javadoc) * @see org.directwebremoting.Container#servletDestroyed() */ public void servletDestroyed() { servletDestroyed(getBeanNames()); } /* (non-Javadoc) * @see org.directwebremoting.Container#servletDestroyed() */ public void servletDestroyed(Collection<String> beanNames) { Loggers.STARTUP.debug("ServletDestroyed for container: " + getClass().getSimpleName()); for (String beanName : beanNames) { Object bean = getBean(beanName); if (bean instanceof UninitializingBean && !(bean instanceof Container)) { UninitializingBean scl = (UninitializingBean) bean; Loggers.STARTUP.debug("- For contained bean: " + beanName); scl.servletDestroyed(); } } } /** * The beans that we know of indexed by type */ protected Map<String, Object> beans = new TreeMap<String, Object>(); }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.plugin.raptor.legacy.storage; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import io.airlift.slice.Slice; import io.airlift.units.DataSize; import io.airlift.units.Duration; import io.prestosql.orc.OrcDataSource; import io.prestosql.orc.OrcRecordReader; import io.prestosql.plugin.raptor.legacy.RaptorColumnHandle; import io.prestosql.plugin.raptor.legacy.backup.BackupManager; import io.prestosql.plugin.raptor.legacy.backup.BackupStore; import io.prestosql.plugin.raptor.legacy.backup.FileBackupStore; import io.prestosql.plugin.raptor.legacy.metadata.ColumnStats; import io.prestosql.plugin.raptor.legacy.metadata.ShardDelta; import io.prestosql.plugin.raptor.legacy.metadata.ShardInfo; import io.prestosql.plugin.raptor.legacy.metadata.ShardManager; import io.prestosql.plugin.raptor.legacy.metadata.ShardRecorder; import io.prestosql.plugin.raptor.legacy.storage.InMemoryShardRecorder.RecordedShard; import io.prestosql.spi.NodeManager; import io.prestosql.spi.Page; import io.prestosql.spi.block.Block; import io.prestosql.spi.connector.ConnectorPageSource; import io.prestosql.spi.predicate.NullableValue; import io.prestosql.spi.predicate.TupleDomain; import io.prestosql.spi.type.SqlDate; import io.prestosql.spi.type.SqlTimestamp; import io.prestosql.spi.type.SqlVarbinary; import io.prestosql.spi.type.Type; import io.prestosql.testing.MaterializedResult; import io.prestosql.testing.TestingNodeManager; import io.prestosql.type.TypeRegistry; import org.joda.time.DateTime; import org.joda.time.Days; import org.joda.time.chrono.ISOChronology; import org.skife.jdbi.v2.DBI; import org.skife.jdbi.v2.Handle; import org.skife.jdbi.v2.IDBI; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.UUID; import java.util.concurrent.TimeUnit; import static com.google.common.hash.Hashing.md5; import static com.google.common.io.Files.createTempDir; import static com.google.common.io.Files.hash; import static com.google.common.io.MoreFiles.deleteRecursively; import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE; import static io.airlift.concurrent.MoreFutures.getFutureValue; import static io.airlift.json.JsonCodec.jsonCodec; import static io.airlift.slice.Slices.utf8Slice; import static io.airlift.slice.Slices.wrappedBuffer; import static io.airlift.units.DataSize.Unit.BYTE; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static io.prestosql.RowPagesBuilder.rowPagesBuilder; import static io.prestosql.plugin.raptor.legacy.metadata.SchemaDaoUtil.createTablesWithRetry; import static io.prestosql.plugin.raptor.legacy.metadata.TestDatabaseShardManager.createShardManager; import static io.prestosql.plugin.raptor.legacy.storage.OrcStorageManager.xxhash64; import static io.prestosql.plugin.raptor.legacy.storage.OrcTestingUtil.createReader; import static io.prestosql.plugin.raptor.legacy.storage.OrcTestingUtil.octets; import static io.prestosql.spi.type.BigintType.BIGINT; import static io.prestosql.spi.type.BooleanType.BOOLEAN; import static io.prestosql.spi.type.DateType.DATE; import static io.prestosql.spi.type.DoubleType.DOUBLE; import static io.prestosql.spi.type.TimeZoneKey.UTC_KEY; import static io.prestosql.spi.type.TimestampType.TIMESTAMP; import static io.prestosql.spi.type.VarbinaryType.VARBINARY; import static io.prestosql.spi.type.VarcharType.createVarcharType; import static io.prestosql.testing.DateTimeTestingUtils.sqlTimestampOf; import static io.prestosql.testing.MaterializedResult.materializeSourceDataStream; import static io.prestosql.testing.MaterializedResult.resultBuilder; import static io.prestosql.testing.TestingConnectorSession.SESSION; import static io.prestosql.testing.assertions.Assert.assertEquals; import static java.lang.String.format; import static org.joda.time.DateTimeZone.UTC; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import static org.testng.FileAssert.assertDirectory; import static org.testng.FileAssert.assertFile; @Test(singleThreaded = true) public class TestOrcStorageManager { private static final ISOChronology UTC_CHRONOLOGY = ISOChronology.getInstanceUTC(); private static final DateTime EPOCH = new DateTime(0, UTC_CHRONOLOGY); private static final String CURRENT_NODE = "node"; private static final String CONNECTOR_ID = "test"; private static final long TRANSACTION_ID = 123; private static final int DELETION_THREADS = 2; private static final Duration SHARD_RECOVERY_TIMEOUT = new Duration(30, TimeUnit.SECONDS); private static final int MAX_SHARD_ROWS = 100; private static final DataSize MAX_FILE_SIZE = new DataSize(1, MEGABYTE); private static final Duration MISSING_SHARD_DISCOVERY = new Duration(5, TimeUnit.MINUTES); private static final ReaderAttributes READER_ATTRIBUTES = new ReaderAttributes(new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true); private final NodeManager nodeManager = new TestingNodeManager(); private Handle dummyHandle; private File temporary; private StorageService storageService; private ShardRecoveryManager recoveryManager; private FileBackupStore fileBackupStore; private Optional<BackupStore> backupStore; private InMemoryShardRecorder shardRecorder; @BeforeMethod public void setup() { temporary = createTempDir(); File directory = new File(temporary, "data"); storageService = new FileStorageService(directory); storageService.start(); File backupDirectory = new File(temporary, "backup"); fileBackupStore = new FileBackupStore(backupDirectory); fileBackupStore.start(); backupStore = Optional.of(fileBackupStore); IDBI dbi = new DBI("jdbc:h2:mem:test" + System.nanoTime()); dummyHandle = dbi.open(); createTablesWithRetry(dbi); ShardManager shardManager = createShardManager(dbi); Duration discoveryInterval = new Duration(5, TimeUnit.MINUTES); recoveryManager = new ShardRecoveryManager(storageService, backupStore, nodeManager, shardManager, discoveryInterval, 10); shardRecorder = new InMemoryShardRecorder(); } @AfterMethod(alwaysRun = true) public void tearDown() throws Exception { if (dummyHandle != null) { dummyHandle.close(); } deleteRecursively(temporary.toPath(), ALLOW_INSECURE); } @Test public void testWriter() throws Exception { OrcStorageManager manager = createOrcStorageManager(); List<Long> columnIds = ImmutableList.of(3L, 7L); List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(10)); StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); List<Page> pages = rowPagesBuilder(columnTypes) .row(123L, "hello") .row(456L, "bye") .build(); sink.appendPages(pages); // shard is not recorded until flush assertEquals(shardRecorder.getShards().size(), 0); sink.flush(); // shard is recorded after flush List<RecordedShard> recordedShards = shardRecorder.getShards(); assertEquals(recordedShards.size(), 1); List<ShardInfo> shards = getFutureValue(sink.commit()); assertEquals(shards.size(), 1); ShardInfo shardInfo = Iterables.getOnlyElement(shards); UUID shardUuid = shardInfo.getShardUuid(); File file = storageService.getStorageFile(shardUuid); File backupFile = fileBackupStore.getBackupFile(shardUuid); assertEquals(recordedShards.get(0).getTransactionId(), TRANSACTION_ID); assertEquals(recordedShards.get(0).getShardUuid(), shardUuid); assertEquals(shardInfo.getRowCount(), 2); assertEquals(shardInfo.getCompressedSize(), file.length()); assertEquals(shardInfo.getXxhash64(), xxhash64(file)); // verify primary and backup shard exist assertFile(file, "primary shard"); assertFile(backupFile, "backup shard"); assertFileEquals(file, backupFile); // remove primary shard to force recovery from backup assertTrue(file.delete()); assertTrue(file.getParentFile().delete()); assertFalse(file.exists()); recoveryManager.restoreFromBackup(shardUuid, shardInfo.getCompressedSize(), OptionalLong.of(shardInfo.getXxhash64())); try (OrcDataSource dataSource = manager.openShard(shardUuid, READER_ATTRIBUTES)) { OrcRecordReader reader = createReader(dataSource, columnIds, columnTypes); assertEquals(reader.nextBatch(), 2); Block column0 = reader.readBlock(BIGINT, 0); assertEquals(column0.isNull(0), false); assertEquals(column0.isNull(1), false); assertEquals(BIGINT.getLong(column0, 0), 123L); assertEquals(BIGINT.getLong(column0, 1), 456L); Block column1 = reader.readBlock(createVarcharType(10), 1); assertEquals(createVarcharType(10).getSlice(column1, 0), utf8Slice("hello")); assertEquals(createVarcharType(10).getSlice(column1, 1), utf8Slice("bye")); assertEquals(reader.nextBatch(), -1); } } @Test public void testReader() throws Exception { OrcStorageManager manager = createOrcStorageManager(); List<Long> columnIds = ImmutableList.of(2L, 4L, 6L, 7L, 8L, 9L); List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(10), VARBINARY, DATE, BOOLEAN, DOUBLE); byte[] bytes1 = octets(0x00, 0xFE, 0xFF); byte[] bytes3 = octets(0x01, 0x02, 0x19, 0x80); StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); Object[][] doubles = { {881L, "-inf", null, null, null, Double.NEGATIVE_INFINITY}, {882L, "+inf", null, null, null, Double.POSITIVE_INFINITY}, {883L, "nan", null, null, null, Double.NaN}, {884L, "min", null, null, null, Double.MIN_VALUE}, {885L, "max", null, null, null, Double.MAX_VALUE}, {886L, "pzero", null, null, null, 0.0}, {887L, "nzero", null, null, null, -0.0}, }; List<Page> pages = rowPagesBuilder(columnTypes) .row(123L, "hello", wrappedBuffer(bytes1), sqlDate(2001, 8, 22).getDays(), true, 123.45) .row(null, null, null, null, null, null) .row(456L, "bye", wrappedBuffer(bytes3), sqlDate(2005, 4, 22).getDays(), false, 987.65) .rows(doubles) .build(); sink.appendPages(pages); List<ShardInfo> shards = getFutureValue(sink.commit()); assertEquals(shards.size(), 1); UUID uuid = Iterables.getOnlyElement(shards).getShardUuid(); MaterializedResult expected = resultBuilder(SESSION, columnTypes) .row(123L, "hello", sqlBinary(bytes1), sqlDate(2001, 8, 22), true, 123.45) .row(null, null, null, null, null, null) .row(456L, "bye", sqlBinary(bytes3), sqlDate(2005, 4, 22), false, 987.65) .rows(doubles) .build(); // no tuple domain (all) TupleDomain<RaptorColumnHandle> tupleDomain = TupleDomain.all(); try (ConnectorPageSource pageSource = getPageSource(manager, columnIds, columnTypes, uuid, tupleDomain)) { MaterializedResult result = materializeSourceDataStream(SESSION, pageSource, columnTypes); assertEquals(result.getRowCount(), expected.getRowCount()); assertEquals(result, expected); } // tuple domain within the column range tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.<RaptorColumnHandle, NullableValue>builder() .put(new RaptorColumnHandle("test", "c1", 2, BIGINT), NullableValue.of(BIGINT, 124L)) .build()); try (ConnectorPageSource pageSource = getPageSource(manager, columnIds, columnTypes, uuid, tupleDomain)) { MaterializedResult result = materializeSourceDataStream(SESSION, pageSource, columnTypes); assertEquals(result.getRowCount(), expected.getRowCount()); } // tuple domain outside the column range tupleDomain = TupleDomain.fromFixedValues(ImmutableMap.<RaptorColumnHandle, NullableValue>builder() .put(new RaptorColumnHandle("test", "c1", 2, BIGINT), NullableValue.of(BIGINT, 122L)) .build()); try (ConnectorPageSource pageSource = getPageSource(manager, columnIds, columnTypes, uuid, tupleDomain)) { MaterializedResult result = materializeSourceDataStream(SESSION, pageSource, columnTypes); assertEquals(result.getRowCount(), 0); } } @Test public void testRewriter() throws Exception { OrcStorageManager manager = createOrcStorageManager(); long transactionId = TRANSACTION_ID; List<Long> columnIds = ImmutableList.of(3L, 7L); List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(10)); // create file with 2 rows StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); List<Page> pages = rowPagesBuilder(columnTypes) .row(123L, "hello") .row(456L, "bye") .build(); sink.appendPages(pages); List<ShardInfo> shards = getFutureValue(sink.commit()); assertEquals(shardRecorder.getShards().size(), 1); // delete one row BitSet rowsToDelete = new BitSet(); rowsToDelete.set(0); Collection<Slice> fragments = manager.rewriteShard(transactionId, OptionalInt.empty(), shards.get(0).getShardUuid(), rowsToDelete); Slice shardDelta = Iterables.getOnlyElement(fragments); ShardDelta shardDeltas = jsonCodec(ShardDelta.class).fromJson(shardDelta.getBytes()); ShardInfo shardInfo = Iterables.getOnlyElement(shardDeltas.getNewShards()); // check that output file has one row assertEquals(shardInfo.getRowCount(), 1); // check that storage file is same as backup file File storageFile = storageService.getStorageFile(shardInfo.getShardUuid()); File backupFile = fileBackupStore.getBackupFile(shardInfo.getShardUuid()); assertFileEquals(storageFile, backupFile); // verify recorded shard List<RecordedShard> recordedShards = shardRecorder.getShards(); assertEquals(recordedShards.size(), 2); assertEquals(recordedShards.get(1).getTransactionId(), TRANSACTION_ID); assertEquals(recordedShards.get(1).getShardUuid(), shardInfo.getShardUuid()); } @Test public void testWriterRollback() { // verify staging directory is empty File staging = new File(new File(temporary, "data"), "staging"); assertDirectory(staging); assertEquals(staging.list(), new String[] {}); // create a shard in staging OrcStorageManager manager = createOrcStorageManager(); List<Long> columnIds = ImmutableList.of(3L, 7L); List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(10)); StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); List<Page> pages = rowPagesBuilder(columnTypes) .row(123L, "hello") .row(456L, "bye") .build(); sink.appendPages(pages); sink.flush(); // verify shard exists in staging String[] files = staging.list(); assertNotNull(files); String stagingFile = Arrays.stream(files) .filter(file -> file.endsWith(".orc")) .findFirst() .orElseThrow(() -> new AssertionError("file not found in staging")); // rollback should cleanup staging files sink.rollback(); files = staging.list(); assertNotNull(files); assertTrue(Arrays.stream(files).noneMatch(stagingFile::equals)); } @Test public void testShardStatsBigint() { List<ColumnStats> stats = columnStats(types(BIGINT), row(2L), row(-3L), row(5L)); assertColumnStats(stats, 1, -3L, 5L); } @Test public void testShardStatsDouble() { List<ColumnStats> stats = columnStats(types(DOUBLE), row(2.5), row(-4.1), row(6.6)); assertColumnStats(stats, 1, -4.1, 6.6); } @Test public void testShardStatsBigintDouble() { List<ColumnStats> stats = columnStats(types(BIGINT, DOUBLE), row(-3L, 6.6), row(5L, -4.1)); assertColumnStats(stats, 1, -3L, 5L); assertColumnStats(stats, 2, -4.1, 6.6); } @Test public void testShardStatsDoubleMinMax() { List<ColumnStats> stats = columnStats(types(DOUBLE), row(3.2), row(Double.MIN_VALUE), row(4.5)); assertColumnStats(stats, 1, Double.MIN_VALUE, 4.5); stats = columnStats(types(DOUBLE), row(3.2), row(Double.MAX_VALUE), row(4.5)); assertColumnStats(stats, 1, 3.2, Double.MAX_VALUE); } @Test public void testShardStatsDoubleNotFinite() { List<ColumnStats> stats = columnStats(types(DOUBLE), row(3.2), row(Double.NEGATIVE_INFINITY), row(4.5)); assertColumnStats(stats, 1, null, 4.5); stats = columnStats(types(DOUBLE), row(3.2), row(Double.POSITIVE_INFINITY), row(4.5)); assertColumnStats(stats, 1, 3.2, null); stats = columnStats(types(DOUBLE), row(3.2), row(Double.NaN), row(4.5)); assertColumnStats(stats, 1, 3.2, 4.5); } @Test public void testShardStatsVarchar() { List<ColumnStats> stats = columnStats( types(createVarcharType(10)), row(utf8Slice("hello")), row(utf8Slice("bye")), row(utf8Slice("foo"))); assertColumnStats(stats, 1, "bye", "hello"); } @Test public void testShardStatsBigintVarbinary() { List<ColumnStats> stats = columnStats(types(BIGINT, VARBINARY), row(5L, wrappedBuffer(octets(0x00))), row(3L, wrappedBuffer(octets(0x01)))); assertColumnStats(stats, 1, 3L, 5L); assertNoColumnStats(stats, 2); } @Test public void testShardStatsDateTimestamp() { long minDate = sqlDate(2001, 8, 22).getDays(); long maxDate = sqlDate(2005, 4, 22).getDays(); long maxTimestamp = sqlTimestamp(2002, 4, 13, 6, 7, 8).getMillisUtc(); long minTimestamp = sqlTimestamp(2001, 3, 15, 9, 10, 11).getMillisUtc(); List<ColumnStats> stats = columnStats(types(DATE, TIMESTAMP), row(minDate, maxTimestamp), row(maxDate, minTimestamp)); assertColumnStats(stats, 1, minDate, maxDate); assertColumnStats(stats, 2, minTimestamp, maxTimestamp); } @Test public void testMaxShardRows() { OrcStorageManager manager = createOrcStorageManager(2, new DataSize(2, MEGABYTE)); List<Long> columnIds = ImmutableList.of(3L, 7L); List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(10)); StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); List<Page> pages = rowPagesBuilder(columnTypes) .row(123L, "hello") .row(456L, "bye") .build(); sink.appendPages(pages); assertTrue(sink.isFull()); } @Test public void testMaxFileSize() { List<Long> columnIds = ImmutableList.of(3L, 7L); List<Type> columnTypes = ImmutableList.of(BIGINT, createVarcharType(5)); List<Page> pages = rowPagesBuilder(columnTypes) .row(123L, "hello") .row(456L, "bye") .build(); // Set maxFileSize to 1 byte, so adding any page makes the StoragePageSink full OrcStorageManager manager = createOrcStorageManager(20, new DataSize(1, BYTE)); StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); sink.appendPages(pages); assertTrue(sink.isFull()); } private static ConnectorPageSource getPageSource( OrcStorageManager manager, List<Long> columnIds, List<Type> columnTypes, UUID uuid, TupleDomain<RaptorColumnHandle> tupleDomain) { return manager.getPageSource(uuid, OptionalInt.empty(), columnIds, columnTypes, tupleDomain, READER_ATTRIBUTES); } private static StoragePageSink createStoragePageSink(StorageManager manager, List<Long> columnIds, List<Type> columnTypes) { long transactionId = TRANSACTION_ID; return manager.createStoragePageSink(transactionId, OptionalInt.empty(), columnIds, columnTypes, false); } private OrcStorageManager createOrcStorageManager() { return createOrcStorageManager(MAX_SHARD_ROWS, MAX_FILE_SIZE); } private OrcStorageManager createOrcStorageManager(int maxShardRows, DataSize maxFileSize) { return createOrcStorageManager(storageService, backupStore, recoveryManager, shardRecorder, maxShardRows, maxFileSize); } public static OrcStorageManager createOrcStorageManager(IDBI dbi, File temporary) { return createOrcStorageManager(dbi, temporary, MAX_SHARD_ROWS); } public static OrcStorageManager createOrcStorageManager(IDBI dbi, File temporary, int maxShardRows) { File directory = new File(temporary, "data"); StorageService storageService = new FileStorageService(directory); storageService.start(); File backupDirectory = new File(temporary, "backup"); FileBackupStore fileBackupStore = new FileBackupStore(backupDirectory); fileBackupStore.start(); Optional<BackupStore> backupStore = Optional.of(fileBackupStore); ShardManager shardManager = createShardManager(dbi); ShardRecoveryManager recoveryManager = new ShardRecoveryManager( storageService, backupStore, new TestingNodeManager(), shardManager, MISSING_SHARD_DISCOVERY, 10); return createOrcStorageManager( storageService, backupStore, recoveryManager, new InMemoryShardRecorder(), maxShardRows, MAX_FILE_SIZE); } public static OrcStorageManager createOrcStorageManager( StorageService storageService, Optional<BackupStore> backupStore, ShardRecoveryManager recoveryManager, ShardRecorder shardRecorder, int maxShardRows, DataSize maxFileSize) { return new OrcStorageManager( CURRENT_NODE, storageService, backupStore, READER_ATTRIBUTES, new BackupManager(backupStore, storageService, 1), recoveryManager, shardRecorder, new TypeRegistry(), CONNECTOR_ID, DELETION_THREADS, SHARD_RECOVERY_TIMEOUT, maxShardRows, maxFileSize, new DataSize(0, BYTE)); } private static void assertFileEquals(File actual, File expected) throws IOException { assertEquals(hash(actual, md5()), hash(expected, md5())); } private static void assertColumnStats(List<ColumnStats> list, long columnId, Object min, Object max) { for (ColumnStats stats : list) { if (stats.getColumnId() == columnId) { assertEquals(stats.getMin(), min); assertEquals(stats.getMax(), max); return; } } fail(format("no stats for column: %s: %s", columnId, list)); } private static void assertNoColumnStats(List<ColumnStats> list, long columnId) { for (ColumnStats stats : list) { assertNotEquals(stats.getColumnId(), columnId); } } private static List<Type> types(Type... types) { return ImmutableList.copyOf(types); } private static Object[] row(Object... values) { return values; } private List<ColumnStats> columnStats(List<Type> columnTypes, Object[]... rows) { ImmutableList.Builder<Long> list = ImmutableList.builder(); for (long i = 1; i <= columnTypes.size(); i++) { list.add(i); } List<Long> columnIds = list.build(); OrcStorageManager manager = createOrcStorageManager(); StoragePageSink sink = createStoragePageSink(manager, columnIds, columnTypes); sink.appendPages(rowPagesBuilder(columnTypes).rows(rows).build()); List<ShardInfo> shards = getFutureValue(sink.commit()); assertEquals(shards.size(), 1); return Iterables.getOnlyElement(shards).getColumnStats(); } private static SqlVarbinary sqlBinary(byte[] bytes) { return new SqlVarbinary(bytes); } private static SqlDate sqlDate(int year, int month, int day) { DateTime date = new DateTime(year, month, day, 0, 0, 0, 0, UTC); return new SqlDate(Days.daysBetween(EPOCH, date).getDays()); } private static SqlTimestamp sqlTimestamp(int year, int month, int day, int hour, int minute, int second) { return sqlTimestampOf(year, month, day, hour, minute, second, 0, UTC, UTC_KEY, SESSION); } }
/* * Copyright (c) 2014. Real Time Genomics Limited. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rtg.relation; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.TreeSet; import com.rtg.launcher.AbstractCli; import com.rtg.launcher.CommonFlags; import com.rtg.reference.Sex; import com.rtg.util.StringUtils; import com.rtg.util.TextTable; import com.rtg.util.cli.CommonFlagCategories; import com.rtg.util.diagnostic.NoTalkbackSlimException; import com.rtg.util.io.LineWriter; /** */ public class PedStatsCli extends AbstractCli { private static final String PRIMARY_IDS = "primary-ids"; private static final String MALE_IDS = "male-ids"; private static final String FEMALE_IDS = "female-ids"; private static final String PATERNAL_IDS = "paternal-ids"; private static final String MATERNAL_IDS = "maternal-ids"; private static final String FOUNDER_IDS = "founder-ids"; private static final String ID_DELIM = "delimiter"; private static final String FAMILIES_OUT = "families"; private static final String DOT_OUT = "dot"; private static final String DOT_SIMPLE = "simple-dot"; private static final String DUMP = "Xdump"; private static final String FAMILY_FLAGS = "Xfamily-flags"; private static final String ORDERING = "Xordering"; private static final String DOT_PROPERTIES = "Xdot-properties"; @Override public String moduleName() { return "pedstats"; } @Override public String description() { return "print information about a pedigree file"; } @Override protected void initFlags() { mFlags.setDescription("Output information from pedigree files of various formats. For quick pedigree visualization using Graphviz, try:\n\n" + " dot -Tpng <(rtg pedstats --dot \"A Title\" PEDFILE) | display -\n" + "\nor for a larger pedigree:\n\n" + " dot -Tpdf -o mypedigree.pdf <(rtg pedstats --dot \"A Title\" PEDFILE)\n" ); CommonFlagCategories.setCategories(mFlags); mFlags.registerRequired(File.class, CommonFlags.FILE, "the pedigree file to process, may be PED or VCF, use '-' to read from stdin").setCategory(CommonFlagCategories.INPUT_OUTPUT); mFlags.registerOptional(PRIMARY_IDS, "output ids of all primary individuals").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(MALE_IDS, "output ids of all males").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(FEMALE_IDS, "output ids of all females").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(PATERNAL_IDS, "output ids of paternal individuals").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(MATERNAL_IDS, "output ids of maternal individuals").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(FOUNDER_IDS, "output ids of all founders").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional('d', ID_DELIM, String.class, CommonFlags.STRING, "output id lists using this separator", "\\n").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(FAMILIES_OUT, "output information about family structures").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(DOT_OUT, String.class, CommonFlags.STRING, "output pedigree in Graphviz format, using the supplied text as a title").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(DOT_SIMPLE, "when outputting Graphviz format, use a layout that looks less like a traditional pedigree diagram but works better with large complex pedigrees").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(DUMP, "dump full relationships structure").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(FAMILY_FLAGS, "output command-line flags for family caller").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(ORDERING, "output family processing order for use during forward backward algorithm").setCategory(CommonFlagCategories.REPORTING); mFlags.registerOptional(DOT_PROPERTIES, File.class, CommonFlags.FILE, "properties file containing overrides for Graphviz attributes").setCategory(CommonFlagCategories.REPORTING); mFlags.setValidator(flags -> mFlags.checkAtMostOne(FAMILIES_OUT, DOT_OUT, DUMP, FAMILY_FLAGS, ORDERING) && (!mFlags.isAnySet(PRIMARY_IDS, MALE_IDS, FEMALE_IDS, MATERNAL_IDS, PATERNAL_IDS, FOUNDER_IDS) || mFlags.checkBanned(FAMILIES_OUT, DOT_OUT, ORDERING, FAMILY_FLAGS)) ); } private Properties loadProperties() throws IOException { final Properties props = new Properties(); if (mFlags.isSet(DOT_PROPERTIES)) { try (Reader r = new FileReader((File) mFlags.getValue(DOT_PROPERTIES))) { props.load(r); } } return props; } @Override protected int mainExec(OutputStream out, PrintStream err) throws IOException { final File pedFile = (File) mFlags.getAnonymousValue(0); final GenomeRelationships pedigree = GenomeRelationships.loadGenomeRelationships(pedFile); try (LineWriter w = new LineWriter(new OutputStreamWriter(out))) { try { if (mFlags.isSet(DOT_OUT)) { // Output dotty stuff w.writeln(pedigree.toGraphViz(loadProperties(), (String) mFlags.getValue(DOT_OUT), mFlags.isSet(DOT_SIMPLE))); } else if (mFlags.isSet(FAMILIES_OUT)) { // Output list of families identified in the ped file: final Set<Family> families = Family.getFamilies(pedigree, false, null); for (final Family f : families) { w.writeln(f.toString()); } } else if (mFlags.isSet(DUMP)) { w.writeln(pedigree.toString()); } else if (mFlags.isSet(ORDERING)) { // ordering stuff final List<Family> families; try { families = MultiFamilyOrdering.orderFamiliesAndSetMates(Family.getFamilies(pedigree, false, null)); } catch (PedigreeException e) { throw new NoTalkbackSlimException(e.getMessage()); } w.writeln("Families in processing order:"); for (final Family f : families) { w.writeln(f.toString()); } final Set<String> nonMonog = MultiFamilyOrdering.nonMonogamousSamples(families); if (nonMonog.size() > 0) { w.writeln("The following individuals are not monogamous:"); for (final String s : nonMonog) { w.writeln(s); } } else { w.writeln("Set of families is monogamous"); } } else if (mFlags.isSet(FAMILY_FLAGS)) { final Set<Family> families = Family.getFamilies(pedigree, false, null); for (final Family f : families) { String familycmd = ""; familycmd += "--father " + f.getFather(); familycmd += " --mother " + f.getMother(); for (final String child : f.getChildren()) { if (pedigree.getSex(child) == Sex.MALE) { familycmd += " --son " + child; } else if (pedigree.getSex(child) == Sex.FEMALE) { familycmd += " --daughter " + child; } else { System.err.println("Child has unknown sex: " + child); } } w.writeln("rtg family " + familycmd); } } else if (mFlags.isAnySet(PRIMARY_IDS, MALE_IDS, FEMALE_IDS, MATERNAL_IDS, PATERNAL_IDS, FOUNDER_IDS)) { final Collection<String> genomes = new TreeSet<>(); if (mFlags.isSet(PRIMARY_IDS)) { genomes.addAll(Arrays.asList(pedigree.genomes(new GenomeRelationships.PrimaryGenomeFilter(pedigree)))); } if (mFlags.isSet(MALE_IDS)) { genomes.addAll(Arrays.asList(pedigree.genomes(new GenomeRelationships.GenomeSexFilter(pedigree, Sex.MALE)))); } if (mFlags.isSet(FEMALE_IDS)) { genomes.addAll(Arrays.asList(pedigree.genomes(new GenomeRelationships.GenomeSexFilter(pedigree, Sex.FEMALE)))); } if (mFlags.isSet(MATERNAL_IDS)) { genomes.addAll(Arrays.asList(pedigree.genomes(new GenomeRelationships.HasRelationshipGenomeFilter(pedigree, Relationship.RelationshipType.PARENT_CHILD, true), new GenomeRelationships.GenomeSexFilter(pedigree, Sex.FEMALE)))); } if (mFlags.isSet(PATERNAL_IDS)) { genomes.addAll(Arrays.asList(pedigree.genomes(new GenomeRelationships.HasRelationshipGenomeFilter(pedigree, Relationship.RelationshipType.PARENT_CHILD, true), new GenomeRelationships.GenomeSexFilter(pedigree, Sex.MALE)))); } if (mFlags.isSet(FOUNDER_IDS)) { genomes.addAll(Arrays.asList(pedigree.genomes(new GenomeRelationships.FounderGenomeFilter(pedigree, false)))); } final String delim = (String) mFlags.getValue(ID_DELIM); w.writeln(StringUtils.join(StringUtils.removeBackslashEscapes(delim), genomes)); } else { // Output summary information final TextTable table = new TextTable(); table.setAlignment(TextTable.Align.LEFT); w.writeln("Pedigree file: " + pedFile); w.writeln(); table.addRow("Total samples:", "" + pedigree.genomes().length); table.addRow("Primary samples:", "" + pedigree.genomes(new GenomeRelationships.PrimaryGenomeFilter(pedigree)).length); table.addRow("Male samples:", "" + pedigree.genomes(new GenomeRelationships.GenomeSexFilter(pedigree, Sex.MALE)).length); table.addRow("Female samples:", "" + pedigree.genomes(new GenomeRelationships.GenomeSexFilter(pedigree, Sex.FEMALE)).length); table.addRow("Afflicted samples:", "" + pedigree.genomes(new GenomeRelationships.DiseasedGenomeFilter(pedigree)).length); table.addRow("Founder samples:", "" + pedigree.genomes(new GenomeRelationships.FounderGenomeFilter(pedigree, false)).length); table.addRow("Parent-child relationships:", "" + pedigree.relationships(new Relationship.RelationshipTypeFilter(Relationship.RelationshipType.PARENT_CHILD)).length); table.addRow("Other relationships:", "" + pedigree.relationships(new Relationship.NotFilter(new Relationship.RelationshipTypeFilter(Relationship.RelationshipType.PARENT_CHILD))).length); table.addRow("Families:", "" + Family.getFamilies(pedigree, false, null).size()); w.writeln(table.toString()); } } catch (PedigreeException e) { throw new NoTalkbackSlimException(e.getMessage()); } } return 0; } }
/* Copyright (c) 2016, Henrique Abdalla <https://github.com/AquariusPower><https://sourceforge.net/u/teike/profile/> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.github.commandsconsolegui.spCmd; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.TreeMap; import javax.script.Bindings; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import com.github.commandsconsolegui.spAppOs.misc.MiscI; import com.github.commandsconsolegui.spAppOs.misc.PrerequisitesNotMetException; import com.github.commandsconsolegui.spCmd.varfield.StringCmdField; import com.google.common.collect.Lists; /** * This class holds all commands that allows users to create * scripts that will run in the console. * * To prevent users using these scripting capabilities, * extend from {@link #ConsoleCommands()} instead. * * @author Henrique Abdalla <https://github.com/AquariusPower><https://sourceforge.net/u/teike/profile/> * */ public class ScriptingCommandsDelegator extends CommandsDelegator { public final StringCmdField CMD_FUNCTION = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public final StringCmdField CMD_FUNCTION_CALL = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public final StringCmdField CMD_FUNCTION_END = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public final StringCmdField scfFunctionList = new StringCmdField(this); public final StringCmdField scfFunctionShow = new StringCmdField(this); public final StringCmdField scfJs = new StringCmdField(this); /** * conditional user coding */ public final StringCmdField CMD_IF = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public final StringCmdField CMD_ELSE_IF = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public final StringCmdField CMD_ELSE = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public final StringCmdField CMD_IF_END = new StringCmdField(this,CommandsHelperI.i().getCmdCodePrefix()); public String strPrepareFunctionBlockForId; public boolean bFuncCmdLineRunning; public boolean bFuncCmdLineSkipTilEnd; private Boolean bIfConditionIsValid; private Boolean bIfConditionExecCommands; private ArrayList<ConditionalNestedData> aIfConditionNestedList = new ArrayList<ConditionalNestedData>(); private ScriptEngine jse = new ScriptEngineManager().getEngineByMimeType("text/javascript"); private Bindings bndJSE = jse.createBindings(); private Object objJSLastEval; public Object jsBindIdValue(String strBindId, Object objBindValue){ return bndJSE.put(strBindId,objBindValue); } public TreeMap<String,ArrayList<String>> tmFunctions = new TreeMap<String, ArrayList<String>>(String.CASE_INSENSITIVE_ORDER); // public ConsoleScriptCommands(IConsoleUI icg) { // super(icg); // } public boolean checkFuncExecEnd() { if(ccl.getOriginalLine()==null)return false; return ccl.getOriginalLine().startsWith(RESTRICTED_CMD_FUNCTION_EXECUTION_ENDS.getUniqueCmdId()); } public boolean checkFuncExecStart() { if(ccl.getOriginalLine()==null)return false; return ccl.getOriginalLine().startsWith(RESTRICTED_CMD_FUNCTION_EXECUTION_STARTS.getUniqueCmdId()); } public boolean cmdFunctionCall() { String strFunctionId = ccl.paramString(1); /** * put cmds block at queue */ ArrayList<String> astrFuncBlock = tmFunctions.get(strFunctionId); if(astrFuncBlock==null)return false; astrFuncBlock.removeAll(Collections.singleton(null)); if(astrFuncBlock!=null && astrFuncBlock.size()>0){ dumpInfoEntry("Running function: "+strFunctionId+" "+getCommentPrefix()+"totLines="+astrFuncBlock.size()); /** * params var ids */ ArrayList<String> astrFuncParams = new ArrayList<String>(); int i=2; while(true){ String strParamValue = ccl.paramString(i); if(strParamValue==null)break; String strParamId=strFunctionId+"_"+(i-1); astrFuncParams.add(strParamId); if(hasVar(strParamId)){ dumpWarnEntry("RmConflictingVar: "+varReportPrepare(strParamId)); varDelete(strParamId); } varSet(strParamId, strParamValue, false); i++; } ArrayList<String> astrFuncBlockToExec = new ArrayList<String>(astrFuncBlock); /** * prepend section (is inverted order) */ // for(String strUnsetVar:astrFuncParams){ // if(hasVar(strUnsetVar)){ // /** // * Tries to inform user about the inconsistency. // */ // dumpWarnEntry("Conflicting func param var will be removed: "+strUnsetVar); // } // astrFuncBlockToExec.add(0,getCommandPrefix()+ // CMD_VAR_SET.toString()+" "+getVarDeleteToken()+strUnsetVar); // } astrFuncBlockToExec.add(0,RESTRICTED_CMD_FUNCTION_EXECUTION_STARTS.getUniqueCmdId()+" "+strFunctionId); /** * append section */ for(String strUnsetVar:astrFuncParams){ astrFuncBlockToExec.add(getCommandPrefix()+ CMD_VAR_SET.toString()+" "+getVarDeleteToken()+strUnsetVar); } astrFuncBlockToExec.add(RESTRICTED_CMD_FUNCTION_EXECUTION_ENDS.getUniqueCmdId()+" "+strFunctionId); addCmdsBlockToPreQueue(astrFuncBlockToExec, true, true, "Func:"+strFunctionId); } return true; } public boolean cmdFunctionBegin() { String strFunctionId = ccl.paramString(1); if(!MiscI.i().isValidIdentifierCmdVarAliasFuncString(strFunctionId))return false; tmFunctions.put(strFunctionId, new ArrayList<String>()); dumpInfoEntry("Function creation begins for: "+strFunctionId); strPrepareFunctionBlockForId=strFunctionId; return true; } public boolean functionFeed(String strCmdLine){ ArrayList<String> astr = tmFunctions.get(strPrepareFunctionBlockForId); astr.add(strCmdLine); dumpDevInfoEntry("Function line added: "+strCmdLine+" "+getCommentPrefix()+"tot="+astr.size()); return true; } public boolean functionEndCheck(String strCmdLine) { if(CMD_FUNCTION_END.equals(extractCommandPart(strCmdLine,0))){ return cmdFunctionEnd(); } // String strCmdCheck=""+getCommandPrefix()+CMD_FUNCTION_END.toString(); // strCmdCheck=strCmdCheck.toLowerCase(); // if(strCmdCheck.equals(strCmdLine.trim().toLowerCase())){ // return cmdFunctionEnd(); // } return false; } public boolean cmdFunctionEnd() { if(strPrepareFunctionBlockForId==null){ dumpExceptionEntry(new NullPointerException("no function being prepared...")); return false; } dumpInfoEntry("Function creation ends for: "+strPrepareFunctionBlockForId); strPrepareFunctionBlockForId=null; return true; } @Override public ECmdReturnStatus execCmdFromConsoleRequestRoot(){ boolean bCommandWorked = false; ECmdReturnStatus ecrs = super.execCmdFromConsoleRequestRoot(); if(ecrs.compareTo(ECmdReturnStatus.NotFound)!=0)return ecrs; if(!bCommandWorked){ if(checkCmdValidity(CMD_FUNCTION,"<id> begins a function block")){ bCommandWorked=cmdFunctionBegin(); }else if(checkCmdValidity(CMD_FUNCTION_CALL,"<id> [parameters...] retrieve parameters values with ex.: ${id_1} ${id_2} ...")){ bCommandWorked=cmdFunctionCall(); }else if(checkCmdValidity(CMD_FUNCTION_END,"ends a function block")){ bCommandWorked=cmdFunctionEnd(); }else if(checkCmdValidity(scfFunctionList,"[filter]")){ String strFilter = ccl.paramString(1); ArrayList<String> astr = Lists.newArrayList(tmFunctions.keySet().iterator()); for(String str:astr){ if(strFilter!=null && !str.toLowerCase().contains(strFilter.toLowerCase()))continue; dumpSubEntry(str); } bCommandWorked=true; }else if(checkCmdValidity(scfFunctionShow,"<functionId>")){ String strFuncId = ccl.paramString(1); if(strFuncId!=null){ ArrayList<String> astr = tmFunctions.get(strFuncId); if(astr!=null){ dumpSubEntry(getCommandPrefixStr()+CMD_FUNCTION+" "+strFuncId+getCommandDelimiter()); for(String str:astr){ str=getSubEntryPrefix()+getSubEntryPrefix()+str+getCommandDelimiter(); // dumpSubEntry("\t"+str+getCommandDelimiter()); dumpEntry(false, true, false, false, str); } dumpSubEntry(getCommandPrefixStr()+CMD_FUNCTION_END+getCommandDelimiter()); bCommandWorked=true; } } }else if(checkCmdValidity(scfJs,"<javascript>")){ String strJS = ccl.paramStringConcatenateAllFrom(1); if(strJS==null){ dumpSubEntry(bndJSE.keySet().toString()); bCommandWorked=true; }else{ try { objJSLastEval=jse.eval(strJS,bndJSE); if(objJSLastEval==null){ dumpSubEntry("Return: null"); }else{ dumpSubEntry("Return: "+objJSLastEval.toString()+" ("+objJSLastEval.getClass()+"), accessible methods:"); Method[] am = objJSLastEval.getClass().getMethods(); ArrayList<String> astr = new ArrayList<String>(); for(Method m:am){ String strM = ""; String strClassSName=m.getDeclaringClass().getSimpleName(); strM+=strClassSName+"."+m.getName(); strM+="("; String strP=""; boolean bHasNonPrimitiveParam = false; for(Class<?> p:m.getParameterTypes()){ if(!p.isPrimitive())bHasNonPrimitiveParam=true; if(!strP.isEmpty())strP+=","; strP+=p.getSimpleName(); } strM+=strP+")"; strM+=":"+m.getReturnType().getSimpleName(); boolean bIsStatic=false; if(Modifier.isStatic(m.getModifiers())){ strM+=" <STATIC>"; bIsStatic=true; } if( !bIsStatic && !bHasNonPrimitiveParam && !strClassSName.equals(Object.class.getSimpleName()) ){ astr.add(strM); // dumpSubEntry(strM); } } Collections.sort(astr); for(String str:astr)dumpSubEntry(str); } bCommandWorked=true; } catch (ScriptException e) { dumpExceptionEntry(e, strJS); } } }else if(checkCmdValidity(CMD_ELSE,"conditinal block")){ bCommandWorked=cmdElse(); }else if(checkCmdValidity(CMD_ELSE_IF,"<[!]<true|false>> conditional block")){ bCommandWorked=cmdElseIf(); }else if(checkCmdValidity(CMD_IF,"<[!]<true|false>> [cmd|alias] if cmd|alias is not present, this will be a multiline block start!")){ bCommandWorked=cmdIf(); }else if(checkCmdValidity(CMD_IF_END,"ends conditional block")){ bCommandWorked=cmdIfEnd(); }else { return ECmdReturnStatus.NotFound; } } return cmdFoundReturnStatus(bCommandWorked); } @Override public ECmdReturnStatus stillExecutingCommand() { Boolean bCmdFoundAndWorked=null; //null is not found, true or false is found but worked or failed if(bCmdFoundAndWorked==null){ if(bFuncCmdLineRunning){ if(checkFuncExecEnd()){ bFuncCmdLineRunning=false; bFuncCmdLineSkipTilEnd=false; bCmdFoundAndWorked=true; } } } if(bCmdFoundAndWorked==null){ if(checkFuncExecStart()){ bFuncCmdLineRunning=true; bCmdFoundAndWorked=true; }else if(strPrepareFunctionBlockForId!=null){ if(bCmdFoundAndWorked==null)bCmdFoundAndWorked = functionEndCheck(ccl.getOriginalLine()); //before feed if(bCmdFoundAndWorked==null)bCmdFoundAndWorked = functionFeed(ccl.getOriginalLine()); }else if(bIfConditionExecCommands!=null && !bIfConditionExecCommands){ /** * These are capable of stopping the skipping. */ if(CMD_ELSE_IF.equals(ccl.paramString(0))){ if(bCmdFoundAndWorked==null)bCmdFoundAndWorked = cmdElseIf(); }else if(CMD_ELSE.equals(ccl.paramString(0))){ if(bCmdFoundAndWorked==null)bCmdFoundAndWorked = cmdElse(); }else if(CMD_IF_END.equals(ccl.paramString(0))){ if(bCmdFoundAndWorked==null)bCmdFoundAndWorked = cmdIfEnd(); }else{ /** * The if condition resulted in false, therefore commands must be skipped. */ dumpInfoEntry("ConditionalSkip: "+ccl.getCmdLinePrepared()); if(bCmdFoundAndWorked==null)bCmdFoundAndWorked = true; } } } if(bCmdFoundAndWorked==null){ if(bFuncCmdLineRunning && bFuncCmdLineSkipTilEnd){ dumpWarnEntry("SkippingRemainingFunctionCmds: "+ccl.getCmdLinePrepared()); bCmdFoundAndWorked = true; //this just means that the skip worked } } if(bCmdFoundAndWorked==null){ /** * normal commands execution */ ECmdReturnStatus ecrs = super.stillExecutingCommand(); if(ecrs.compareTo(ECmdReturnStatus.NotFound)!=0)return ecrs; } if(bCmdFoundAndWorked==null){ if(bFuncCmdLineRunning){ // a command may fail inside a function, only that first one will generate error message bFuncCmdLineSkipTilEnd=true; } } if(bCmdFoundAndWorked==null)return ECmdReturnStatus.NotFound; return cmdFoundReturnStatus(bCmdFoundAndWorked); } @Override public String prepareStatsFieldText() { String strStatsLast = super.prepareStatsFieldText(); if(EStats.FunctionCreation.isShow() && strPrepareFunctionBlockForId!=null){ strStatsLast+= "F="+strPrepareFunctionBlockForId +";"; } if(EStats.IfConditionalBlock.isShow() && aIfConditionNestedList.size()>0){ strStatsLast+= "If"+aIfConditionNestedList.size() +";"; } return strStatsLast; } public boolean cmdIf() { return cmdIf(false); } public boolean cmdIf(boolean bSkipNesting) { bIfConditionIsValid=false; String strCondition = ccl.paramString(1); boolean bNegate = false; if(strCondition.startsWith("!")){ strCondition=strCondition.substring(1); bNegate=true; } Boolean bCondition = null; try{bCondition = MiscI.i().parseBoolean(strCondition);}catch(NumberFormatException e){};//accepted exception if(bNegate)bCondition=!bCondition; if(bCondition==null){ dumpWarnEntry("Invalid condition: "+strCondition); return false; } String strCmds = ccl.paramStringConcatenateAllFrom(2); if(strCmds==null)strCmds=""; strCmds.trim(); if(strCmds.isEmpty() || strCmds.startsWith(getCommentPrefixStr())){ if(bSkipNesting){ ConditionalNestedData cn = aIfConditionNestedList.get(aIfConditionNestedList.size()-1); cn.bCondition = bCondition; }else{ aIfConditionNestedList.add(new ConditionalNestedData(bCondition)); } bIfConditionExecCommands=bCondition; }else{ if(!bSkipNesting){ if(bCondition){ addCmdToQueue(strCmds,true); } } } return true; } public boolean cmdElse(){ // bIfConditionExecCommands=!aIfConditionNestedList.get(aIfConditionNestedList.size()-1); ConditionalNestedData cn = aIfConditionNestedList.get(aIfConditionNestedList.size()-1); bIfConditionExecCommands = !cn.bCondition; cn.bIfEndIsRequired = true; return true; } public boolean cmdElseIf(){ ConditionalNestedData cn = aIfConditionNestedList.get(aIfConditionNestedList.size()-1); if(cn.bIfEndIsRequired){ dumpExceptionEntry(new NullPointerException("command "+CMD_ELSE_IF.toString() +" is missplaced, ignoring")); bIfConditionExecCommands=false; //will also skip this block commands return false; } boolean bConditionSuccessAlready = cn.bCondition; if(bConditionSuccessAlready){ /** * if one of the conditions was successful, will skip all the remaining ones */ bIfConditionExecCommands=false; }else{ return cmdIf(true); } return true; } public boolean cmdIfEnd(){ if(aIfConditionNestedList.size()>0){ aIfConditionNestedList.remove(aIfConditionNestedList.size()-1); if(aIfConditionNestedList.size()==0){ bIfConditionExecCommands=null; // bIfEndIsRequired = false; }else{ ConditionalNestedData cn = aIfConditionNestedList.get(aIfConditionNestedList.size()-1); bIfConditionExecCommands = cn.bCondition; } }else{ dumpExceptionEntry(new PrerequisitesNotMetException("pointless condition ending...")); return false; } return true; } @Override public Object getFieldValue(Field fld) throws IllegalArgumentException, IllegalAccessException { if(fld.getDeclaringClass()!=ScriptingCommandsDelegator.class)return super.getFieldValue(fld); return fld.get(this); } @Override public void setFieldValue(Field fld, Object value) throws IllegalArgumentException, IllegalAccessException { if(fld.getDeclaringClass()!=ScriptingCommandsDelegator.class){super.setFieldValue(fld,value);return;} fld.set(this,value); } }
package org.twak.viewTrace.franken; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import javax.imageio.ImageIO; import javax.vecmath.Point2d; import org.twak.tweed.Tweed; import org.twak.utils.Filez; import org.twak.utils.collections.Loop; import org.twak.utils.collections.MultiMap; import org.twak.utils.geom.DRectangle; import org.twak.viewTrace.facades.CMPLabel; import org.twak.viewTrace.facades.FRect; import org.twak.viewTrace.facades.MiniFacade; import org.twak.viewTrace.facades.MiniFacade.Feature; import org.twak.viewTrace.facades.NormSpecGen; public class FacadeSuperApp extends SuperSuper <MiniFacade> { MiniFacade mf; public FacadeSuperApp( MiniFacade mf) { super(); this.mf = mf; } public FacadeSuperApp( FacadeSuperApp o ) { super( (SuperSuper) o ); this.mf = o.mf; } @Override public App copy() { return new FacadeSuperApp( this ); } @Override public void setTexture( FacState<MiniFacade> state, BufferedImage cropped ) { NormSpecGen ns = renderLabels( mf, cropped ); BufferedImage[] maps = new BufferedImage[] { cropped, ns.spec, ns.norm }; // NetInfo ni = NetInfo.get( this ); String fileName = "scratch/" + UUID.randomUUID() + ".png"; DRectangle mfBounds = Pix2Pix.findBounds( mf, false ); try { for ( FRect f : mf.featureGen.getRects( Feature.WINDOW, Feature.SHOP, Feature.DOOR ) ) { DRectangle d = new DRectangle( 0, 0, maps[ 0 ].getWidth(), maps[ 0 ].getHeight() ). transform( mfBounds.normalize( f ) ); d.y = maps[ 0 ].getHeight() - d.y - d.height; PanesLabelApp pla = f.panesLabelApp; File wf = new File( Tweed.DATA + "/" + pla.texture ); if (!wf.exists()) continue; BufferedImage[] windowMaps = new BufferedImage[] { ImageIO.read( wf ), ImageIO.read( Filez.extTo( wf, "_spec.png" ) ), ImageIO.read( Filez.extTo( wf, "_norm.png" ) ) }; for ( int i = 0; i < 3; i++ ) { Graphics2D tpg = maps[ i ].createGraphics(); tpg.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC ); tpg.drawImage( windowMaps[ i ], (int) d.x, (int) d.y, (int) d.width, (int) d.height, null ); tpg.dispose(); } } ImageIO.write( maps[ 0 ], "png", new File( Tweed.DATA + "/" + fileName ) ); ImageIO.write( maps[ 1 ], "png", new File( Tweed.DATA + "/" + Filez.extTo( fileName, "_spec.png" ) ) ); ImageIO.write( maps[ 2 ], "png", new File( Tweed.DATA + "/" + Filez.extTo( fileName, "_norm.png" ) ) ); } catch ( IOException e1 ) { e1.printStackTrace(); } mf.facadeTexApp.textureUVs = TextureUVs.Square; mf.facadeTexApp.texture = fileName; } private NormSpecGen renderLabels( MiniFacade mf, BufferedImage cropped ) { BufferedImage labels = new BufferedImage( cropped.getWidth(), cropped.getHeight(), BufferedImage.TYPE_3BYTE_BGR ); DRectangle bounds = Pix2Pix.findBounds( mf, false ); DRectangle cropRect = new DRectangle(cropped.getWidth(), cropped.getHeight()); Graphics2D g = labels.createGraphics(); g.setColor( CMPLabel.Facade.rgb ); Stroke stroke = new BasicStroke( 3 ); g.setStroke( stroke ); FacadeTexApp fta = mf.facadeTexApp; if (fta.postState == null) fta.resetPostProcessState(); for ( Loop<? extends Point2d> l : fta.postState.wallFaces ) { Polygon p = Pix2Pix.toPoly( mf, cropRect, bounds, l ) ; g.fill( p ); g.draw( p ); } List<FRect> renderedWindows = mf.featureGen.getRects( Feature.WINDOW ).stream().filter( r -> r.panesLabelApp.renderedOnFacade ).collect( Collectors.toList() ); Pix2Pix.cmpRects( mf, g, bounds, cropRect, CMPLabel.Window.rgb, renderedWindows, getNetInfo().resolution ); for (Feature f : mf.featureGen.keySet()) if (f != Feature.WINDOW) Pix2Pix.cmpRects( mf, g, bounds, cropRect, f.color, mf.featureGen.get(f), getNetInfo().resolution ); g.dispose(); NormSpecGen ns = new NormSpecGen( cropped, labels, FacadeTexApp.specLookup ); return ns; } public void drawCoarse( MultiMap<MiniFacade, FacState> todo ) throws IOException { FacadeTexApp fta = mf.facadeTexApp; BufferedImage src = ImageIO.read( Tweed.toWorkspace( fta.coarse ) ); DRectangle mini = Pix2Pix.findBounds( mf, false ); int outWidth = (int) Math.ceil ( ( mini.width * scale ) / tileWidth ) * tileWidth, // round to exact tile multiples outHeight = (int) Math.ceil ( ( mini.height * scale ) / tileWidth ) * tileWidth; BufferedImage bigCoarse = new BufferedImage( outWidth + overlap * 2, outHeight + overlap * 2, BufferedImage.TYPE_3BYTE_BGR ); Graphics2D g = bigCoarse.createGraphics(); g.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC ); g.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY ); int w = bigCoarse.getWidth() - 2 * overlap, h = bigCoarse.getHeight() - 2 * overlap; for ( int wi = -1; wi <= 1; wi++ ) for ( int hi = -1; hi <= 1; hi++ ) g.drawImage( src, overlap + wi * w, overlap + hi * h, w, h, null ); { DRectangle dest = new DRectangle(overlap, overlap, w, h); g.setColor( new Color (255, 255, 255, 50) ); for (FRect s : mf.featureGen.get( Feature.CORNICE )) { DRectangle draw = dest.transform( mini.normalize( s ) ); draw.y = bigCoarse.getHeight() - draw.y - draw.height; g.fillRect( (int) draw.x, (int)draw.y, (int)draw.width, (int) draw.height ); } g.setColor( new Color (78, 51, 51, 50) ); for (FRect s : mf.featureGen.get( Feature.SILL )) { DRectangle draw = dest.transform( mini.normalize( s ) ); draw.y = bigCoarse.getHeight() - draw.y - draw.height; g.fillRect( (int) draw.x, (int)draw.y, (int)draw.width, (int) draw.height ); } g.setColor( new Color (78, 51, 51, 50) ); for (FRect s : mf.featureGen.get( Feature.MOULDING )) { DRectangle draw = dest.transform( mini.normalize( s ) ); draw.y = bigCoarse.getHeight() - draw.y - draw.height; g.fillRect( (int) draw.x, (int)draw.y, (int)draw.width, (int) draw.height ); } } g.dispose(); FacState state = new FacState( bigCoarse, mf, mini, null ); for (int x =0; x <= w / tileWidth; x ++) for (int y =0; y <= h / tileWidth; y ++) state.nextTiles.add( new TileState( state, x, y ) ); todo.put( mf, state ); } @Override public App getUp( ) { return mf.facadeTexApp; } }
/******************************************************************************* * Copyright 2015 MobileMan GmbH * www.mobileman.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /** * SysuserTest * * Project: projecth * * @author MobileMan GmbH * @date 05.11.2010 * @version 1.0 * * (c) 2010 MobileMan GmbH */ package com.mobileman.projecth.business; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.math.BigDecimal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Set; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.mobileman.projecth.TestCaseBase; import com.mobileman.projecth.business.exception.LoginException; import com.mobileman.projecth.business.exception.UserConnectionException; import com.mobileman.projecth.business.exception.UserRegistrationException; import com.mobileman.projecth.business.security.DecoderService; import com.mobileman.projecth.business.security.EncoderService; import com.mobileman.projecth.domain.data.MedicalInstitution; import com.mobileman.projecth.domain.data.Name; import com.mobileman.projecth.domain.data.PhoneNumber; import com.mobileman.projecth.domain.disease.Disease; import com.mobileman.projecth.domain.disease.DiseaseGroup; import com.mobileman.projecth.domain.disease.DiseaseSubgroup; import com.mobileman.projecth.domain.doctor.Doctor; import com.mobileman.projecth.domain.patient.Patient; import com.mobileman.projecth.domain.user.User; import com.mobileman.projecth.domain.user.UserState; import com.mobileman.projecth.domain.user.UserType; import com.mobileman.projecth.domain.user.UserWeight; import com.mobileman.projecth.domain.user.connection.UserConnection; import com.mobileman.projecth.domain.user.connection.UserConnectionState; import com.mobileman.projecth.domain.user.rights.GrantedRight; /** * @author MobileMan GmbH * */ public class UserServiceTest extends TestCaseBase { @Autowired private UserService userService; @Autowired PatientService patientService; @Autowired private UserConnectionService userConnectionService; @Autowired EncoderService encoderService; @Autowired DecoderService decoderService; DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); /** * * @throws Exception */ @Test public void login() throws Exception { UserService userService = (UserService)applicationContext.getBean(ComponentNames.USER_SERVICE); assertNotNull(userService); User doctor = userService.login("sysuser3", "54321"); assertNotNull(doctor); assertTrue(Doctor.class.isInstance(doctor)); assertEquals(0, doctor.getUnsuccessfulLoginsCount()); try { doctor = userService.login("sysuser3", "zleHeslo"); } catch (LoginException e) { assertEquals(LoginException.Reason.INVALID_CREDENTIALS, e.getReason()); assertEquals(1, e.getUnsuccessfulLoginsCount()); assertEquals(1, userService.findById(doctor.getId()).getUnsuccessfulLoginsCount()); } try{ doctor = userService.login("zlyLogin", "54321"); } catch (LoginException e) { assertEquals(LoginException.Reason.USER_DOES_NOT_EXISTS, e.getReason()); } assertEquals(0, userService.login("sysuser3", "54321").getUnsuccessfulLoginsCount()); User patient = userService.login("sysuser1", "12345"); assertNotNull(patient); assertTrue(Patient.class.isInstance(patient)); patient = userService.login("sysuser2", "67890"); assertNotNull(patient); assertEquals(1, patient.getLoginsCount()); } /** * * @throws Exception */ @Test public void changePassword() throws Exception { UserService userService = (UserService)applicationContext.getBean(ComponentNames.USER_SERVICE); assertNotNull(userService); String login = "sysuser1"; String badPassword = "1234567890"; String oldPassword = "12345"; String newPassword = "54321"; User patient = userService.login(login, oldPassword); assertNotNull(patient); assertTrue(Patient.class.isInstance(patient)); try { userService.changePassword(patient.getId(), badPassword, newPassword); fail(); } catch (LoginException e) { assertEquals(LoginException.Reason.INVALID_CREDENTIALS, e.getReason()); } try { userService.changePassword(patient.getId(), oldPassword, "a"); fail(); } catch (LoginException e) { assertEquals(LoginException.Reason.PASSWORD_TOO_SHORT, e.getReason()); } try { userService.changePassword(patient.getId(), oldPassword, "aqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"); fail(); } catch (LoginException e) { assertEquals(LoginException.Reason.PASSWORD_TOO_LONG, e.getReason()); } userService.changePassword(patient.getId(), oldPassword, newPassword); patient = userService.login(login, newPassword); assertNotNull(patient); assertTrue(Patient.class.isInstance(patient)); userService.changePassword(patient.getId(), newPassword, oldPassword); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void deleteUser_NullId() throws Exception { userService.deleteUserAccount(null); } /** * * @throws Exception */ @Test public void deleteUser() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); assertNotNull(doctor.getUserAccount()); List<UserConnection> connections =userConnectionService.findConfirmedConnections(doctor.getId()); assertEquals(1, connections.size()); assertEquals(UserConnectionState.A, connections.get(0).getState()); assertEquals(doctor, connections.get(0).getOwner()); userService.deleteUserAccount(doctor.getId()); doctor = (Doctor)userService.findById(doctor.getId()); assertNotNull(doctor); assertNull(doctor.getUserAccount()); connections =userConnectionService.findConfirmedConnections(doctor.getId()); assertEquals(0, connections.size()); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void deleteUser_AlreadyDeleted() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); assertNotNull(doctor.getUserAccount()); userService.deleteUserAccount(doctor.getId()); userService.deleteUserAccount(doctor.getId()); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void activateUserAccount_NullCode() throws Exception { userService.activateUserAccount(null); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void activateUserAccount_BlankCode() throws Exception { userService.activateUserAccount(" "); } /** * * @throws Exception */ @Test(expected = IllegalStateException.class) public void activateUserAccount_UserNotExists() throws Exception { userService.activateUserAccount("aaaa"); } /** * * @throws Exception */ @Test public void activateUserAccount() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); String actuid = "aaa"; doctor.setActivationUid(actuid); userService.update(doctor); doctor = (Doctor)userService.activateUserAccount(actuid); assertNotNull(doctor); assertNull(doctor.getActivationUid()); } /** * * @throws Exception */ @Test(expected=IllegalStateException.class) public void findUserByActivationUID_InactiveUserNotExits() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); userService.findUserByActivationUID("aaa"); } /** * * @throws Exception */ @Test public void findUserByActivationUID() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); String actuid = "aaa"; doctor.setActivationUid(actuid); doctor.setState(UserState.R); userService.update(doctor); Doctor doctor2 = (Doctor) userService.findUserByActivationUID("aaa"); assertNotNull(doctor2); assertEquals(doctor, doctor2); assertEquals(actuid, doctor2.getActivationUid()); } /** * * @throws Exception */ @Test public void acceptInvitation() throws Exception { UserConnectionService userConnectionBo = (UserConnectionService)applicationContext.getBean(ComponentNames.USER_CONNECTION_SERVICE); assertNotNull(userConnectionBo); User owner = userService.login("sysuser1", "12345"); assertNotNull(owner); assertTrue(Patient.class.isInstance(owner)); User user = userService.login("sysuser1", "12345"); assertNotNull(user); assertTrue(Patient.class.isInstance(user)); try { userConnectionBo.acceptInvitation(user.getId(), null); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equals("Owner id must not be null")); } try { userConnectionBo.acceptInvitation(null, owner.getId()); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equals("User id must not be null")); } try { userConnectionBo.acceptInvitation(user.getId(), owner.getId()); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().equals("Connection not exists")); } List<UserConnection> connections = userConnectionBo.findAll(); int oldSize = connections.size(); UserConnection userConnection = new UserConnection(); userConnection.setState(UserConnectionState.P); userConnection.setOwner(owner); userConnection.setUser(user); userConnection.setCreated(new Date()); Long userConnectionId = userConnectionBo.save(userConnection); assertTrue(!userConnectionId.equals(0L)); assertNotNull(userConnectionId); connections = userConnectionBo.findAll(); assertTrue(connections.size() == oldSize + 1); userConnectionBo.acceptInvitation(user.getId(), owner.getId()); UserConnection connection = userConnectionBo.findById(userConnectionId); assertTrue(connection.getState().equals(UserConnectionState.A)); try { userConnectionBo.acceptInvitation(user.getId(), owner.getId()); fail(); } catch (IllegalStateException e) { assertTrue(e.getMessage().equals("Connection wrong state, it isn't pending")); } } /** * * @throws Exception */ @Test public void register() throws Exception { String name = "name"; String login = "login"; String password = "12345"; UserType userType = UserType.P; String email = "test@gmail.com"; try { userService.register((Patient)null, login, password, email, null, "projecth.com"); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equals("user must not be null")); } try { userService.register(new Patient(), null, password, email, null, "projecth.com"); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equals("login must not be null or empty")); } try { userService.register(new Patient(), login, null, email, null, "projecth.com"); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equals("password must not be null or empty")); } try { userService.register(new Patient(), login, password, null, null, "projecth.com"); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equals("email must not be null or empty")); } try { userService.register(new Patient(), login, password, "pat1@projecth.com", null, "projecth.com"); fail(); } catch (UserRegistrationException e) { assertEquals(UserRegistrationException.Reason.EMAIL_ALREADY_EXISTS, e.getReason()); } Patient patient = new Patient(); patient.setName(new Name(name, null)); Long userId = userService.register(patient, login, password, email, null, "projecth.com"); flushSession(); assertTrue(wiser.getMessages().size() == 1); wiser.getMessages().clear(); User user = userService.findById(userId); assertTrue(user.getName().getName().equals(name)); assertTrue(user.getUserAccount().getLogin().equals(login)); assertTrue(user.getUserAccount().getEmail().equals(email)); assertTrue(user.getUserType().equals(userType)); userService.activateUserAccount(user.getActivationUid()); user = userService.login(login, password); assertNotNull(user); assertTrue(user.getName().getName().equals(name)); assertTrue(user.getUserAccount().getLogin().equals(login)); assertTrue(user.getUserAccount().getEmail().equals(email)); assertTrue(user.getUserType().equals(userType)); assertTrue(user.getActivationUid() == null); } /** * * @throws Exception */ @Test public void registerDoctor() throws Exception { String login = "login"; String password = "12345"; UserType userType = UserType.D; String email = "jozef.novak@test.com"; Doctor doctor = new Doctor(); doctor.setName(new Name("Jan", "Novak")); MedicalInstitution medicalInstitution = new MedicalInstitution(); medicalInstitution.setName("MI Berlin"); medicalInstitution.setPhoneNumber(new PhoneNumber("49", "098765431")); medicalInstitution.setFaxNumber(new PhoneNumber("49", "098765432")); doctor.setMedicalInstitution(medicalInstitution); Long userId = userService.register(doctor, login, password, email, null, "projecth.com"); assertTrue(wiser.getMessages().size() == 1); wiser.getMessages().clear(); User user = userService.findById(userId); List<UserConnection> connections = patientService.findAllByDoctor(userId); assertEquals(1, connections.size()); assertEquals(UserConnectionState.A, connections.get(0).getState()); userService.activateUserAccount(user.getActivationUid()); flushSession(); // unverified ok user = userService.login(login, password); userService.verifyUser(user.getId()); user = userService.login(login, password); user = userService.findById(user.getId()); assertNotNull(user); assertEquals("Jan", user.getName().getName()); assertEquals("Novak", user.getName().getSurname()); assertTrue(user.getUserAccount().getLogin().equals(login)); assertTrue(user.getUserAccount().getEmail().equals(email)); assertTrue(user.getUserType().equals(userType)); assertTrue(user.getActivationUid() == null); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void resetCredientials_NullString() throws Exception { userService.resetCredientials(null, "projecth.com"); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void resetCredientials_BlankString() throws Exception { userService.resetCredientials(" ", "projecth.com"); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void resetCredientials_UnknownEmail() throws Exception { userService.resetCredientials("aaaaa", "projecth.com"); } /** * * @throws Exception */ @Test public void resetCredientials() throws Exception { String name = "name"; String login = "login"; String password = "12345"; String email = "test@gmail.com"; Patient patient = new Patient(); patient.setName(new Name(name, name)); Long userId = userService.register(patient, login, password, email, null, "projecth.com"); assertTrue(wiser.getMessages().size() == 1); wiser.getMessages().clear(); User user = userService.findById(userId); user = userService.activateUserAccount(user.getActivationUid()); assertTrue(user.getState().equals(UserState.A)); userService.resetCredientials(email, "projecth.com"); assertTrue(wiser.getMessages().size() == 1); wiser.getMessages().clear(); try { userService.login(login, password); fail(); } catch (LoginException e) { assertEquals(LoginException.Reason.USER_IS_NOT_ACTIVE, e.getReason()); } user = userService.findById(userId); assertTrue(user.getState().equals(UserState.P)); userService.changePassword(userId, null, password); user = userService.login(login, password); assertTrue(user.getState().equals(UserState.A)); } /** * * @throws Exception */ @Test public void addAndRemoveDiseasesToUser() throws Exception { DiseaseService diseaseService = (DiseaseService)applicationContext.getBean(ComponentNames.DISEASE_SERVICE); assertNotNull(diseaseService); DiseaseGroup diseaseGroup = new DiseaseGroup(); diseaseGroup.setCode("code"); diseaseGroup.setName("name"); Long diseaseGroupId = diseaseService.saveGroup(diseaseGroup); assertNotNull(diseaseGroupId); assertTrue(!diseaseGroupId.equals(0L)); DiseaseSubgroup diseaseSubgroup = new DiseaseSubgroup(); diseaseSubgroup.setCode("code"); diseaseSubgroup.setName("name"); diseaseSubgroup.setDiseaseGroup(diseaseGroup); Long diseaseSubgroupId = diseaseService.saveSubgroup(diseaseSubgroup); assertNotNull(diseaseSubgroupId); assertTrue(!diseaseSubgroupId.equals(0L)); Disease disease1 = new Disease(); disease1.setCode("code1"); disease1.setName("name1"); disease1.setImageName("imageName1"); disease1.setDiseaseSubgroup(diseaseSubgroup); Disease disease2 = new Disease(); disease2.setCode("code2"); disease2.setName("name2"); disease2.setImageName("imageName2"); disease2.setDiseaseSubgroup(diseaseSubgroup); Long diseaseId1 = diseaseService.save(disease1); assertNotNull(diseaseId1); assertTrue(!diseaseId1.equals(0L)); Long diseaseId2 = diseaseService.save(disease2); assertNotNull(diseaseId2); assertTrue(!diseaseId2.equals(0L)); List<Disease> diseases = diseaseService.findAll(); String name1 = "name1"; String name2 = "name2"; String login1 = "login1"; String login2 = "login2"; String password = "12345"; String email1 = "email1@email.com"; String email2 = "email2@email.com"; Patient patient1 = new Patient(); patient1.setName(new Name(name1, null)); Long userId1 = userService.register(patient1, login1, password, email1, null, "projecth.com"); User user1 = userService.findById(userId1); userService.activateUserAccount(user1.getActivationUid()); user1 = userService.login(login1, password); assertNotNull(user1); Patient patient2 = new Patient(); patient2.setName(new Name(name2, null)); Long userId2 = userService.register(patient2, login2, password, email2, null, "projecth.com"); User user2 = userService.findById(userId2); userService.activateUserAccount(user2.getActivationUid()); user2 = userService.login(login2, password); assertNotNull(user2); userService.addDiseasesToUser(user1.getId(), diseases); user1 = userService.findById(user1.getId()); assertTrue(user1.getDiseases().size() == diseases.size()); List<Disease> diseases2 = new ArrayList<Disease>(); Disease disease20 = diseases.get(0); diseases2.add(disease20); userService.addDiseasesToUser(user2.getId(), diseases2); user2 = userService.findById(user2.getId()); assertTrue(user2.getDiseases().size() == diseases2.size()); int oldSize = user2.getDiseases().size(); userService.removeDiseasesFromUser(user2.getId(), diseases2); user2 = userService.findById(user2.getId()); assertTrue(user2.getDiseases().size() == oldSize - diseases2.size()); } /** * * @throws Exception */ @Test public void cancelInvitation() throws Exception { UserConnectionService userConnectionBo = (UserConnectionService)applicationContext.getBean(ComponentNames.USER_CONNECTION_SERVICE); assertNotNull(userConnectionBo); Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); Patient user = (Patient)userService.login("sysuser1", "12345"); assertNotNull(user); int oldSize = userConnectionBo.findAll().size(); List<UserConnection> connections = userConnectionBo.findConfirmedConnections(doctor.getId()); assertEquals(1, connections.size()); assertEquals(UserConnectionState.A, connections.get(0).getState()); userConnectionBo.cancelInvitation(doctor.getId(), user.getId()); UserConnection connection = userConnectionBo.findById(connections.get(0).getId()); assertEquals(UserConnectionState.C, connection.getState()); assertEquals(oldSize, userConnectionBo.findAll().size()); try { userConnectionBo.cancelInvitation(doctor.getId(), user.getId()); fail(); } catch (IllegalStateException e) { } } /** * * @throws Exception */ @Test public void invite() throws Exception { UserConnectionService userConnectionBo = (UserConnectionService)applicationContext.getBean(ComponentNames.USER_CONNECTION_SERVICE); assertNotNull(userConnectionBo); Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); Patient user = (Patient)userService.login("sysuser1", "12345"); assertNotNull(user); int oldSize = userConnectionBo.findAll().size(); List<UserConnection> connections = userConnectionBo.findConfirmedConnections(doctor.getId()); assertEquals(1, connections.size()); assertEquals(UserConnectionState.A, connections.get(0).getState()); userConnectionBo.cancelInvitation(doctor.getId(), user.getId()); UserConnection connection = userConnectionBo.findById(connections.get(0).getId()); assertEquals(UserConnectionState.C, connection.getState()); Long id = userConnectionBo.invite(doctor.getId(), user.getId()); assertNotNull(id); assertEquals(connection.getId(), id); assertEquals(oldSize, userConnectionBo.findAll().size()); connection = userConnectionBo.findById(connections.get(0).getId()); assertEquals(UserConnectionState.P, connection.getState()); } /** * * @throws Exception */ @Test public void invitePatientByUnverifiedDoctor() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); Patient user = (Patient)userService.login("sysuser1", "12345"); assertNotNull(user); List<UserConnection> connections = userConnectionService.findConfirmedConnections(doctor.getId()); assertEquals(1, connections.size()); assertEquals(UserConnectionState.A, connections.get(0).getState()); userConnectionService.cancelInvitation(doctor.getId(), user.getId()); UserConnection connection = userConnectionService.findById(connections.get(0).getId()); assertEquals(UserConnectionState.C, connection.getState()); userService.unverifyUser(doctor.getId()); try { userConnectionService.invite(doctor.getId(), user.getId()); fail(); } catch (UserConnectionException e) { assertEquals(UserConnectionException.Reason.INVITING_USER_IS_NOT_VERIFIED, e.getReason()); } } /** * * @throws Exception */ @Test public void inviteUnverifiedDoctorByPatient() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); Patient user = (Patient)userService.login("sysuser1", "12345"); assertNotNull(user); List<UserConnection> connections = userConnectionService.findConfirmedConnections(doctor.getId()); assertEquals(1, connections.size()); assertEquals(UserConnectionState.A, connections.get(0).getState()); userConnectionService.cancelInvitation(doctor.getId(), user.getId()); UserConnection connection = userConnectionService.findById(connections.get(0).getId()); assertEquals(UserConnectionState.C, connection.getState()); userService.unverifyUser(doctor.getId()); try { userConnectionService.invite(user.getId(), doctor.getId()); fail(); } catch (UserConnectionException e) { assertEquals(UserConnectionException.Reason.INVITED_USER_IS_NOT_VERIFIED, e.getReason()); } } /** * * @throws Exception */ @Test public void setConnectionRequestsBlocked() throws Exception { User doctor = userService.login("sysuser3", "54321"); assertFalse(doctor.isConnectionRequestsBlocked()); userService.setConnectionRequestsBlocked(doctor.getId(), true); doctor = userService.login("sysuser3", "54321"); assertTrue(doctor.isConnectionRequestsBlocked()); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void changePassword_NullIdString() throws Exception { userService.changePassword(null, "aaaa"); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void changePassword_IdNullString() throws Exception { userService.changePassword(1L, null); } /** * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void changePassword_IdEmptyString() throws Exception { userService.changePassword(1L, " "); } /** * * @throws Exception */ @Test public void changePasswordIdString() throws Exception { String login = "sysuser1"; String oldPassword = "12345"; String newPassword = "54321"; User patient = userService.login(login, oldPassword); assertNotNull(patient); String oldPasswordHash = patient.getUserAccount().getPassword(); userService.changePassword(patient.getId(), newPassword); patient = userService.findById(patient.getId()); assertFalse(oldPasswordHash.equals(patient.getUserAccount().getPassword())); } /** * * @throws Exception */ @Test public void findUserByEmail() throws Exception { User doctor = userService.login("sysuser3", "54321"); assertNotNull(doctor); assertNull(userService.findUserByEmail("aaa")); assertEquals(doctor, userService.findUserByEmail(doctor.getUserAccount().getEmail())); } /** * * @throws Exception */ @Test public void incrementNumberOfLogins() throws Exception { User user = userService.login("sysuser3", "54321"); assertNotNull(user); int oldLoginsCount = user.getLoginsCount(); Date oldLastLoginDate = user.getLastLogin(); Thread.sleep(500); userService.incrementNumberOfLogins(user.getId()); user = userService.findById(user.getId()); assertEquals(oldLoginsCount + 1, user.getLoginsCount()); assertFalse(oldLastLoginDate.equals(user.getLastLogin())); } /** * * @throws Exception */ @Test public void updateDoctorWeigth() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); List<UserWeight> weights = doctor.getWeights(); assertTrue(weights.isEmpty()); weights.add(new UserWeight()); weights.get(0).setDate(dateFormat.parse("1.13.2003")); weights.get(0).setWeight(new BigDecimal("99.00")); userService.update(doctor); doctor = (Doctor)userService.findById(doctor.getId()); weights = doctor.getWeights(); assertFalse(weights.isEmpty()); assertEquals(dateFormat.parse("1.13.2003"), weights.get(0).getDate()); assertEquals(new BigDecimal("99.00"), weights.get(0).getWeight()); } /** * * @throws Exception */ @Test public void updatePatientRights() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); Set<GrantedRight> rights = doctor.getGrantedDataRights(); assertTrue(rights.isEmpty()); rights.add(GrantedRight.BASE_DATA_ALL); rights.add(GrantedRight.BASE_DATA_CONNECTIONS); userService.update(doctor); doctor = (Doctor)userService.findById(doctor.getId()); rights = doctor.getGrantedDataRights(); assertEquals(2, rights.size()); assertTrue(rights.contains(GrantedRight.BASE_DATA_CONNECTIONS)); assertTrue(rights.contains(GrantedRight.BASE_DATA_ALL)); rights.remove(GrantedRight.BASE_DATA_ALL); userService.update(doctor); doctor = (Doctor)userService.findById(doctor.getId()); rights = doctor.getGrantedDataRights(); assertEquals(1, rights.size()); assertFalse(rights.contains(GrantedRight.BASE_DATA_ALL)); assertTrue(rights.contains(GrantedRight.BASE_DATA_CONNECTIONS)); } /** * * @throws Exception */ @Test public void updateAboutMe() throws Exception { Doctor doctor = (Doctor)userService.login("sysuser3", "54321"); assertNotNull(doctor); assertNull(doctor.getAboutMe()); userService.updateAboutMe(doctor.getId(), "AAAAAA"); doctor = (Doctor)userService.login("sysuser3", "54321"); assertEquals("AAAAAA", doctor.getAboutMe()); userService.updateAboutMe(doctor.getId(), null); doctor = (Doctor)userService.login("sysuser3", "54321"); assertEquals(null, doctor.getAboutMe()); } /** * * @throws Exception */ @Test public void login_activationState() throws Exception { userService.findAll(); Doctor doctor = (Doctor)userService.findUserByLogin("sysuser3"); assertNotNull(doctor); userService.unverifyUser(doctor.getId()); // unverified ok userService.login(doctor.getUserAccount().getLogin(), "54321"); userService.blockUser(doctor.getId()); try { userService.login(doctor.getUserAccount().getLogin(), "54321"); fail(); } catch (LoginException e) { assertEquals(LoginException.Reason.BLOCKED, e.getReason()); } userService.unblockUser(doctor.getId()); userService.login(doctor.getUserAccount().getLogin(), "54321"); userService.verifyUser(doctor.getId()); doctor = (Doctor)userService.login(doctor.getUserAccount().getLogin(), "54321"); assertNotNull(doctor); } /** * * @throws Exception */ @Test public void findUsersByLoginNamePlace() throws Exception { String filter = "sysuser3"; List<User> users = userService.findUsersByLoginNamePlace(filter); assertEquals(1, users.size()); } }
/* Copyright 2013 Antti Kolehmainen 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.sturdyhelmetgames.roomforchange.entity; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.sturdyhelmetgames.roomforchange.level.Level; import com.sturdyhelmetgames.roomforchange.level.Level.LevelTile; public class Entity { public Level level; public EntityState state; public Direction direction = Direction.DOWN; public static final float ACCEL_MAX = 2f; public static final float VEL_MAX = 0.05f; public static final float INERTIA = 10f; private static final float MIN_WALK_VELOCITY = 0.001f; protected static final float INVULNERABLE_TIME_MIN = 1.5f; protected static final float BLINK_TICK_MAX = 0.1f; public final Vector2 accel = new Vector2(0f, 0f); public final Vector2 vel = new Vector2(0f, 0f); public float stateTime = 0f; public float width, height; public final Rectangle bounds = new Rectangle(); public final Rectangle[] r = { new Rectangle(), new Rectangle(), new Rectangle(), new Rectangle() }; public final HoleFallWrapper[] holes = { new HoleFallWrapper(), new HoleFallWrapper(), new HoleFallWrapper(), new HoleFallWrapper() }; public int[][] tiles; public float pause = 0f; protected float invulnerableTick; protected float blinkTick; public class HoleFallWrapper { public final Rectangle bounds = new Rectangle(); public void set(float x, float y, float width, float height) { bounds.set(x, y, width, height); } public void unset() { bounds.set(-1, -1, 0, 0); } } public float getMaxVelocity() { return VEL_MAX; } public float getInertia() { return INERTIA; } public enum Direction { UP, DOWN, LEFT, RIGHT; public Direction turnLeft() { switch (this) { case UP: return LEFT; case DOWN: return RIGHT; case LEFT: return DOWN; case RIGHT: return UP; } return UP; } public Direction turnRight() { switch (this) { case UP: return RIGHT; case DOWN: return LEFT; case LEFT: return UP; case RIGHT: return DOWN; } return DOWN; } } public enum EntityState { IDLE, WALKING, FALLING, DYING, DEAD; } public Entity(float x, float y, float width, float height, Level level) { this.level = level; this.width = width; this.height = height; bounds.set(x, y, width - 0.2f, height - 0.2f); state = EntityState.IDLE; } public void render(float delta, SpriteBatch batch) { } public void update(float fixedStep) { if (pause > 0f) { pause -= fixedStep; } // tick dying if (blinkTick > BLINK_TICK_MAX) { blinkTick = 0f; } // tick alive & dying times invulnerableTick -= fixedStep; if (invulnerableTick > 0f) { blinkTick += fixedStep; } if (invulnerableTick <= 0f) { blinkTick = 0f; } if (pause <= 0f) { tryMove(); vel.add(accel); if (vel.x > getMaxVelocity()) { vel.x = getMaxVelocity(); } if (vel.x < -getMaxVelocity()) { vel.x = -getMaxVelocity(); } if (vel.y > getMaxVelocity()) { vel.y = getMaxVelocity(); } if (vel.y < -getMaxVelocity()) { vel.y = -getMaxVelocity(); } accel.scl(fixedStep); if (state == EntityState.WALKING) { vel.lerp(Vector2.Zero, getInertia() * fixedStep); } else { vel.scl(fixedStep); } stateTime += fixedStep; } } public void moveWithAccel(Direction dir) { if (dir == Direction.UP) { accel.y = ACCEL_MAX; } else if (dir == Direction.DOWN) { accel.y = -ACCEL_MAX; } else if (dir == Direction.LEFT) { accel.x = -ACCEL_MAX; } else if (dir == Direction.RIGHT) { accel.x = ACCEL_MAX; } direction = dir; state = EntityState.WALKING; } protected void tryMove() { bounds.y += vel.y; fetchCollidableRects(); for (int i = 0; i < holes.length; i++) { HoleFallWrapper hole = holes[i]; if (bounds.overlaps(hole.bounds)) { fall(); } } for (int i = 0; i < r.length; i++) { Rectangle rect = r[i]; if (bounds.overlaps(rect)) { if (vel.y < 0) { bounds.y = rect.y + rect.height + 0.01f; } else bounds.y = rect.y - bounds.height - 0.01f; vel.y = 0; hitWallHook(); } } bounds.x += vel.x; fetchCollidableRects(); for (int i = 0; i < holes.length; i++) { HoleFallWrapper hole = holes[i]; if (bounds.overlaps(hole.bounds)) { fall(); } } for (int i = 0; i < r.length; i++) { Rectangle rect = r[i]; if (bounds.overlaps(rect)) { if (vel.x < 0) bounds.x = rect.x + rect.width + 0.01f; else bounds.x = rect.x - bounds.width - 0.01f; vel.x = 0; hitWallHook(); } } } protected void fall() { state = EntityState.FALLING; } protected void fetchCollidableRects() { int p1x = (int) bounds.x; int p1y = (int) Math.floor(bounds.y); int p2x = (int) (bounds.x + bounds.width); int p2y = (int) Math.floor(bounds.y); int p3x = (int) (bounds.x + bounds.width); int p3y = (int) (bounds.y + bounds.height); int p4x = (int) bounds.x; int p4y = (int) (bounds.y + bounds.height); try { LevelTile tile1 = null; if (level.getTiles().length >= p1x && p1x >= 0 && level.getTiles()[p1x].length >= p1y && p1y >= 0) tile1 = level.getTiles()[p1x][p1y]; LevelTile tile2 = null; if (level.getTiles().length >= p2x && p1x >= 0 && level.getTiles()[p2x].length >= p2y && p2y >= 0) tile2 = level.getTiles()[p2x][p2y]; LevelTile tile3 = null; if (level.getTiles().length >= p3x && p3x >= 0 && level.getTiles()[p3x].length >= p3y && p3y >= 0) tile3 = level.getTiles()[p3x][p3y]; LevelTile tile4 = null; if (level.getTiles().length >= p4x && p4x >= 0 && level.getTiles()[p4x].length >= p4y && p4y >= 0) tile4 = level.getTiles()[p4x][p4y]; if (tile1 != null && tile1.isHole()) holes[0].set(p1x + 0.4f, p1y + 0.5f, 0.2f, 0.05f); else holes[0].unset(); if (tile1 != null && tile1.isCollidable()) { r[0].set(p1x, p1y, 1, 1); } else { r[0].set(-1, -1, 0, 0); } if (tile2 != null && tile2.isHole()) holes[1].set(p2x + 0.4f, p2y + 0.5f, 0.2f, 0.05f); else holes[1].unset(); if (tile2 != null && tile2.isCollidable()) { r[1].set(p2x, p2y, 1, 1); } else { r[1].set(-1, -1, 0, 0); } if (tile3 != null && tile3.isHole()) holes[2].set(p3x + 0.4f, p3y + 0.5f, 0.2f, 0.05f); else holes[2].unset(); if (tile3 != null && tile3.isCollidable()) { r[2].set(p3x, p3y, 1, 1); } else { r[2].set(-1, -1, 0, 0); } if (tile4 != null && tile4.isHole()) holes[3].set(p4x + 0.4f, p4y + 0.5f, 0.2f, 0.05f); else holes[3].unset(); if (tile4 != null && tile4.isCollidable()) { r[3].set(p4x, p4y, 1, 1); } else { r[3].set(-1, -1, 0, 0); } } catch (ArrayIndexOutOfBoundsException e) { Gdx.app.log("Creature", "Creature went off screen"); } } public boolean isNotWalking() { if (vel.x > -MIN_WALK_VELOCITY && vel.x < MIN_WALK_VELOCITY && vel.y > -MIN_WALK_VELOCITY && vel.y < MIN_WALK_VELOCITY) { state = EntityState.IDLE; return true; } return false; } public void hit(Rectangle hitBounds) { } public void hitWallHook() { } public boolean isFalling() { return state == EntityState.FALLING; } public boolean isDying() { return state == EntityState.DYING; } public boolean isDead() { return state == EntityState.DEAD; } public boolean isAlive() { return !isDying() && !isDead() && !isFalling(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.type; import com.facebook.presto.operator.scalar.AbstractTestFunctions; import org.testng.annotations.Test; import static com.facebook.presto.spi.StandardErrorCode.DIVISION_BY_ZERO; import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.FloatType.FLOAT; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.SmallintType.SMALLINT; import static com.facebook.presto.spi.type.TinyintType.TINYINT; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static java.lang.String.format; public class TestTinyintOperators extends AbstractTestFunctions { @Test public void testLiteral() throws Exception { assertFunction("TINYINT'37'", TINYINT, (byte) 37); assertFunction("TINYINT'17'", TINYINT, (byte) 17); assertInvalidCast("TINYINT'" + ((long) Byte.MAX_VALUE + 1L) + "'"); } @Test public void testUnaryPlus() throws Exception { assertFunction("+TINYINT'37'", TINYINT, (byte) 37); assertFunction("+TINYINT'17'", TINYINT, (byte) 17); } @Test public void testUnaryMinus() throws Exception { assertFunction("TINYINT'-37'", TINYINT, (byte) -37); assertFunction("TINYINT'-17'", TINYINT, (byte) -17); assertInvalidFunction("TINYINT'-" + Byte.MIN_VALUE + "'", INVALID_CAST_ARGUMENT); } @Test public void testAdd() throws Exception { assertFunction("TINYINT'37' + TINYINT'37'", TINYINT, (byte) (37 + 37)); assertFunction("TINYINT'37' + TINYINT'17'", TINYINT, (byte) (37 + 17)); assertFunction("TINYINT'17' + TINYINT'37'", TINYINT, (byte) (17 + 37)); assertFunction("TINYINT'17' + TINYINT'17'", TINYINT, (byte) (17 + 17)); assertNumericOverflow(format("TINYINT'%s' + TINYINT'1'", Byte.MAX_VALUE), "tinyint addition overflow: 127 + 1"); } @Test public void testSubtract() throws Exception { assertFunction("TINYINT'37' - TINYINT'37'", TINYINT, (byte) 0); assertFunction("TINYINT'37' - TINYINT'17'", TINYINT, (byte) (37 - 17)); assertFunction("TINYINT'17' - TINYINT'37'", TINYINT, (byte) (17 - 37)); assertFunction("TINYINT'17' - TINYINT'17'", TINYINT, (byte) 0); assertNumericOverflow(format("TINYINT'%s' - TINYINT'1'", Byte.MIN_VALUE), "tinyint subtraction overflow: -128 - 1"); } @Test public void testMultiply() throws Exception { assertFunction("TINYINT'11' * TINYINT'11'", TINYINT, (byte) (11 * 11)); assertFunction("TINYINT'11' * TINYINT'9'", TINYINT, (byte) (11 * 9)); assertFunction("TINYINT'9' * TINYINT'11'", TINYINT, (byte) (9 * 11)); assertFunction("TINYINT'9' * TINYINT'9'", TINYINT, (byte) (9 * 9)); assertNumericOverflow(format("TINYINT'%s' * TINYINT'2'", Byte.MAX_VALUE), "tinyint multiplication overflow: 127 * 2"); } @Test public void testDivide() throws Exception { assertFunction("TINYINT'37' / TINYINT'37'", TINYINT, (byte) 1); assertFunction("TINYINT'37' / TINYINT'17'", TINYINT, (byte) (37 / 17)); assertFunction("TINYINT'17' / TINYINT'37'", TINYINT, (byte) (17 / 37)); assertFunction("TINYINT'17' / TINYINT'17'", TINYINT, (byte) 1); assertInvalidFunction("TINYINT'17' / TINYINT'0'", DIVISION_BY_ZERO); } @Test public void testModulus() throws Exception { assertFunction("TINYINT'37' % TINYINT'37'", TINYINT, (byte) 0); assertFunction("TINYINT'37' % TINYINT'17'", TINYINT, (byte) (37 % 17)); assertFunction("TINYINT'17' % TINYINT'37'", TINYINT, (byte) (17 % 37)); assertFunction("TINYINT'17' % TINYINT'17'", TINYINT, (byte) 0); assertInvalidFunction("TINYINT'17' % TINYINT'0'", DIVISION_BY_ZERO); } @Test public void testNegation() throws Exception { assertFunction("-(TINYINT'37')", TINYINT, (byte) -37); assertFunction("-(TINYINT'17')", TINYINT, (byte) -17); assertFunction("-(TINYINT'" + Byte.MAX_VALUE + "')", TINYINT, (byte) (Byte.MIN_VALUE + 1)); assertNumericOverflow(format("-(TINYINT'%s')", Byte.MIN_VALUE), "tinyint negation overflow: -128"); } @Test public void testEqual() throws Exception { assertFunction("TINYINT'37' = TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' = TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'17' = TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'17' = TINYINT'17'", BOOLEAN, true); } @Test public void testNotEqual() throws Exception { assertFunction("TINYINT'37' <> TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'37' <> TINYINT'17'", BOOLEAN, true); assertFunction("TINYINT'17' <> TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'17' <> TINYINT'17'", BOOLEAN, false); } @Test public void testLessThan() throws Exception { assertFunction("TINYINT'37' < TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'37' < TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'17' < TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'17' < TINYINT'17'", BOOLEAN, false); } @Test public void testLessThanOrEqual() throws Exception { assertFunction("TINYINT'37' <= TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' <= TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'17' <= TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'17' <= TINYINT'17'", BOOLEAN, true); } @Test public void testGreaterThan() throws Exception { assertFunction("TINYINT'37' > TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'37' > TINYINT'17'", BOOLEAN, true); assertFunction("TINYINT'17' > TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'17' > TINYINT'17'", BOOLEAN, false); } @Test public void testGreaterThanOrEqual() throws Exception { assertFunction("TINYINT'37' >= TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' >= TINYINT'17'", BOOLEAN, true); assertFunction("TINYINT'17' >= TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'17' >= TINYINT'17'", BOOLEAN, true); } @Test public void testBetween() throws Exception { assertFunction("TINYINT'37' BETWEEN TINYINT'37' AND TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' BETWEEN TINYINT'37' AND TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'37' BETWEEN TINYINT'17' AND TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'37' BETWEEN TINYINT'17' AND TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'17' BETWEEN TINYINT'37' AND TINYINT'37'", BOOLEAN, false); assertFunction("TINYINT'17' BETWEEN TINYINT'37' AND TINYINT'17'", BOOLEAN, false); assertFunction("TINYINT'17' BETWEEN TINYINT'17' AND TINYINT'37'", BOOLEAN, true); assertFunction("TINYINT'17' BETWEEN TINYINT'17' AND TINYINT'17'", BOOLEAN, true); } @Test public void testCastToBigint() throws Exception { assertFunction("cast(TINYINT'37' as bigint)", BIGINT, 37L); assertFunction("cast(TINYINT'17' as bigint)", BIGINT, 17L); } @Test public void testCastToInteger() throws Exception { assertFunction("cast(TINYINT'37' as integer)", INTEGER, 37); assertFunction("cast(TINYINT'17' as integer)", INTEGER, 17); } @Test public void testCastToSmallint() throws Exception { assertFunction("cast(TINYINT'37' as smallint)", SMALLINT, (short) 37); assertFunction("cast(TINYINT'17' as smallint)", SMALLINT, (short) 17); } @Test public void testCastToVarchar() throws Exception { assertFunction("cast(TINYINT'37' as varchar)", VARCHAR, "37"); assertFunction("cast(TINYINT'17' as varchar)", VARCHAR, "17"); } @Test public void testCastToDouble() throws Exception { assertFunction("cast(TINYINT'37' as double)", DOUBLE, 37.0); assertFunction("cast(TINYINT'17' as double)", DOUBLE, 17.0); } @Test public void testCastToFloat() throws Exception { assertFunction("cast(TINYINT'37' as float)", FLOAT, 37.0f); assertFunction("cast(TINYINT'-128' as float)", FLOAT, -128.0f); assertFunction("cast(TINYINT'0' as float)", FLOAT, 0.0f); } @Test public void testCastToBoolean() throws Exception { assertFunction("cast(TINYINT'37' as boolean)", BOOLEAN, true); assertFunction("cast(TINYINT'17' as boolean)", BOOLEAN, true); assertFunction("cast(TINYINT'0' as boolean)", BOOLEAN, false); } @Test public void testCastFromVarchar() throws Exception { assertFunction("cast('37' as tinyint)", TINYINT, (byte) 37); assertFunction("cast('17' as tinyint)", TINYINT, (byte) 17); } }
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2017 Eric Lafortune @ GuardSquare * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.classfile.instruction; /** * Representation of an instruction. * * @author Eric Lafortune */ public interface InstructionConstants { public static final byte OP_NOP = 0; public static final byte OP_ACONST_NULL = 1; public static final byte OP_ICONST_M1 = 2; public static final byte OP_ICONST_0 = 3; public static final byte OP_ICONST_1 = 4; public static final byte OP_ICONST_2 = 5; public static final byte OP_ICONST_3 = 6; public static final byte OP_ICONST_4 = 7; public static final byte OP_ICONST_5 = 8; public static final byte OP_LCONST_0 = 9; public static final byte OP_LCONST_1 = 10; public static final byte OP_FCONST_0 = 11; public static final byte OP_FCONST_1 = 12; public static final byte OP_FCONST_2 = 13; public static final byte OP_DCONST_0 = 14; public static final byte OP_DCONST_1 = 15; public static final byte OP_BIPUSH = 16; public static final byte OP_SIPUSH = 17; public static final byte OP_LDC = 18; public static final byte OP_LDC_W = 19; public static final byte OP_LDC2_W = 20; public static final byte OP_ILOAD = 21; public static final byte OP_LLOAD = 22; public static final byte OP_FLOAD = 23; public static final byte OP_DLOAD = 24; public static final byte OP_ALOAD = 25; public static final byte OP_ILOAD_0 = 26; public static final byte OP_ILOAD_1 = 27; public static final byte OP_ILOAD_2 = 28; public static final byte OP_ILOAD_3 = 29; public static final byte OP_LLOAD_0 = 30; public static final byte OP_LLOAD_1 = 31; public static final byte OP_LLOAD_2 = 32; public static final byte OP_LLOAD_3 = 33; public static final byte OP_FLOAD_0 = 34; public static final byte OP_FLOAD_1 = 35; public static final byte OP_FLOAD_2 = 36; public static final byte OP_FLOAD_3 = 37; public static final byte OP_DLOAD_0 = 38; public static final byte OP_DLOAD_1 = 39; public static final byte OP_DLOAD_2 = 40; public static final byte OP_DLOAD_3 = 41; public static final byte OP_ALOAD_0 = 42; public static final byte OP_ALOAD_1 = 43; public static final byte OP_ALOAD_2 = 44; public static final byte OP_ALOAD_3 = 45; public static final byte OP_IALOAD = 46; public static final byte OP_LALOAD = 47; public static final byte OP_FALOAD = 48; public static final byte OP_DALOAD = 49; public static final byte OP_AALOAD = 50; public static final byte OP_BALOAD = 51; public static final byte OP_CALOAD = 52; public static final byte OP_SALOAD = 53; public static final byte OP_ISTORE = 54; public static final byte OP_LSTORE = 55; public static final byte OP_FSTORE = 56; public static final byte OP_DSTORE = 57; public static final byte OP_ASTORE = 58; public static final byte OP_ISTORE_0 = 59; public static final byte OP_ISTORE_1 = 60; public static final byte OP_ISTORE_2 = 61; public static final byte OP_ISTORE_3 = 62; public static final byte OP_LSTORE_0 = 63; public static final byte OP_LSTORE_1 = 64; public static final byte OP_LSTORE_2 = 65; public static final byte OP_LSTORE_3 = 66; public static final byte OP_FSTORE_0 = 67; public static final byte OP_FSTORE_1 = 68; public static final byte OP_FSTORE_2 = 69; public static final byte OP_FSTORE_3 = 70; public static final byte OP_DSTORE_0 = 71; public static final byte OP_DSTORE_1 = 72; public static final byte OP_DSTORE_2 = 73; public static final byte OP_DSTORE_3 = 74; public static final byte OP_ASTORE_0 = 75; public static final byte OP_ASTORE_1 = 76; public static final byte OP_ASTORE_2 = 77; public static final byte OP_ASTORE_3 = 78; public static final byte OP_IASTORE = 79; public static final byte OP_LASTORE = 80; public static final byte OP_FASTORE = 81; public static final byte OP_DASTORE = 82; public static final byte OP_AASTORE = 83; public static final byte OP_BASTORE = 84; public static final byte OP_CASTORE = 85; public static final byte OP_SASTORE = 86; public static final byte OP_POP = 87; public static final byte OP_POP2 = 88; public static final byte OP_DUP = 89; public static final byte OP_DUP_X1 = 90; public static final byte OP_DUP_X2 = 91; public static final byte OP_DUP2 = 92; public static final byte OP_DUP2_X1 = 93; public static final byte OP_DUP2_X2 = 94; public static final byte OP_SWAP = 95; public static final byte OP_IADD = 96; public static final byte OP_LADD = 97; public static final byte OP_FADD = 98; public static final byte OP_DADD = 99; public static final byte OP_ISUB = 100; public static final byte OP_LSUB = 101; public static final byte OP_FSUB = 102; public static final byte OP_DSUB = 103; public static final byte OP_IMUL = 104; public static final byte OP_LMUL = 105; public static final byte OP_FMUL = 106; public static final byte OP_DMUL = 107; public static final byte OP_IDIV = 108; public static final byte OP_LDIV = 109; public static final byte OP_FDIV = 110; public static final byte OP_DDIV = 111; public static final byte OP_IREM = 112; public static final byte OP_LREM = 113; public static final byte OP_FREM = 114; public static final byte OP_DREM = 115; public static final byte OP_INEG = 116; public static final byte OP_LNEG = 117; public static final byte OP_FNEG = 118; public static final byte OP_DNEG = 119; public static final byte OP_ISHL = 120; public static final byte OP_LSHL = 121; public static final byte OP_ISHR = 122; public static final byte OP_LSHR = 123; public static final byte OP_IUSHR = 124; public static final byte OP_LUSHR = 125; public static final byte OP_IAND = 126; public static final byte OP_LAND = 127; public static final byte OP_IOR = -128; public static final byte OP_LOR = -127; public static final byte OP_IXOR = -126; public static final byte OP_LXOR = -125; public static final byte OP_IINC = -124; public static final byte OP_I2L = -123; public static final byte OP_I2F = -122; public static final byte OP_I2D = -121; public static final byte OP_L2I = -120; public static final byte OP_L2F = -119; public static final byte OP_L2D = -118; public static final byte OP_F2I = -117; public static final byte OP_F2L = -116; public static final byte OP_F2D = -115; public static final byte OP_D2I = -114; public static final byte OP_D2L = -113; public static final byte OP_D2F = -112; public static final byte OP_I2B = -111; public static final byte OP_I2C = -110; public static final byte OP_I2S = -109; public static final byte OP_LCMP = -108; public static final byte OP_FCMPL = -107; public static final byte OP_FCMPG = -106; public static final byte OP_DCMPL = -105; public static final byte OP_DCMPG = -104; public static final byte OP_IFEQ = -103; public static final byte OP_IFNE = -102; public static final byte OP_IFLT = -101; public static final byte OP_IFGE = -100; public static final byte OP_IFGT = -99; public static final byte OP_IFLE = -98; public static final byte OP_IFICMPEQ = -97; public static final byte OP_IFICMPNE = -96; public static final byte OP_IFICMPLT = -95; public static final byte OP_IFICMPGE = -94; public static final byte OP_IFICMPGT = -93; public static final byte OP_IFICMPLE = -92; public static final byte OP_IFACMPEQ = -91; public static final byte OP_IFACMPNE = -90; public static final byte OP_GOTO = -89; public static final byte OP_JSR = -88; public static final byte OP_RET = -87; public static final byte OP_TABLESWITCH = -86; public static final byte OP_LOOKUPSWITCH = -85; public static final byte OP_IRETURN = -84; public static final byte OP_LRETURN = -83; public static final byte OP_FRETURN = -82; public static final byte OP_DRETURN = -81; public static final byte OP_ARETURN = -80; public static final byte OP_RETURN = -79; public static final byte OP_GETSTATIC = -78; public static final byte OP_PUTSTATIC = -77; public static final byte OP_GETFIELD = -76; public static final byte OP_PUTFIELD = -75; public static final byte OP_INVOKEVIRTUAL = -74; public static final byte OP_INVOKESPECIAL = -73; public static final byte OP_INVOKESTATIC = -72; public static final byte OP_INVOKEINTERFACE = -71; public static final byte OP_INVOKEDYNAMIC = -70; public static final byte OP_NEW = -69; public static final byte OP_NEWARRAY = -68; public static final byte OP_ANEWARRAY = -67; public static final byte OP_ARRAYLENGTH = -66; public static final byte OP_ATHROW = -65; public static final byte OP_CHECKCAST = -64; public static final byte OP_INSTANCEOF = -63; public static final byte OP_MONITORENTER = -62; public static final byte OP_MONITOREXIT = -61; public static final byte OP_WIDE = -60; public static final byte OP_MULTIANEWARRAY = -59; public static final byte OP_IFNULL = -58; public static final byte OP_IFNONNULL = -57; public static final byte OP_GOTO_W = -56; public static final byte OP_JSR_W = -55; public static final String[] NAMES = { "nop", "aconst_null", "iconst_m1", "iconst_0", "iconst_1", "iconst_2", "iconst_3", "iconst_4", "iconst_5", "lconst_0", "lconst_1", "fconst_0", "fconst_1", "fconst_2", "dconst_0", "dconst_1", "bipush", "sipush", "ldc", "ldc_w", "ldc2_w", "iload", "lload", "fload", "dload", "aload", "iload_0", "iload_1", "iload_2", "iload_3", "lload_0", "lload_1", "lload_2", "lload_3", "fload_0", "fload_1", "fload_2", "fload_3", "dload_0", "dload_1", "dload_2", "dload_3", "aload_0", "aload_1", "aload_2", "aload_3", "iaload", "laload", "faload", "daload", "aaload", "baload", "caload", "saload", "istore", "lstore", "fstore", "dstore", "astore", "istore_0", "istore_1", "istore_2", "istore_3", "lstore_0", "lstore_1", "lstore_2", "lstore_3", "fstore_0", "fstore_1", "fstore_2", "fstore_3", "dstore_0", "dstore_1", "dstore_2", "dstore_3", "astore_0", "astore_1", "astore_2", "astore_3", "iastore", "lastore", "fastore", "dastore", "aastore", "bastore", "castore", "sastore", "pop", "pop2", "dup", "dup_x1", "dup_x2", "dup2", "dup2_x1", "dup2_x2", "swap", "iadd", "ladd", "fadd", "dadd", "isub", "lsub", "fsub", "dsub", "imul", "lmul", "fmul", "dmul", "idiv", "ldiv", "fdiv", "ddiv", "irem", "lrem", "frem", "drem", "ineg", "lneg", "fneg", "dneg", "ishl", "lshl", "ishr", "lshr", "iushr", "lushr", "iand", "land", "ior", "lor", "ixor", "lxor", "iinc", "i2l", "i2f", "i2d", "l2i", "l2f", "l2d", "f2i", "f2l", "f2d", "d2i", "d2l", "d2f", "i2b", "i2c", "i2s", "lcmp", "fcmpl", "fcmpg", "dcmpl", "dcmpg", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "ificmpeq", "ificmpne", "ificmplt", "ificmpge", "ificmpgt", "ificmple", "ifacmpeq", "ifacmpne", "goto", "jsr", "ret", "tableswitch", "lookupswitch", "ireturn", "lreturn", "freturn", "dreturn", "areturn", "return", "getstatic", "putstatic", "getfield", "putfield", "invokevirtual", "invokespecial", "invokestatic", "invokeinterface", "invokedynamic", "new", "newarray", "anewarray", "arraylength", "athrow", "checkcast", "instanceof", "monitorenter", "monitorexit", "wide", "multianewarray", "ifnull", "ifnonnull", "goto_w", "jsr_w", }; public static final byte ARRAY_T_BOOLEAN = 4; public static final byte ARRAY_T_CHAR = 5; public static final byte ARRAY_T_FLOAT = 6; public static final byte ARRAY_T_DOUBLE = 7; public static final byte ARRAY_T_BYTE = 8; public static final byte ARRAY_T_SHORT = 9; public static final byte ARRAY_T_INT = 10; public static final byte ARRAY_T_LONG = 11; }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.execution; import com.intellij.execution.configurations.JavaParameters; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.impl.scopes.LibraryRuntimeClasspathScope; import com.intellij.openapi.module.impl.scopes.ModuleWithDependenciesScope; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.impl.DirectoryIndex; import com.intellij.openapi.roots.impl.LibraryScopeCache; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.search.DelegatingGlobalSearchScope; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.PsiTestUtil; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.maven.MavenMultiVersionImportingTestCase; import org.jetbrains.idea.maven.importing.ArtifactsDownloadingTestCase; import org.jetbrains.idea.maven.importing.MavenModuleImporter; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class MavenClasspathsAndSearchScopesTest extends MavenMultiVersionImportingTestCase { private enum Type {PRODUCTION, TESTS} private enum Scope {COMPILE, RUNTIME, MODULE} @Override protected void setUpInWriteAction() throws Exception { super.setUpInWriteAction(); createProjectSubDirs("m1/src/main/java", "m1/src/test/java", "m2/src/main/java", "m2/src/test/java", "m3/src/main/java", "m3/src/test/java", "m4/src/main/java", "m4/src/test/java"); } @Test public void testConfiguringModuleDependencies() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m4</artifactId>" + " <version>1</version>" + " <optional>true</optional>" + " </dependency>" + "</dependencies>"); VirtualFile m3 = createModulePom("m3", "<groupId>test</groupId>" + "<artifactId>m3</artifactId>" + "<version>1</version>"); VirtualFile m4 = createModulePom("m4", "<groupId>test</groupId>" + "<artifactId>m4</artifactId>" + "<version>1</version>"); importProjects(m1, m2, m3, m4); assertModules("m1", "m2", "m3", "m4"); assertModuleModuleDeps("m1", "m2", "m3"); assertModuleModuleDeps("m2", "m3", "m4"); setupJdkForModules("m1", "m2", "m3", "m4"); assertModuleScopes("m1", "m2", "m3", "m4"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m3/src/main/java"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m3/src/main/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m3/target/classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m3/target/classes"); assertAllProductionSearchScope("m2", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m3/src/main/java", getProjectPath() + "/m4/src/main/java"); assertAllTestsSearchScope("m2", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java", getProjectPath() + "/m3/src/main/java", getProjectPath() + "/m4/src/main/java"); assertAllProductionClasspath("m2", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m3/target/classes", getProjectPath() + "/m4/target/classes"); assertAllTestsClasspath("m2", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m3/target/classes", getProjectPath() + "/m4/target/classes"); } @Test public void testDoNotIncludeTargetDirectoriesOfModuleDependenciesToLibraryClassesRoots() { VirtualFile m = createModulePom("m", "<groupId>test</groupId>" + "<artifactId>m</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>dep</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile dep = createModulePom("dep", "<groupId>test</groupId>" + "<artifactId>dep</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " </dependency>" + "</dependencies>"); importProjects(m, dep); assertModules("m", "dep"); assertModuleModuleDeps("m", "dep"); setupJdkForModules("m", "dep"); createOutputDirectories(); Module module = getModule("m"); VirtualFile[] jdkRoots = ModuleRootManager.getInstance(module).getSdk().getRootProvider().getFiles(OrderRootType.CLASSES); VirtualFile[] junitRoots = LibraryTablesRegistrar.getInstance().getLibraryTable(myProject).getLibraryByName("Maven: junit:junit:4.0") .getFiles(OrderRootType.CLASSES); assertOrderedEquals(OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots(), ArrayUtil.mergeArrays(jdkRoots, junitRoots)); } @Test public void testDoNotIncludeTestClassesWhenConfiguringModuleDependenciesForProductionCode() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); importProjects(m1, m2); assertModules("m1", "m2"); assertModuleModuleDeps("m1", "m2"); setupJdkForModules("m1", "m2"); assertModuleScopes("m1", "m2"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes"); assertAllProductionSearchScope("m2", getProjectPath() + "/m2/src/main/java"); assertAllProductionClasspath("m2", getProjectPath() + "/m2/target/classes"); } @Test public void testConfiguringModuleDependenciesOnTestJar() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <type>test-jar</type>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " <classifier>tests</classifier>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); VirtualFile m3 = createModulePom("m3", "<groupId>test</groupId>" + "<artifactId>m3</artifactId>" + "<version>1</version>"); importProjects(m1, m2, m3); assertModules("m1", "m2", "m3"); setupJdkForModules("m1", "m2", "m3"); assertModuleScopes("m1", "m2", "m3"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/test/java", getProjectPath() + "/m3/src/test/java"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/test/java", getProjectPath() + "/m3/src/test/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m3/target/test-classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m3/target/test-classes"); } @Test public void testConfiguringModuleDependenciesOnTestJarWithTestScope() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <type>test-jar</type>" + " <scope>test</scope>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " <classifier>tests</classifier>" + " <scope>test</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); VirtualFile m3 = createModulePom("m3", "<groupId>test</groupId>" + "<artifactId>m3</artifactId>" + "<version>1</version>"); importProjects(m1, m2, m3); assertModules("m1", "m2", "m3"); setupJdkForModules("m1", "m2", "m3"); assertModuleScopes("m1", "m2", "m3"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/test/java", getProjectPath() + "/m3/src/test/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m3/target/test-classes"); } @Test public void testConfiguringModuleDependenciesOnBothNormalAndTestJar() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <type>test-jar</type>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); importProjects(m1, m2); assertModules("m1", "m2"); setupJdkForModules("m1", "m2"); assertModuleScopes("m1", "m2"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m2/target/test-classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m2/target/test-classes"); } @Test public void testConfiguringModuleDependenciesOnNormalAndTestJarWithTestScope() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <type>test-jar</type>" + " <scope>test</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); importProjects(m1, m2); assertModules("m1", "m2"); setupJdkForModules("m1", "m2"); assertModuleScopes("m1", "m2"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getProjectPath() + "/m2/target/test-classes"); } @Test public void testOptionalLibraryDependencies() throws Exception { createRepositoryFile("jmock/jmock/1.0/jmock-1.0.jar"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>jmock</groupId>" + " <artifactId>jmock</artifactId>" + " <version>1.0</version>" + " </dependency>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " <optional>true</optional>" + " </dependency>" + "</dependencies>"); importProjects(m1, m2); assertModules("m1", "m2"); assertModuleScopes("m1", "m2"); assertModuleModuleDeps("m1", "m2"); assertModuleLibDeps("m1", "Maven: jmock:jmock:1.0"); assertModuleLibDeps("m2", "Maven: jmock:jmock:1.0", "Maven: junit:junit:4.0"); setupJdkForModules("m1", "m2"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertAllProductionSearchScope("m2", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsSearchScope("m2", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllProductionClasspath("m2", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsClasspath("m2", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); } @Test public void testProvidedAndTestDependencies() throws Exception { createRepositoryFile("jmock/jmock/4.0/jmock-4.0.jar"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <scope>provided</scope>" + " </dependency>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " <scope>provided</scope>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " <scope>test</scope>" + " </dependency>" + " <dependency>" + " <groupId>jmock</groupId>" + " <artifactId>jmock</artifactId>" + " <version>4.0</version>" + " <scope>test</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); VirtualFile m3 = createModulePom("m3", "<groupId>test</groupId>" + "<artifactId>m3</artifactId>" + "<version>1</version>"); importProjects(m1, m2, m3); assertModules("m1", "m2", "m3"); setupJdkForModules("m1", "m2", "m3"); assertModuleScopes("m1", "m2", "m3"); assertCompileProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertRuntimeProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar", getProjectPath() + "/m3/src/main/java", getRepositoryPath() + "/jmock/jmock/4.0/jmock-4.0.jar"); assertCompileProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertRuntimeProductionClasspath("m1", getProjectPath() + "/m1/target/classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar", getProjectPath() + "/m3/target/classes", getRepositoryPath() + "/jmock/jmock/4.0/jmock-4.0.jar"); } @Test public void testRuntimeDependency() throws Exception { createRepositoryFile("jmock/jmock/4.0/jmock-4.0.jar"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <scope>runtime</scope>" + " </dependency>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " <scope>runtime</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); importProjects(m1, m2); assertModules("m1", "m2"); setupJdkForModules("m1", "m2"); assertModuleScopes("m1", "m2"); assertCompileProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java"); assertRuntimeProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertCompileProductionClasspath("m1", getProjectPath() + "/m1/target/classes"); assertRuntimeProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); } @Test public void testDoNotIncludeProvidedAndTestTransitiveDependencies() throws Exception { createRepositoryFile("jmock/jmock/1.0/jmock-1.0.jar"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>jmock</groupId>" + " <artifactId>jmock</artifactId>" + " <version>1.0</version>" + " <scope>provided</scope>" + " </dependency>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " <scope>test</scope>" + " </dependency>" + "</dependencies>"); importProjects(m1, m2); assertModules("m1", "m2"); assertModuleModuleDeps("m1", "m2"); assertModuleLibDeps("m1"); assertModuleLibDeps("m2", "Maven: jmock:jmock:1.0", "Maven: junit:junit:4.0"); setupJdkForModules("m1", "m2"); assertModuleScopes("m1", "m2"); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m2/src/main/java"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java"); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes"); assertCompileProductionSearchScope("m2", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertRuntimeProductionSearchScope("m2", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertAllTestsSearchScope("m2", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertCompileProductionClasspath("m2", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar"); assertRuntimeProductionClasspath("m2", getProjectPath() + "/m2/target/classes"); assertAllTestsClasspath("m2", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/jmock/jmock/1.0/jmock-1.0.jar", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); } @Test public void testLibraryScopeForTwoDependentModules() { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>" + " <dependencies>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " <scope>provided</scope>" + " </dependency>" + " </dependencies>"); importProjects(m1, m2); assertModules("m1", "m2"); Module m1m = ModuleManager.getInstance(myProject).findModuleByName("m1"); List<OrderEntry> modules1 = new ArrayList<>(); ModuleRootManager.getInstance(m1m).orderEntries().withoutSdk().withoutModuleSourceEntries().forEach( new CommonProcessors.CollectProcessor<>(modules1)); GlobalSearchScope scope1 = LibraryScopeCache.getInstance(myProject).getLibraryScope(modules1); assertSearchScope(scope1, getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java" ); String libraryPath = getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"; String librarySrcPath = getRepositoryPath() + "/junit/junit/4.0/junit-4.0-sources.jar"; Module m2m = ModuleManager.getInstance(myProject).findModuleByName("m2"); List<OrderEntry> modules2 = new ArrayList<>(); ModuleRootManager.getInstance(m2m).orderEntries().withoutSdk().withoutModuleSourceEntries().forEach( new CommonProcessors.CollectProcessor<>(modules2)); GlobalSearchScope scope2 = LibraryScopeCache.getInstance(myProject).getLibraryScope(modules2); List<String> expectedPaths = ContainerUtil.newArrayList(getProjectPath() + "/m2/src/main/java", getProjectPath() + "/m2/src/test/java", libraryPath); if (new File(librarySrcPath).exists()) { expectedPaths.add(librarySrcPath); } assertSearchScope(scope2, ArrayUtilRt.toStringArray(expectedPaths)); } @Test public void testDoNotIncludeConflictingTransitiveDependenciesInTheClasspath() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " </dependency>" + "</dependencies>"); VirtualFile m3 = createModulePom("m3", "<groupId>test</groupId>" + "<artifactId>m3</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.5</version>" + " </dependency>" + "</dependencies>"); importProjects(m1, m2, m3); assertModules("m1", "m2", "m3"); assertModuleModuleDeps("m1", "m2", "m3"); assertModuleLibDeps("m1", "Maven: junit:junit:4.0"); setupJdkForModules("m1", "m2", "m3"); assertModuleScopes("m1", "m2", "m3"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getProjectPath() + "/m2/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar", getProjectPath() + "/m3/src/main/java"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar", getProjectPath() + "/m3/target/classes"); } public void _testAdditionalClasspathElementsInTests() throws Exception { File iof1 = new File(myDir, "foo/bar1"); File iof2 = new File(myDir, "foo/bar2"); iof1.mkdirs(); iof2.mkdirs(); VirtualFile f1 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(iof1); VirtualFile f2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(iof2); VirtualFile f3 = createProjectSubDir("m1/foo/bar3"); VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " </dependency>" + "</dependencies>" + "<build>" + " <plugins>" + " <plugin>" + " <groupId>org.apache.maven.plugins</groupId>" + " <artifactId>maven-surefire-plugin</artifactId>" + " <version>2.5</version>" + " <configuration>" + " <additionalClasspathElements>" + " <additionalClasspathElement>" + f1.getPath() + "</additionalClasspathElement>" + " <additionalClasspathElement>" + f2.getPath() + "</additionalClasspathElement>" + " <additionalClasspathElement>${project.basedir}/foo/bar3</additionalClasspathElement>" + " </additionalClasspathElements>" + " </configuration>" + " </plugin>" + " </plugins>" + "</build>"); importProjects(m1); assertModules("m1"); assertModuleModuleDeps("m1"); assertModuleLibDeps("m1", "Maven: junit:junit:4.0", MavenModuleImporter.SUREFIRE_PLUGIN_LIBRARY_NAME); setupJdkForModules("m1"); //assertModuleSearchScope("m1", // getProjectPath() + "/m1/src/main/java", // getProjectPath() + "/m1/src/test/java", // f1.getPath(), // f2.getPath()); assertAllProductionSearchScope("m1", getProjectPath() + "/m1/src/main/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsSearchScope("m1", getProjectPath() + "/m1/src/main/java", getProjectPath() + "/m1/src/test/java", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar", f1.getPath(), f2.getPath(), f3.getPath()); assertAllProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar", f1.getPath(), f2.getPath(), f3.getPath()); } @Test public void testDoNotChangeClasspathForRegularModules() throws Exception { VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <scope>runtime</scope>" + " <optional>true</optional>" + " </dependency>" + " <dependency>" + " <groupId>junit</groupId>" + " <artifactId>junit</artifactId>" + " <version>4.0</version>" + " <scope>provided</scope>" + " <optional>true</optional>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>"); importProjects(m1, m2); assertModules("m1", "m2"); final Module user = createModule("user"); WriteCommandAction.writeCommandAction(myProject).run(() -> { ModuleRootModificationUtil.addDependency(user, getModule("m1")); VirtualFile out = user.getModuleFile().getParent().createChildDirectory(this, "output"); VirtualFile testOut = user.getModuleFile().getParent().createChildDirectory(this, "test-output"); PsiTestUtil.setCompilerOutputPath(user, out.getUrl(), false); PsiTestUtil.setCompilerOutputPath(user, testOut.getUrl(), true); }); assertModuleModuleDeps("m1", "m2"); assertModuleLibDeps("m1", "Maven: junit:junit:4.0"); assertModuleModuleDeps("user", "m1"); assertModuleLibDeps("user"); setupJdkForModules("m1", "m2", "user"); // todo check search scopes assertModuleScopes("m1", "m2"); assertCompileProductionClasspath("user", getProjectPath() + "/user/output", getProjectPath() + "/m1/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertRuntimeProductionClasspath("user", getProjectPath() + "/user/output", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes"); assertCompileTestsClasspath("user", getProjectPath() + "/user/test-output", getProjectPath() + "/user/output", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertRuntimeTestsClasspath("user", getProjectPath() + "/user/test-output", getProjectPath() + "/user/output", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/test-classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertCompileProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); assertRuntimeProductionClasspath("m1", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes"); assertAllTestsClasspath("m1", getProjectPath() + "/m1/target/test-classes", getProjectPath() + "/m1/target/classes", getProjectPath() + "/m2/target/classes", getRepositoryPath() + "/junit/junit/4.0/junit-4.0.jar"); } @Test public void testDirIndexOrderEntriesTransitiveCompileScope() throws IOException { List<Module> modules = setupDirIndexTestModulesWithScope("compile"); checkDirIndexTestModulesWithCompileOrRuntimeScope(modules); } @Test public void testDirIndexOrderEntriesTransitiveRuntimeScope() throws IOException { List<Module> modules = setupDirIndexTestModulesWithScope("runtime"); checkDirIndexTestModulesWithCompileOrRuntimeScope(modules); } // Creates a Maven dependency graph for testing DirectoryIndex#getOrderEntries. private List<Module> setupDirIndexTestModulesWithScope(String scope) throws IOException { createRepositoryFile("jmock/jmock/1.0/jmock-1.0.jar"); // Dependency graph: // m4 // | // v // m1 -> m2 -> m3-| // |----------> jmock // v // m5 -> m6 // Dependencies are set up to be under the given scope, except that jmock is under a test scope, // and the m5 -> m6 dep is always under a compile scope. VirtualFile m1 = createModulePom("m1", "<groupId>test</groupId>" + "<artifactId>m1</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m2</artifactId>" + " <version>1</version>" + " <scope>" + scope + "</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m2 = createModulePom("m2", "<groupId>test</groupId>" + "<artifactId>m2</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " <scope>" + scope + "</scope>" + " </dependency>" + " <dependency>" + " <groupId>jmock</groupId>" + " <artifactId>jmock</artifactId>" + " <version>1.0</version>" + " <scope>test</scope>" + " </dependency>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m5</artifactId>" + " <version>1</version>" + " <scope>" + scope + "</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m3 = createModulePom("m3", "<groupId>test</groupId>" + "<artifactId>m3</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>jmock</groupId>" + " <artifactId>jmock</artifactId>" + " <version>1.0</version>" + " <scope>test</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m4 = createModulePom("m4", "<groupId>test</groupId>" + "<artifactId>m4</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m3</artifactId>" + " <version>1</version>" + " <scope>" + scope + "</scope>" + " </dependency>" + "</dependencies>"); // The default setupInWriteAction only creates directories up to m4. // Create directories for m5 and m6 which we will use for this test. WriteCommandAction.writeCommandAction(myProject).run(() -> createProjectSubDirs("m5/src/main/java", "m5/src/test/java", "m6/src/main/java", "m6/src/test/java")); VirtualFile m5 = createModulePom("m5", "<groupId>test</groupId>" + "<artifactId>m5</artifactId>" + "<version>1</version>" + "<dependencies>" + " <dependency>" + " <groupId>test</groupId>" + " <artifactId>m6</artifactId>" + " <version>1</version>" + " <scope>compile</scope>" + " </dependency>" + "</dependencies>"); VirtualFile m6 = createModulePom("m6", "<groupId>test</groupId>" + "<artifactId>m6</artifactId>" + "<version>1</version>"); importProjects(m1, m2, m3, m4, m5, m6); assertModules("m1", "m2", "m3", "m4", "m5", "m6"); createOutputDirectories(); return Arrays.asList(getModule("m1"), getModule("m2"), getModule("m3"), getModule("m4"), getModule("m5"), getModule("m6")); } // Checks that the DirectoryIndex#getOrderEntries() returns the expected values // for the dependency graph set up by setupDirIndexTestModulesWithScope(). // The result is the same for "compile" and "runtime" scopes. private void checkDirIndexTestModulesWithCompileOrRuntimeScope(List<Module> modules) { assertEquals(6, modules.size()); DirectoryIndex index = DirectoryIndex.getInstance(myProject); VirtualFile m3JavaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "m3/src/main/java"), true); assertNotNull(m3JavaDir); // Should be: m1 -> m3, m2 -> m3, m3 -> source, and m4 -> m3 List<OrderEntry> orderEntries = index.getOrderEntries(index.getInfoForFile(m3JavaDir)); assertEquals(4, orderEntries.size()); List<Module> ownerModules = orderEntriesToOwnerModules(orderEntries); List<Module> depModules = orderEntriesToDepModules(orderEntries); assertOrderedElementsAreEqual(ownerModules, Arrays.asList(modules.get(0), modules.get(1), modules.get(2), modules.get(3))); assertOrderedElementsAreEqual(depModules, Arrays.asList(modules.get(2), modules.get(2), null, modules.get(2))); // m3 -> source OrderEntry m3E2 = orderEntries.get(2); assertInstanceOf(m3E2, ModuleSourceOrderEntry.class); VirtualFile m6javaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "m6/src/main/java"), true); assertNotNull(m6javaDir); // Should be m1 -> m6, m2 -> m6, m5 -> m6, m6 -> source List<OrderEntry> m6OrderEntries = index.getOrderEntries(index.getInfoForFile(m6javaDir)); assertEquals(4, m6OrderEntries.size()); List<Module> m6OwnerModules = orderEntriesToOwnerModules(m6OrderEntries); List<Module> m6DepModules = orderEntriesToDepModules(m6OrderEntries); assertOrderedElementsAreEqual(m6OwnerModules, Arrays.asList(modules.get(0), modules.get(1), modules.get(4), modules.get(5))); assertOrderedElementsAreEqual(m6DepModules, Arrays.asList(modules.get(5), modules.get(5), modules.get(5), null)); // m6 -> source OrderEntry m6E3 = m6OrderEntries.get(3); assertInstanceOf(m6E3, ModuleSourceOrderEntry.class); VirtualFile jmockDir = VfsUtil.findFileByIoFile(new File(getRepositoryPath(), "jmock/jmock/1.0/jmock-1.0.jar"), true); assertNotNull(jmockDir); VirtualFile jmockJar = JarFileSystem.getInstance().getJarRootForLocalFile(jmockDir); assertNotNull(jmockJar); // m2 -> jmock, m3 -> jmock List<OrderEntry> jmockOrderEntries = index.getOrderEntries(index.getInfoForFile(jmockJar)); assertEquals(2, jmockOrderEntries.size()); OrderEntry jmockE0 = jmockOrderEntries.get(0); assertEquals(modules.get(1), jmockE0.getOwnerModule()); assertInstanceOf(jmockE0, LibraryOrderEntry.class); OrderEntry jmockE1 = jmockOrderEntries.get(1); assertEquals(modules.get(2), jmockE1.getOwnerModule()); assertInstanceOf(jmockE1, LibraryOrderEntry.class); } @Test public void testDirIndexOrderEntriesTransitiveTestScope() throws IOException { // This test is a bit different from the above tests of compile or runtime scope, // because test scope does not propagate transitive dependencies. List<Module> modules = setupDirIndexTestModulesWithScope("test"); assertEquals(6, modules.size()); DirectoryIndex index = DirectoryIndex.getInstance(myProject); VirtualFile m3JavaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "m3/src/main/java"), true); assertNotNull(m3JavaDir); // Should be no transitive deps: m2 -> m3, m3 -> source, and m4 -> m3 List<OrderEntry> orderEntries = index.getOrderEntries(index.getInfoForFile(m3JavaDir)); assertEquals(3, orderEntries.size()); List<Module> ownerModules = orderEntriesToOwnerModules(orderEntries); List<Module> depModules = orderEntriesToDepModules(orderEntries); assertOrderedElementsAreEqual(ownerModules, Arrays.asList(modules.get(1), modules.get(2), modules.get(3))); assertOrderedElementsAreEqual(depModules, Arrays.asList(modules.get(2), null, modules.get(2))); // m3 -> source OrderEntry m3E1 = orderEntries.get(1); assertInstanceOf(m3E1, ModuleSourceOrderEntry.class); VirtualFile m6javaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "m6/src/main/java"), true); assertNotNull(m6javaDir); // Still has some transitive deps because m5 -> m6 is hardcoded to be compile scope // m2 -> m6, m5 -> m6, m6 -> source List<OrderEntry> m6OrderEntries = index.getOrderEntries(index.getInfoForFile(m6javaDir)); assertEquals(3, m6OrderEntries.size()); List<Module> m6OwnerModules = orderEntriesToOwnerModules(m6OrderEntries); List<Module> m6DepModules = orderEntriesToDepModules(m6OrderEntries); assertOrderedElementsAreEqual(m6OwnerModules, Arrays.asList(modules.get(1), modules.get(4), modules.get(5))); assertOrderedElementsAreEqual(m6DepModules, Arrays.asList(modules.get(5), modules.get(5), null)); // m6 -> source OrderEntry m6E2 = m6OrderEntries.get(2); assertInstanceOf(m6E2, ModuleSourceOrderEntry.class); VirtualFile jmockDir = VfsUtil.findFileByIoFile(new File(getRepositoryPath(), "jmock/jmock/1.0/jmock-1.0.jar"), true); assertNotNull(jmockDir); VirtualFile jmockJar = JarFileSystem.getInstance().getJarRootForLocalFile(jmockDir); assertNotNull(jmockJar); // m2 -> jmock, m3 -> jmock List<OrderEntry> jmockOrderEntries = index.getOrderEntries(index.getInfoForFile(jmockJar)); assertEquals(2, jmockOrderEntries.size()); OrderEntry jmockE0 = jmockOrderEntries.get(0); assertEquals(modules.get(1), jmockE0.getOwnerModule()); assertInstanceOf(jmockE0, LibraryOrderEntry.class); OrderEntry jmockE1 = jmockOrderEntries.get(1); assertEquals(modules.get(2), jmockE1.getOwnerModule()); assertInstanceOf(jmockE1, LibraryOrderEntry.class); } @Test public void testDirIndexOrderEntriesStartingFromRegularModule() throws IOException { final List<Module> modules = setupDirIndexTestModulesWithScope("compile"); assertEquals(6, modules.size()); final Module nonMavenM1 = createModule("nonMavenM1"); final Module nonMavenM2 = createModule("nonMavenM2"); WriteCommandAction.writeCommandAction(myProject).run(() -> { ModuleRootModificationUtil.addDependency(nonMavenM1, nonMavenM2, DependencyScope.COMPILE, true); ModuleRootModificationUtil.addDependency(nonMavenM2, modules.get(0), DependencyScope.COMPILE, true); createProjectSubDirs("nonMavenM1/src/main/java", "nonMavenM1/src/test/java", "nonMavenM2/src/main/java", "nonMavenM2/src/test/java"); VirtualFile nonMavenM1JavaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "nonMavenM1/src/main/java"), true); assertNotNull(nonMavenM1JavaDir); PsiTestUtil.addSourceContentToRoots(nonMavenM1, nonMavenM1JavaDir); VirtualFile nonMavenM2JavaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "nonMavenM2/src/main/java"), true); assertNotNull(nonMavenM2JavaDir); PsiTestUtil.addSourceContentToRoots(nonMavenM2, nonMavenM2JavaDir); }); assertModuleModuleDeps("nonMavenM1", "nonMavenM2"); assertModuleModuleDeps("nonMavenM2", "m1"); assertModuleModuleDeps("m1", "m2", "m3", "m5", "m6"); DirectoryIndex index = DirectoryIndex.getInstance(myProject); VirtualFile m3JavaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "m3/src/main/java"), true); assertNotNull(m3JavaDir); // Should be: m1 -> m3, m2 -> m3, m3 -> source, and m4 -> m3 // It doesn't trace back to nonMavenM1 and nonMavenM2. List<OrderEntry> orderEntries = index.getOrderEntries(index.getInfoForFile(m3JavaDir)); List<Module> ownerModules = orderEntriesToOwnerModules(orderEntries); List<Module> depModules = orderEntriesToDepModules(orderEntries); assertOrderedElementsAreEqual(ownerModules, Arrays.asList(modules.get(0), modules.get(1), modules.get(2), modules.get(3))); assertOrderedElementsAreEqual(depModules, Arrays.asList(modules.get(2), modules.get(2), null, modules.get(2))); VirtualFile m6javaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "m6/src/main/java"), true); assertNotNull(m6javaDir); // Should be m1 -> m6, m2 -> m6, m5 -> m6, m6 -> source List<OrderEntry> m6OrderEntries = index.getOrderEntries(index.getInfoForFile(m6javaDir)); List<Module> m6OwnerModules = orderEntriesToOwnerModules(m6OrderEntries); List<Module> m6DepModules = orderEntriesToDepModules(m6OrderEntries); assertOrderedElementsAreEqual(m6OwnerModules, Arrays.asList(modules.get(0), modules.get(1), modules.get(4), modules.get(5))); assertOrderedElementsAreEqual(m6DepModules, Arrays.asList(modules.get(5), modules.get(5), modules.get(5), null)); VirtualFile nonMavenM2JavaDir = VfsUtil.findFileByIoFile(new File(getProjectPath(), "nonMavenM2/src/main/java"), true); assertNotNull(nonMavenM2JavaDir); // Should be nonMavenM1 -> nonMavenM2, nonMavenM2 -> source List<OrderEntry> nonMavenM2JavaOrderEntries = index.getOrderEntries(index.getInfoForFile(nonMavenM2JavaDir)); List<Module> nonMavenM2OwnerModules = orderEntriesToOwnerModules(nonMavenM2JavaOrderEntries); List<Module> nonMavenM2DepModules = orderEntriesToDepModules(nonMavenM2JavaOrderEntries); assertOrderedElementsAreEqual(nonMavenM2OwnerModules, Arrays.asList(nonMavenM1, nonMavenM2)); assertOrderedElementsAreEqual(nonMavenM2DepModules, Arrays.asList(nonMavenM2, null)); } private static List<Module> orderEntriesToOwnerModules(List<OrderEntry> orderEntries) { return ContainerUtil.map(orderEntries, orderEntry -> orderEntry.getOwnerModule()); } private static List<Module> orderEntriesToDepModules(List<OrderEntry> orderEntries) { return ContainerUtil.map(orderEntries, orderEntry -> (orderEntry instanceof ModuleOrderEntry) ? ((ModuleOrderEntry)orderEntry).getModule() : null); } private void assertAllProductionClasspath(String moduleName, String... paths) throws Exception { assertCompileProductionClasspath(moduleName, paths); assertRuntimeProductionClasspath(moduleName, paths); } private void assertAllTestsClasspath(String moduleName, String... paths) throws Exception { assertCompileTestsClasspath(moduleName, paths); assertRuntimeTestsClasspath(moduleName, paths); } private void assertCompileProductionClasspath(String moduleName, String... paths) throws Exception { assertClasspath(moduleName, Scope.COMPILE, Type.PRODUCTION, paths); } private void assertCompileTestsClasspath(String moduleName, String... paths) throws Exception { assertClasspath(moduleName, Scope.COMPILE, Type.TESTS, paths); } private void assertRuntimeProductionClasspath(String moduleName, String... paths) throws Exception { assertClasspath(moduleName, Scope.RUNTIME, Type.PRODUCTION, paths); } private void assertRuntimeTestsClasspath(String moduleName, String... paths) throws Exception { assertClasspath(moduleName, Scope.RUNTIME, Type.TESTS, paths); } private void assertClasspath(String moduleName, Scope scope, Type type, String... expectedPaths) throws Exception { createOutputDirectories(); PathsList actualPathsList; Module module = getModule(moduleName); if (scope == Scope.RUNTIME) { JavaParameters params = new JavaParameters(); params.configureByModule(module, type == Type.TESTS ? JavaParameters.CLASSES_AND_TESTS : JavaParameters.CLASSES_ONLY); actualPathsList = params.getClassPath(); } else { OrderEnumerator en = OrderEnumerator.orderEntries(module).recursively().withoutSdk().compileOnly(); if (type == Type.PRODUCTION) en.productionOnly(); actualPathsList = en.classes().getPathsList(); } assertPaths(expectedPaths, actualPathsList.getPathList()); } private void assertModuleScopes(String... modules) { for (String each : modules) { assertModuleSearchScope(each, getProjectPath() + "/" + each + "/src/main/java", getProjectPath() + "/" + each + "/src/test/java"); } } private void assertModuleSearchScope(String moduleName, String... paths) { assertSearchScope(moduleName, Scope.MODULE, null, paths); } private void assertAllProductionSearchScope(String moduleName, String... paths) { assertCompileProductionSearchScope(moduleName, paths); assertRuntimeProductionSearchScope(moduleName, paths); } private void assertAllTestsSearchScope(String moduleName, String... paths) { assertCompileTestsSearchScope(moduleName, paths); assertRuntimeTestsSearchScope(moduleName, paths); } private void assertCompileProductionSearchScope(String moduleName, String... paths) { assertSearchScope(moduleName, Scope.COMPILE, Type.PRODUCTION, paths); } private void assertCompileTestsSearchScope(String moduleName, String... paths) { assertSearchScope(moduleName, Scope.COMPILE, Type.TESTS, paths); } private void assertRuntimeProductionSearchScope(String moduleName, String... paths) { assertSearchScope(moduleName, Scope.RUNTIME, Type.PRODUCTION, paths); } private void assertRuntimeTestsSearchScope(String moduleName, String... paths) { assertSearchScope(moduleName, Scope.RUNTIME, Type.TESTS, paths); } private void assertSearchScope(String moduleName, Scope scope, Type type, String... expectedPaths) { createOutputDirectories(); Module module = getModule(moduleName); GlobalSearchScope searchScope = null; switch (scope) { case MODULE: searchScope = module.getModuleScope(); break; case COMPILE: searchScope = module.getModuleWithDependenciesAndLibrariesScope(type == Type.TESTS); break; case RUNTIME: searchScope = module.getModuleRuntimeScope(type == Type.TESTS); break; } assertSearchScope(searchScope, expectedPaths); } private void assertSearchScope(GlobalSearchScope searchScope, String... expectedPaths) { Collection<VirtualFile> roots; if (searchScope instanceof DelegatingGlobalSearchScope) { searchScope = ReflectionUtil.getField(DelegatingGlobalSearchScope.class, searchScope, GlobalSearchScope.class, "myBaseScope"); } if (searchScope instanceof ModuleWithDependenciesScope) { roots = ((ModuleWithDependenciesScope)searchScope).getRoots(); } else { roots = ((LibraryRuntimeClasspathScope)searchScope).getRoots(); } final List<VirtualFile> entries = new ArrayList<>(roots); entries.removeAll(Arrays.asList(ProjectRootManager.getInstance(myProject).orderEntries().sdkOnly().classes().getRoots())); List<String> actualPaths = new ArrayList<>(); for (VirtualFile each : entries) { actualPaths.add(each.getPresentableUrl()); } assertPaths(expectedPaths, actualPaths); } private static void assertPaths(String[] expectedPaths, List<String> actualPaths) { List<String> normalizedActualPaths = new ArrayList<>(); List<String> normalizedExpectedPaths = new ArrayList<>(); for (String each : actualPaths) { normalizedActualPaths.add(FileUtil.toSystemDependentName(each)); } for (String each : expectedPaths) { normalizedExpectedPaths.add(FileUtil.toSystemDependentName(each)); } assertOrderedElementsAreEqual(normalizedActualPaths, normalizedExpectedPaths); } private void createRepositoryFile(String filePath) throws IOException { File f = new File(getProjectPath(), "repo/" + filePath); f.getParentFile().mkdirs(); ArtifactsDownloadingTestCase.createEmptyJar(f.getParent(), f.getName()); setRepositoryPath(createProjectSubDir("repo").getPath()); } private void createOutputDirectories() { for (Module module : ModuleManager.getInstance(myProject).getModules()) { CompilerModuleExtension extension = CompilerModuleExtension.getInstance(module); if (extension != null) { createDirectoryIfDoesntExist(extension.getCompilerOutputUrl()); createDirectoryIfDoesntExist(extension.getCompilerOutputUrlForTests()); } } } private static void createDirectoryIfDoesntExist(@Nullable String url) { if (StringUtil.isEmpty(url)) return; File file = new File(FileUtil.toSystemDependentName(VfsUtil.urlToPath(url))); if (file.exists()) return; if (!file.mkdirs()) { fail("Cannot create directory " + file); } VirtualFileManager.getInstance().refreshAndFindFileByUrl(url); } }
/** * Copyright (C) 2014-2016 LinkedIn Corp. (pinot-core@linkedin.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.linkedin.pinot.tools.admin.command; import com.linkedin.pinot.common.utils.CommonConstants.Helix.TableType; import com.linkedin.pinot.common.utils.TenantRole; import com.linkedin.pinot.tools.QuickstartTableRequest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.commons.io.FileUtils; import org.json.JSONObject; public class QuickstartRunner { private static final Random RANDOM = new Random(); private static final String CLUSTER_NAME = "QuickStartCluster"; private static final int ZK_PORT = 2123; private static final String ZK_ADDRESS = "localhost:" + ZK_PORT; private static final int DEFAULT_SERVER_NETTY_PORT = 7000; private static final int DEFAULT_SERVER_ADMIN_API_PORT = 7500; private static final int DEFAULT_BROKER_PORT = 8000; private static final int DEFAULT_CONTROLLER_PORT = 9000; private final List<QuickstartTableRequest> _tableRequests; private final int _numServers; private final int _numBrokers; private final int _numControllers; private final File _tempDir; private final boolean _enableTenantIsolation; private final List<Integer> _brokerPorts = new ArrayList<>(); private final List<Integer> _controllerPorts = new ArrayList<>(); private final List<String> _segmentDirs = new ArrayList<>(); private boolean _isStopped = false; public QuickstartRunner(List<QuickstartTableRequest> tableRequests, int numServers, int numBrokers, int numControllers, File tempDir, boolean enableIsolation) throws Exception { _tableRequests = tableRequests; _numServers = numServers; _numBrokers = numBrokers; _numControllers = numControllers; _tempDir = tempDir; _enableTenantIsolation = enableIsolation; clean(); } public QuickstartRunner(List<QuickstartTableRequest> tableRequests, int numServers, int numBrokers, int numControllers, File tempDir) throws Exception { this(tableRequests, numServers, numBrokers, numControllers, tempDir, true); } private void startZookeeper() throws IOException { StartZookeeperCommand zkStarter = new StartZookeeperCommand(); zkStarter.setPort(ZK_PORT); zkStarter.execute(); } private void startControllers() throws Exception { for (int i = 0; i < _numControllers; i++) { StartControllerCommand controllerStarter = new StartControllerCommand(); controllerStarter.setControllerPort(String.valueOf(DEFAULT_CONTROLLER_PORT + i)) .setZkAddress(ZK_ADDRESS) .setClusterName(CLUSTER_NAME) .setTenantIsolation(_enableTenantIsolation); controllerStarter.execute(); _controllerPorts.add(DEFAULT_CONTROLLER_PORT + i); } } private void startBrokers() throws Exception { for (int i = 0; i < _numBrokers; i++) { StartBrokerCommand brokerStarter = new StartBrokerCommand(); brokerStarter.setPort(DEFAULT_BROKER_PORT + i).setZkAddress(ZK_ADDRESS).setClusterName(CLUSTER_NAME); brokerStarter.execute(); _brokerPorts.add(DEFAULT_BROKER_PORT + i); } } private void startServers() throws Exception { for (int i = 0; i < _numServers; i++) { StartServerCommand serverStarter = new StartServerCommand(); serverStarter.setPort(DEFAULT_SERVER_NETTY_PORT + i) .setAdminPort(DEFAULT_SERVER_ADMIN_API_PORT + i) .setZkAddress(ZK_ADDRESS) .setClusterName(CLUSTER_NAME) .setDataDir(new File(_tempDir, "PinotServerData" + i).getAbsolutePath()) .setSegmentDir(new File(_tempDir, "PinotServerSegment" + i).getAbsolutePath()); serverStarter.execute(); } } private void clean() throws Exception { FileUtils.cleanDirectory(_tempDir); } public void startAll() throws Exception { startZookeeper(); startControllers(); startBrokers(); startServers(); } public void stop() throws Exception { if (_isStopped) { return; } StopProcessCommand stopper = new StopProcessCommand(false); stopper.stopController().stopBroker().stopServer().stopZookeeper(); stopper.execute(); clean(); _isStopped = true; } public void createServerTenantWith(int numOffline, int numRealtime, String tenantName) throws Exception { new AddTenantCommand().setControllerUrl("http://localhost:" + _controllerPorts.get(0)) .setName(tenantName) .setOffline(numOffline) .setRealtime(numRealtime) .setInstances(numOffline + numRealtime) .setRole(TenantRole.SERVER) .setExecute(true) .execute(); } public void createBrokerTenantWith(int number, String tenantName) throws Exception { new AddTenantCommand().setControllerUrl("http://localhost:" + _controllerPorts.get(0)) .setName(tenantName) .setInstances(number) .setRole(TenantRole.BROKER) .setExecute(true) .execute(); } public void addSchema() throws Exception { for (QuickstartTableRequest request : _tableRequests) { new AddSchemaCommand().setControllerPort(String.valueOf(_controllerPorts.get(0))) .setSchemaFilePath(request.getSchemaFile().getAbsolutePath()) .setExecute(true) .execute(); } } public void addTable() throws Exception { for (QuickstartTableRequest request : _tableRequests) { new AddTableCommand().setFilePath(request.getTableRequestFile().getAbsolutePath()) .setControllerPort(String.valueOf(_controllerPorts.get(0))) .setExecute(true) .execute(); } } public void buildSegment() throws Exception { for (QuickstartTableRequest request : _tableRequests) { if (request.getTableType() == TableType.OFFLINE) { File tempDir = new File(_tempDir, request.getTableName() + "_segment"); new CreateSegmentCommand().setDataDir(request.getDataDir().getAbsolutePath()) .setFormat(request.getSegmentFileFormat()) .setSchemaFile(request.getSchemaFile().getAbsolutePath()) .setTableName(request.getTableName()) .setSegmentName(request.getTableName() + "_" + System.currentTimeMillis()) .setOutDir(tempDir.getAbsolutePath()) .execute(); _segmentDirs.add(tempDir.getAbsolutePath()); } } } public void pushSegment() throws Exception { for (String segmentDir : _segmentDirs) { new UploadSegmentCommand().setControllerPort(String.valueOf(_controllerPorts.get(0))) .setSegmentDir(segmentDir) .execute(); } } public JSONObject runQuery(String query) throws Exception { int brokerPort = _brokerPorts.get(RANDOM.nextInt(_brokerPorts.size())); return new JSONObject(new PostQueryCommand().setBrokerPort(String.valueOf(brokerPort)).setQuery(query).run()); } }
package com.ucla.nesl.universalservice; import android.content.Context; import android.os.Binder; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.RemoteException; import android.util.Log; import com.ucla.nesl.aidl.Device; import com.ucla.nesl.aidl.IUniversalDriverManager; import com.ucla.nesl.aidl.IUniversalManagerService; import com.ucla.nesl.aidl.IUniversalSensorManager; import com.ucla.nesl.lib.HelperWrapper; import com.ucla.nesl.lib.UniversalConstants; import com.ucla.nesl.lib.UniversalSensor; import com.ucla.nesl.lib.UniversalSensorNameMap; import com.ucla.nesl.universaldatastore.DataPurger; import com.ucla.nesl.universaldatastore.DataStoreManager; import com.ucla.nesl.universaldatastore.UniversalDataStore; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import io.vec.demo.android.ipc.IPC; public class UniversalManagerService extends IUniversalManagerService.Stub { private static String tag = UniversalManagerService.class.getCanonicalName(); private Handler mHandler = null; // Cleanup handler private Thread cleanupThread; UniversalService parent; UniversalDataStore mUniversalDataStore = null; private static DataStoreManager mDataStoreManager = null; DataPurger mDataPurger = null; Map<String, UniversalServiceDevice> registeredDevices = new HashMap<String, UniversalServiceDevice>(); HashMap<String, UniversalServiceListener> registeredListeners = new HashMap<String, UniversalServiceListener>(); private Runnable cleanupRunnable = new Runnable() { @Override public void run() { Looper.prepare(); mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UniversalConstants.MSG_UnregisterListener: unregisterListenerAll((String)msg.obj); break; case UniversalConstants.MSG_UnregisterDriver: unregisterDriverAll((String) msg.obj); break; } } }; Looper.loop(); } }; public Handler getHandler() { return mHandler; } public static void createDataStore(Context context) { if (mDataStoreManager == null) mDataStoreManager = new DataStoreManager(context, null, null, 1); } public UniversalManagerService(UniversalService parent) { this.parent = parent; cleanupThread = new Thread(cleanupRunnable); cleanupThread.start(); createDataStore(parent.getApplicationContext()); // Create the DataStore thread mUniversalDataStore = new UniversalDataStore(mDataStoreManager); mUniversalDataStore.start(); mDataPurger = new DataPurger(mDataStoreManager); mDataPurger.start(); } public String generateSensorKey(String devID, int sType) { return ""+ devID + "_" + sType; } public String generateListenerKey(int pid) { return "" + pid; } public boolean notifyListeners(Device mdevice) { Handler mhandler; UniversalServiceListener mlistener; Log.i(tag, "notify for new device"); synchronized (registeredListeners) { for (Map.Entry<String, UniversalServiceListener> entry : registeredListeners.entrySet()) { Log.d(tag, "sending notification to " + entry.getKey()); Log.d(tag, "sending notification to " + entry.getValue()); mlistener = entry.getValue(); if (mlistener.isNotifySet() == false) continue; mhandler = mlistener.getHandler(); if (mhandler == null) { Log.e(tag, "mhandler of " + mlistener.callingPid + " is null"); continue; } mhandler.sendMessage(mhandler.obtainMessage(UniversalConstants.MSG_NotifyNewDevice, mdevice)); } } return true; } public boolean addRegisteredDevice(String devID, UniversalServiceDevice mdevice) { synchronized (registeredDevices) { registeredDevices.put(devID, mdevice); } return true; } public UniversalServiceDevice getRegisteredDevice(String devID) { UniversalServiceDevice mdevice = null; synchronized (registeredDevices) { mdevice = registeredDevices.get(devID); } return mdevice; } public UniversalServiceDevice removeRegisteredDevice(String devID) { UniversalServiceDevice mdevice = null; synchronized (registeredDevices) { mdevice = registeredDevices.remove(devID); } return mdevice; } public boolean addRegisteredListener(String listenerKey, UniversalServiceListener mlistener) { synchronized (registeredListeners) { registeredListeners.put(listenerKey, mlistener); } return true; } public UniversalServiceListener getRegisteredListener(String listenerKey) { UniversalServiceListener mlistener = null; synchronized (registeredListeners) { mlistener = registeredListeners.get(listenerKey); } return mlistener; } public boolean hasRegisteredListener(String listnerKey) { synchronized (registeredListeners) { return registeredListeners.containsKey(listnerKey); } } public UniversalServiceListener removeRegisteredListener(String listenerKey) { UniversalServiceListener mlistener = null; synchronized (registeredListeners) { mlistener = registeredListeners.remove(listenerKey); } return mlistener; } @Override public ArrayList<Device> listDevices() throws RemoteException { ArrayList<Device> deviceList = new ArrayList<Device>(); Log.i(tag, "listDevices requested by " + Binder.getCallingPid()); synchronized (registeredDevices) { for(Map.Entry<String, UniversalServiceDevice> entry : registeredDevices.entrySet()) { deviceList.add(entry.getValue()); } } return deviceList; } @Override public boolean registerDriver(Device mdevice, IUniversalDriverManager mDriverListener, int sType, int[] maxRate, int[] bundleSize) throws RemoteException { String mSensorKey = null; UniversalServiceDevice mUniversalDevice = null; mUniversalDevice = getRegisteredDevice(mdevice.getDevID()); if (mUniversalDevice == null) { // Create an instance of the Device Log.d(tag, "registering a new device"); mUniversalDevice = new UniversalServiceDevice(this, mdevice, mDriverListener); addRegisteredDevice(mUniversalDevice.getDevID(), mUniversalDevice); } Log.d(tag, "registering driver " + mdevice.getDevID() + " mdevice sensorlist " + mdevice.getSensorList()); mSensorKey = generateSensorKey(mdevice.getDevID(), sType); mUniversalDevice.registerSensor(mSensorKey, sType, maxRate, bundleSize); // if (addDriverSensor(mUniversalDevice.getDevID(), sType, maxRate) == false) { // return false; // } // // Log.d(tag, "list of registered sensors"); // // for(Map.Entry<String, UniversalServiceSensor> entry : mUniversalDevice.getSensorList().entrySet()) // Log.d("tag", "as " + entry.getKey()); notifyListeners(mdevice); return true; } // public boolean addDriverSensor(String devID, int sType, int maxRate) // throws RemoteException { // UniversalServiceSensor mSensor = null; // UniversalServiceDevice mdevice = null; // // mdevice = getRegisteredDevice(devID); // if (mdevice == null) // return false; // // mSensor = new UniversalServiceSensor(devID, generateSensorKey(devID, sType), mdevice, sType, maxRate); // mdevice.addSensor(mSensor, maxRate); // // // add the sensor the universal list of sensors // addRegisteredSensor(generateSensorKey(devID, sType), mSensor); // return true; // } // // public boolean removeDriverSensor(UniversalServiceDevice mdevice, String devID, int sType) // throws RemoteException { // String mSensorKey = null; // UniversalServiceSensor mSensor = null; // // mSensorKey = generateSensorKey(devID, sType); // mSensor = removeRegisteredSensor(mSensorKey); // if (mSensor == null) // return false; // // // Notify all the listeners // mSensor.unregister(); // // // Unregister the sensor from its device // mdevice.removeSensor(mSensor); // // return true; // } @Override public boolean unregisterDriver(String devID, int sType) { // remove the entry from the registeredDevices, // we should send notifications to all the applications that have asked for the notification // also free all the sensor objects String mSensorKey = null; Log.i(tag, "unregisterDriver: " + devID + ", sensorType " + sType); UniversalServiceDevice mdevice = getRegisteredDevice(devID); if (mdevice == null) { return false; } mSensorKey = generateSensorKey(devID, sType); mdevice.unregisterSensor(sType, mSensorKey); if (mdevice.isEmpty()) { Log.d(tag, "no more sensors, removing the device entry"); removeRegisteredDevice(devID); } return true; } private boolean unregisterDriverAll(String devID) { return unregisterDriver(devID, UniversalSensor.TYPE_ALL); } private void _registerListener(int listenerPid, String mlistenerKey, IUniversalSensorManager cbk) { Log.d(tag, "adding a new listener with pid " + mlistenerKey); UniversalServiceListener mlistener = new UniversalServiceListener(this, cbk, listenerPid); mlistener.start(); Handler mhandler = mlistener.getHandler(); while (mhandler == null) { Log.d(tag, "_registerListener::handler is null"); try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } mhandler = mlistener.getHandler(); } addRegisteredListener(mlistenerKey, mlistener); } // TODO: Check if the listener has already registered @Override public boolean registerListener(IUniversalSensorManager mManager, String devID, int sType, boolean periodic, int rate, int bundleSize) throws RemoteException { String mSensorKey = generateSensorKey(devID, sType); int listenerPid = Binder.getCallingPid(); String mListenerKey = generateListenerKey(listenerPid); UniversalServiceDevice mDevice = null; UniversalServiceSensor mSensor = null; mDevice = getRegisteredDevice(devID); if (mDevice == null) { Log.e(tag, "Invalid device mentioned, registeration failed"); return false; } mSensor = mDevice.getSensor(mSensorKey); if (mSensor == null) { // a null here means that the app wants to register to a sensor that // doesn't exist. Log.e(tag, "Incorrect sensor type, registering failed"); return false; } // Check if this is a supported Rate and bundlesize if (!mSensor.checkParams(rate, bundleSize)) { Log.e(tag, "Incorrect rate or bundleSize, registerListener failed"); return false; } // Add the listener to the map if it already doesn't exists if (!hasRegisteredListener(mListenerKey)) { _registerListener(listenerPid, mListenerKey, mManager); } UniversalServiceListener mlistener = getRegisteredListener(mListenerKey); Log.i(tag, "Registering to the sensor " + mSensorKey); Map<String, Object> mMap = new HashMap<String, Object>(); mMap.put("key", mSensorKey); mMap.put("value", mSensor); mMap.put("periodic", periodic); mMap.put("rate", Integer.valueOf(rate)); mMap.put("bundleSize", Integer.valueOf(bundleSize)); Handler mhandler = mlistener.getHandler(); if (mhandler == null) { Log.i(tag, "registerListener::handler is null"); return false; } mhandler.sendMessage(mhandler.obtainMessage(UniversalConstants.MSG_Link_Sensor, mMap)); Log.i(tag, "registering listener " + Binder.getCallingPid() + ", " + sType); return true; } @Override public boolean unregisterListener(String devID, int sType) { String mListenerKey = generateListenerKey(Binder.getCallingPid()); String mSensorKey = generateSensorKey(devID, sType); UniversalServiceListener mlistener; // Handler mHandler; Log.d(tag, "unregisterListener on " + devID + ":" + sType); // remove the entry from registeredListener if (!hasRegisteredListener(mListenerKey)) { Log.i(tag, "Failed to unregister listener to sensor " + devID + ":" + UniversalSensorNameMap.getName(sType)); return false; } mlistener = getRegisteredListener(mListenerKey); // Calling unregister directly for now because the // next call to check empty will never succeed if // we send a message via handler. One fix is we can // sleep for a while or make mlistener class trigger // cleanup when it is no more registered with a sensor. // mlistener.getHandler()unregister(mSensorKey); mlistener.unregister(mSensorKey); // remove the entry only when this is the last sensor // that this app is registered to if (mlistener.isEmpty()) { // this is the last entry, so remove the listener from // registeredListeners removeRegisteredListener(mListenerKey); } // We should disable the sensor if removal of the // listener has made its listener list empty // setDriverSensorRate(devID, sType, msensor.isEmpty()? 0 : msensor.getNextRate()); return true; } @Override public boolean fetchRecord(String devID, int sType) { String mListenerKey = generateListenerKey(Binder.getCallingPid()); String mSensorKey = generateSensorKey(devID, sType); UniversalServiceListener mlistener; // Handler mHandler; Log.d(tag, "unregisterListener on " + devID + ":" + sType); // remove the entry from registeredListener if (!hasRegisteredListener(mListenerKey)) { Log.i(tag, "Failed to unregister listener to sensor " + devID + ":" + UniversalSensorNameMap.getName(sType)); return false; } mlistener = getRegisteredListener(mListenerKey); Handler mHandler = mlistener.getHandler(); mHandler.sendMessage(mHandler.obtainMessage(UniversalConstants.MSG_FETCH_RECORD, mSensorKey)); return true; } public boolean unregisterListenerAll(String listenerKey) { UniversalServiceListener mlistener; mlistener = getRegisteredListener(listenerKey); mlistener.unregister(); return true; } // @Override // public void onSensorChanged(SensorParcel event) throws RemoteException { // String key = generateSensorKey(event.devID, event.sType); // // UniversalServiceSensor msensor = getRegisteredDevice(event.devID).getRegisteredSensor(key); // if(msensor == null) { // Log.i(tag, "msensor is null " + key); // return; // } // // msensor.onSensorChanged(event); // return; // } @Override public String getDevID() throws RemoteException { return new String(""+Math.random()); //compute devID, for now using a random number } @Override public void setFileDescriptor(ParcelFileDescriptor fd) throws RemoteException { Log.d(tag, "got ParcelFileDescriptor: " + fd); Log.d(tag, " fd = " + fd.getFd()); IPC.setFd(fd.getFd()); } @Override public void registerNotification(IUniversalSensorManager mManager) { String mlistenerKey = generateListenerKey(Binder.getCallingPid()); Log.d(tag, "adding listener to notification list " + Binder.getCallingPid()); // Add the listener to the map if it already doesn't exists if (!hasRegisteredListener(mlistenerKey)) { _registerListener(Binder.getCallingPid(), mlistenerKey, mManager); } UniversalServiceListener mlistener = getRegisteredListener(mlistenerKey); mlistener.setNotify(); } @Override public void onSensorChanged(String devID, int sType, float[] values, long[] timestamp) { //Log.i(tag, "values: " + values[0] + "," + values[1] + "," + values[2]); String key = generateSensorKey(devID, sType); if (getRegisteredDevice(devID) == null) { Log.e(tag, "onSensorChanged:: received data from " + devID + ", but device is not registered"); return; } UniversalServiceSensor msensor = getRegisteredDevice(devID).getRegisteredSensor(key); if(msensor == null) { Log.e(tag, "onSensorChanged:: msensor is null " + key); return; } msensor.onSensorChanged(devID, sType, values, timestamp); } @Override public boolean listHistoricalDevices(IUniversalSensorManager mListenerStub) { String mlistenerKey = generateListenerKey(Binder.getCallingPid()); Log.d(tag, "adding listener to notification list " + Binder.getCallingPid()); Handler mhandler = UniversalDataStore.getHandler(); if (mhandler == null) { Log.i(tag, "registerListener::handler is null"); return false; } mhandler.sendMessage(mhandler.obtainMessage(UniversalConstants.MSG_ListHistoricalDevices, mListenerStub)); return true; } @Override public boolean fetchHistoricalData(IUniversalSensorManager mListener, int txnID, String devID, int sType, long start, long end, long interval, int function) { Bundle mBundle = new Bundle(); mBundle.putString("tableName", generateSensorKey(devID, sType)); mBundle.putInt("txnID", txnID); mBundle.putString("devID", devID); mBundle.putInt("sType", sType); mBundle.putLong("start", start); mBundle.putLong("end", end); mBundle.putLong("interval", interval); mBundle.putInt("function", function); Handler mhandler = UniversalDataStore.getHandler(); if (mhandler == null) { Log.i(tag, "registerListener::handler is null"); return false; } Log.d(tag, "request for historical data of " + generateSensorKey(devID, sType) + " table"); mhandler.sendMessage(mhandler.obtainMessage(UniversalConstants.MSG_FETCH_HISTORICAL_DATA, new HelperWrapper(mListener, mBundle))); return false; } }
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1beta1/schema/predict/instance/text_classification.proto package com.google.cloud.aiplatform.v1beta1.schema.predict.instance; /** * * * <pre> * Prediction input format for Text Classification. * </pre> * * Protobuf type {@code * google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance} */ public final class TextClassificationPredictionInstance extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance) TextClassificationPredictionInstanceOrBuilder { private static final long serialVersionUID = 0L; // Use TextClassificationPredictionInstance.newBuilder() to construct. private TextClassificationPredictionInstance( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TextClassificationPredictionInstance() { content_ = ""; mimeType_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new TextClassificationPredictionInstance(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private TextClassificationPredictionInstance( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); content_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); mimeType_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstanceProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_instance_TextClassificationPredictionInstance_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstanceProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_instance_TextClassificationPredictionInstance_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance.class, com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance.Builder.class); } public static final int CONTENT_FIELD_NUMBER = 1; private volatile java.lang.Object content_; /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @return The content. */ @java.lang.Override public java.lang.String getContent() { java.lang.Object ref = content_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); content_ = s; return s; } } /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @return The bytes for content. */ @java.lang.Override public com.google.protobuf.ByteString getContentBytes() { java.lang.Object ref = content_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); content_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int MIME_TYPE_FIELD_NUMBER = 2; private volatile java.lang.Object mimeType_; /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @return The mimeType. */ @java.lang.Override public java.lang.String getMimeType() { java.lang.Object ref = mimeType_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mimeType_ = s; return s; } } /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @return The bytes for mimeType. */ @java.lang.Override public com.google.protobuf.ByteString getMimeTypeBytes() { java.lang.Object ref = mimeType_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); mimeType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(content_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, content_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(mimeType_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, mimeType_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(content_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, content_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(mimeType_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, mimeType_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance)) { return super.equals(obj); } com.google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance other = (com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance) obj; if (!getContent().equals(other.getContent())) return false; if (!getMimeType().equals(other.getMimeType())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + CONTENT_FIELD_NUMBER; hash = (53 * hash) + getContent().hashCode(); hash = (37 * hash) + MIME_TYPE_FIELD_NUMBER; hash = (53 * hash) + getMimeType().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Prediction input format for Text Classification. * </pre> * * Protobuf type {@code * google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance) com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstanceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstanceProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_instance_TextClassificationPredictionInstance_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstanceProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_instance_TextClassificationPredictionInstance_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance.class, com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance.Builder.class); } // Construct using // com.google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); content_ = ""; mimeType_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstanceProto .internal_static_google_cloud_aiplatform_v1beta1_schema_predict_instance_TextClassificationPredictionInstance_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance build() { com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance buildPartial() { com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance result = new com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance(this); result.content_ = content_; result.mimeType_ = mimeType_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance) { return mergeFrom( (com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance other) { if (other == com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance.getDefaultInstance()) return this; if (!other.getContent().isEmpty()) { content_ = other.content_; onChanged(); } if (!other.getMimeType().isEmpty()) { mimeType_ = other.mimeType_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object content_ = ""; /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @return The content. */ public java.lang.String getContent() { java.lang.Object ref = content_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); content_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @return The bytes for content. */ public com.google.protobuf.ByteString getContentBytes() { java.lang.Object ref = content_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); content_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @param value The content to set. * @return This builder for chaining. */ public Builder setContent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } content_ = value; onChanged(); return this; } /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @return This builder for chaining. */ public Builder clearContent() { content_ = getDefaultInstance().getContent(); onChanged(); return this; } /** * * * <pre> * The text snippet to make the predictions on. * </pre> * * <code>string content = 1;</code> * * @param value The bytes for content to set. * @return This builder for chaining. */ public Builder setContentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); content_ = value; onChanged(); return this; } private java.lang.Object mimeType_ = ""; /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @return The mimeType. */ public java.lang.String getMimeType() { java.lang.Object ref = mimeType_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); mimeType_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @return The bytes for mimeType. */ public com.google.protobuf.ByteString getMimeTypeBytes() { java.lang.Object ref = mimeType_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); mimeType_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @param value The mimeType to set. * @return This builder for chaining. */ public Builder setMimeType(java.lang.String value) { if (value == null) { throw new NullPointerException(); } mimeType_ = value; onChanged(); return this; } /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @return This builder for chaining. */ public Builder clearMimeType() { mimeType_ = getDefaultInstance().getMimeType(); onChanged(); return this; } /** * * * <pre> * The MIME type of the text snippet. The supported MIME types are listed * below. * - text/plain * </pre> * * <code>string mime_type = 2;</code> * * @param value The bytes for mimeType to set. * @return This builder for chaining. */ public Builder setMimeTypeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); mimeType_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.schema.predict.instance.TextClassificationPredictionInstance) private static final com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance(); } public static com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TextClassificationPredictionInstance> PARSER = new com.google.protobuf.AbstractParser<TextClassificationPredictionInstance>() { @java.lang.Override public TextClassificationPredictionInstance parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new TextClassificationPredictionInstance(input, extensionRegistry); } }; public static com.google.protobuf.Parser<TextClassificationPredictionInstance> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TextClassificationPredictionInstance> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1beta1.schema.predict.instance .TextClassificationPredictionInstance getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
/* * Copyright (c) 2017, Tyler <https://github.com/tylerthardy> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.config; import java.awt.Color; import java.awt.Dimension; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import net.runelite.api.Constants; import net.runelite.client.Notifier; import net.runelite.client.ui.ContainableFrame; import net.runelite.client.ui.overlay.components.ComponentConstants; @ConfigGroup(RuneLiteConfig.GROUP_NAME) public interface RuneLiteConfig extends Config { String GROUP_NAME = "runelite"; @ConfigSection( name = "Window Settings", description = "Settings relating to the client's window and frame", position = 0 ) String windowSettings = "windowSettings"; @ConfigSection( name = "Notification Settings", description = "Settings relating to notifications", position = 1 ) String notificationSettings = "notificationSettings"; @ConfigSection( name = "Overlay Settings", description = "Settings relating to fonts", position = 2 ) String overlaySettings = "overlaySettings"; @ConfigItem( keyName = "gameSize", name = "Game size", description = "The game will resize to this resolution upon starting the client", position = 10, section = windowSettings ) default Dimension gameSize() { return Constants.GAME_FIXED_SIZE; } @ConfigItem( keyName = "automaticResizeType", name = "Resize type", description = "Choose how the window should resize when opening and closing panels", position = 11, section = windowSettings ) default ExpandResizeType automaticResizeType() { return ExpandResizeType.KEEP_GAME_SIZE; } @ConfigItem( keyName = "lockWindowSize", name = "Lock window size", description = "Determines if the window resizing is allowed or not", position = 12, section = windowSettings ) default boolean lockWindowSize() { return false; } @ConfigItem( keyName = "containInScreen2", name = "Contain in screen", description = "Makes the client stay contained in the screen when attempted to move out of it.<br>Note: 'Always' only works if custom chrome is enabled.", position = 13, section = windowSettings ) default ContainableFrame.Mode containInScreen() { return ContainableFrame.Mode.RESIZING; } @ConfigItem( keyName = "rememberScreenBounds", name = "Remember client position", description = "Save the position and size of the client after exiting", position = 14, section = windowSettings ) default boolean rememberScreenBounds() { return true; } @ConfigItem( keyName = "uiEnableCustomChrome", name = "Enable custom window chrome", description = "Use Runelite's custom window title and borders.", warning = "Please restart your client after changing this setting", position = 15, section = windowSettings ) default boolean enableCustomChrome() { return true; } @Range( min = 10, max = 100 ) @ConfigItem( keyName = "uiWindowOpacity", name = "Window opacity", description = "Set the windows opacity. Requires \"Enable custom window chrome\" to be enabled.", position = 16, section = windowSettings ) default int windowOpacity() { return 100; } @ConfigItem( keyName = "gameAlwaysOnTop", name = "Enable client always on top", description = "The game will always be on the top of the screen", position = 17, section = windowSettings ) default boolean gameAlwaysOnTop() { return false; } @ConfigItem( keyName = "warningOnExit", name = "Display warning on exit", description = "Toggles a warning popup when trying to exit the client", position = 18, section = windowSettings ) default WarningOnExit warningOnExit() { return WarningOnExit.LOGGED_IN; } @ConfigItem( keyName = "usernameInTitle", name = "Show display name in title", description = "Toggles displaying of local player's display name in client title", position = 19, section = windowSettings ) default boolean usernameInTitle() { return true; } @ConfigItem( keyName = "notificationTray", name = "Enable tray notifications", description = "Enables tray notifications", position = 20, section = notificationSettings ) default boolean enableTrayNotifications() { return true; } @ConfigItem( keyName = "notificationRequestFocus", name = "Request focus on notification", description = "Configures the window focus request type on notification", position = 21, section = notificationSettings ) default RequestFocusType notificationRequestFocus() { return RequestFocusType.OFF; } @ConfigItem( keyName = "notificationSound", name = "Notification sound", description = "Enables the playing of a beep sound when notifications are displayed", position = 22, section = notificationSettings ) default Notifier.NativeCustomOff notificationSound() { return Notifier.NativeCustomOff.NATIVE; } @ConfigItem( keyName = "notificationGameMessage", name = "Enable game message notifications", description = "Puts a notification message in the chatbox", position = 23, section = notificationSettings ) default boolean enableGameMessageNotification() { return false; } @ConfigItem( keyName = "flashNotification", name = "Flash notification", description = "Flashes the game frame as a notification", position = 24, section = notificationSettings ) default FlashNotification flashNotification() { return FlashNotification.DISABLED; } @ConfigItem( keyName = "notificationFocused", name = "Send notifications when focused", description = "Toggles all notifications for when the client is focused", position = 25, section = notificationSettings ) default boolean sendNotificationsWhenFocused() { return false; } @Alpha @ConfigItem( keyName = "notificationFlashColor", name = "Notification Flash Color", description = "Sets the color of the notification flashes.", position = 26, section = notificationSettings ) default Color notificationFlashColor() { return new Color(255, 0, 0, 70); } @ConfigItem( keyName = "fontType", name = "Dynamic Overlay Font", description = "Configures what font type is used for in-game overlays such as player name, ground items, etc.", position = 30, section = overlaySettings ) default FontType fontType() { return FontType.SMALL; } @ConfigItem( keyName = "tooltipFontType", name = "Tooltip Font", description = "Configures what font type is used for in-game tooltips such as food stats, NPC names, etc.", position = 31, section = overlaySettings ) default FontType tooltipFontType() { return FontType.SMALL; } @ConfigItem( keyName = "interfaceFontType", name = "Interface Overlay Font", description = "Configures what font type is used for in-game interface overlays such as panels, opponent info, clue scrolls etc.", position = 32, section = overlaySettings ) default FontType interfaceFontType() { return FontType.REGULAR; } @ConfigItem( keyName = "menuEntryShift", name = "Require Shift for overlay menu", description = "Overlay right-click menu will require shift to be added", position = 33, section = overlaySettings ) default boolean menuEntryShift() { return true; } @ConfigItem( keyName = "tooltipPosition", name = "Tooltip Position", description = "Configures whether to show the tooltip above or under the cursor", position = 35, section = overlaySettings ) default TooltipPositionType tooltipPosition() { return TooltipPositionType.UNDER_CURSOR; } @ConfigItem( keyName = "infoBoxVertical", name = "Display infoboxes vertically", description = "Toggles the infoboxes to display vertically", position = 40, section = overlaySettings, hidden = true ) default boolean infoBoxVertical() { return false; } @ConfigItem( keyName = "infoBoxSize", name = "Infobox size", description = "Configures the size of each infobox in pixels", position = 42, section = overlaySettings ) @Units(Units.PIXELS) default int infoBoxSize() { return 35; } @ConfigItem( keyName = "infoBoxTextOutline", name = "Outline infobox text", description = "Draw a full outline instead of a simple shadow for infobox text", position = 43, section = overlaySettings ) default boolean infoBoxTextOutline() { return false; } @ConfigItem( keyName = "overlayBackgroundColor", name = "Overlay Color", description = "Configures the background color of infoboxes and overlays", position = 44, section = overlaySettings ) @Alpha default Color overlayBackgroundColor() { return ComponentConstants.STANDARD_BACKGROUND_COLOR; } @ConfigItem( keyName = "blockExtraMouseButtons", name = "Block Extra Mouse Buttons", description = "Blocks extra mouse buttons (4 and above)", position = 44 ) default boolean blockExtraMouseButtons() { return true; } @ConfigItem( keyName = "sidebarToggleKey", name = "Sidebar Toggle Key", description = "The key that will toggle the sidebar (accepts modifiers)", position = 45, section = windowSettings ) default Keybind sidebarToggleKey() { return new Keybind(KeyEvent.VK_F11, InputEvent.CTRL_DOWN_MASK); } @ConfigItem( keyName = "panelToggleKey", name = "Plugin Panel Toggle Key", description = "The key that will toggle the current or last opened plugin panel (accepts modifiers)", position = 46, section = windowSettings ) default Keybind panelToggleKey() { return new Keybind(KeyEvent.VK_F12, InputEvent.CTRL_DOWN_MASK); } }
package org.opencds.cqf.ruler.cr.r4.builder; import java.util.ArrayList; import java.util.List; import org.hl7.fhir.exceptions.FHIRException; import org.hl7.fhir.r4.model.Annotation; import org.hl7.fhir.r4.model.CanonicalType; import org.hl7.fhir.r4.model.CarePlan; import org.hl7.fhir.r4.model.CodeableConcept; import org.hl7.fhir.r4.model.Identifier; import org.hl7.fhir.r4.model.Period; import org.hl7.fhir.r4.model.Reference; import org.hl7.fhir.r4.model.Resource; public class CarePlanBuilder extends BaseBuilder<CarePlan> { public CarePlanBuilder() { super(new CarePlan()); } public CarePlanBuilder(CarePlan carePlan) { super(carePlan); } public CarePlanBuilder buildIdentifier(List<Identifier> identifiers) { complexProperty.setIdentifier(identifiers); return this; } public CarePlanBuilder buildIdentifier(Identifier identifier) { if (!complexProperty.hasIdentifier()) { complexProperty.setIdentifier(new ArrayList<>()); } complexProperty.addIdentifier(identifier); return this; } public CarePlanBuilder buildInstantiatesCanonical(List<CanonicalType> references) { complexProperty.setInstantiatesCanonical(references); return this; } public CarePlanBuilder buildInstantiatesCanonical(String reference) { if (!complexProperty.hasInstantiatesCanonical()) { complexProperty.setInstantiatesCanonical(new ArrayList<>()); } complexProperty.addInstantiatesCanonical(reference); return this; } public CarePlanBuilder buildBasedOn(List<Reference> references) { complexProperty.setBasedOn(references); return this; } public CarePlanBuilder buildBasedOn(Reference reference) { if (!complexProperty.hasBasedOn()) { complexProperty.setBasedOn(new ArrayList<>()); } complexProperty.addBasedOn(reference); return this; } public CarePlanBuilder buildReplaces(List<Reference> references) { complexProperty.setReplaces(references); return this; } public CarePlanBuilder buildReplaces(Reference reference) { if (!complexProperty.hasReplaces()) { complexProperty.setReplaces(new ArrayList<>()); } complexProperty.addReplaces(reference); return this; } public CarePlanBuilder buildPartOf(List<Reference> references) { complexProperty.setPartOf(references); return this; } public CarePlanBuilder buildPartOf(Reference reference) { if (!complexProperty.hasPartOf()) { complexProperty.setPartOf(new ArrayList<>()); } complexProperty.addPartOf(reference); return this; } // required public CarePlanBuilder buildStatus(CarePlan.CarePlanStatus status) { complexProperty.setStatus(status); return this; } // String overload public CarePlanBuilder buildStatus(String status) throws FHIRException { complexProperty.setStatus(CarePlan.CarePlanStatus.fromCode(status)); return this; } // required public CarePlanBuilder buildIntent(CarePlan.CarePlanIntent intent) { complexProperty.setIntent(intent); return this; } // String overload public CarePlanBuilder buildIntent(String intent) throws FHIRException { complexProperty.setIntent(CarePlan.CarePlanIntent.fromCode(intent)); return this; } public CarePlanBuilder buildCategory(List<CodeableConcept> categories) { complexProperty.setCategory(categories); return this; } public CarePlanBuilder buildCategory(CodeableConcept category) { if (!complexProperty.hasCategory()) { complexProperty.setCategory(new ArrayList<>()); } complexProperty.addCategory(category); return this; } public CarePlanBuilder buildTitle(String title) { complexProperty.setTitle(title); return this; } public CarePlanBuilder buildDescription(String description) { complexProperty.setDescription(description); return this; } // required public CarePlanBuilder buildSubject(Reference reference) { complexProperty.setSubject(reference); return this; } public CarePlanBuilder buildEncounter(Reference reference) { complexProperty.setEncounter(reference); return this; } public CarePlanBuilder buildPeriod(Period period) { complexProperty.setPeriod(period); return this; } public CarePlanBuilder buildAuthor(Reference reference) { complexProperty.setAuthor(reference); return this; } public CarePlanBuilder buildCareTeam(List<Reference> careTeams) { complexProperty.setCareTeam(careTeams); return this; } public CarePlanBuilder buildCareTeam(Reference careTeam) { if (!complexProperty.hasCareTeam()) { complexProperty.setCareTeam(new ArrayList<>()); } complexProperty.addCareTeam(careTeam); return this; } public CarePlanBuilder buildAddresses(List<Reference> addresses) { complexProperty.setAddresses(addresses); return this; } public CarePlanBuilder buildAddresses(Reference address) { if (!complexProperty.hasAddresses()) { complexProperty.setAddresses(new ArrayList<>()); } complexProperty.addAddresses(address); return this; } public CarePlanBuilder buildSupportingInfo(List<Reference> supportingInfo) { complexProperty.setSupportingInfo(supportingInfo); return this; } public CarePlanBuilder buildSupportingInfo(Reference supportingInfo) { if (!complexProperty.hasSupportingInfo()) { complexProperty.setSupportingInfo(new ArrayList<>()); } complexProperty.addSupportingInfo(supportingInfo); return this; } public CarePlanBuilder buildGoal(List<Reference> goals) { complexProperty.setGoal(goals); return this; } public CarePlanBuilder buildGoal(Reference goal) { if (!complexProperty.hasGoal()) { complexProperty.setGoal(new ArrayList<>()); } complexProperty.addGoal(goal); return this; } public CarePlanBuilder buildActivity(List<CarePlan.CarePlanActivityComponent> activities) { complexProperty.setActivity(activities); return this; } public CarePlanBuilder buildActivity(CarePlan.CarePlanActivityComponent activity) { complexProperty.addActivity(activity); return this; } public CarePlanBuilder buildNotes(List<Annotation> notes) { complexProperty.setNote(notes); return this; } public CarePlanBuilder buildNotes(Annotation note) { if (!complexProperty.hasNote()) { complexProperty.setNote(new ArrayList<>()); } complexProperty.addNote(note); return this; } public CarePlanBuilder buildLanguage(String language) { complexProperty.setLanguage(language); return this; } public CarePlanBuilder buildContained(Resource result) { complexProperty.addContained(result); return this; } }
package org.hisp.dhis.dataelement; /* * Copyright (c) 2004-2015, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project 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. */ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import org.hisp.dhis.common.BaseDimensionalObject; import org.hisp.dhis.common.BaseIdentifiableObject; import org.hisp.dhis.common.DataDimensionType; import org.hisp.dhis.common.DimensionType; import org.hisp.dhis.common.DxfNamespaces; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.MergeStrategy; import org.hisp.dhis.common.NameableObject; import org.hisp.dhis.common.annotation.Scanned; import org.hisp.dhis.common.view.DetailedView; import org.hisp.dhis.common.view.DimensionalView; import org.hisp.dhis.common.view.ExportView; import java.util.ArrayList; import java.util.List; /** * A Category is a dimension of a data element. DataElements can have sets of * dimensions (known as CategoryCombos). An Example of a Category might be * "Sex". The Category could have two (or more) CategoryOptions such as "Male" * and "Female". * * @author Abyot Asalefew */ @JacksonXmlRootElement( localName = "category", namespace = DxfNamespaces.DXF_2_0 ) public class DataElementCategory extends BaseDimensionalObject { public static final String DEFAULT_NAME = "default"; private DataDimensionType dataDimensionType; @Scanned private List<DataElementCategoryOption> categoryOptions = new ArrayList<>(); // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- public DataElementCategory() { } public DataElementCategory( String name ) { this.name = name; } public DataElementCategory( String name, List<DataElementCategoryOption> categoryOptions ) { this( name ); this.categoryOptions = categoryOptions; } // ------------------------------------------------------------------------- // Logic // ------------------------------------------------------------------------- public void addDataElementCategoryOption( DataElementCategoryOption dataElementCategoryOption ) { categoryOptions.add( dataElementCategoryOption ); dataElementCategoryOption.getCategories().add( this ); } public void removeDataElementCategoryOption( DataElementCategoryOption dataElementCategoryOption ) { categoryOptions.remove( dataElementCategoryOption ); dataElementCategoryOption.getCategories().remove( this ); } public void removeAllCategoryOptions() { for ( DataElementCategoryOption categoryOption : categoryOptions ) { categoryOption.getCategories().remove( this ); } categoryOptions.clear(); } public DataElementCategoryOption getCategoryOption( DataElementCategoryOptionCombo categoryOptionCombo ) { for ( DataElementCategoryOption categoryOption : categoryOptions ) { if ( categoryOption.getCategoryOptionCombos().contains( categoryOptionCombo ) ) { return categoryOption; } } return null; } public boolean isDefault() { return DEFAULT_NAME.equals( name ); } // ------------------------------------------------------------------------- // Dimensional object // ------------------------------------------------------------------------- @Override @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) @JsonView( { DetailedView.class, DimensionalView.class } ) @JacksonXmlElementWrapper( localName = "items", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "item", namespace = DxfNamespaces.DXF_2_0 ) public List<NameableObject> getItems() { return new ArrayList<>( categoryOptions ); } @Override public DimensionType getDimensionType() { return DimensionType.CATEGORY; } // ------------------------------------------------------------------------ // Logic // ------------------------------------------------------------------------ @Override public boolean isAutoGenerated() { return name != null && name.equals( DEFAULT_NAME ); } // ------------------------------------------------------------------------ // Getters and setters // ------------------------------------------------------------------------ @Override public String getShortName() { if ( getName() == null || getName().length() <= 50 ) { return getName(); } else { return getName().substring( 0, 49 ); } } @JsonProperty @JsonView( { DetailedView.class, ExportView.class } ) @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public DataDimensionType getDataDimensionType() { return dataDimensionType; } public void setDataDimensionType( DataDimensionType dataDimensionType ) { this.dataDimensionType = dataDimensionType; } @JsonProperty @JsonSerialize( contentAs = BaseIdentifiableObject.class ) @JsonView( { DetailedView.class, ExportView.class } ) @JacksonXmlElementWrapper( localName = "categoryOptions", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "categoryOption", namespace = DxfNamespaces.DXF_2_0 ) public List<DataElementCategoryOption> getCategoryOptions() { return categoryOptions; } public void setCategoryOptions( List<DataElementCategoryOption> categoryOptions ) { this.categoryOptions = categoryOptions; } @Override public void mergeWith( IdentifiableObject other, MergeStrategy strategy ) { super.mergeWith( other, strategy ); if ( other.getClass().isInstance( this ) ) { DataElementCategory category = (DataElementCategory) other; if ( strategy.isReplace() ) { dataDimensionType = category.getDataDimensionType(); } else if ( strategy.isMerge() ) { dataDimensionType = category.getDataDimensionType() == null ? dataDimensionType : category.getDataDimensionType(); } removeAllCategoryOptions(); for ( DataElementCategoryOption dataElementCategoryOption : category.getCategoryOptions() ) { addDataElementCategoryOption( dataElementCategoryOption ); } } } }
/* * Copyright (c) 2018 stnetix.com. 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.stnetix.ariaddna.commonutils.logger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is wrapper of standard SLF4J framework. * Typical usage pattern: * public class A{ * private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(A.class); * //or private static final AriaddnaLogger LOGGER = AriaddnaLogger.getLogger(A.class.getName()); * void doSomething(Object arg){ * LOGGER.trace(Begin of method {{doSomething}});; * LOGGER.info("Execution method {{doSomething}} with argument {}", arg); * } * } * * @author Kotov Alexandr */ public class AriaddnaLogger { /** * This method return instance of {@link AriaddnaLogger} class. * * @param className is name of logger. * @return new instance of AriaddnaLogger. */ public static AriaddnaLogger getLogger(String className) { if (className == null) { throw new IllegalArgumentException("Variable className cannot be null."); } return new AriaddnaLogger(className); } /** * This method return instance of {@link AriaddnaLogger} class. * * @param clazz is instance of {@link Class} class to get logger name. * @return new instance of AriaddnaLogger. */ public static AriaddnaLogger getLogger(Class<?> clazz) { if (clazz == null) { throw new IllegalArgumentException("Variable clazz cannot be null."); } return new AriaddnaLogger(clazz); } /** * Wrapped instance of SLF4J */ private Logger logger; private AriaddnaLogger(String className) { logger = LoggerFactory.getLogger(className); } private AriaddnaLogger(Class<?> clazz) { logger = LoggerFactory.getLogger(clazz); } /** * Is the logger instance enabled for the TRACE level? * * @return True if this Logger is enabled for the TRACE level, * false otherwise. */ public boolean isTraceEnabled() { return logger.isTraceEnabled(); } /** * Similar to {@link #isTraceEnabled()} method except that the * marker data is also taken into account. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the TRACE level, * false otherwise. */ public boolean isTraceEnabled(Marker marker) { return logger.isTraceEnabled(marker); } /** * Log a message at the TRACE level. * * @param message the message string to be logged */ public void trace(String message) { logger.trace(message); } /** * Log a message with the specific Marker at the TRACE level. * * @param marker the marker data specific to this log statement * @param message the message string to be logged */ public void trace(Marker marker, String message) { logger.trace(marker, message); } /** * Log a message at the TRACE level according to the specified format * and argument. * * @param formatMessage the format string * @param arg the argument */ public void trace(String formatMessage, Object arg) { logger.trace(formatMessage, arg); } /** * This method is similar to {@link #trace(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg the argument */ public void trace(Marker marker, String formatMessage, Object arg) { logger.trace(marker, formatMessage, arg); } /** * Log a message at the TRACE level according to the specified format * and arguments. * * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void trace(String formatMessage, Object arg1, Object arg2) { logger.trace(formatMessage, arg1, arg2); } /** * This method is similar to {@link #trace(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void trace(Marker marker, String formatMessage, Object arg1, Object arg2) { logger.trace(marker, formatMessage, arg1, arg2); } /** * Log a message at the TRACE level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the TRACE level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.</p> * * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void trace(String formatMessage, Object... arguments) { logger.trace(formatMessage, arguments); } /** * This method is similar to {@link #trace(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arguments an array of arguments */ public void trace(Marker marker, String formatMessage, Object... arguments) { logger.trace(marker, formatMessage, arguments); } /** * Log an exception (throwable) at the TRACE level with an * accompanying message. * * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void trace(String message, Throwable throwable) { logger.trace(message, throwable); } /** * This method is similar to {@link #trace(String, Throwable)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void trace(Marker marker, String message, Throwable throwable) { logger.trace(marker, message, throwable); } /** * Is the logger instance enabled for the INFO level? * * @return True if this Logger is enabled for the INFO level, * false otherwise. */ public boolean isInfoEnabled() { return logger.isInfoEnabled(); } /** * Similar to {@link #isInfoEnabled()} method except that the marker * data is also taken into consideration. * * @param marker The marker data to take into consideration * @return true if this logger is warn enabled, false otherwise */ public boolean isInfoEnabled(Marker marker) { return logger.isInfoEnabled(marker); } /** * Log a message at the INFO level. * * @param message the message string to be logged */ public void info(String message) { logger.info(message); } /** * Log a message with the specific Marker at the INFO level. * * @param marker The marker specific to this log statement * @param message the message string to be logged */ public void info(Marker marker, String message) { logger.info(marker, message); } /** * Log a message at the INFO level according to the specified format * and argument. * * @param formatMessage the format string * @param arg the argument */ public void info(String formatMessage, Object arg) { logger.info(formatMessage, arg); } /** * This method is similar to {@link #info(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg the argument */ public void info(Marker marker, String formatMessage, Object arg) { logger.info(marker, formatMessage, arg); } /** * Log a message at the INFO level according to the specified format * and arguments. * * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void info(String formatMessage, Object arg1, Object arg2) { logger.info(formatMessage, arg1, arg2); } /** * This method is similar to {@link #info(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void info(Marker marker, String formatMessage, Object arg1, Object arg2) { logger.info(marker, formatMessage, arg1, arg2); } /** * Log a message at the INFO level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the INFO level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for INFO. The variants taking * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost.</p> * * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void info(String formatMessage, Object... arguments) { logger.info(formatMessage, arguments); } /** * This method is similar to {@link #info(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void info(Marker marker, String formatMessage, Object... arguments) { logger.info(marker, formatMessage, arguments); } /** * Log an exception (throwable) at the INFO level with an * accompanying message. * * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void info(String message, Throwable throwable) { logger.info(message, throwable); } /** * except that the marker data is also taken into consideration. * * @param marker the marker data for this log statement * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void info(Marker marker, String message, Throwable throwable) { logger.info(marker, message, throwable); } /** * Is the logger instance enabled for the DEBUG level? * * @return True if this Logger is enabled for the DEBUG level, * false otherwise. */ public boolean isDebugEnabled() { return logger.isDebugEnabled(); } /** * Similar to {@link #isDebugEnabled()} method except that the * marker data is also taken into account. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the DEBUG level, * false otherwise. */ public boolean isDebugEnabled(Marker marker) { return logger.isDebugEnabled(marker); } /** * Log a message at the DEBUG level. * * @param message the message string to be logged */ public void debug(String message) { logger.debug(message); } /** * Log a message with the specific Marker at the DEBUG level. * * @param marker the marker data specific to this log statement * @param message the message string to be logged */ public void debug(Marker marker, String message) { logger.debug(marker, message); } /** * Log a message at the DEBUG level according to the specified format * and argument. * * @param formatMessage the format string * @param arg the argument */ public void debug(String formatMessage, Object arg) { logger.debug(formatMessage, arg); } /** * This method is similar to {@link #debug(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg the argument */ public void debug(Marker marker, String formatMessage, Object arg) { logger.debug(marker, formatMessage, arg); } /** * Log a message at the DEBUG level according to the specified format * and arguments. * * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void debug(String formatMessage, Object arg1, Object arg2) { logger.debug(formatMessage, arg1, arg2); } /** * This method is similar to {@link #debug(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void debug(Marker marker, String formatMessage, Object arg1, Object arg2) { logger.debug(marker, formatMessage, arg1, arg2); } /** * Log a message at the DEBUG level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the DEBUG level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for DEBUG. The variants taking * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost.</p> * * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void debug(String formatMessage, Object... arguments) { logger.debug(formatMessage, arguments); } /** * This method is similar to {@link #debug(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void debug(Marker marker, String formatMessage, Object... arguments) { logger.debug(marker, formatMessage, arguments); } /** * Log an exception (throwable) at the DEBUG level with an * accompanying message. * * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void debug(String message, Throwable throwable) { logger.debug(message, throwable); } /** * This method is similar to {@link #debug(String, Throwable)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void debug(Marker marker, String message, Throwable throwable) { logger.debug(marker, message, throwable); } /** * Is the logger instance enabled for the WARN level? * * @return True if this Logger is enabled for the WARN level, * false otherwise. */ public boolean isWarnEnabled() { return logger.isWarnEnabled(); } /** * Similar to {@link #isWarnEnabled()} method except that the marker * data is also taken into consideration. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the WARN level, * false otherwise. */ public boolean isWarnEnabled(Marker marker) { return logger.isWarnEnabled(marker); } /** * Log a message at the WARN level. * * @param message the message string to be logged */ public void warn(String message) { logger.warn(message); } /** * Log a message with the specific Marker at the WARN level. * * @param marker The marker specific to this log statement * @param message the message string to be logged */ public void warn(Marker marker, String message) { logger.warn(marker, message); } /** * Log a message at the WARN level according to the specified format * and argument. * * @param formatMessage the format string * @param arg the argument */ public void warn(String formatMessage, Object arg) { logger.warn(formatMessage, arg); } /** * This method is similar to {@link #warn(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg the argument */ public void warn(Marker marker, String formatMessage, Object arg) { logger.warn(marker, formatMessage, arg); } /** * Log a message at the WARN level according to the specified format * and arguments. * * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void warn(String formatMessage, Object arg1, Object arg2) { logger.warn(formatMessage, arg1, arg2); } /** * This method is similar to {@link #warn(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void warn(Marker marker, String formatMessage, Object arg1, Object arg2) { logger.warn(marker, formatMessage, arg1, arg2); } /** * Log a message at the WARN level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the WARN level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for WARN. The variants taking * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost.</p> * * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void warn(String formatMessage, Object... arguments) { logger.warn(formatMessage, arguments); } /** * This method is similar to {@link #warn(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void warn(Marker marker, String formatMessage, Object... arguments) { logger.warn(marker, formatMessage, arguments); } /** * Log an exception (throwable) at the WARN level with an * accompanying message. * * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void warn(String message, Throwable throwable) { logger.warn(message, throwable); } /** * This method is similar to {@link #warn(String, Throwable)} method * except that the marker data is also taken into consideration. * * @param marker the marker data for this log statement * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void warn(Marker marker, String message, Throwable throwable) { logger.warn(marker, message, throwable); } /** * Is the logger instance enabled for the ERROR level? * * @return True if this Logger is enabled for the ERROR level, * false otherwise. */ public boolean isErrorEnabled() { return logger.isErrorEnabled(); } /** * Similar to {@link #isErrorEnabled()} method except that the * marker data is also taken into consideration. * * @param marker The marker data to take into consideration * @return True if this Logger is enabled for the ERROR level, * false otherwise. */ public boolean isErrorEnabled(Marker marker) { return logger.isErrorEnabled(marker); } /** * Log a message at the ERROR level. * * @param message the message string to be logged */ public void error(String message) { logger.error(message); } /** * Log a message with the specific Marker at the ERROR level. * * @param marker The marker specific to this log statement * @param message the message string to be logged */ public void error(Marker marker, String message) { logger.error(marker, message); } /** * Log a message at the ERROR level according to the specified format * and argument. * <p/> * <p>This form avoids superfluous object creation when the logger * is disabled for the ERROR level. </p> * * @param formatMessage the format string * @param arg the argument */ public void error(String formatMessage, Object arg) { logger.error(formatMessage, arg); } /** * This method is similar to {@link #error(String, Object)} method except that the * marker data is also taken into consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg the argument */ public void error(Marker marker, String formatMessage, Object arg) { logger.error(marker, formatMessage, arg); } /** * Log a message at the ERROR level according to the specified format * and arguments. * * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void error(String formatMessage, Object arg1, Object arg2) { logger.error(formatMessage, arg1, arg2); } /** * This method is similar to {@link #error(String, Object, Object)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arg1 the first argument * @param arg2 the second argument */ public void error(Marker marker, String formatMessage, Object arg1, Object arg2) { logger.error(marker, formatMessage, arg1, arg2); } /** * * Log a message at the ERROR level according to the specified format * and arguments. * <p/> * <p>This form avoids superfluous string concatenation when the logger * is disabled for the ERROR level. However, this variant incurs the hidden * (and relatively small) cost of creating an <code>Object[]</code> before invoking the method, * even if this logger is disabled for ERROR. The variants taking * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two} * arguments exist solely in order to avoid this hidden cost.</p> * * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void error(String formatMessage, Object... arguments) { logger.error(formatMessage, arguments); } /** * This method is similar to {@link #error(String, Object...)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param formatMessage the format string * @param arguments a list of 3 or more arguments */ public void error(Marker marker, String formatMessage, Object... arguments) { logger.error(marker, formatMessage, arguments); } /** * Log an exception (throwable) at the ERROR level with an * accompanying message. * * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void error(String message, Throwable throwable) { logger.error(message, throwable); } /** * This method is similar to {@link #error(String, Throwable)} * method except that the marker data is also taken into * consideration. * * @param marker the marker data specific to this log statement * @param message the message accompanying the exception * @param throwable the exception (throwable) to log */ public void error(Marker marker, String message, Throwable throwable) { logger.error(marker, message, throwable); } }
/** * 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.hdfs; import org.apache.hadoop.fs.MD5MD5CRC32CastagnoliFileChecksum; import org.apache.hadoop.fs.MD5MD5CRC32FileChecksum; import org.apache.hadoop.fs.MD5MD5CRC32GzipFileChecksum; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicy; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.protocol.HdfsConstants; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.protocol.LocatedBlocks; import org.apache.hadoop.hdfs.protocol.LocatedStripedBlock; import org.apache.hadoop.hdfs.protocol.StripedBlockInfo; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtoUtil; import org.apache.hadoop.hdfs.protocol.datatransfer.IOStreamPair; import org.apache.hadoop.hdfs.protocol.datatransfer.Op; import org.apache.hadoop.hdfs.protocol.datatransfer.Sender; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.BlockOpResponseProto; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.OpBlockChecksumResponseProto; import org.apache.hadoop.hdfs.protocolPB.PBHelperClient; import org.apache.hadoop.hdfs.security.token.block.InvalidBlockTokenException; import org.apache.hadoop.io.DataOutputBuffer; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.MD5Hash; import org.apache.hadoop.util.DataChecksum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; /** * Utility classes to compute file checksum for both replicated and striped * files. */ final class FileChecksumHelper { static final Logger LOG = LoggerFactory.getLogger(FileChecksumHelper.class); private FileChecksumHelper() {} /** * A common abstract class to compute file checksum. */ static abstract class FileChecksumComputer { private final String src; private final long length; private final DFSClient client; private final ClientProtocol namenode; private final DataOutputBuffer md5out = new DataOutputBuffer(); private MD5MD5CRC32FileChecksum fileChecksum; private LocatedBlocks blockLocations; private int timeout; private List<LocatedBlock> locatedBlocks; private long remaining = 0L; private int bytesPerCRC = -1; private DataChecksum.Type crcType = DataChecksum.Type.DEFAULT; private long crcPerBlock = 0; private boolean isRefetchBlocks = false; private int lastRetriedIndex = -1; /** * Constructor that accepts all the input parameters for the computing. */ FileChecksumComputer(String src, long length, LocatedBlocks blockLocations, ClientProtocol namenode, DFSClient client) throws IOException { this.src = src; this.length = length; this.blockLocations = blockLocations; this.namenode = namenode; this.client = client; this.remaining = length; if (src.contains(HdfsConstants.SEPARATOR_DOT_SNAPSHOT_DIR_SEPARATOR)) { this.remaining = Math.min(length, blockLocations.getFileLength()); } this.locatedBlocks = blockLocations.getLocatedBlocks(); } String getSrc() { return src; } long getLength() { return length; } DFSClient getClient() { return client; } ClientProtocol getNamenode() { return namenode; } DataOutputBuffer getMd5out() { return md5out; } MD5MD5CRC32FileChecksum getFileChecksum() { return fileChecksum; } LocatedBlocks getBlockLocations() { return blockLocations; } void refetchBlocks() throws IOException { this.blockLocations = getClient().getBlockLocations(getSrc(), getLength()); this.locatedBlocks = getBlockLocations().getLocatedBlocks(); this.isRefetchBlocks = false; } int getTimeout() { return timeout; } void setTimeout(int timeout) { this.timeout = timeout; } List<LocatedBlock> getLocatedBlocks() { return locatedBlocks; } long getRemaining() { return remaining; } void setRemaining(long remaining) { this.remaining = remaining; } int getBytesPerCRC() { return bytesPerCRC; } void setBytesPerCRC(int bytesPerCRC) { this.bytesPerCRC = bytesPerCRC; } DataChecksum.Type getCrcType() { return crcType; } void setCrcType(DataChecksum.Type crcType) { this.crcType = crcType; } long getCrcPerBlock() { return crcPerBlock; } void setCrcPerBlock(long crcPerBlock) { this.crcPerBlock = crcPerBlock; } boolean isRefetchBlocks() { return isRefetchBlocks; } void setRefetchBlocks(boolean refetchBlocks) { this.isRefetchBlocks = refetchBlocks; } int getLastRetriedIndex() { return lastRetriedIndex; } void setLastRetriedIndex(int lastRetriedIndex) { this.lastRetriedIndex = lastRetriedIndex; } /** * Perform the file checksum computing. The intermediate results are stored * in the object and will be used later. * @throws IOException */ void compute() throws IOException { checksumBlocks(); fileChecksum = makeFinalResult(); } /** * Compute and aggregate block checksums block by block. * @throws IOException */ abstract void checksumBlocks() throws IOException; /** * Make final file checksum result given the computing process done. */ MD5MD5CRC32FileChecksum makeFinalResult() { //compute file MD5 final MD5Hash fileMD5 = MD5Hash.digest(md5out.getData()); switch (crcType) { case CRC32: return new MD5MD5CRC32GzipFileChecksum(bytesPerCRC, crcPerBlock, fileMD5); case CRC32C: return new MD5MD5CRC32CastagnoliFileChecksum(bytesPerCRC, crcPerBlock, fileMD5); default: // If there is no block allocated for the file, // return one with the magic entry that matches what previous // hdfs versions return. if (locatedBlocks.isEmpty()) { return new MD5MD5CRC32GzipFileChecksum(0, 0, fileMD5); } // we should never get here since the validity was checked // when getCrcType() was called above. return null; } } /** * Create and return a sender given an IO stream pair. */ Sender createSender(IOStreamPair pair) { DataOutputStream out = (DataOutputStream) pair.out; return new Sender(out); } /** * Close an IO stream pair. */ void close(IOStreamPair pair) { if (pair != null) { IOUtils.closeStream(pair.in); IOUtils.closeStream(pair.out); } } } /** * Replicated file checksum computer. */ static class ReplicatedFileChecksumComputer extends FileChecksumComputer { private int blockIdx; ReplicatedFileChecksumComputer(String src, long length, LocatedBlocks blockLocations, ClientProtocol namenode, DFSClient client) throws IOException { super(src, length, blockLocations, namenode, client); } @Override void checksumBlocks() throws IOException { // get block checksum for each block for (blockIdx = 0; blockIdx < getLocatedBlocks().size() && getRemaining() >= 0; blockIdx++) { if (isRefetchBlocks()) { // refetch to get fresh tokens refetchBlocks(); } LocatedBlock locatedBlock = getLocatedBlocks().get(blockIdx); if (!checksumBlock(locatedBlock)) { throw new IOException("Fail to get block MD5 for " + locatedBlock); } } } /** * Return true when sounds good to continue or retry, false when severe * condition or totally failed. */ private boolean checksumBlock( LocatedBlock locatedBlock) throws IOException { ExtendedBlock block = locatedBlock.getBlock(); if (getRemaining() < block.getNumBytes()) { block.setNumBytes(getRemaining()); } setRemaining(getRemaining() - block.getNumBytes()); DatanodeInfo[] datanodes = locatedBlock.getLocations(); int tmpTimeout = 3000 * datanodes.length + getClient().getConf().getSocketTimeout(); setTimeout(tmpTimeout); //try each datanode location of the block boolean done = false; for (int j = 0; !done && j < datanodes.length; j++) { try { tryDatanode(locatedBlock, datanodes[j]); done = true; } catch (InvalidBlockTokenException ibte) { if (blockIdx > getLastRetriedIndex()) { LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM " + "for file {} for block {} from datanode {}. Will retry " + "the block once.", getSrc(), block, datanodes[j]); setLastRetriedIndex(blockIdx); done = true; // actually it's not done; but we'll retry blockIdx--; // repeat at blockIdx-th block setRefetchBlocks(true); } } catch (IOException ie) { LOG.warn("src={}" + ", datanodes[{}]={}", getSrc(), j, datanodes[j], ie); } } return done; } /** * Try one replica or datanode to compute the block checksum given a block. */ private void tryDatanode(LocatedBlock locatedBlock, DatanodeInfo datanode) throws IOException { ExtendedBlock block = locatedBlock.getBlock(); try (IOStreamPair pair = getClient().connectToDN(datanode, getTimeout(), locatedBlock.getBlockToken())) { LOG.debug("write to {}: {}, block={}", datanode, Op.BLOCK_CHECKSUM, block); // get block MD5 createSender(pair).blockChecksum(block, locatedBlock.getBlockToken()); final BlockOpResponseProto reply = BlockOpResponseProto.parseFrom( PBHelperClient.vintPrefixed(pair.in)); String logInfo = "for block " + block + " from datanode " + datanode; DataTransferProtoUtil.checkBlockOpStatus(reply, logInfo); OpBlockChecksumResponseProto checksumData = reply.getChecksumResponse(); //read byte-per-checksum final int bpc = checksumData.getBytesPerCrc(); if (blockIdx == 0) { //first block setBytesPerCRC(bpc); } else if (bpc != getBytesPerCRC()) { throw new IOException("Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + getBytesPerCRC()); } //read crc-per-block final long cpb = checksumData.getCrcPerBlock(); if (getLocatedBlocks().size() > 1 && blockIdx == 0) { setCrcPerBlock(cpb); } //read md5 final MD5Hash md5 = new MD5Hash(checksumData.getMd5().toByteArray()); md5.write(getMd5out()); // read crc-type final DataChecksum.Type ct; if (checksumData.hasCrcType()) { ct = PBHelperClient.convert(checksumData.getCrcType()); } else { LOG.debug("Retrieving checksum from an earlier-version DataNode: " + "inferring checksum by reading first byte"); ct = getClient().inferChecksumTypeByReading(locatedBlock, datanode); } if (blockIdx == 0) { // first block setCrcType(ct); } else if (getCrcType() != DataChecksum.Type.MIXED && getCrcType() != ct) { // if crc types are mixed in a file setCrcType(DataChecksum.Type.MIXED); } if (LOG.isDebugEnabled()) { if (blockIdx == 0) { LOG.debug("set bytesPerCRC=" + getBytesPerCRC() + ", crcPerBlock=" + getCrcPerBlock()); } LOG.debug("got reply from " + datanode + ": md5=" + md5); } } } } /** * Striped file checksum computing. */ static class StripedFileNonStripedChecksumComputer extends FileChecksumComputer { private final ErasureCodingPolicy ecPolicy; private int bgIdx; StripedFileNonStripedChecksumComputer(String src, long length, LocatedBlocks blockLocations, ClientProtocol namenode, DFSClient client, ErasureCodingPolicy ecPolicy) throws IOException { super(src, length, blockLocations, namenode, client); this.ecPolicy = ecPolicy; } @Override void checksumBlocks() throws IOException { int tmpTimeout = 3000 * 1 + getClient().getConf().getSocketTimeout(); setTimeout(tmpTimeout); for (bgIdx = 0; bgIdx < getLocatedBlocks().size() && getRemaining() >= 0; bgIdx++) { if (isRefetchBlocks()) { // refetch to get fresh tokens refetchBlocks(); } LocatedBlock locatedBlock = getLocatedBlocks().get(bgIdx); LocatedStripedBlock blockGroup = (LocatedStripedBlock) locatedBlock; if (!checksumBlockGroup(blockGroup)) { throw new IOException("Fail to get block MD5 for " + locatedBlock); } } } private boolean checksumBlockGroup( LocatedStripedBlock blockGroup) throws IOException { ExtendedBlock block = blockGroup.getBlock(); if (getRemaining() < block.getNumBytes()) { block.setNumBytes(getRemaining()); } setRemaining(getRemaining() - block.getNumBytes()); StripedBlockInfo stripedBlockInfo = new StripedBlockInfo(block, blockGroup.getLocations(), blockGroup.getBlockTokens(), ecPolicy); DatanodeInfo[] datanodes = blockGroup.getLocations(); //try each datanode in the block group. boolean done = false; for (int j = 0; !done && j < datanodes.length; j++) { try { tryDatanode(blockGroup, stripedBlockInfo, datanodes[j]); done = true; } catch (InvalidBlockTokenException ibte) { if (bgIdx > getLastRetriedIndex()) { LOG.debug("Got access token error in response to OP_BLOCK_CHECKSUM " + "for file {} for block {} from datanode {}. Will retry " + "the block once.", getSrc(), block, datanodes[j]); setLastRetriedIndex(bgIdx); done = true; // actually it's not done; but we'll retry bgIdx--; // repeat at bgIdx-th block setRefetchBlocks(true); } } catch (IOException ie) { LOG.warn("src={}" + ", datanodes[{}]={}", getSrc(), j, datanodes[j], ie); } } return done; } /** * Return true when sounds good to continue or retry, false when severe * condition or totally failed. */ private void tryDatanode(LocatedStripedBlock blockGroup, StripedBlockInfo stripedBlockInfo, DatanodeInfo datanode) throws IOException { try (IOStreamPair pair = getClient().connectToDN(datanode, getTimeout(), blockGroup.getBlockToken())) { LOG.debug("write to {}: {}, blockGroup={}", datanode, Op.BLOCK_GROUP_CHECKSUM, blockGroup); // get block MD5 createSender(pair).blockGroupChecksum(stripedBlockInfo, blockGroup.getBlockToken()); BlockOpResponseProto reply = BlockOpResponseProto.parseFrom( PBHelperClient.vintPrefixed(pair.in)); String logInfo = "for blockGroup " + blockGroup + " from datanode " + datanode; DataTransferProtoUtil.checkBlockOpStatus(reply, logInfo); OpBlockChecksumResponseProto checksumData = reply.getChecksumResponse(); //read byte-per-checksum final int bpc = checksumData.getBytesPerCrc(); if (bgIdx == 0) { //first block setBytesPerCRC(bpc); } else { if (bpc != getBytesPerCRC()) { throw new IOException("Byte-per-checksum not matched: bpc=" + bpc + " but bytesPerCRC=" + getBytesPerCRC()); } } //read crc-per-block final long cpb = checksumData.getCrcPerBlock(); if (getLocatedBlocks().size() > 1 && bgIdx == 0) { // first block setCrcPerBlock(cpb); } //read md5 final MD5Hash md5 = new MD5Hash( checksumData.getMd5().toByteArray()); md5.write(getMd5out()); // read crc-type final DataChecksum.Type ct; if (checksumData.hasCrcType()) { ct = PBHelperClient.convert(checksumData.getCrcType()); } else { LOG.debug("Retrieving checksum from an earlier-version DataNode: " + "inferring checksum by reading first byte"); ct = getClient().inferChecksumTypeByReading(blockGroup, datanode); } if (bgIdx == 0) { setCrcType(ct); } else if (getCrcType() != DataChecksum.Type.MIXED && getCrcType() != ct) { // if crc types are mixed in a file setCrcType(DataChecksum.Type.MIXED); } if (LOG.isDebugEnabled()) { if (bgIdx == 0) { LOG.debug("set bytesPerCRC=" + getBytesPerCRC() + ", crcPerBlock=" + getCrcPerBlock()); } LOG.debug("got reply from " + datanode + ": md5=" + md5); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.druid.sql.calcite.planner; import org.apache.calcite.avatica.remote.TypedValue; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.RelShuttle; import org.apache.calcite.rel.RelVisitor; import org.apache.calcite.rel.core.TableFunctionScan; import org.apache.calcite.rel.core.TableScan; import org.apache.calcite.rel.logical.LogicalAggregate; import org.apache.calcite.rel.logical.LogicalCorrelate; import org.apache.calcite.rel.logical.LogicalExchange; import org.apache.calcite.rel.logical.LogicalFilter; import org.apache.calcite.rel.logical.LogicalIntersect; import org.apache.calcite.rel.logical.LogicalJoin; import org.apache.calcite.rel.logical.LogicalMatch; import org.apache.calcite.rel.logical.LogicalMinus; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.logical.LogicalSort; import org.apache.calcite.rel.logical.LogicalUnion; import org.apache.calcite.rel.logical.LogicalValues; import org.apache.calcite.rel.type.RelDataTypeFactory; import org.apache.calcite.rex.RexBuilder; import org.apache.calcite.rex.RexDynamicParam; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexShuttle; import org.apache.calcite.sql.type.SqlTypeName; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.sql.SqlPlanningException; import org.apache.druid.sql.SqlPlanningException.PlanningError; /** * Traverse {@link RelNode} tree and replaces all {@link RexDynamicParam} with {@link org.apache.calcite.rex.RexLiteral} * using {@link RexBuilder} if a value binding exists for the parameter. All parameters must have a value by the time * {@link RelParameterizerShuttle} is run, or else it will throw an exception. * * Note: none of the tests currently hit this anymore since {@link SqlParameterizerShuttle} has been modified to handle * most common jdbc types, but leaving this here provides a safety net to try again to convert parameters * to literal values in case {@link SqlParameterizerShuttle} fails. */ public class RelParameterizerShuttle implements RelShuttle { private final PlannerContext plannerContext; public RelParameterizerShuttle(PlannerContext plannerContext) { this.plannerContext = plannerContext; } @Override public RelNode visit(TableScan scan) { return bindRel(scan); } @Override public RelNode visit(TableFunctionScan scan) { return bindRel(scan); } @Override public RelNode visit(LogicalValues values) { return bindRel(values); } @Override public RelNode visit(LogicalFilter filter) { return bindRel(filter); } @Override public RelNode visit(LogicalProject project) { return bindRel(project); } @Override public RelNode visit(LogicalJoin join) { return bindRel(join); } @Override public RelNode visit(LogicalCorrelate correlate) { return bindRel(correlate); } @Override public RelNode visit(LogicalUnion union) { return bindRel(union); } @Override public RelNode visit(LogicalIntersect intersect) { return bindRel(intersect); } @Override public RelNode visit(LogicalMinus minus) { return bindRel(minus); } @Override public RelNode visit(LogicalAggregate aggregate) { return bindRel(aggregate); } @Override public RelNode visit(LogicalMatch match) { return bindRel(match); } @Override public RelNode visit(LogicalSort sort) { final RexBuilder builder = sort.getCluster().getRexBuilder(); final RelDataTypeFactory typeFactory = sort.getCluster().getTypeFactory(); RexNode newFetch = bind(sort.fetch, builder, typeFactory); RexNode newOffset = bind(sort.offset, builder, typeFactory); sort = (LogicalSort) sort.copy(sort.getTraitSet(), sort.getInput(), sort.getCollation(), newOffset, newFetch); return bindRel(sort, builder, typeFactory); } @Override public RelNode visit(LogicalExchange exchange) { return bindRel(exchange); } @Override public RelNode visit(RelNode other) { return bindRel(other); } private RelNode bindRel(RelNode node) { final RexBuilder builder = node.getCluster().getRexBuilder(); final RelDataTypeFactory typeFactory = node.getCluster().getTypeFactory(); return bindRel(node, builder, typeFactory); } private RelNode bindRel(RelNode node, RexBuilder builder, RelDataTypeFactory typeFactory) { final RexShuttle binder = new RexShuttle() { @Override public RexNode visitDynamicParam(RexDynamicParam dynamicParam) { return bind(dynamicParam, builder, typeFactory); } }; node = node.accept(binder); node.childrenAccept(new RelVisitor() { @Override public void visit(RelNode node, int ordinal, RelNode parent) { super.visit(node, ordinal, parent); RelNode transformed = node.accept(binder); if (!node.equals(transformed)) { parent.replaceInput(ordinal, transformed); } } }); return node; } private RexNode bind(RexNode node, RexBuilder builder, RelDataTypeFactory typeFactory) { if (node instanceof RexDynamicParam) { RexDynamicParam dynamicParam = (RexDynamicParam) node; // if we have a value for dynamic parameter, replace with a literal, else add to list of unbound parameters if (plannerContext.getParameters().size() > dynamicParam.getIndex()) { TypedValue param = plannerContext.getParameters().get(dynamicParam.getIndex()); if (param == null) { throw new SqlPlanningException( PlanningError.VALIDATION_ERROR, StringUtils.format("Parameter at position[%s] is not bound", dynamicParam.getIndex()) ); } if (param.value == null) { return builder.makeNullLiteral(typeFactory.createSqlType(SqlTypeName.NULL)); } SqlTypeName typeName = SqlTypeName.getNameForJdbcType(param.type.typeId); return builder.makeLiteral( param.value, typeFactory.createSqlType(typeName), true ); } else { throw new SqlPlanningException( PlanningError.VALIDATION_ERROR, StringUtils.format("Parameter at position[%s] is not bound", dynamicParam.getIndex()) ); } } return node; } }
/* * Copyright (C) 2015 Archie L. Cobbs. All rights reserved. */ package org.jsimpledb.util; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.NavigableSet; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.dellroad.stuff.xml.IndentXMLStreamWriter; import org.jsimpledb.core.CollectionField; import org.jsimpledb.core.CounterField; import org.jsimpledb.core.Field; import org.jsimpledb.core.FieldType; import org.jsimpledb.core.ListField; import org.jsimpledb.core.MapField; import org.jsimpledb.core.ObjId; import org.jsimpledb.core.ObjType; import org.jsimpledb.core.ReferenceField; import org.jsimpledb.core.Schema; import org.jsimpledb.core.SchemaItem; import org.jsimpledb.core.SetField; import org.jsimpledb.core.SimpleField; import org.jsimpledb.core.SnapshotTransaction; import org.jsimpledb.core.Transaction; import org.jsimpledb.core.UnknownTypeException; import org.jsimpledb.schema.NameIndex; import org.jsimpledb.schema.SchemaField; import org.jsimpledb.schema.SchemaModel; import org.jsimpledb.schema.SchemaObjectType; /** * Utility methods for serializing and deserializing objects in a {@link Transaction} to/from XML. * * <p> * There are two supported formats. The "Storage ID Format" specifies objects and fields using their storage IDs * and supports all possible database contents. * <pre> * &lt;objects&gt; * &lt;object storageId="100" id="64a971e1aef01cc8" version="1"&gt; * &lt;field storageId="101"&gt;George Washington&lt;/field&gt; * &lt;field storageId="102"&gt;true&lt;/field&gt; * &lt;field storageId="103"&gt; * &lt;entry&gt; * &lt;key&gt;teeth&lt;/key&gt; * &lt;value&gt;wooden&lt;/value&gt; * &lt;/entry&gt; * &lt;/field&gt; * &lt;field storageId="104"&gt;c8b84a08e5c2b1a2&lt;/field&gt; * &lt;/object&gt; * ... * &lt;/objects&gt; * </pre> * * <p> * "Name Format" differs from "Storage ID Format" in that object types and fields are specified by name instead of storage ID. * However, it does not support schemas that use names that are not valid XML tags. * <pre> * &lt;objects&gt; * &lt;Person id="64a971e1aef01cc8" version="1"&gt; * &lt;name&gt;George Washington&lt;/name&gt; * &lt;wasPresident&gt;true&lt;/wasPresident&gt; * &lt;attributes&gt; * &lt;entry&gt; * &lt;key&gt;teeth&lt;/key&gt; * &lt;value&gt;wooden&lt;/value&gt; * &lt;/entry&gt; * &lt;/attributes&gt; * &lt;spouse&gt;c8b84a08e5c2b1a2&lt;/spouse&gt; * &lt;/Person&gt; * ... * &lt;/objects&gt; * </pre> * * <p> * Some details on the input logic: * <ul> * <li>Simple fields that are equal to their default values, and complex fields that are empty, may be omitted</li> * <li>The {@code "version"} attribute may be omitted, in which case the default schema version associated with * the {@link Transaction} being written to is assumed.</li> * <li>The {@code "id"} attribute may be omitted, in which case a random unassigned ID is generated</li> * <li>Any object ID (including the {@code "id"} attribute) may have the special form * <code>generated:<i>TYPE</i>:<i>SUFFIX</i></code>, where <code><i>TYPE</i></code> is the object type * name or storage ID and <code><i>SUFFIX</i></code> is an arbitrary string. * In this case, a random, unassigned object ID for type <code><i>TYPE</i></code> is generated * on first occurrence, and on subsequent occurences the previously generated ID is recalled. This facilitates * input generated via XSL and the {@code generate-id()} function. * The {@linkplain #getGeneratedIdCache configured} {@link GeneratedIdCache} keeps track of generated IDs.</li> * </ul> */ public class XMLObjectSerializer extends AbstractXMLStreaming { public static final QName ELEMENT_TAG = new QName("element"); public static final QName ENTRY_TAG = new QName("entry"); public static final QName FIELD_TAG = new QName("field"); public static final QName KEY_TAG = new QName("key"); public static final QName OBJECTS_TAG = new QName("objects"); public static final QName OBJECT_TAG = new QName("object"); public static final QName VALUE_TAG = new QName("value"); public static final QName ID_ATTR = new QName("id"); public static final QName STORAGE_ID_ATTR = new QName("storageId"); public static final QName VERSION_ATTR = new QName("version"); public static final QName NULL_ATTR = new QName("null"); private static final Pattern GENERATED_ID_PATTERN = Pattern.compile("generated:([^:]+):(.*)"); private final Transaction tx; private final HashMap<Integer, NameIndex> nameIndexMap = new HashMap<>(); private GeneratedIdCache generatedIdCache = new GeneratedIdCache(); /** * Constructor. * * @param tx {@link Transaction} on which to operate * @throws IllegalArgumentException if {@code tx} is null */ public XMLObjectSerializer(Transaction tx) { Preconditions.checkArgument(tx != null, "null tx"); this.tx = tx; // Build name index for each schema version for (Schema schema : this.tx.getSchemas().getVersions().values()) nameIndexMap.put(schema.getVersionNumber(), new NameIndex(schema.getSchemaModel())); } /** * Get the {@link GeneratedIdCache} associated with this instance. * * @return the associated {@link GeneratedIdCache} */ public GeneratedIdCache getGeneratedIdCache() { return this.generatedIdCache; } /** * Set the {@link GeneratedIdCache} associated with this instance. * * @param generatedIdCache the {@link GeneratedIdCache} for this instance to use * @throws IllegalArgumentException if {@code generatedIdCache} is null */ public void setGeneratedIdCache(GeneratedIdCache generatedIdCache) { Preconditions.checkArgument(generatedIdCache != null, "null generatedIdCache"); this.generatedIdCache = generatedIdCache; } /** * Import objects pairs into the {@link Transaction} associated with this instance from the given XML input. * * <p> * The input format is auto-detected for each {@code <object>} based on the presense of the {@code "type"} attribute. * </p> * * @param input XML input * @return the number of objects read * @throws XMLStreamException if an error occurs * @throws IllegalArgumentException if {@code input} is null */ public int read(InputStream input) throws XMLStreamException { Preconditions.checkArgument(input != null, "null input"); return this.read(XMLInputFactory.newFactory().createXMLStreamReader(input)); } /** * Import objects into the {@link Transaction} associated with this instance from the given XML input. * This method expects to see an opening {@code <objects>} as the next event (not counting whitespace, comments, etc.), * which is then consumed up through the closing {@code </objects>} event. Therefore this tag could be part of a * larger XML document. * * <p> * The input format is auto-detected for each {@code <object>} based on the presense of the {@code "type"} attribute. * </p> * * @param reader XML reader * @return the number of objects read * @throws XMLStreamException if an error occurs * @throws IllegalArgumentException if {@code reader} is null */ @SuppressWarnings("unchecked") public int read(XMLStreamReader reader) throws XMLStreamException { Preconditions.checkArgument(reader != null, "null reader"); this.expect(reader, false, OBJECTS_TAG); // Create a snapshot transaction so we can replace objects without triggering DeleteAction's final SnapshotTransaction snapshot = this.tx.createSnapshotTransaction(); // Iterate over objects QName name; int count; for (count = 0; (name = this.next(reader)) != null; count++) { // Determine schema version final String versionAttr = this.getAttr(reader, VERSION_ATTR, false); final Schema schema; if (versionAttr != null) { try { schema = this.tx.getSchemas().getVersion(Integer.parseInt(versionAttr)); } catch (IllegalArgumentException e) { throw new XMLStreamException("invalid object schema version `" + versionAttr + "': " + e, reader.getLocation(), e); } } else schema = this.tx.getSchema(); final NameIndex nameIndex = this.nameIndexMap.get(schema.getVersionNumber()); final SchemaModel schemaModel = schema.getSchemaModel(); // Determine object type String storageIdAttr = this.getAttr(reader, STORAGE_ID_ATTR, false); ObjType objType = null; if (storageIdAttr != null) { try { objType = schema.getObjType(Integer.parseInt(storageIdAttr)); } catch (UnknownTypeException e) { throw new XMLStreamException("invalid object type storage ID `" + storageIdAttr + "': " + e, reader.getLocation(), e); } if (!name.equals(OBJECT_TAG)) { if (!XMLConstants.NULL_NS_URI.equals(name.getNamespaceURI())) { throw new XMLStreamException("unexpected element <" + name.getPrefix() + ":" + name.getLocalPart() + ">; expected <" + OBJECT_TAG.getLocalPart() + ">", reader.getLocation()); } if (!objType.getName().equals(name.getLocalPart())) { throw new XMLStreamException("element <" + name.getLocalPart() + "> does not match storage ID " + objType.getStorageId() + "; should be <" + objType.getName() + ">", reader.getLocation()); } } } else { if (!XMLConstants.NULL_NS_URI.equals(name.getNamespaceURI())) { throw new XMLStreamException("unexpected element <" + name.getPrefix() + ":" + name.getLocalPart() + ">; expected <object> or object type name", reader.getLocation()); } if (!name.equals(OBJECT_TAG)) { final SchemaObjectType schemaObjectType = nameIndex.getSchemaObjectType(name.getLocalPart()); if (schemaObjectType == null) { throw new XMLStreamException("unexpected element <" + name.getLocalPart() + ">; no object type named `" + name.getLocalPart() + "' found in schema version " + schema.getVersionNumber(), reader.getLocation()); } objType = schema.getObjType(schemaObjectType.getStorageId()); } } // Reset snapshot snapshot.reset(); // Determine object ID and create object in snapshot final String idAttr = this.getAttr(reader, ID_ATTR, true); ObjId id; if (idAttr == null) { // Verify we know object type if (objType == null) { throw new XMLStreamException("invalid <" + OBJECT_TAG.getLocalPart() + "> element: either \"" + STORAGE_ID_ATTR.getLocalPart() + "\" or \"" + ID_ATTR.getLocalPart() + "\" attribute is required", reader.getLocation()); } // Create object id = snapshot.create(objType.getStorageId(), schema.getVersionNumber()); } else { // Parse id try { id = new ObjId(idAttr); } catch (IllegalArgumentException e) { final Matcher matcher = GENERATED_ID_PATTERN.matcher(idAttr); if (!matcher.matches()) throw new XMLStreamException("invalid object ID `" + idAttr + "'", reader.getLocation()); final String typeAttr = matcher.group(1); final ObjType genType = this.parseGeneratedType(reader, idAttr, typeAttr, schema); if (objType == null) objType = genType; else if (!genType.equals(objType)) { throw new XMLStreamException("type `" + typeAttr + "' in generated object ID `" + idAttr + "' does not match type `" + objType.getName() + "' in schema version " + schema.getVersionNumber(), reader.getLocation()); } id = this.generatedIdCache.getGeneratedId(this.tx, objType.getStorageId(), matcher.group(2)); } // Create object snapshot.create(id, schema.getVersionNumber()); } // Iterate over fields final SchemaObjectType schemaObjectType = schemaModel.getSchemaObjectTypes().get(objType.getStorageId()); while ((name = this.next(reader)) != null) { final QName fieldTagName = name; // Determine the field storageIdAttr = this.getAttr(reader, STORAGE_ID_ATTR, false); final Field<?> field; if (storageIdAttr != null) { try { field = objType.getFields().get(Integer.parseInt(storageIdAttr)); } catch (IllegalArgumentException e) { throw new XMLStreamException("invalid field storage ID `" + storageIdAttr + "': " + e, reader.getLocation(), e); } if (field == null) { throw new XMLStreamException("unknown field storage ID `" + storageIdAttr + "' for object type `" + objType.getName() + "' #" + objType.getStorageId() + " in schema version " + schema.getVersionNumber(), reader.getLocation()); } } else { if (!XMLConstants.NULL_NS_URI.equals(name.getNamespaceURI())) { throw new XMLStreamException("unexpected element <" + name.getPrefix() + ":" + name.getLocalPart() + ">; expected field name", reader.getLocation()); } final SchemaField schemaField = nameIndex.getSchemaField(schemaObjectType, name.getLocalPart()); if (schemaField == null) { throw new XMLStreamException("unexpected element <" + name.getLocalPart() + ">; unknown field `" + name.getLocalPart() + "' in object type `" + objType.getName() + "' #" + objType.getStorageId() + " in schema version " + schema.getVersionNumber(), reader.getLocation()); } field = objType.getFields().get(schemaField.getStorageId()); assert field != null : "field=" + schemaField + " fields=" + objType.getFields(); } // Parse the field if (field instanceof SimpleField) snapshot.writeSimpleField(id, field.getStorageId(), this.readSimpleField(reader, (SimpleField<?>)field), false); else if (field instanceof CounterField) { final long value; try { value = Long.parseLong(reader.getElementText()); } catch (Exception e) { throw new XMLStreamException("invalid counter value for field `" + field.getName() + "': " + e, reader.getLocation(), e); } snapshot.writeCounterField(id, field.getStorageId(), value, false); } else if (field instanceof CollectionField) { final SimpleField<?> elementField = ((CollectionField<?, ?>)field).getElementField(); final Collection<?> collection; if (field instanceof SetField) collection = snapshot.readSetField(id, field.getStorageId(), false); else if (field instanceof ListField) collection = snapshot.readListField(id, field.getStorageId(), false); else throw new RuntimeException("internal error: " + field); while ((name = this.next(reader)) != null) { if (!ELEMENT_TAG.equals(name)) { throw new XMLStreamException("invalid field element; expected <" + ELEMENT_TAG.getLocalPart() + "> but found opening <" + name.getLocalPart() + ">", reader.getLocation()); } ((Collection<Object>)collection).add(this.readSimpleField(reader, elementField)); } } else if (field instanceof MapField) { final SimpleField<?> keyField = ((MapField<?, ?>)field).getKeyField(); final SimpleField<?> valueField = ((MapField<?, ?>)field).getValueField(); final Map<?, ?> map = snapshot.readMapField(id, field.getStorageId(), false); while ((name = this.next(reader)) != null) { if (!ENTRY_TAG.equals(name)) { throw new XMLStreamException("invalid map field entry; expected <" + ENTRY_TAG.getLocalPart() + "> but found opening <" + name.getLocalPart() + ">", reader.getLocation()); } if (!KEY_TAG.equals(this.next(reader))) { throw new XMLStreamException("invalid map entry key; expected <" + KEY_TAG.getLocalPart() + ">", reader.getLocation()); } final Object key = this.readSimpleField(reader, keyField); if (!VALUE_TAG.equals(this.next(reader))) { throw new XMLStreamException("invalid map entry value; expected <" + VALUE_TAG.getLocalPart() + ">", reader.getLocation()); } final Object value = this.readSimpleField(reader, valueField); ((Map<Object, Object>)map).put(key, value); if ((name = this.next(reader)) != null) { throw new XMLStreamException("invalid map field entry; expected closing <" + ENTRY_TAG.getLocalPart() + "> but found opening <" + name.getLocalPart() + ">", reader.getLocation()); } } } else throw new RuntimeException("internal error: " + field); } // Copy over object, replacing any previous snapshot.copy(id, id, this.tx, false); } // Done return count; } /** * Export all objects from the {@link Transaction} associated with this instance to the given output. * * @param output XML output; will not be closed by this method * @param nameFormat true for Name Format, false for Storage ID Format * @param indent true to indent output, false for all on one line * @return the number of objects written * @throws XMLStreamException if an error occurs * @throws IllegalArgumentException if {@code output} is null */ public int write(OutputStream output, boolean nameFormat, boolean indent) throws XMLStreamException { Preconditions.checkArgument(output != null, "null output"); XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(output, "UTF-8"); if (indent) xmlWriter = new IndentXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("UTF-8", "1.0"); return this.write(xmlWriter, nameFormat); } /** * Export all objects from the {@link Transaction} associated with this instance to the given writer. * * @param writer XML output; will not be closed by this method * @param nameFormat true for Name Format, false for Storage ID Format * @param indent true to indent output, false for all on one line * @return the number of objects written * @throws XMLStreamException if an error occurs * @throws IllegalArgumentException if {@code writer} is null */ public int write(Writer writer, boolean nameFormat, boolean indent) throws XMLStreamException { Preconditions.checkArgument(writer != null, "null writer"); XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); if (indent) xmlWriter = new IndentXMLStreamWriter(xmlWriter); xmlWriter.writeStartDocument("1.0"); return this.write(xmlWriter, nameFormat); } private int write(XMLStreamWriter writer, boolean nameFormat) throws XMLStreamException { // Gather all known object storage IDs final TreeSet<Integer> storageIds = new TreeSet<>(); for (Schema schema : this.tx.getSchemas().getVersions().values()) storageIds.addAll(schema.getSchemaModel().getSchemaObjectTypes().keySet()); // Get corresponding iterators final ArrayList<NavigableSet<ObjId>> sets = new ArrayList<>(storageIds.size()); for (int storageId : storageIds) sets.add(this.tx.getAll(storageId)); // Output all objects return this.write(writer, nameFormat, Iterables.concat(sets)); } /** * Export the given objects from the {@link Transaction} associated with this instance to the given XML output. * * <p> * This method writes a start element as its first action, allowing the output to be embedded into a larger XML document. * Callers not embedding the output may with to precede invocation of this method with a call to * {@link XMLStreamWriter#writeStartDocument writer.writeStartDocument()}. * </p> * * @param writer XML writer; will not be closed by this method * @param nameFormat true for Name Format, false for Storage ID Format * @param objIds object IDs * @return the number of objects written * @throws XMLStreamException if an error occurs * @throws IllegalArgumentException if {@code writer} is null */ public int write(XMLStreamWriter writer, boolean nameFormat, Iterable<? extends ObjId> objIds) throws XMLStreamException { Preconditions.checkArgument(writer != null, "null writer"); Preconditions.checkArgument(objIds != null, "null objIds"); final NameComparator nameComparator = new NameComparator(); writer.setDefaultNamespace(OBJECTS_TAG.getNamespaceURI()); writer.writeStartElement(OBJECTS_TAG.getNamespaceURI(), OBJECTS_TAG.getLocalPart()); int count = 0; for (ObjId id : objIds) { // Get object info final int typeStorageId = id.getStorageId(); final int version = this.tx.getSchemaVersion(id); final Schema schema = this.tx.getSchemas().getVersion(version); final ObjType objType = schema.getObjType(typeStorageId); // Get format info final QName objectElement = nameFormat ? new QName(objType.getName()) : OBJECT_TAG; final int storageIdAttr = nameFormat ? -1 : typeStorageId; // Output fields; if all are default, output empty tag boolean tagOutput = false; ArrayList<Field<?>> fieldList = new ArrayList<>(objType.getFields().values()); if (nameFormat) Collections.sort(fieldList, nameComparator); for (Field<?> field : fieldList) { // Determine if field equals its default value; if so, skip it if (field.hasDefaultValue(this.tx, id)) continue; // Output <object> opening tag if not output yet if (!tagOutput) { this.writeOpenTag(writer, false, objectElement, storageIdAttr, id, version); tagOutput = true; } // Get tag name final QName fieldTag = nameFormat ? new QName(field.getName()) : FIELD_TAG; // Special case for simple fields, which use empty tags when null if (field instanceof SimpleField) { final Object value = this.tx.readSimpleField(id, field.getStorageId(), false); if (value != null) writer.writeStartElement(fieldTag.getNamespaceURI(), fieldTag.getLocalPart()); else writer.writeEmptyElement(fieldTag.getNamespaceURI(), fieldTag.getLocalPart()); if (!nameFormat) this.writeAttribute(writer, STORAGE_ID_ATTR, field.getStorageId()); if (value != null) { this.writeSimpleField(writer, (SimpleField<?>)field, value); writer.writeEndElement(); } else this.writeAttribute(writer, NULL_ATTR, "true"); continue; } // Output field opening tag writer.writeStartElement(fieldTag.getNamespaceURI(), fieldTag.getLocalPart()); if (!nameFormat) this.writeAttribute(writer, STORAGE_ID_ATTR, field.getStorageId()); // Output field value if (field instanceof CounterField) writer.writeCharacters("" + this.tx.readCounterField(id, field.getStorageId(), false)); else if (field instanceof CollectionField) { final SimpleField<?> elementField = ((CollectionField<?, ?>)field).getElementField(); final Iterable<?> collection = field instanceof SetField ? this.tx.readSetField(id, field.getStorageId(), false) : this.tx.readListField(id, field.getStorageId(), false); for (Object element : collection) this.writeSimpleTag(writer, ELEMENT_TAG, elementField, element); } else if (field instanceof MapField) { final SimpleField<?> keyField = ((MapField<?, ?>)field).getKeyField(); final SimpleField<?> valueField = ((MapField<?, ?>)field).getValueField(); for (Map.Entry<?, ?> entry : this.tx.readMapField(id, field.getStorageId(), false).entrySet()) { writer.writeStartElement(ENTRY_TAG.getNamespaceURI(), ENTRY_TAG.getLocalPart()); this.writeSimpleTag(writer, KEY_TAG, keyField, entry.getKey()); this.writeSimpleTag(writer, VALUE_TAG, valueField, entry.getValue()); writer.writeEndElement(); } } else throw new RuntimeException("internal error: " + field); // Output field closing tag writer.writeEndElement(); } // Output empty opening tag if not output yet, otherwise closing tag if (!tagOutput) this.writeOpenTag(writer, true, objectElement, storageIdAttr, id, version); else writer.writeEndElement(); count++; } // Done writer.writeEndElement(); writer.flush(); return count; } // Internal methods private <T> boolean isDefaultValue(SimpleField<T> field, Object value) throws XMLStreamException { final ByteWriter writer = new ByteWriter(); final FieldType<T> fieldType = field.getFieldType(); fieldType.write(writer, fieldType.validate(value)); return Arrays.equals(writer.getBytes(), field.getFieldType().getDefaultValue()); } private void writeSimpleTag(XMLStreamWriter writer, QName tag, SimpleField<?> field, Object value) throws XMLStreamException { if (value != null) { writer.writeStartElement(tag.getNamespaceURI(), tag.getLocalPart()); this.writeSimpleField(writer, field, value); writer.writeEndElement(); } else { writer.writeEmptyElement(tag.getNamespaceURI(), tag.getLocalPart()); this.writeAttribute(writer, NULL_ATTR, "true"); } } private <T> void writeSimpleField(XMLStreamWriter writer, SimpleField<T> field, Object value) throws XMLStreamException { final FieldType<T> fieldType = field.getFieldType(); writer.writeCharacters(fieldType.toString(fieldType.validate(value))); } private <T> T readSimpleField(XMLStreamReader reader, SimpleField<T> field) throws XMLStreamException { // Get field type final FieldType<T> fieldType = field.getFieldType(); // Check for null final String nullAttr = this.getAttr(reader, NULL_ATTR, false); boolean isNull = false; if (nullAttr != null) { switch (nullAttr) { case "true": case "false": isNull = Boolean.valueOf(nullAttr); break; default: throw new XMLStreamException("invalid value `" + nullAttr + "' for `" + NULL_ATTR.getLocalPart() + "' attribute: value must be \"true\" or \"false\"", reader.getLocation()); } } // Get text content final String text; try { text = reader.getElementText(); } catch (Exception e) { throw new XMLStreamException("invalid value for field `" + field.getName() + "': " + e, reader.getLocation(), e); } // If null, verify there is no text content if (isNull) { if (text.length() != 0) throw new XMLStreamException("text content not allowed for values with null=\"true\"", reader.getLocation()); return null; } // Handle generated ID's for reference fields if (field instanceof ReferenceField) { final Matcher matcher = GENERATED_ID_PATTERN.matcher(text); if (matcher.matches()) { final int storageId = this.parseGeneratedType(reader, text, matcher.group(1)); return fieldType.validate(this.generatedIdCache.getGeneratedId(this.tx, storageId, matcher.group(2))); } } // Parse field value try { return fieldType.fromString(text); } catch (Exception e) { throw new XMLStreamException("invalid value `" + text + "' for field `" + field.getName() + "': " + e, reader.getLocation(), e); } } // Parse a generated ID type found in a reference private int parseGeneratedType(XMLStreamReader reader, String text, String attr) throws XMLStreamException { int storageId = -1; for (Schema schema : this.tx.getSchemas().getVersions().values()) { final ObjType objType; try { objType = this.parseGeneratedType(reader, text, attr, schema); } catch (XMLStreamException e) { continue; } if (storageId != -1 && storageId != objType.getStorageId()) { throw new XMLStreamException("invalid object type `" + attr + "' in generated object ID `" + text + "': two or more incompatible object types named `" + attr + "' exist (in different schema versions)", reader.getLocation()); } storageId = objType.getStorageId(); } if (storageId == -1) { throw new XMLStreamException("invalid object type `" + attr + "' in generated object ID `" + text + "': no such object type found in any schema version", reader.getLocation()); } return storageId; } // Parse a generated ID type found in an object definition private ObjType parseGeneratedType(XMLStreamReader reader, String text, String attr, Schema schema) throws XMLStreamException { // Try object type name final NameIndex nameIndex = this.nameIndexMap.get(schema.getVersionNumber()); final SchemaObjectType schemaObjectType = nameIndex.getSchemaObjectType(attr); if (schemaObjectType != null) return schema.getObjType(schemaObjectType.getStorageId()); // Try storage ID final int storageId; try { storageId = Integer.parseInt(attr); } catch (IllegalArgumentException e) { throw new XMLStreamException("invalid object type `" + attr + "' in generated object ID `" + text + "': no such object type found in schema version " + schema.getVersionNumber(), reader.getLocation()); } try { return schema.getObjType(storageId); } catch (UnknownTypeException e) { throw new XMLStreamException("invalid storage ID " + storageId + " in generated object ID `" + text + "': no such object type found in schema version " + schema.getVersionNumber(), reader.getLocation()); } } private void writeOpenTag(XMLStreamWriter writer, boolean empty, QName element, int storageId, ObjId id, int version) throws XMLStreamException { if (empty) writer.writeEmptyElement(element.getNamespaceURI(), element.getLocalPart()); else writer.writeStartElement(element.getNamespaceURI(), element.getLocalPart()); if (storageId != -1) this.writeAttribute(writer, STORAGE_ID_ATTR, storageId); this.writeAttribute(writer, ID_ATTR, id); this.writeAttribute(writer, VERSION_ATTR, version); } private void writeAttribute(XMLStreamWriter writer, QName attr, Object value) throws XMLStreamException { writer.writeAttribute(attr.getNamespaceURI(), attr.getLocalPart(), "" + value); } private QName next(XMLStreamReader reader) throws XMLStreamException { while (true) { if (!reader.hasNext()) throw new XMLStreamException("unexpected end of input", reader.getLocation()); final int eventType = reader.next(); if (eventType == XMLStreamConstants.END_ELEMENT) return null; if (eventType == XMLStreamConstants.START_ELEMENT) return reader.getName(); } } // NameComparator private static class NameComparator implements Comparator<SchemaItem> { @Override public int compare(SchemaItem item1, SchemaItem item2) { return item1.getName().compareTo(item2.getName()); } } }
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.getroadmap.r2rlib.parser; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; /** * Adapts values whose runtime type may differ from their declaration type. This * is necessary when a field's type is not the same type that GSON should create * when deserializing that field. For example, consider these types: * <pre> {@code * abstract class Shape { * int x; * int y; * } * class Circle extends Shape { * int radius; * } * class Rectangle extends Shape { * int width; * int height; * } * class Diamond extends Shape { * int width; * int height; * } * class Drawing { * Shape bottomShape; * Shape topShape; * } * }</pre> * <p>Without additional type information, the serialized JSON is ambiguous. Is * the bottom shape in this drawing a rectangle or a diamond? <pre> {@code * { * "bottomShape": { * "width": 10, * "height": 5, * "x": 0, * "y": 0 * }, * "topShape": { * "radius": 2, * "x": 4, * "y": 1 * } * }}</pre> * This class addresses this problem by adding type information to the * serialized JSON and honoring that type information when the JSON is * deserialized: <pre> {@code * { * "bottomShape": { * "type": "Diamond", * "width": 10, * "height": 5, * "x": 0, * "y": 0 * }, * "topShape": { * "type": "Circle", * "radius": 2, * "x": 4, * "y": 1 * } * }}</pre> * Both the type field name ({@code "type"}) and the type labels ({@code * "Rectangle"}) are configurable. * * <h3>Registering Types</h3> * Create a {@code RuntimeTypeAdapterFactory} by passing the base type and type field * name to the {@link #of} factory method. If you don't supply an explicit type * field name, {@code "type"} will be used. <pre> {@code * RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory * = RuntimeTypeAdapterFactory.of(Shape.class, "type"); * }</pre> * Next register all of your subtypes. Every subtype must be explicitly * registered. This protects your application from injection attacks. If you * don't supply an explicit type label, the type's simple name will be used. * <pre> {@code * shapeAdapter.registerSubtype(Rectangle.class, "Rectangle"); * shapeAdapter.registerSubtype(Circle.class, "Circle"); * shapeAdapter.registerSubtype(Diamond.class, "Diamond"); * }</pre> * Finally, register the type adapter factory in your application's GSON builder: * <pre> {@code * Gson gson = new GsonBuilder() * .registerTypeAdapterFactory(shapeAdapterFactory) * .create(); * }</pre> * Like {@code GsonBuilder}, this API supports chaining: <pre> {@code * RuntimeTypeAdapterFactory<Shape> shapeAdapterFactory = RuntimeTypeAdapterFactory.of(Shape.class) * .registerSubtype(Rectangle.class) * .registerSubtype(Circle.class) * .registerSubtype(Diamond.class); * }</pre> */ public final class RuntimeTypeAdapterFactory<T> implements TypeAdapterFactory { private final Class<?> baseType; private final String typeFieldName; private final Map<String, Class<?>> labelToSubtype = new LinkedHashMap<String, Class<?>>(); private final Map<Class<?>, String> subtypeToLabel = new LinkedHashMap<Class<?>, String>(); private RuntimeTypeAdapterFactory(Class<?> baseType, String typeFieldName) { if (typeFieldName == null || baseType == null) { throw new NullPointerException(); } this.baseType = baseType; this.typeFieldName = typeFieldName; } /** * Creates a new runtime type adapter using for {@code baseType} using {@code * typeFieldName} as the type field name. Type field names are case sensitive. */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType, String typeFieldName) { return new RuntimeTypeAdapterFactory<T>(baseType, typeFieldName); } /** * Creates a new runtime type adapter for {@code baseType} using {@code "type"} as * the type field name. */ public static <T> RuntimeTypeAdapterFactory<T> of(Class<T> baseType) { return new RuntimeTypeAdapterFactory<T>(baseType, "type"); } /** * Registers {@code type} identified by {@code label}. Labels are case * sensitive. * * @throws IllegalArgumentException if either {@code type} or {@code label} * have already been registered on this type adapter. */ public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type, String label) { if (type == null || label == null) { throw new NullPointerException(); } if (subtypeToLabel.containsKey(type) || labelToSubtype.containsKey(label)) { throw new IllegalArgumentException("types and labels must be unique"); } labelToSubtype.put(label, type); subtypeToLabel.put(type, label); return this; } /** * Registers {@code type} identified by its {@link Class#getSimpleName simple * name}. Labels are case sensitive. * * @throws IllegalArgumentException if either {@code type} or its simple name * have already been registered on this type adapter. */ public RuntimeTypeAdapterFactory<T> registerSubtype(Class<? extends T> type) { return registerSubtype(type, type.getSimpleName()); } public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; } final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>(); final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>(); for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) { TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue())); labelToDelegate.put(entry.getKey(), delegate); subtypeToDelegate.put(entry.getValue(), delegate); } return new TypeAdapter<R>() { @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName); if (labelJsonElement == null) { throw new JsonParseException("cannot deserialize " + baseType + " because it does not define a field named " + typeFieldName); } String label = labelJsonElement.getAsString(); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label); if (delegate == null) { throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label + "; did you forget to register a subtype?"); } return delegate.fromJsonTree(jsonElement); } @Override public void write(JsonWriter out, R value) throws IOException { Class<?> srcType = value.getClass(); String label = subtypeToLabel.get(srcType); @SuppressWarnings("unchecked") // registration requires that subtype extends T TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType); if (delegate == null) { throw new JsonParseException("cannot serialize " + srcType.getName() + "; did you forget to register a subtype?"); } JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject(); if (jsonObject.has(typeFieldName)) { throw new JsonParseException("cannot serialize " + srcType.getName() + " because it already defines a field named " + typeFieldName); } JsonObject clone = new JsonObject(); clone.add(typeFieldName, new JsonPrimitive(label)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } }.nullSafe(); } }
/* * Copyright (c) 2015 Spotify AB. * * 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.spotify.heroic.aggregation; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.spotify.heroic.common.DateRange; import com.spotify.heroic.common.Series; import com.spotify.heroic.common.Statistics; import com.spotify.heroic.metric.Event; import com.spotify.heroic.metric.Metric; import com.spotify.heroic.metric.MetricCollection; import com.spotify.heroic.metric.MetricGroup; import com.spotify.heroic.metric.MetricType; import com.spotify.heroic.metric.Point; import com.spotify.heroic.metric.ShardedResultGroup; import com.spotify.heroic.metric.Spread; import com.spotify.heroic.metric.TagValues; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.ToString; @Data @EqualsAndHashCode(of = { "of", "each" }) public abstract class GroupingAggregation implements AggregationInstance { private final Optional<List<String>> of; private final AggregationInstance each; public GroupingAggregation(final Optional<List<String>> of, final AggregationInstance each) { this.of = of; this.each = checkNotNull(each, "each"); } /** * Generate a key for the specific group. * * @param input The input tags for the group. * @return The keys for a specific group. */ protected abstract Map<String, String> key(final Map<String, String> input); /** * Create a new instance of this aggregation. */ protected abstract AggregationInstance newInstance(final Optional<List<String>> of, final AggregationInstance each); @Override public AggregationTraversal session(List<AggregationState> states, DateRange range) { return traversal(map(states), range); } /** * Traverse the given input states, and map them to their corresponding keys. * * @param states Input states to map. * @return A mapping for the group key, to a set of series. */ Map<Map<String, String>, Set<Series>> map(final List<AggregationState> states) { final Map<Map<String, String>, Set<Series>> output = new HashMap<>(); for (final AggregationState state : states) { final Map<String, String> k = key(state.getKey()); Set<Series> series = output.get(k); if (series == null) { series = new HashSet<Series>(); output.put(k, series); } series.addAll(state.getSeries()); } return output; } /** * Setup traversal and the corresponding session from the given mapping. * * @param mapping The mapping of series. * @param range The range to setup child sessions using. * @return A new traversal instance. */ AggregationTraversal traversal(final Map<Map<String, String>, Set<Series>> mapping, final DateRange range) { final Map<Map<String, String>, AggregationSession> sessions = new HashMap<>(); final List<AggregationState> states = new ArrayList<>(); for (final Map.Entry<Map<String, String>, Set<Series>> e : mapping.entrySet()) { final Set<Series> series = new HashSet<>(); final AggregationTraversal traversal = each.session( ImmutableList.of(new AggregationState(e.getKey(), e.getValue())), range); for (final AggregationState state : traversal.getStates()) { series.addAll(state.getSeries()); } sessions.put(e.getKey(), traversal.getSession()); states.add(new AggregationState(e.getKey(), series)); } return new AggregationTraversal(states, new GroupSession(sessions)); } @Override public long estimate(DateRange range) { return each.estimate(range); } @Override public long cadence() { return each.cadence(); } @Override public AggregationInstance distributed() { return newInstance(of, each.distributed()); } @Override public ReducerSession reducer(final DateRange range) { return each.reducer(range); } @Override public AggregationCombiner combiner(final DateRange range) { return new AggregationCombiner() { @Override public List<ShardedResultGroup> combine(final List<List<ShardedResultGroup>> all) { final Map<Map<String, String>, Reduction> sessions = new HashMap<>(); // combine all the tags. final Iterator<ShardedResultGroup> step1 = Iterators.concat(Iterators.transform(all.iterator(), Iterable::iterator)); while (step1.hasNext()) { final ShardedResultGroup g = step1.next(); final Map<String, String> key = key(TagValues.mapOfSingles(g.getTags())); Reduction red = sessions.get(key); if (red == null) { red = new Reduction(each.reducer(range)); sessions.put(key, red); } g.getGroup().updateReducer(red.session, key); red.tagValues.add(g.getTags().iterator()); } final ImmutableList.Builder<ShardedResultGroup> groups = ImmutableList.builder(); for (final Map.Entry<Map<String, String>, Reduction> e : sessions.entrySet()) { final Reduction red = e.getValue(); final ReducerSession session = red.session; final List<TagValues> tagValues = TagValues.fromEntries(Iterators .concat(Iterators.transform(Iterators.concat(red.tagValues.iterator()), TagValues::iterator))); for (final MetricCollection metrics : session.result().getResult()) { groups.add(new ShardedResultGroup(e.getKey(), tagValues, metrics, each.cadence())); } } return groups.build(); } }; } @Override public String toString() { return String.format("%s(of=%s, each=%s)", getClass().getSimpleName(), of, each); } @Data private final class Reduction { private final ReducerSession session; private final List<Iterator<TagValues>> tagValues = new ArrayList<>(); } @ToString @RequiredArgsConstructor private final class GroupSession implements AggregationSession { private final Map<Map<String, String>, AggregationSession> sessions; @Override public void updatePoints(Map<String, String> group, Set<Series> series, List<Point> values) { session(group).updatePoints(group, series, values); } @Override public void updateEvents(Map<String, String> group, Set<Series> series, List<Event> values) { session(group).updateEvents(group, series, values); } @Override public void updateSpreads(Map<String, String> group, Set<Series> series, List<Spread> values) { session(group).updateSpreads(group, series, values); } @Override public void updateGroup(Map<String, String> group, Set<Series> series, List<MetricGroup> values) { session(group).updateGroup(group, series, values); } private AggregationSession session(final Map<String, String> group) { final Map<String, String> key = key(group); final AggregationSession session = sessions.get(key); if (session == null) { throw new IllegalStateException( String.format("no session for key (%s) derived from %s, has (%s)", key, group, sessions.keySet())); } return session; } @Override public AggregationResult result() { final Map<ResultKey, ResultValues> groups = new HashMap<>(); Statistics statistics = Statistics.empty(); for (final Map.Entry<Map<String, String>, AggregationSession> e : sessions.entrySet()) { final AggregationResult r = e.getValue().result(); statistics = statistics.merge(r.getStatistics()); for (final AggregationData data : r.getResult()) { final MetricCollection metrics = data.getMetrics(); final ResultKey key = new ResultKey(e.getKey(), metrics.getType()); ResultValues result = groups.get(key); if (result == null) { result = new ResultValues(); groups.put(key, result); } result.series.addAll(data.getSeries()); result.values.add(metrics.getData()); } } final List<AggregationData> data = new ArrayList<>(); for (final Map.Entry<ResultKey, ResultValues> e : groups.entrySet()) { final ResultKey k = e.getKey(); final ResultValues v = e.getValue(); final MetricCollection metrics = MetricCollection.mergeSorted(k.type, v.values); data.add(new AggregationData(k.group, v.series, metrics)); } return new AggregationResult(data, statistics); } } @Data private static class ResultKey { final Map<String, String> group; final MetricType type; } private static class ResultValues { final Set<Series> series = new HashSet<>(); final List<List<? extends Metric>> values = new ArrayList<>(); } }
/* * Copyright 2012 Sebastian Annies, Hamburg * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an AS IS BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.mp4parser.authoring.builder; import com.coremedia.iso.BoxParser; import com.coremedia.iso.IsoFile; import com.coremedia.iso.IsoTypeWriter; import com.coremedia.iso.boxes.*; import com.googlecode.mp4parser.BasicContainer; import com.googlecode.mp4parser.DataSource; import com.googlecode.mp4parser.authoring.Edit; import com.googlecode.mp4parser.authoring.Movie; import com.googlecode.mp4parser.authoring.Sample; import com.googlecode.mp4parser.authoring.Track; import com.googlecode.mp4parser.authoring.tracks.CencEncryptedTrack; import com.googlecode.mp4parser.boxes.dece.SampleEncryptionBox; import com.googlecode.mp4parser.boxes.mp4.samplegrouping.GroupEntry; import com.googlecode.mp4parser.boxes.mp4.samplegrouping.SampleGroupDescriptionBox; import com.googlecode.mp4parser.boxes.mp4.samplegrouping.SampleToGroupBox; import com.googlecode.mp4parser.util.Path; import com.mp4parser.iso14496.part12.SampleAuxiliaryInformationOffsetsBox; import com.mp4parser.iso14496.part12.SampleAuxiliaryInformationSizesBox; import com.mp4parser.iso23001.part7.CencSampleAuxiliaryDataFormat; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import static com.googlecode.mp4parser.util.CastUtils.l2i; /** * Creates a plain MP4 file from a video. Plain as plain can be. */ public class DefaultMp4Builder implements Mp4Builder { private static Logger LOG = Logger.getLogger(DefaultMp4Builder.class.getName()); Set<StaticChunkOffsetBox> chunkOffsetBoxes = new HashSet<StaticChunkOffsetBox>(); Set<SampleAuxiliaryInformationOffsetsBox> sampleAuxiliaryInformationOffsetsBoxes = new HashSet<SampleAuxiliaryInformationOffsetsBox>(); HashMap<Track, List<Sample>> track2Sample = new HashMap<Track, List<Sample>>(); HashMap<Track, long[]> track2SampleSizes = new HashMap<Track, long[]>(); private FragmentIntersectionFinder intersectionFinder; private static long sum(int[] ls) { long rc = 0; for (long l : ls) { rc += l; } return rc; } private static long sum(long[] ls) { long rc = 0; for (long l : ls) { rc += l; } return rc; } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public void setIntersectionFinder(FragmentIntersectionFinder intersectionFinder) { this.intersectionFinder = intersectionFinder; } /** * {@inheritDoc} */ public Container build(Movie movie) { if (intersectionFinder == null) { intersectionFinder = new TwoSecondIntersectionFinder(movie, 2); } LOG.fine("Creating movie " + movie); for (Track track : movie.getTracks()) { // getting the samples may be a time consuming activity List<Sample> samples = track.getSamples(); putSamples(track, samples); long[] sizes = new long[samples.size()]; for (int i = 0; i < sizes.length; i++) { Sample b = samples.get(i); sizes[i] = b.getSize(); } track2SampleSizes.put(track, sizes); } BasicContainer isoFile = new BasicContainer(); isoFile.addBox(createFileTypeBox(movie)); Map<Track, int[]> chunks = new HashMap<Track, int[]>(); for (Track track : movie.getTracks()) { chunks.put(track, getChunkSizes(track, movie)); } Box moov = createMovieBox(movie, chunks); isoFile.addBox(moov); List<SampleSizeBox> stszs = Path.getPaths(moov, "trak/mdia/minf/stbl/stsz"); long contentSize = 0; for (SampleSizeBox stsz : stszs) { contentSize += sum(stsz.getSampleSizes()); } InterleaveChunkMdat mdat = new InterleaveChunkMdat(movie, chunks, contentSize); isoFile.addBox(mdat); /* dataOffset is where the first sample starts. In this special mdat the samples always start at offset 16 so that we can use the same offset for large boxes and small boxes */ long dataOffset = mdat.getDataOffset(); for (StaticChunkOffsetBox chunkOffsetBox : chunkOffsetBoxes) { long[] offsets = chunkOffsetBox.getChunkOffsets(); for (int i = 0; i < offsets.length; i++) { offsets[i] += dataOffset; } } for (SampleAuxiliaryInformationOffsetsBox saio : sampleAuxiliaryInformationOffsetsBoxes) { long offset = saio.getSize(); // the calculation is systematically wrong by 4, I don't want to debug why. Just a quick correction --san 14.May.13 offset += 4 + 4 + 4 + 4 + 4 + 24; // size of all header we were missing otherwise (moov, trak, mdia, minf, stbl) Object b = saio; do { Object current = b; b = ((Box) b).getParent(); for (Box box : ((Container) b).getBoxes()) { if (box == current) { break; } offset += box.getSize(); } } while (b instanceof Box); long[] saioOffsets = saio.getOffsets(); for (int i = 0; i < saioOffsets.length; i++) { saioOffsets[i] = saioOffsets[i] + offset; } saio.setOffsets(saioOffsets); } return isoFile; } protected List<Sample> putSamples(Track track, List<Sample> samples) { return track2Sample.put(track, samples); } protected FileTypeBox createFileTypeBox(Movie movie) { List<String> minorBrands = new LinkedList<String>(); minorBrands.add("isom"); minorBrands.add("iso2"); minorBrands.add("avc1"); return new FileTypeBox("isom", 0, minorBrands); } protected MovieBox createMovieBox(Movie movie, Map<Track, int[]> chunks) { MovieBox movieBox = new MovieBox(); MovieHeaderBox mvhd = new MovieHeaderBox(); mvhd.setCreationTime(new Date()); mvhd.setModificationTime(new Date()); mvhd.setMatrix(movie.getMatrix()); long movieTimeScale = getTimescale(movie); long duration = 0; for (Track track : movie.getTracks()) { long tracksDuration = 0; if (track.getEdits() == null || track.getEdits().isEmpty()) { tracksDuration = (track.getDuration() * getTimescale(movie) / track.getTrackMetaData().getTimescale()); } else { long d = 0; for (Edit edit : track.getEdits()) { d += (long) edit.getSegmentDuration(); } tracksDuration = (d * getTimescale(movie)); } if (tracksDuration > duration) { duration = tracksDuration; } } mvhd.setDuration(duration); mvhd.setTimescale(movieTimeScale); // find the next available trackId long nextTrackId = 0; for (Track track : movie.getTracks()) { nextTrackId = nextTrackId < track.getTrackMetaData().getTrackId() ? track.getTrackMetaData().getTrackId() : nextTrackId; } mvhd.setNextTrackId(++nextTrackId); movieBox.addBox(mvhd); for (Track track : movie.getTracks()) { movieBox.addBox(createTrackBox(track, movie, chunks)); } // metadata here Box udta = createUdta(movie); if (udta != null) { movieBox.addBox(udta); } return movieBox; } /** * Override to create a user data box that may contain metadata. * * @param movie source movie * @return a 'udta' box or <code>null</code> if none provided */ protected Box createUdta(Movie movie) { return null; } protected TrackBox createTrackBox(Track track, Movie movie, Map<Track, int[]> chunks) { TrackBox trackBox = new TrackBox(); TrackHeaderBox tkhd = new TrackHeaderBox(); tkhd.setEnabled(true); tkhd.setInMovie(true); tkhd.setInPreview(true); tkhd.setInPoster(true); tkhd.setMatrix(track.getTrackMetaData().getMatrix()); tkhd.setAlternateGroup(track.getTrackMetaData().getGroup()); tkhd.setCreationTime(track.getTrackMetaData().getCreationTime()); if (track.getEdits() == null || track.getEdits().isEmpty()) { tkhd.setDuration(track.getDuration() * getTimescale(movie) / track.getTrackMetaData().getTimescale()); } else { long d = 0; for (Edit edit : track.getEdits()) { d += (long) edit.getSegmentDuration(); } tkhd.setDuration(d * track.getTrackMetaData().getTimescale()); } tkhd.setHeight(track.getTrackMetaData().getHeight()); tkhd.setWidth(track.getTrackMetaData().getWidth()); tkhd.setLayer(track.getTrackMetaData().getLayer()); tkhd.setModificationTime(new Date()); tkhd.setTrackId(track.getTrackMetaData().getTrackId()); tkhd.setVolume(track.getTrackMetaData().getVolume()); trackBox.addBox(tkhd); trackBox.addBox(createEdts(track, movie)); MediaBox mdia = new MediaBox(); trackBox.addBox(mdia); MediaHeaderBox mdhd = new MediaHeaderBox(); mdhd.setCreationTime(track.getTrackMetaData().getCreationTime()); mdhd.setDuration(track.getDuration()); mdhd.setTimescale(track.getTrackMetaData().getTimescale()); mdhd.setLanguage(track.getTrackMetaData().getLanguage()); mdia.addBox(mdhd); HandlerBox hdlr = new HandlerBox(); mdia.addBox(hdlr); hdlr.setHandlerType(track.getHandler()); MediaInformationBox minf = new MediaInformationBox(); if (track.getHandler().equals("vide")) { minf.addBox(new VideoMediaHeaderBox()); } else if (track.getHandler().equals("soun")) { minf.addBox(new SoundMediaHeaderBox()); } else if (track.getHandler().equals("text")) { minf.addBox(new NullMediaHeaderBox()); } else if (track.getHandler().equals("subt")) { minf.addBox(new SubtitleMediaHeaderBox()); } else if (track.getHandler().equals("hint")) { minf.addBox(new HintMediaHeaderBox()); } else if (track.getHandler().equals("sbtl")) { minf.addBox(new NullMediaHeaderBox()); } // dinf: all these three boxes tell us is that the actual // data is in the current file and not somewhere external DataInformationBox dinf = new DataInformationBox(); DataReferenceBox dref = new DataReferenceBox(); dinf.addBox(dref); DataEntryUrlBox url = new DataEntryUrlBox(); url.setFlags(1); dref.addBox(url); minf.addBox(dinf); // Box stbl = createStbl(track, movie, chunks); minf.addBox(stbl); mdia.addBox(minf); return trackBox; } protected Box createEdts(Track track, Movie movie) { if (track.getEdits() != null && track.getEdits().size() > 0) { EditListBox elst = new EditListBox(); elst.setVersion(1); List<EditListBox.Entry> entries = new ArrayList<EditListBox.Entry>(); for (Edit edit : track.getEdits()) { entries.add(new EditListBox.Entry(elst, Math.round(edit.getSegmentDuration() * movie.getTimescale()), edit.getMediaTime() * track.getTrackMetaData().getTimescale() / edit.getTimeScale(), edit.getMediaRate())); } elst.setEntries(entries); EditBox edts = new EditBox(); edts.addBox(elst); return edts; } else { return null; } } protected Box createStbl(Track track, Movie movie, Map<Track, int[]> chunks) { SampleTableBox stbl = new SampleTableBox(); createStsd(track, stbl); createStts(track, stbl); createCtts(track, stbl); createStss(track, stbl); createSdtp(track, stbl); createStsc(track, chunks, stbl); createStsz(track, stbl); createStco(track, movie, chunks, stbl); Map<String, List<GroupEntry>> groupEntryFamilies = new HashMap<String, List<GroupEntry>>(); for (Map.Entry<GroupEntry, long[]> sg : track.getSampleGroups().entrySet()) { String type = sg.getKey().getType(); List<GroupEntry> groupEntries = groupEntryFamilies.get(type); if (groupEntries == null) { groupEntries = new ArrayList<GroupEntry>(); groupEntryFamilies.put(type, groupEntries); } groupEntries.add(sg.getKey()); } for (Map.Entry<String, List<GroupEntry>> sg : groupEntryFamilies.entrySet()) { SampleGroupDescriptionBox sgdb = new SampleGroupDescriptionBox(); String type = sg.getKey(); sgdb.setGroupEntries(sg.getValue()); SampleToGroupBox sbgp = new SampleToGroupBox(); sbgp.setGroupingType(type); SampleToGroupBox.Entry last = null; for (int i = 0; i < track.getSamples().size(); i++) { int index = 0; for (int j = 0; j < sg.getValue().size(); j++) { GroupEntry groupEntry = sg.getValue().get(j); long[] sampleNums = track.getSampleGroups().get(groupEntry); if (Arrays.binarySearch(sampleNums, i) >= 0) { index = j + 1; } } if (last == null || last.getGroupDescriptionIndex() != index) { last = new SampleToGroupBox.Entry(1, index); sbgp.getEntries().add(last); } else { last.setSampleCount(last.getSampleCount() + 1); } } stbl.addBox(sgdb); stbl.addBox(sbgp); } if (track instanceof CencEncryptedTrack) { createCencBoxes((CencEncryptedTrack) track, stbl, chunks.get(track)); } createSubs(track, stbl); return stbl; } protected void createSubs(Track track, SampleTableBox stbl) { if (track.getSubsampleInformationBox() != null) { stbl.addBox(track.getSubsampleInformationBox()); } } protected void createCencBoxes(CencEncryptedTrack track, SampleTableBox stbl, int[] chunkSizes) { SampleAuxiliaryInformationSizesBox saiz = new SampleAuxiliaryInformationSizesBox(); saiz.setAuxInfoType("cenc"); saiz.setFlags(1); List<CencSampleAuxiliaryDataFormat> sampleEncryptionEntries = track.getSampleEncryptionEntries(); if (track.hasSubSampleEncryption()) { short[] sizes = new short[sampleEncryptionEntries.size()]; for (int i = 0; i < sizes.length; i++) { sizes[i] = (short) sampleEncryptionEntries.get(i).getSize(); } saiz.setSampleInfoSizes(sizes); } else { saiz.setDefaultSampleInfoSize(8); // 8 bytes iv saiz.setSampleCount(track.getSamples().size()); } SampleAuxiliaryInformationOffsetsBox saio = new SampleAuxiliaryInformationOffsetsBox(); SampleEncryptionBox senc = new SampleEncryptionBox(); senc.setSubSampleEncryption(track.hasSubSampleEncryption()); senc.setEntries(sampleEncryptionEntries); long offset = senc.getOffsetToFirstIV(); int index = 0; long[] offsets = new long[chunkSizes.length]; for (int i = 0; i < chunkSizes.length; i++) { offsets[i] = offset; for (int j = 0; j < chunkSizes[i]; j++) { offset += sampleEncryptionEntries.get(index++).getSize(); } } saio.setOffsets(offsets); stbl.addBox(saiz); stbl.addBox(saio); stbl.addBox(senc); sampleAuxiliaryInformationOffsetsBoxes.add(saio); } protected void createStsd(Track track, SampleTableBox stbl) { stbl.addBox(track.getSampleDescriptionBox()); } protected void createStco(Track track, Movie movie, Map<Track, int[]> chunks, SampleTableBox stbl) { int[] tracksChunkSizes = chunks.get(track); // The ChunkOffsetBox we create here is just a stub // since we haven't created the whole structure we can't tell where the // first chunk starts (mdat box). So I just let the chunk offset // start at zero and I will add the mdat offset later. StaticChunkOffsetBox stco = new StaticChunkOffsetBox(); this.chunkOffsetBoxes.add(stco); long offset = 0; long[] chunkOffset = new long[tracksChunkSizes.length]; // all tracks have the same number of chunks if (LOG.isLoggable(Level.FINE)) { LOG.fine("Calculating chunk offsets for track_" + track.getTrackMetaData().getTrackId()); } for (int i = 0; i < tracksChunkSizes.length; i++) { // The filelayout will be: // chunk_1_track_1,... ,chunk_1_track_n, chunk_2_track_1,... ,chunk_2_track_n, ... , chunk_m_track_1,... ,chunk_m_track_n // calculating the offsets if (LOG.isLoggable(Level.FINER)) { LOG.finer("Calculating chunk offsets for track_" + track.getTrackMetaData().getTrackId() + " chunk " + i); } for (Track current : movie.getTracks()) { if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Adding offsets of track_" + current.getTrackMetaData().getTrackId()); } int[] chunkSizes = chunks.get(current); long firstSampleOfChunk = 0; for (int j = 0; j < i; j++) { firstSampleOfChunk += chunkSizes[j]; } if (current == track) { chunkOffset[i] = offset; } for (int j = l2i(firstSampleOfChunk); j < firstSampleOfChunk + chunkSizes[i]; j++) { offset += track2SampleSizes.get(current)[j]; } } } stco.setChunkOffsets(chunkOffset); stbl.addBox(stco); } protected void createStsz(Track track, SampleTableBox stbl) { SampleSizeBox stsz = new SampleSizeBox(); stsz.setSampleSizes(track2SampleSizes.get(track)); stbl.addBox(stsz); } protected void createStsc(Track track, Map<Track, int[]> chunks, SampleTableBox stbl) { int[] tracksChunkSizes = chunks.get(track); SampleToChunkBox stsc = new SampleToChunkBox(); stsc.setEntries(new LinkedList<SampleToChunkBox.Entry>()); long lastChunkSize = Integer.MIN_VALUE; // to be sure the first chunks hasn't got the same size for (int i = 0; i < tracksChunkSizes.length; i++) { // The sample description index references the sample description box // that describes the samples of this chunk. My Tracks cannot have more // than one sample description box. Therefore 1 is always right // the first chunk has the number '1' if (lastChunkSize != tracksChunkSizes[i]) { stsc.getEntries().add(new SampleToChunkBox.Entry(i + 1, tracksChunkSizes[i], 1)); lastChunkSize = tracksChunkSizes[i]; } } stbl.addBox(stsc); } protected void createSdtp(Track track, SampleTableBox stbl) { if (track.getSampleDependencies() != null && !track.getSampleDependencies().isEmpty()) { SampleDependencyTypeBox sdtp = new SampleDependencyTypeBox(); sdtp.setEntries(track.getSampleDependencies()); stbl.addBox(sdtp); } } protected void createStss(Track track, SampleTableBox stbl) { long[] syncSamples = track.getSyncSamples(); if (syncSamples != null && syncSamples.length > 0) { SyncSampleBox stss = new SyncSampleBox(); stss.setSampleNumber(syncSamples); stbl.addBox(stss); } } protected void createCtts(Track track, SampleTableBox stbl) { List<CompositionTimeToSample.Entry> compositionTimeToSampleEntries = track.getCompositionTimeEntries(); if (compositionTimeToSampleEntries != null && !compositionTimeToSampleEntries.isEmpty()) { CompositionTimeToSample ctts = new CompositionTimeToSample(); ctts.setEntries(compositionTimeToSampleEntries); stbl.addBox(ctts); } } protected void createStts(Track track, SampleTableBox stbl) { TimeToSampleBox.Entry lastEntry = null; List<TimeToSampleBox.Entry> entries = new ArrayList<TimeToSampleBox.Entry>(); for (long delta : track.getSampleDurations()) { if (lastEntry != null && lastEntry.getDelta() == delta) { lastEntry.setCount(lastEntry.getCount() + 1); } else { lastEntry = new TimeToSampleBox.Entry(1, delta); entries.add(lastEntry); } } TimeToSampleBox stts = new TimeToSampleBox(); stts.setEntries(entries); stbl.addBox(stts); } /** * Gets the chunk sizes for the given track. * * @param track * @param movie * @return */ int[] getChunkSizes(Track track, Movie movie) { long[] referenceChunkStarts = intersectionFinder.sampleNumbers(track); int[] chunkSizes = new int[referenceChunkStarts.length]; for (int i = 0; i < referenceChunkStarts.length; i++) { long start = referenceChunkStarts[i] - 1; long end; if (referenceChunkStarts.length == i + 1) { end = track.getSamples().size(); } else { end = referenceChunkStarts[i + 1] - 1; } chunkSizes[i] = l2i(end - start); // The Stretch makes sure that there are as much audio and video chunks! } assert DefaultMp4Builder.this.track2Sample.get(track).size() == sum(chunkSizes) : "The number of samples and the sum of all chunk lengths must be equal"; return chunkSizes; } public long getTimescale(Movie movie) { long timescale = movie.getTracks().iterator().next().getTrackMetaData().getTimescale(); for (Track track : movie.getTracks()) { timescale = gcd(track.getTrackMetaData().getTimescale(), timescale); } return timescale; } private class InterleaveChunkMdat implements Box { List<Track> tracks; List<List<Sample>> chunkList = new ArrayList<List<Sample>>(); Container parent; long contentSize; private InterleaveChunkMdat(Movie movie, Map<Track, int[]> chunks, long contentSize) { this.contentSize = contentSize; this.tracks = movie.getTracks(); for (int i = 0; i < chunks.values().iterator().next().length; i++) { for (Track track : tracks) { int[] chunkSizes = chunks.get(track); long firstSampleOfChunk = 0; for (int j = 0; j < i; j++) { firstSampleOfChunk += chunkSizes[j]; } List<Sample> chunk = DefaultMp4Builder.this.track2Sample.get(track).subList(l2i(firstSampleOfChunk), l2i(firstSampleOfChunk + chunkSizes[i])); chunkList.add(chunk); } } } public Container getParent() { return parent; } public void setParent(Container parent) { this.parent = parent; } public long getOffset() { throw new RuntimeException("Doesn't have any meaning for programmatically created boxes"); } public void parse(DataSource dataSource, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException { } public long getDataOffset() { Object b = this; long offset = 16; while (b instanceof Box) { for (Box box : ((Box) b).getParent().getBoxes()) { if (b == box) { break; } offset += box.getSize(); } b = ((Box) b).getParent(); } return offset; } public String getType() { return "mdat"; } public long getSize() { return 16 + contentSize; } private boolean isSmallBox(long contentSize) { return (contentSize + 8) < 4294967296L; } public void getBox(WritableByteChannel writableByteChannel) throws IOException { ByteBuffer bb = ByteBuffer.allocate(16); long size = getSize(); if (isSmallBox(size)) { IsoTypeWriter.writeUInt32(bb, size); } else { IsoTypeWriter.writeUInt32(bb, 1); } bb.put(IsoFile.fourCCtoBytes("mdat")); if (isSmallBox(size)) { bb.put(new byte[8]); } else { IsoTypeWriter.writeUInt64(bb, size); } bb.rewind(); writableByteChannel.write(bb); for (List<Sample> samples : chunkList) { for (Sample sample : samples) { sample.writeTo(writableByteChannel); } } } } }
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cloudformation.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ListStackSetOperationResults" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListStackSetOperationResultsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the specified * operation results, for accounts and Amazon Web Services Regions that are included in the operation. * </p> */ private com.amazonaws.internal.SdkInternalList<StackSetOperationResultSummary> summaries; /** * <p> * If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next set of * results, call <code>ListOperationResults</code> again and assign that token to the request object's * <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is set to * <code>null</code>. * </p> */ private String nextToken; /** * <p> * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the specified * operation results, for accounts and Amazon Web Services Regions that are included in the operation. * </p> * * @return A list of <code>StackSetOperationResultSummary</code> structures that contain information about the * specified operation results, for accounts and Amazon Web Services Regions that are included in the * operation. */ public java.util.List<StackSetOperationResultSummary> getSummaries() { if (summaries == null) { summaries = new com.amazonaws.internal.SdkInternalList<StackSetOperationResultSummary>(); } return summaries; } /** * <p> * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the specified * operation results, for accounts and Amazon Web Services Regions that are included in the operation. * </p> * * @param summaries * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the * specified operation results, for accounts and Amazon Web Services Regions that are included in the * operation. */ public void setSummaries(java.util.Collection<StackSetOperationResultSummary> summaries) { if (summaries == null) { this.summaries = null; return; } this.summaries = new com.amazonaws.internal.SdkInternalList<StackSetOperationResultSummary>(summaries); } /** * <p> * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the specified * operation results, for accounts and Amazon Web Services Regions that are included in the operation. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setSummaries(java.util.Collection)} or {@link #withSummaries(java.util.Collection)} if you want to * override the existing values. * </p> * * @param summaries * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the * specified operation results, for accounts and Amazon Web Services Regions that are included in the * operation. * @return Returns a reference to this object so that method calls can be chained together. */ public ListStackSetOperationResultsResult withSummaries(StackSetOperationResultSummary... summaries) { if (this.summaries == null) { setSummaries(new com.amazonaws.internal.SdkInternalList<StackSetOperationResultSummary>(summaries.length)); } for (StackSetOperationResultSummary ele : summaries) { this.summaries.add(ele); } return this; } /** * <p> * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the specified * operation results, for accounts and Amazon Web Services Regions that are included in the operation. * </p> * * @param summaries * A list of <code>StackSetOperationResultSummary</code> structures that contain information about the * specified operation results, for accounts and Amazon Web Services Regions that are included in the * operation. * @return Returns a reference to this object so that method calls can be chained together. */ public ListStackSetOperationResultsResult withSummaries(java.util.Collection<StackSetOperationResultSummary> summaries) { setSummaries(summaries); return this; } /** * <p> * If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next set of * results, call <code>ListOperationResults</code> again and assign that token to the request object's * <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is set to * <code>null</code>. * </p> * * @param nextToken * If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next * set of results, call <code>ListOperationResults</code> again and assign that token to the request object's * <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is set to * <code>null</code>. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next set of * results, call <code>ListOperationResults</code> again and assign that token to the request object's * <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is set to * <code>null</code>. * </p> * * @return If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next * set of results, call <code>ListOperationResults</code> again and assign that token to the request * object's <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is * set to <code>null</code>. */ public String getNextToken() { return this.nextToken; } /** * <p> * If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next set of * results, call <code>ListOperationResults</code> again and assign that token to the request object's * <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is set to * <code>null</code>. * </p> * * @param nextToken * If the request doesn't return all results, <code>NextToken</code> is set to a token. To retrieve the next * set of results, call <code>ListOperationResults</code> again and assign that token to the request object's * <code>NextToken</code> parameter. If there are no remaining results, <code>NextToken</code> is set to * <code>null</code>. * @return Returns a reference to this object so that method calls can be chained together. */ public ListStackSetOperationResultsResult withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSummaries() != null) sb.append("Summaries: ").append(getSummaries()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListStackSetOperationResultsResult == false) return false; ListStackSetOperationResultsResult other = (ListStackSetOperationResultsResult) obj; if (other.getSummaries() == null ^ this.getSummaries() == null) return false; if (other.getSummaries() != null && other.getSummaries().equals(this.getSummaries()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSummaries() == null) ? 0 : getSummaries().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListStackSetOperationResultsResult clone() { try { return (ListStackSetOperationResultsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * 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.modules.util; import static org.apache.geode.test.awaitility.GeodeAwaitility.await; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import javax.servlet.http.HttpSession; import org.apache.juli.logging.Log; import org.junit.Rule; import org.junit.Test; import org.junit.rules.RuleChain; import org.apache.geode.cache.Cache; import org.apache.geode.cache.DataPolicy; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; import org.apache.geode.cache.RegionShortcut; import org.apache.geode.cache.Scope; import org.apache.geode.cache.client.ClientCache; import org.apache.geode.cache.client.ClientCacheFactory; import org.apache.geode.cache.client.NoAvailableServersException; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.server.CacheServer; import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.MembershipListener; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.internal.cache.execute.metrics.FunctionStats; import org.apache.geode.internal.cache.execute.metrics.FunctionStatsManager; import org.apache.geode.modules.session.catalina.ClientServerSessionCache; import org.apache.geode.modules.session.catalina.SessionManager; import org.apache.geode.test.dunit.DistributedTestUtils; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.rules.CacheRule; import org.apache.geode.test.dunit.rules.ClientCacheRule; import org.apache.geode.test.dunit.rules.DistributedRule; public class ClientServerSessionCacheDUnitTest implements Serializable { private static final String SESSION_REGION_NAME = RegionHelper.NAME + "_sessions"; private CacheRule cacheRule = new CacheRule(); private DistributedRule distributedRule = new DistributedRule(); private ClientCacheRule clientCacheRule = new ClientCacheRule(); @Rule public transient RuleChain ruleChain = RuleChain.outerRule(distributedRule) .around(cacheRule) .around(clientCacheRule); @Test public void multipleGeodeServersCreateSessionRegion() { final VM server0 = VM.getVM(0); final VM server1 = VM.getVM(1); final VM client = VM.getVM(2); server0.invoke(this::startCacheServer); server1.invoke(this::startCacheServer); client.invoke(this::startClientSessionCache); server0.invoke(this::validateServer); server1.invoke(this::validateServer); } @Test public void addServerToExistingClusterCreatesSessionRegion() { final VM server0 = VM.getVM(0); final VM server1 = VM.getVM(1); final VM client = VM.getVM(2); server0.invoke(this::startCacheServer); client.invoke(this::startClientSessionCache); server0.invoke(this::validateServer); server1.invoke(this::startCacheServer); // Session region may be created asynchronously on the second server server1.invoke(() -> await().untilAsserted(this::validateServer)); } @Test public void startingAClientWithoutServersFails() { final VM client = VM.getVM(2); assertThatThrownBy(() -> client.invoke(this::startClientSessionCache)) .hasCauseInstanceOf(NoAvailableServersException.class); } @Test public void canPreCreateSessionRegionBeforeStartingClient() { final VM server0 = VM.getVM(0); final VM server1 = VM.getVM(1); final VM client = VM.getVM(2); server0.invoke(this::startCacheServer); server1.invoke(this::startCacheServer); server0.invoke(this::createSessionRegion); server1.invoke(this::createSessionRegion); client.invoke(this::startClientSessionCache); server0.invoke(this::validateServer); server1.invoke(this::validateServer); } @Test public void preCreatedRegionIsNotCopiedToNewlyStartedServers() { final VM server0 = VM.getVM(0); final VM server1 = VM.getVM(1); final VM client = VM.getVM(2); server0.invoke(this::startCacheServer); server0.invoke(this::createSessionRegion); client.invoke(this::startClientSessionCache); server1.invoke(this::startCacheServer); server1.invoke(() -> await().untilAsserted(this::validateBootstrapped)); // server1 should not have created the session region // If the user precreated the region, they must manually // create it on all servers server1.invoke(() -> { Region<Object, Object> region = cacheRule.getCache().getRegion(SESSION_REGION_NAME); assertThat(region).isNull(); }); } @Test public void cantPreCreateMismatchedSessionRegionBeforeStartingClient() { final VM server0 = VM.getVM(0); final VM server1 = VM.getVM(1); final VM client = VM.getVM(2); server0.invoke(this::startCacheServer); server1.invoke(this::startCacheServer); server0.invoke(this::createMismatchedSessionRegion); server1.invoke(this::createMismatchedSessionRegion); assertThatThrownBy(() -> client.invoke(this::startClientSessionCache)) .hasCauseInstanceOf(IllegalStateException.class); } @Test public void sessionCacheSizeShouldNotInvokeFunctionsOnTheCluster() { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client1 = VM.getVM(3); server1.invoke(this::startCacheServer); server2.invoke(this::startCacheServer); server1.invoke(this::createSessionRegion); server2.invoke(this::createSessionRegion); client1.invoke(() -> { final SessionManager sessionManager = mock(SessionManager.class); final Log logger = mock(Log.class); when(sessionManager.getLogger()).thenReturn(logger); when(sessionManager.getRegionName()).thenReturn(RegionHelper.NAME + "_sessions"); when(sessionManager.getRegionAttributesId()) .thenReturn(RegionShortcut.PARTITION_REDUNDANT.toString()); final ClientCacheFactory clientCacheFactory = new ClientCacheFactory(); clientCacheFactory.addPoolLocator("localhost", DistributedTestUtils.getLocatorPort()); clientCacheFactory.setPoolSubscriptionEnabled(true); clientCacheRule.createClientCache(clientCacheFactory); final ClientCache clientCache = clientCacheRule.getClientCache(); ClientServerSessionCache clientServerSessionCache = new ClientServerSessionCache(sessionManager, clientCache); clientServerSessionCache.initialize(); assertThat(clientServerSessionCache.size()).isEqualTo(0); }); // Verify defaults server1.invoke(this::validateServer); server2.invoke(this::validateServer); // Verify that RegionSizeFunction was never executed . server1.invoke(this::validateRegionSizeFunctionCalls); server2.invoke(this::validateRegionSizeFunctionCalls); } private void createSessionRegion() { Cache cache = cacheRule.getCache(); cache.<String, HttpSession>createRegionFactory(RegionShortcut.PARTITION_REDUNDANT) .setCustomEntryIdleTimeout(new SessionCustomExpiry()) .create(SESSION_REGION_NAME); } private void createMismatchedSessionRegion() { Cache cache = cacheRule.getCache(); cache.<String, HttpSession>createRegionFactory(RegionShortcut.PARTITION) .setCustomEntryIdleTimeout(new SessionCustomExpiry()) .create(SESSION_REGION_NAME); } private void validateSessionRegion() { final InternalCache cache = cacheRule.getCache(); final Region<String, HttpSession> region = cache.getRegion(SESSION_REGION_NAME); assertThat(region).isNotNull(); final RegionAttributes<Object, Object> expectedAttributes = cache.getRegionAttributes(RegionShortcut.PARTITION_REDUNDANT.toString()); final RegionAttributes attributes = region.getAttributes(); assertThat(attributes.getScope()).isEqualTo(expectedAttributes.getScope()); assertThat(attributes.getDataPolicy()).isEqualTo(expectedAttributes.getDataPolicy()); assertThat(attributes.getPartitionAttributes()) .isEqualTo(expectedAttributes.getPartitionAttributes()); assertThat(attributes.getCustomEntryIdleTimeout()).isInstanceOf(SessionCustomExpiry.class); } private void validateServer() { validateBootstrapped(); validateSessionRegion(); } private void validateBootstrapped() { final InternalCache cache = cacheRule.getCache(); final DistributionManager distributionManager = cache.getInternalDistributedSystem().getDistributionManager(); final Collection<MembershipListener> listeners = distributionManager.getMembershipListeners(); assertThat(listeners) .filteredOn(listener -> listener instanceof BootstrappingFunction) .hasSize(1); assertThat(FunctionService.getFunction(CreateRegionFunction.ID)) .isInstanceOf(CreateRegionFunction.class); assertThat(FunctionService.getFunction(TouchPartitionedRegionEntriesFunction.ID)) .isInstanceOf(TouchPartitionedRegionEntriesFunction.class); assertThat(FunctionService.getFunction(TouchReplicatedRegionEntriesFunction.ID)) .isInstanceOf(TouchReplicatedRegionEntriesFunction.class); assertThat(FunctionService.getFunction(RegionSizeFunction.ID)) .isInstanceOf(RegionSizeFunction.class); final Region<String, RegionConfiguration> region = cache.getRegion(CreateRegionFunction.REGION_CONFIGURATION_METADATA_REGION); assertThat(region).isNotNull(); final RegionAttributes<String, RegionConfiguration> attributes = region.getAttributes(); assertThat(attributes.getDataPolicy()).isEqualTo(DataPolicy.REPLICATE); assertThat(attributes.getScope()).isEqualTo(Scope.DISTRIBUTED_ACK); assertThat(attributes.getDataPolicy()).isEqualTo(DataPolicy.REPLICATE); assertThat(attributes.getCacheListeners()) .filteredOn(listener -> listener instanceof RegionConfigurationCacheListener) .hasSize(1); } private void validateRegionSizeFunctionCalls() { FunctionStats functionStats = FunctionStatsManager.getFunctionStats(RegionSizeFunction.ID); assertThat(functionStats.getFunctionExecutionCalls()) .as("No function should be invoked to get the region size.") .isEqualTo(0); } private void startClientSessionCache() { final SessionManager sessionManager = mock(SessionManager.class); final Log logger = mock(Log.class); when(sessionManager.getLogger()).thenReturn(logger); when(sessionManager.getRegionName()).thenReturn(RegionHelper.NAME + "_sessions"); when(sessionManager.getRegionAttributesId()) .thenReturn(RegionShortcut.PARTITION_REDUNDANT.toString()); final ClientCacheFactory clientCacheFactory = new ClientCacheFactory(); clientCacheFactory.addPoolLocator("localhost", DistributedTestUtils.getLocatorPort()); clientCacheFactory.setPoolSubscriptionEnabled(true); clientCacheRule.createClientCache(clientCacheFactory); final ClientCache clientCache = clientCacheRule.getClientCache(); new ClientServerSessionCache(sessionManager, clientCache).initialize(); } private void startCacheServer() throws IOException { final Cache cache = cacheRule.getOrCreateCache(); final CacheServer cacheServer = cache.addCacheServer(); cacheServer.setPort(0); cacheServer.start(); } }
/* * 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.index.shard; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.common.inject.internal.Nullable; import org.elasticsearch.common.lease.Releasable; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; public class IndexShardOperationsLockTests extends ESTestCase { private static ThreadPool threadPool; private IndexShardOperationsLock block; @BeforeClass public static void setupThreadPool() { threadPool = new TestThreadPool("IndexShardOperationsLockTests"); } @AfterClass public static void shutdownThreadPool() { ThreadPool.terminate(threadPool, 30, TimeUnit.SECONDS); threadPool = null; } @Before public void createIndexShardOperationsLock() { block = new IndexShardOperationsLock(new ShardId("blubb", "id", 0), logger, threadPool); } @After public void checkNoInflightOperations() { assertThat(block.semaphore.availablePermits(), equalTo(Integer.MAX_VALUE)); assertThat(block.getActiveOperationsCount(), equalTo(0)); } public void testAllOperationsInvoked() throws InterruptedException, TimeoutException, ExecutionException { int numThreads = 10; List<PlainActionFuture<Releasable>> futures = new ArrayList<>(); List<Thread> operationThreads = new ArrayList<>(); CountDownLatch latch = new CountDownLatch(numThreads / 2); for (int i = 0; i < numThreads; i++) { PlainActionFuture<Releasable> future = new PlainActionFuture<Releasable>() { @Override public void onResponse(Releasable releasable) { releasable.close(); super.onResponse(releasable); } }; Thread thread = new Thread() { public void run() { latch.countDown(); block.acquire(future, ThreadPool.Names.GENERIC, true); } }; futures.add(future); operationThreads.add(thread); } CountDownLatch blockFinished = new CountDownLatch(1); threadPool.generic().execute(() -> { try { latch.await(); blockAndWait().close(); blockFinished.countDown(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); for (Thread thread : operationThreads) { thread.start(); } for (PlainActionFuture<Releasable> future : futures) { assertNotNull(future.get(1, TimeUnit.MINUTES)); } for (Thread thread : operationThreads) { thread.join(); } blockFinished.await(); } public void testOperationsInvokedImmediatelyIfNoBlock() throws ExecutionException, InterruptedException { PlainActionFuture<Releasable> future = new PlainActionFuture<>(); block.acquire(future, ThreadPool.Names.GENERIC, true); assertTrue(future.isDone()); future.get().close(); } public void testOperationsIfClosed() throws ExecutionException, InterruptedException { PlainActionFuture<Releasable> future = new PlainActionFuture<>(); block.close(); block.acquire(future, ThreadPool.Names.GENERIC, true); ExecutionException exception = expectThrows(ExecutionException.class, future::get); assertThat(exception.getCause(), instanceOf(IndexShardClosedException.class)); } public void testBlockIfClosed() throws ExecutionException, InterruptedException { block.close(); expectThrows(IndexShardClosedException.class, () -> block.blockOperations(randomInt(10), TimeUnit.MINUTES, () -> { throw new IllegalArgumentException("fake error"); })); } public void testOperationsDelayedIfBlock() throws ExecutionException, InterruptedException, TimeoutException { PlainActionFuture<Releasable> future = new PlainActionFuture<>(); try (Releasable releasable = blockAndWait()) { block.acquire(future, ThreadPool.Names.GENERIC, true); assertFalse(future.isDone()); } future.get(1, TimeUnit.MINUTES).close(); } protected Releasable blockAndWait() throws InterruptedException { CountDownLatch blockAcquired = new CountDownLatch(1); CountDownLatch releaseBlock = new CountDownLatch(1); CountDownLatch blockReleased = new CountDownLatch(1); boolean throwsException = randomBoolean(); IndexShardClosedException exception = new IndexShardClosedException(new ShardId("blubb", "id", 0)); threadPool.generic().execute(() -> { try { block.blockOperations(1, TimeUnit.MINUTES, () -> { try { blockAcquired.countDown(); releaseBlock.await(); if (throwsException) { throw exception; } } catch (InterruptedException e) { throw new RuntimeException(); } }); } catch (Exception e) { if (e != exception) { throw new RuntimeException(e); } } finally { blockReleased.countDown(); } }); blockAcquired.await(); return () -> { releaseBlock.countDown(); try { blockReleased.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } }; } public void testActiveOperationsCount() throws ExecutionException, InterruptedException { PlainActionFuture<Releasable> future1 = new PlainActionFuture<>(); block.acquire(future1, ThreadPool.Names.GENERIC, true); assertTrue(future1.isDone()); assertThat(block.getActiveOperationsCount(), equalTo(1)); PlainActionFuture<Releasable> future2 = new PlainActionFuture<>(); block.acquire(future2, ThreadPool.Names.GENERIC, true); assertTrue(future2.isDone()); assertThat(block.getActiveOperationsCount(), equalTo(2)); future1.get().close(); assertThat(block.getActiveOperationsCount(), equalTo(1)); future1.get().close(); // check idempotence assertThat(block.getActiveOperationsCount(), equalTo(1)); future2.get().close(); assertThat(block.getActiveOperationsCount(), equalTo(0)); try (Releasable releasable = blockAndWait()) { assertThat(block.getActiveOperationsCount(), equalTo(0)); } PlainActionFuture<Releasable> future3 = new PlainActionFuture<>(); block.acquire(future3, ThreadPool.Names.GENERIC, true); assertTrue(future3.isDone()); assertThat(block.getActiveOperationsCount(), equalTo(1)); future3.get().close(); assertThat(block.getActiveOperationsCount(), equalTo(0)); } }
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.engine.modes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.TeraOVR; import org.terasology.asset.AssetManager; import org.terasology.audio.AudioManager; import org.terasology.config.Config; import org.terasology.engine.ComponentSystemManager; import org.terasology.engine.GameEngine; import org.terasology.engine.GameThread; import org.terasology.engine.module.ModuleManager; import org.terasology.engine.subsystem.DisplayDevice; import org.terasology.entitySystem.entity.EntityManager; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.entity.internal.EngineEntityManager; import org.terasology.entitySystem.event.internal.EventSystem; import org.terasology.entitySystem.systems.UpdateSubscriberSystem; import org.terasology.game.GameManifest; import org.terasology.input.InputSystem; import org.terasology.input.cameraTarget.CameraTargetSystem; import org.terasology.logic.console.Console; import org.terasology.module.Module; import org.terasology.module.ModuleEnvironment; import org.terasology.monitoring.PerformanceMonitor; import org.terasology.network.NetworkMode; import org.terasology.network.NetworkSystem; import org.terasology.persistence.StorageManager; import org.terasology.physics.engine.PhysicsEngine; import org.terasology.registry.CoreRegistry; import org.terasology.rendering.nui.NUIManager; import org.terasology.rendering.nui.databinding.ReadOnlyBinding; import org.terasology.rendering.oculusVr.OculusVrHelper; import org.terasology.rendering.world.WorldRenderer; import org.terasology.rendering.world.WorldRenderer.WorldRenderingStage; import org.terasology.world.block.BlockManager; import java.util.Collections; /** * Play mode. * * @author Benjamin Glatzel * @author Anton Kireev * @version 0.1 */ public class StateIngame implements GameState { private static final Logger logger = LoggerFactory.getLogger(StateIngame.class); private ComponentSystemManager componentSystemManager; private EventSystem eventSystem; private NUIManager nuiManager; private WorldRenderer worldRenderer; private EngineEntityManager entityManager; private CameraTargetSystem cameraTargetSystem; private InputSystem inputSystem; private NetworkSystem networkSystem; /* GAME LOOP */ private boolean pauseGame; private StorageManager storageManager; private GameManifest gameManifest; public StateIngame(GameManifest gameManifest) { this.gameManifest = gameManifest; } @Override public void init(GameEngine engine) { nuiManager = CoreRegistry.get(NUIManager.class); worldRenderer = CoreRegistry.get(WorldRenderer.class); eventSystem = CoreRegistry.get(EventSystem.class); componentSystemManager = CoreRegistry.get(ComponentSystemManager.class); entityManager = (EngineEntityManager) CoreRegistry.get(EntityManager.class); cameraTargetSystem = CoreRegistry.get(CameraTargetSystem.class); inputSystem = CoreRegistry.get(InputSystem.class); eventSystem.registerEventHandler(nuiManager); networkSystem = CoreRegistry.get(NetworkSystem.class); storageManager = CoreRegistry.get(StorageManager.class); if (CoreRegistry.get(Config.class).getRendering().isOculusVrSupport() && OculusVrHelper.isNativeLibraryLoaded()) { logger.info("Trying to initialize Oculus SDK..."); TeraOVR.initSDK(); logger.info("Updating Oculus projection parameters from device..."); OculusVrHelper.updateFromDevice(); } // Show or hide the HUD according to the settings nuiManager.getHUD().bindVisible(new ReadOnlyBinding<Boolean>() { @Override public Boolean get() { return !CoreRegistry.get(Config.class).getRendering().getDebug().isHudHidden(); } }); } @Override public void dispose() { if (CoreRegistry.get(Config.class).getRendering().isOculusVrSupport() && OculusVrHelper.isNativeLibraryLoaded()) { logger.info("Shutting down Oculus SDK..."); TeraOVR.clear(); } boolean save = networkSystem.getMode().isAuthority(); if (save) { storageManager.waitForCompletionOfPreviousSaveAndStartSaving(); } networkSystem.shutdown(); // TODO: Shutdown background threads eventSystem.process(); GameThread.processWaitingProcesses(); nuiManager.clear(); CoreRegistry.get(AudioManager.class).stopAllSounds(); if (worldRenderer != null) { worldRenderer.dispose(); worldRenderer = null; } componentSystemManager.shutdown(); CoreRegistry.get(PhysicsEngine.class).dispose(); entityManager.clear(); //if (storageManager != null) { // storageManager.finishSavingAndShutdown(); //} ModuleEnvironment environment = CoreRegistry.get(ModuleManager.class).loadEnvironment(Collections.<Module>emptySet(), true); CoreRegistry.get(AssetManager.class).setEnvironment(environment); CoreRegistry.get(Console.class).dispose(); CoreRegistry.clear(); BlockManager.getAir().setEntity(EntityRef.NULL); GameThread.clearWaitingProcesses(); /* * Clear the binding as otherwise the complete ingame state would be * referenced. */ nuiManager.getHUD().clearVisibleBinding(); } @Override public void update(float delta) { eventSystem.process(); for (UpdateSubscriberSystem system : componentSystemManager.iterateUpdateSubscribers()) { PerformanceMonitor.startActivity(system.getClass().getSimpleName()); system.update(delta); PerformanceMonitor.endActivity(); } if (worldRenderer != null && shouldUpdateWorld()) { worldRenderer.update(delta); } if (storageManager != null) { storageManager.update(); } updateUserInterface(delta); } @Override public void handleInput(float delta) { cameraTargetSystem.update(delta); inputSystem.update(delta); } private boolean shouldUpdateWorld() { return !pauseGame; } @Override public void render() { DisplayDevice displayDevice = CoreRegistry.get(DisplayDevice.class); displayDevice.prepareToRender(); if (worldRenderer != null) { if (!CoreRegistry.get(Config.class).getRendering().isOculusVrSupport()) { worldRenderer.render(WorldRenderingStage.MONO); } else { worldRenderer.render(WorldRenderingStage.LEFT_EYE); worldRenderer.render(WorldRenderingStage.RIGHT_EYE); } } /* UI */ PerformanceMonitor.startActivity("Render and Update UI"); renderUserInterface(); PerformanceMonitor.endActivity(); } @Override public boolean isHibernationAllowed() { return networkSystem.getMode() == NetworkMode.NONE; } @Override public String getLoggingPhase() { return gameManifest.getTitle(); } public void renderUserInterface() { PerformanceMonitor.startActivity("Rendering NUI"); nuiManager.render(); PerformanceMonitor.endActivity(); } private void updateUserInterface(float delta) { nuiManager.update(delta); } public void pause() { pauseGame = true; } public void unpause() { pauseGame = false; } public void togglePauseGame() { if (pauseGame) { unpause(); } else { pause(); } } public boolean isGamePaused() { return pauseGame; } }
/* * Copyright 2013-2016 Uncharted Software Inc. * * Property of Uncharted(TM), formerly Oculus Info Inc. * https://uncharted.software/ * * 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 influent.server.dataaccess; import influent.idl.FL_DateInterval; import influent.idl.FL_DateRange; import influent.idl.FL_DirectionFilter; import influent.idl.FL_LinkEntityTypeFilter; import influent.server.configuration.ApplicationConfiguration; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import java.io.Serializable; import java.util.*; public class DataAccessHelper { // --- Flow --- public static final String FLOW_TABLE = "FinFlow"; public static final String FLOW_COLUMN_FROM_ENTITY_ID = "FinFlow_FromEntityId"; public static final String FLOW_COLUMN_FROM_ENTITY_TYPE = "FinFlow_FromEntityType"; public static final String FLOW_COLUMN_TO_ENTITY_ID = "FinFlow_ToEntityId"; public static final String FLOW_COLUMN_TO_ENTITY_TYPE = "FinFlow_ToEntityType"; public static final String FLOW_COLUMN_AMOUNT = "FinFlow_Amount"; public static final String FLOW_COLUMN_PERIOD_DATE = "FinFlow_PeriodDate"; // --- Entity --- public static final String ENTITY_TABLE = "FinEntity"; public static final String ENTITY_COLUMN_ENTITY_ID = "FinEntity_EntityId"; public static final String ENTITY_COLUMN_INBOUND_AMOUNT = "FinEntity_InboundAmount"; public static final String ENTITY_COLUMN_INBOUND_DEGREE = "FinEntity_InboundDegree"; public static final String ENTITY_COLUMN_UNIQUE_INBOUND_DEGREE = "FinEntity_UniqueInboundDegree"; public static final String ENTITY_COLUMN_OUTBOUND_AMOUNT = "FinEntity_OutboundAmount"; public static final String ENTITY_COLUMN_OUTBOUND_DEGREE = "FinEntity_OutboundDegree"; public static final String ENTITY_COLUMN_UNIQUE_OUTBOUND_DEGREE = "FinEntity_UniqueOutboundDegree"; public static final String ENTITY_COLUMN_PERIOD_DATE = "FinEntity_PeriodDate"; public static final String ENTITY_COLUMN_NUM_TRANSACTIONS = "FinEntity_NumTransactions"; public static final String ENTITY_COLUMN_EARLIEST_TRANSACTION = "FinEntity_StartDate"; public static final String ENTITY_COLUMN_LATEST_TRANSACTION = "FinEntity_EndDate"; public static final String ENTITY_COLUMN_MAX_TRANSACTION = "FinEntity_MaxTransaction"; public static final String ENTITY_COLUMN_AVG_TRANSACTION = "FinEntity_AvgTransaction"; // --- Transactions public static final String RAW_TRANSACTIONS_TABLE = "RawTransactions"; // --- DataSummary public static final String DATA_SUMMARY_TABLE = "DataSummary"; public static final String DATA_SUMMARY_TABLE_COLUMN_SUMMARY_ORDER = "DataSummary_SummaryOrder"; public static final String DATA_SUMMARY_TABLE_COLUMN_SUMMARY_KEY = "DataSummary_SummaryKey"; public static final String DATA_SUMMARY_TABLE_COLUMN_SUMMARY_LABEL = "DataSummary_SummaryLabel"; public static final String DATA_SUMMARY_TABLE_COLUMN_SUMMARY_VALUE = "DataSummary_SummaryValue"; // Serves no purpose other than for us to identify popup requests down the line when we are looking up entities. public interface DetailsSubject {} public static List<String> detailsSubject(String id) { return new DetailsSubjectList(id); } private static class DetailsSubjectList extends AbstractList<String> implements DetailsSubject, RandomAccess, Serializable { static final long serialVersionUID = 3093736618740652951L; private final String _id; DetailsSubjectList(String id) { _id = id; } public int size() { return 1; } public boolean contains(Object obj) { return _id.equals(obj); } public String get(int index) { if (index != 0) throw new IndexOutOfBoundsException("Index: "+index+", Size: 1"); return _id; } } /** * Formats a date, exclusive of time, as a UTC date string. */ public static String format(Long date) { if (date == null) { return null; } return format(new DateTime((long)date, DateTimeZone.UTC)); } private static void pad00( int n, StringBuilder s ) { if (n < 10) { s.append('0'); } s.append(n); } public static String format(DateTime dateTime) { if (dateTime == null) { return null; } StringBuilder s = new StringBuilder(10); s.append(dateTime.getYear()); s.append('-'); pad00(dateTime.getMonthOfYear(), s); s.append('-'); pad00(dateTime.getDayOfMonth(), s); s.append(' '); pad00(dateTime.getHourOfDay(), s); s.append(':'); pad00(dateTime.getMinuteOfHour(), s); s.append(':'); pad00(dateTime.getSecondOfMinute(), s); s.append('.'); int ms = dateTime.getMillisOfSecond(); if (ms < 100) { s.append('0'); } pad00(ms, s); return s.toString(); } public static DateTime getStartDate(FL_DateRange date) { if (date == null || date.getStartDate() == null) { return null; } return new DateTime((long)date.getStartDate(), DateTimeZone.UTC); } public static DateTime getExclusiveEndDate(FL_DateRange date) { if (date == null) { return null; } DateTime d = new DateTime((long)date.getStartDate(), DateTimeZone.UTC); switch (date.getDurationPerBin().getInterval()) { case SECONDS: return d.plusSeconds(date.getNumBins().intValue()); case HOURS: return d.plusHours(date.getNumBins().intValue()); case DAYS: return d.plusDays(date.getNumBins().intValue()); case WEEKS: return d.plusWeeks(date.getNumBins().intValue()); case MONTHS: return d.plusMonths(date.getNumBins().intValue()); case QUARTERS: return d.plusMonths(date.getNumBins().intValue() * 3); case YEARS: return d.plusYears(date.getNumBins().intValue()); } return d; } /** * Gets the inclusive end date for SQL between. */ public static DateTime getEndDate(FL_DateRange date) { if (date == null) { return null; } // max millisecond precision in SQL datetime is .997 return getExclusiveEndDate(date).minusMillis(3); } public static List<Date> getDateIntervals(FL_DateRange date) { Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTimeInMillis(date.getStartDate()); List<Date> dates = new ArrayList<Date>(date.getNumBins().intValue()); for (int i = 0; i < date.getNumBins().intValue(); i++) { dates.add(c.getTime()); switch (date.getDurationPerBin().getInterval()) { case SECONDS: c.add(Calendar.SECOND, 1); break; case HOURS: c.add(Calendar.HOUR_OF_DAY, 1); break; case DAYS: c.add(Calendar.DATE, 1); break; case WEEKS: c.add(Calendar.DATE, 7); break; case MONTHS: c.add(Calendar.MONTH, 1); break; case QUARTERS: c.add(Calendar.MONTH, 3); break; case YEARS: c.add(Calendar.YEAR, 1); break; } } return dates; } public static boolean isDateInRange(long date, FL_DateRange range) { return range.getStartDate() <= date && date <= getEndDate(range).getMillis(); } public static String standardTableName(String tableSeriesName, FL_DateInterval interval) { if (interval != null) { return tableSeriesName + getIntervalLevel(interval); } return tableSeriesName; } public static String getIntervalLevel(FL_DateInterval interval) { switch (interval) { case SECONDS: return "By The Second"; case HOURS: return "Hourly"; case DAYS: return "Daily"; case WEEKS: return "Weekly"; case MONTHS: return "Monthly"; case QUARTERS: return "Quarterly"; case YEARS: return "Yearly"; } return "Yearly"; } public static String createInClause(Collection<String> inItems) { return createInClause(inItems, null, null); } public static String createInClause( Collection<String> inItemIds, DataNamespaceHandler nameSpaceHandler, ApplicationConfiguration.SystemColumnType idType ) { StringBuilder resultString = new StringBuilder(); resultString.append("("); for (String item : inItemIds) { if(nameSpaceHandler == null) { resultString.append("'" + item + "',"); } else { resultString.append(nameSpaceHandler.toSQLId(item, idType) + ","); } } if (!inItemIds.isEmpty()) { resultString.deleteCharAt(resultString.lastIndexOf(",")); } resultString.append(")"); return resultString.toString(); } public static String linkEntityTypeClause( FL_DirectionFilter direction, FL_LinkEntityTypeFilter entityType ) { if (entityType == FL_LinkEntityTypeFilter.ANY) return " 1=1 "; StringBuilder clause = new StringBuilder(); String type = "A"; if (entityType == FL_LinkEntityTypeFilter.ACCOUNT_OWNER) { type = "O"; } else if (entityType == FL_LinkEntityTypeFilter.CLUSTER_SUMMARY) { type = "S"; } // reverse direction - we are filtering on other entity switch (direction) { case DESTINATION: clause.append(" FromEntityType = '" + type + "' "); break; case SOURCE: clause.append(" ToEntityType = '" + type + "' "); break; case BOTH: clause.append(" ToEntityType = '" + type + "' AND FromEntityType = '" + type + "' "); break; } return clause.toString(); } }
package com.alibaba.jstorm.yarn; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.io.OutputStreamWriter; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import java.util.jar.JarEntry; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceType; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import org.yaml.snakeyaml.Yaml; import com.google.common.base.Joiner; public class Util { private static final String JSTORM_CONF_PATH_STRING = "conf" + Path.SEPARATOR + "storm.yaml"; static String getJStormHome() { // String ret = System.getenv().get("JSTORM_HOME"); String ret = System.getProperty("jstorm.home"); if (ret == null) { throw new RuntimeException("jstorm.home is not set"); } return ret; } @SuppressWarnings("rawtypes") static Version getJStormVersion() throws IOException { String versionNumber = "Unknown"; // String versionNumber = "0.9.3.1"; System.out.println(getJStormHome()); File releaseFile = new File(getJStormHome(), "RELEASE"); if (releaseFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(releaseFile)); try { versionNumber = reader.readLine().trim(); } finally { reader.close(); } } File buildFile = new File(getJStormHome(), "BUILD"); String buildNumber = null; if (buildFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(buildFile)); try { buildNumber = reader.readLine().trim(); } finally { reader.close(); } } Version version = new Version(versionNumber, buildNumber); return version; } static String getJStormHomeInZip(FileSystem fs, Path zip, String jstormVersion) throws IOException, RuntimeException { FSDataInputStream fsInputStream = fs.open(zip); ZipInputStream zipInputStream = new ZipInputStream(fsInputStream); ZipEntry entry = zipInputStream.getNextEntry(); while (entry != null) { String entryName = entry.getName(); if (entryName.matches("^jstorm(-" + jstormVersion + ")?/")) { fsInputStream.close(); return entryName.replace("/", ""); } entry = zipInputStream.getNextEntry(); } fsInputStream.close(); throw new RuntimeException("Can not find jstorm home entry in jstorm zip file."); } static LocalResource newYarnAppResource(FileSystem fs, Path path, LocalResourceType type, LocalResourceVisibility vis) throws IOException { Path qualified = fs.makeQualified(path); FileStatus status = fs.getFileStatus(qualified); LocalResource resource = Records.newRecord(LocalResource.class); resource.setType(type); resource.setVisibility(vis); resource.setResource(ConverterUtils.getYarnUrlFromPath(qualified)); resource.setTimestamp(status.getModificationTime()); resource.setSize(status.getLen()); return resource; } @SuppressWarnings("rawtypes") static void rmNulls(Map map) { Set s = map.entrySet(); Iterator it = s.iterator(); while (it.hasNext()) { Map.Entry m =(Map.Entry)it.next(); if (m.getValue() == null) it.remove(); } } @SuppressWarnings("rawtypes") static Path createConfigurationFileInFs(FileSystem fs, String appHome, Map stormConf, YarnConfiguration yarnConf) throws IOException { // dump stringwriter's content into FS conf/storm.yaml Path confDst = new Path(fs.getHomeDirectory(), appHome + Path.SEPARATOR + JSTORM_CONF_PATH_STRING); Path dirDst = confDst.getParent(); fs.mkdirs(dirDst); //storm.yaml FSDataOutputStream out = fs.create(confDst); Yaml yaml = new Yaml(); OutputStreamWriter writer = new OutputStreamWriter(out); rmNulls(stormConf); yaml.dump(stormConf, writer); writer.close(); out.close(); //yarn-site.xml Path yarn_site_xml = new Path(dirDst, "yarn-site.xml"); out = fs.create(yarn_site_xml); writer = new OutputStreamWriter(out); yarnConf.writeXml(writer); writer.close(); out.close(); //logback.xml Path logback_xml = new Path(dirDst, "logback.xml"); out = fs.create(logback_xml); CreateLogbackXML(out); out.close(); return dirDst; } static LocalResource newYarnAppResource(FileSystem fs, Path path) throws IOException { return Util.newYarnAppResource(fs, path, LocalResourceType.FILE, LocalResourceVisibility.APPLICATION); } private static void CreateLogbackXML(OutputStream out) throws IOException { Enumeration<URL> logback_xml_urls; logback_xml_urls = Thread.currentThread().getContextClassLoader().getResources("logback.xml"); while (logback_xml_urls.hasMoreElements()) { URL logback_xml_url = logback_xml_urls.nextElement(); if (logback_xml_url.getProtocol().equals("file")) { //Case 1: logback.xml as simple file FileInputStream is = new FileInputStream(logback_xml_url.getPath()); while (is.available() > 0) { out.write(is.read()); } is.close(); return; } if (logback_xml_url.getProtocol().equals("jar")) { //Case 2: logback.xml included in a JAR String path = logback_xml_url.getPath(); String jarFile = path.substring("file:".length(), path.indexOf("!")); java.util.jar.JarFile jar = new java.util.jar.JarFile(jarFile); Enumeration<JarEntry> enums = jar.entries(); while (enums.hasMoreElements()) { java.util.jar.JarEntry file = enums.nextElement(); if (!file.isDirectory() && file.getName().equals("logback.xml")) { InputStream is = jar.getInputStream(file); // get the input stream while (is.available() > 0) { out.write(is.read()); } is.close(); jar.close(); return; } } jar.close(); } } throw new IOException("Failed to locate a logback.xml"); } @SuppressWarnings("rawtypes") private static List<String> buildCommandPrefix(Map conf, String childOptsKey) throws IOException { String jstormHomePath = getJStormHome(); List<String> toRet = new ArrayList<String>(); if (System.getenv("JAVA_HOME") != null) toRet.add(System.getenv("JAVA_HOME") + "/bin/java"); else toRet.add("java"); toRet.add("-server"); toRet.add("-Djstorm.home=" + jstormHomePath); toRet.add("-Djava.library.path=" + conf.get(backtype.storm.Config.JAVA_LIBRARY_PATH)); toRet.add("-Djstorm.conf.file=" + new File(JSTORM_CONF_PATH_STRING).getName()); //for debug // toRet.add("-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"); toRet.add("-cp"); toRet.add(buildClassPathArgument()); /* if (conf.containsKey(childOptsKey) && conf.get(childOptsKey) != null) { toRet.add((String) conf.get(childOptsKey)); } */ return toRet; } @SuppressWarnings("rawtypes") static List<String> buildUICommands(Map conf) throws IOException { List<String> toRet = buildCommandPrefix(conf, backtype.storm.Config.UI_CHILDOPTS); toRet.add("-Dstorm.options=" + backtype.storm.Config.NIMBUS_HOST + "=localhost"); toRet.add("-Dlogfile.name=" + System.getenv("JSTORM_LOG_DIR") + "/ui.log"); toRet.add("backtype.storm.ui.core"); return toRet; } @SuppressWarnings("rawtypes") static List<String> buildNimbusCommands(Map conf) throws IOException { List<String> toRet = buildCommandPrefix(conf, backtype.storm.Config.NIMBUS_CHILDOPTS); toRet.add("-Dlogfile.name=" + System.getenv("JSTORM_LOG_DIR") + "/nimbus.log"); toRet.add("com.alibaba.jstorm.daemon.nimbus.NimbusServer"); return toRet; } @SuppressWarnings("rawtypes") static List<String> buildSupervisorCommands(Map conf) throws IOException { List<String> toRet = buildCommandPrefix(conf, backtype.storm.Config.NIMBUS_CHILDOPTS); toRet.add("-Dworker.logdir="+ ApplicationConstants.LOG_DIR_EXPANSION_VAR); toRet.add("-Dlogfile.name=" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/supervisor.log"); toRet.add("com.alibaba.jstorm.daemon.supervisor.Supervisor"); return toRet; } private static String buildClassPathArgument() throws IOException { List<String> paths = new ArrayList<String>(); paths.add(new File(JSTORM_CONF_PATH_STRING).getParent()); paths.add(getJStormHome()); for (String jarPath : findAllJarsInPaths(getJStormHome(), getJStormHome() + File.separator + "lib")) { paths.add(jarPath); } return Joiner.on(File.pathSeparatorChar).join(paths); } private static interface FileVisitor { public void visit(File file); } private static List<String> findAllJarsInPaths(String... pathStrs) { final LinkedHashSet<String> pathSet = new LinkedHashSet<String>(); FileVisitor visitor = new FileVisitor() { @Override public void visit(File file) { String name = file.getName(); if (name.endsWith(".jar")) { pathSet.add(file.getPath()); } } }; for (String path : pathStrs) { File file = new File(path); traverse(file, visitor); } final List<String> toRet = new ArrayList<String>(); for (String p : pathSet) { toRet.add(p); } return toRet; } private static void traverse(File file, FileVisitor visitor) { if (file.isDirectory()) { File childs[] = file.listFiles(); if (childs.length > 0) { for (int i = 0; i < childs.length; i++) { File child = childs[i]; traverse(child, visitor); } } } else { visitor.visit(file); } } static String getApplicationHomeForId(String id) { if (id.isEmpty()) { throw new IllegalArgumentException( "The ID of the application cannot be empty."); } return ".jstorm" + Path.SEPARATOR + id; } /** * Returns a boolean to denote whether a cache file is visible to all(public) * or not * @param fs Hadoop file system * @param path file path * @return true if the path is visible to all, false otherwise * @throws IOException */ static boolean isPublic(FileSystem fs, Path path) throws IOException { //the leaf level file should be readable by others if (!checkPermissionOfOther(fs, path, FsAction.READ)) { return false; } return ancestorsHaveExecutePermissions(fs, path.getParent()); } /** * Checks for a given path whether the Other permissions on it * imply the permission in the passed FsAction * @param fs * @param path * @param action * @return true if the path in the uri is visible to all, false otherwise * @throws IOException */ private static boolean checkPermissionOfOther(FileSystem fs, Path path, FsAction action) throws IOException { FileStatus status = fs.getFileStatus(path); FsPermission perms = status.getPermission(); FsAction otherAction = perms.getOtherAction(); if (otherAction.implies(action)) { return true; } return false; } /** * Returns true if all ancestors of the specified path have the 'execute' * permission set for all users (i.e. that other users can traverse * the directory hierarchy to the given path) */ static boolean ancestorsHaveExecutePermissions(FileSystem fs, Path path) throws IOException { Path current = path; while (current != null) { //the subdirs in the path should have execute permissions for others if (!checkPermissionOfOther(fs, current, FsAction.EXECUTE)) { return false; } current = current.getParent(); } return true; } static void redirectStreamAsync(final InputStream input, final PrintStream output) { new Thread(new Runnable() { @Override public void run() { Scanner scanner = new Scanner(input); while (scanner.hasNextLine()) { output.println(scanner.nextLine()); } } }).start(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.aws.xray; import java.net.URI; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.Set; import java.util.regex.Pattern; import com.amazonaws.xray.AWSXRay; import com.amazonaws.xray.entities.Entity; import com.amazonaws.xray.entities.Segment; import com.amazonaws.xray.entities.Subsegment; import com.amazonaws.xray.entities.TraceID; import com.amazonaws.xray.exceptions.AlreadyEmittedException; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.ExtendedCamelContext; import org.apache.camel.NamedNode; import org.apache.camel.Route; import org.apache.camel.RuntimeCamelException; import org.apache.camel.StaticService; import org.apache.camel.spi.CamelEvent; import org.apache.camel.spi.CamelEvent.ExchangeSendingEvent; import org.apache.camel.spi.CamelEvent.ExchangeSentEvent; import org.apache.camel.spi.InterceptStrategy; import org.apache.camel.spi.RoutePolicy; import org.apache.camel.spi.RoutePolicyFactory; import org.apache.camel.support.EventNotifierSupport; import org.apache.camel.support.RoutePolicySupport; import org.apache.camel.support.service.ServiceHelper; import org.apache.camel.support.service.ServiceSupport; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To use AWS XRay with Camel setup this {@link XRayTracer} in your Camel application. * <p/> * This class uses a {@link org.apache.camel.spi.RoutePolicy} as well as a {@link org.apache.camel.spi.EventNotifier} * internally to manage the creation and termination of AWS XRay {@link Segment Segments} and {@link Subsegment * Subsegments} once an exchange was created, forwarded or closed in order to allow monitoring the lifetime metrics of * the exchange. * <p/> * A {@link InterceptStrategy} is used in order to track invocations and durations of EIP patterns used in processed * routes. If no strategy is passed while configuration via {@link #setTracingStrategy(InterceptStrategy)}, a * {@link NoopTracingStrategy} will be used by default which will not monitor any invocations at all. * <p/> * By default every invoked route will be tracked by AWS XRay. If certain routes shell not be tracked * {@link #addExcludePattern(String)} and {@link #setExcludePatterns(Set)} can be used to provide the <em>routeId</em> * of the routes to exclude from monitoring. */ public class XRayTracer extends ServiceSupport implements RoutePolicyFactory, StaticService, CamelContextAware { /** Header value kept in the message of the exchange **/ public static final String XRAY_TRACE_ID = "Camel-AWS-XRay-Trace-ID"; // Note that the Entity itself is not serializable, so don't share this object among different VMs! public static final String XRAY_TRACE_ENTITY = "Camel-AWS-XRay-Trace-Entity"; private static final Logger LOG = LoggerFactory.getLogger(XRayTracer.class); private static final Pattern SANITIZE_NAME_PATTERN = Pattern.compile("[^\\w.:/%&#=+\\-@]"); private static Map<String, SegmentDecorator> decorators = new HashMap<>(); /** Exchange property for passing a segment between threads **/ private static final String CURRENT_SEGMENT = "CAMEL_PROPERTY_AWS_XRAY_CURRENT_SEGMENT"; private final XRayEventNotifier eventNotifier = new XRayEventNotifier(); private CamelContext camelContext; private Set<String> excludePatterns = new HashSet<>(); private InterceptStrategy tracingStrategy; static { ServiceLoader.load(SegmentDecorator.class).forEach(d -> { SegmentDecorator existing = decorators.get(d.getComponent()); // Add segment decorator only if no existing decorator for the component exists yet or if we have have a // derived one. This allows custom decorators to be added if they extend the standard decorators if (existing == null || existing.getClass().isInstance(d)) { Logger log = LoggerFactory.getLogger(XRayTracer.class); log.trace("Adding segment decorator {}", d.getComponent()); decorators.put(d.getComponent(), d); } }); } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return this.camelContext; } @Override public RoutePolicy createRoutePolicy(CamelContext camelContext, String routeId, NamedNode route) { init(camelContext); return new XRayRoutePolicy(routeId); } @Override protected void doInit() throws Exception { ObjectHelper.notNull(camelContext, "CamelContext", this); camelContext.getManagementStrategy().addEventNotifier(eventNotifier); if (!camelContext.getRoutePolicyFactories().contains(this)) { camelContext.addRoutePolicyFactory(this); } if (null == tracingStrategy) { LOG.info("No tracing strategy available. Defaulting to no-op strategy"); tracingStrategy = new NoopTracingStrategy(); } camelContext.adapt(ExtendedCamelContext.class).addInterceptStrategy(tracingStrategy); LOG.debug("Initialized XRay tracer"); } @Override protected void doShutdown() throws Exception { // stop event notifier camelContext.getManagementStrategy().removeEventNotifier(eventNotifier); ServiceHelper.stopAndShutdownService(eventNotifier); camelContext.getRoutePolicyFactories().remove(this); LOG.debug("XRay tracer shutdown"); } /** * Initializes this AWS XRay tracer implementation as service within the Camel environment. * * @param camelContext The context to register this tracer as service with */ public void init(CamelContext camelContext) { if (!camelContext.hasService(this)) { try { LOG.debug("Initializing XRay tracer"); // start this service eager so we init before Camel is starting up camelContext.addService(this, true, true); } catch (Exception e) { throw RuntimeCamelException.wrapRuntimeCamelException(e); } } } /** * Returns the currently used tracing strategy which is responsible for tracking invoked EIP or beans. * * @return The currently used tracing strategy */ public InterceptStrategy getTracingStrategy() { return tracingStrategy; } /** * Specifies the instance responsible for tracking invoked EIP and beans with AWS XRay. * * @param tracingStrategy The instance which tracks invoked EIP and beans */ public void setTracingStrategy(InterceptStrategy tracingStrategy) { this.tracingStrategy = tracingStrategy; } /** * Returns the set of currently excluded routes. Any route ID specified in the returned set will not be monitored by * this AWS XRay tracer implementation. * * @return The IDs of the currently excluded routes for which no tracking will be performed */ public Set<String> getExcludePatterns() { return this.excludePatterns; } /** * Excludes all of the routes matching any of the contained routeIds within the given argument from tracking by this * tracer implementation. Excluded routes will not appear within the AWS XRay monitoring. * * @param excludePatterns A set of routeIds which should not be tracked by this tracer */ public void setExcludePatterns(Set<String> excludePatterns) { this.excludePatterns = excludePatterns; } /** * Adds an exclude pattern that will disable tracing for Camel messages that matches the pattern. * * @param pattern The pattern such as route id, endpoint url */ public void addExcludePattern(String pattern) { excludePatterns.add(pattern); } private boolean isExcluded(String routeId) { // check for a defined routeId if (!excludePatterns.isEmpty()) { for (String pattern : excludePatterns) { if (pattern.equals(routeId)) { LOG.debug("Ignoring route with ID {}", routeId); return true; } } } return false; } protected SegmentDecorator getSegmentDecorator(Endpoint endpoint) { SegmentDecorator sd = decorators.get(URI.create(endpoint.getEndpointUri()).getScheme()); if (null == sd) { return SegmentDecorator.DEFAULT; } return sd; } protected Entity getTraceEntityFromExchange(Exchange exchange) { Entity entity = exchange.getIn().getHeader(XRAY_TRACE_ENTITY, Entity.class); if (entity == null) { entity = (Entity) exchange.getProperty(CURRENT_SEGMENT); } return entity; } /** * Custom camel event handler that will create a new {@link Subsegment XRay subsegment} in case the current exchange * is forwarded via <code>.to(someEndpoint)</code> to some endpoint and accordingly closes the subsegment if the * execution returns. * <p/> * Note that AWS XRay is designed to manage {@link Segment segments} and {@link Subsegment subsegments} within a * {@link ThreadLocal} context. Forwarding the exchange to a <em>SEDA</em> endpoint will thus copy over the exchange * to a new thread, though any available segment information collected by AWS XRay will not be available within that * new thread! * <p/> * As {@link ExchangeSendingEvent} and {@link ExchangeSentEvent} both are executed within the invoking thread (in * contrast to {@link org.apache.camel.spi.CamelEvent.ExchangeCreatedEvent ExchangeCreatedEvent} and * {@link org.apache.camel.spi.CamelEvent.ExchangeCompletedEvent ExchangeCompletedEvent} which both run in the * context of the spawned thread), adding further subsegments by this {@link org.apache.camel.spi.EventNotifier * EventNotifier} implementation should be safe. */ private final class XRayEventNotifier extends EventNotifierSupport { @Override public void notify(CamelEvent event) throws Exception { if (event instanceof ExchangeSendingEvent) { ExchangeSendingEvent ese = (ExchangeSendingEvent) event; if (LOG.isTraceEnabled()) { LOG.trace("-> {} - target: {} (routeId: {})", event.getClass().getSimpleName(), ese.getEndpoint(), ese.getExchange().getFromRouteId()); } SegmentDecorator sd = getSegmentDecorator(ese.getEndpoint()); if (!sd.newSegment()) { return; } Entity entity = getTraceEntityFromExchange(ese.getExchange()); if (entity != null) { AWSXRay.setTraceEntity(entity); // AWS XRay does only allow a certain set of characters to appear within a name // Allowed characters: a-z, A-Z, 0-9, _, ., :, /, %, &, #, =, +, \, -, @ String name = sd.getOperationName(ese.getExchange(), ese.getEndpoint()); if (sd.getComponent() != null) { name = sd.getComponent() + ":" + name; } name = sanitizeName(name); try { Subsegment subsegment = AWSXRay.beginSubsegment(name); sd.pre(subsegment, ese.getExchange(), ese.getEndpoint()); if (LOG.isTraceEnabled()) { LOG.trace("Creating new subsegment with ID {} and name {} (parent {}, references: {})", subsegment.getId(), subsegment.getName(), subsegment.getParentSegment().getId(), subsegment.getParentSegment().getReferenceCount()); } ese.getExchange().setProperty(CURRENT_SEGMENT, subsegment); } catch (AlreadyEmittedException aeEx) { LOG.warn("Ignoring starting of subsegment " + name + " as its parent segment" + " was already emitted to AWS."); } } else { LOG.trace("Ignoring creation of XRay subsegment as no segment exists in the current thread"); } } else if (event instanceof ExchangeSentEvent) { ExchangeSentEvent ese = (ExchangeSentEvent) event; if (LOG.isTraceEnabled()) { LOG.trace("-> {} - target: {} (routeId: {})", event.getClass().getSimpleName(), ese.getEndpoint(), ese.getExchange().getFromRouteId()); } Entity entity = getTraceEntityFromExchange(ese.getExchange()); if (entity instanceof Subsegment) { AWSXRay.setTraceEntity(entity); SegmentDecorator sd = getSegmentDecorator(ese.getEndpoint()); try { Subsegment subsegment = (Subsegment) entity; sd.post(subsegment, ese.getExchange(), ese.getEndpoint()); subsegment.close(); if (LOG.isTraceEnabled()) { LOG.trace("Closing down subsegment with ID {} and name {}", subsegment.getId(), subsegment.getName()); LOG.trace("Setting trace entity for exchange {} to {}", ese.getExchange(), subsegment.getParent()); } ese.getExchange().setProperty(CURRENT_SEGMENT, subsegment.getParent()); } catch (AlreadyEmittedException aeEx) { LOG.warn("Ignoring close of subsegment " + entity.getName() + " as its parent segment was already emitted to AWS"); } } } else { LOG.trace("Received event {} from source {}", event, event.getSource()); } } @Override public boolean isEnabled(CamelEvent event) { // listen for either when an exchange invoked an other endpoint return event instanceof ExchangeSendingEvent || event instanceof ExchangeSentEvent; } @Override public String toString() { return "XRayEventNotifier"; } } /** * A custom {@link org.apache.camel.spi.RoutePolicy RoutePolicy} implementation that will create a new AWS XRay * {@link Segment} once a new exchange is being created and the current thread does not know of an active segment * yet. In case the exchange was forwarded within the same thread (i.e. by forwarding to a direct endpoint via * <code>.to("direct:...)</code>) and a previous exchange already created a {@link Segment} this policy will add a * new {@link Subsegment} for the created exchange to the trace. * <p/> * This policy will also manage the termination of created {@link Segment Segments} and {@link Subsegment * Subsegments}. * <p/> * As AWS XRay is designed to manage {@link Segment Segments} in a {@link ThreadLocal} context this policy will * create a new segment for each forward to a new thread i.e. by sending the exchange to a <em>SEDA</em> endpoint. */ private final class XRayRoutePolicy extends RoutePolicySupport { private String routeId; XRayRoutePolicy(String routeId) { this.routeId = routeId; } @Override public void onExchangeBegin(Route route, Exchange exchange) { // kicks in after a seda-thread was created. The new thread has the control if (isExcluded(route.getId())) { return; } if (LOG.isTraceEnabled()) { LOG.trace("=> RoutePolicy-Begin: Route: {} - RouteId: {}", routeId, route.getId()); } Entity entity = getTraceEntityFromExchange(exchange); boolean createSegment = entity == null || !Objects.equals(entity.getName(), routeId); TraceID traceID; if (exchange.getIn().getHeaders().containsKey(XRAY_TRACE_ID)) { traceID = TraceID.fromString(exchange.getIn().getHeader(XRAY_TRACE_ID, String.class)); } else { traceID = new TraceID(); exchange.getIn().setHeader(XRAY_TRACE_ID, traceID.toString()); } AWSXRay.setTraceEntity(entity); SegmentDecorator sd = getSegmentDecorator(route.getEndpoint()); if (createSegment) { Segment segment = AWSXRay.beginSegment(sanitizeName(route.getId())); segment.setParent(entity); segment.setTraceId(traceID); sd.pre(segment, exchange, route.getEndpoint()); if (LOG.isTraceEnabled()) { LOG.trace("Created new XRay segment {} with name {}", segment.getId(), segment.getName()); } exchange.setProperty(CURRENT_SEGMENT, segment); } else { String segmentName = entity.getId(); try { Subsegment subsegment = AWSXRay.beginSubsegment(route.getId()); sd.pre(subsegment, exchange, route.getEndpoint()); if (LOG.isTraceEnabled()) { LOG.trace("Creating new subsegment with ID {} and name {} (parent {}, references: {})", subsegment.getId(), subsegment.getName(), subsegment.getParentSegment().getId(), subsegment.getParentSegment().getReferenceCount()); } exchange.setProperty(CURRENT_SEGMENT, subsegment); } catch (AlreadyEmittedException aeEx) { LOG.warn("Ignoring opening of subsegment " + route.getId() + " as its parent segment " + segmentName + " was already emitted before."); } } } @Override public void onExchangeDone(Route route, Exchange exchange) { // kicks in before the seda-thread is terminated. Control is still in the seda-thread if (isExcluded(route.getId())) { return; } if (LOG.isTraceEnabled()) { LOG.trace("=> RoutePolicy-Done: Route: {} - RouteId: {}", routeId, route.getId()); } Entity entity = getTraceEntityFromExchange(exchange); AWSXRay.setTraceEntity(entity); try { SegmentDecorator sd = getSegmentDecorator(route.getEndpoint()); sd.post(entity, exchange, route.getEndpoint()); entity.close(); if (LOG.isTraceEnabled()) { LOG.trace("Closing down (sub)segment {} with name {} (parent {}, references: {})", entity.getId(), entity.getName(), entity.getParentSegment().getId(), entity.getParentSegment().getReferenceCount()); } exchange.setProperty(CURRENT_SEGMENT, entity.getParent()); } catch (AlreadyEmittedException aeEx) { LOG.warn("Ignoring closing of (sub)segment {} as the segment was already emitted.", route.getId()); } catch (Exception e) { LOG.warn("Error closing entity"); } finally { AWSXRay.setTraceEntity(null); } } @Override public String toString() { return "XRayRoutePolicy"; } } /** * Removes invalid characters from AWS XRay (sub-)segment names and replaces the invalid characters with an * underscore character. * * @param name The name to assign to an AWS XRay (sub-)segment * @return The sanitized name of the (sub-)segment */ public static String sanitizeName(String name) { // Allowed characters: a-z, A-Z, 0-9, _, ., :, /, %, &, #, =, +, \, -, @ // \w = a-zA-Z0-9_ return SANITIZE_NAME_PATTERN.matcher(name).replaceAll("_"); } }
/* * (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP * * 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.hp.ov.sdk.dto; import java.io.Serializable; import java.util.Date; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import com.google.gson.GsonBuilder; import com.hp.ov.sdk.util.URIUtils; public class BaseModelResource implements Serializable { private static final long serialVersionUID = 5688679045442246487L; private String category; private Date created; private String description; private String eTag; private Date modified; private String name; private String state; private String status; private String type; private String uri; /** * @return the category */ public String getCategory() { return category; } /** * @param category the category to set */ public void setCategory(String category) { this.category = category; } /** * @return the created */ public Date getCreated() { return created; } /** * @param created the created to set */ public void setCreated(Date created) { this.created = created; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the eTag */ public String getETag() { return eTag; } /** * @param eTag the eTag to set */ public void setETag(String eTag) { this.eTag = eTag; } /** * @return the modified */ public Date getModified() { return modified; } /** * @param modified the modified to set */ public void setModified(Date modified) { this.modified = modified; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the state */ public String getState() { return state; } /** * @param state the state to set */ public void setState(String state) { this.state = state; } /** * @return the status */ public String getStatus() { return status; } /** * @param status the status to set */ public void setStatus(String status) { this.status = status; } /** * @return the type */ public String getType() { return type; } /** * @param type the type to set */ public void setType(String type) { this.type = type; } /** * @return the uri */ public String getUri() { return uri; } /** * @param uri the uri to set */ public void setUri(String uri) { this.uri = uri; } public String getResourceId() { return URIUtils.getResourceIdFromUri(this.getUri()); } public boolean canEqual(Object obj) { return (obj instanceof BaseModelResource); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj instanceof BaseModelResource) { BaseModelResource that = (BaseModelResource) obj; return that.canEqual(this) && new EqualsBuilder() .append(category, that.category) .append(created, that.created) .append(description, that.description) .append(eTag, that.eTag) .append(modified, that.modified) .append(name, that.name) .append(state, that.state) .append(status, that.status) .append(type, that.type) .append(uri, that.uri) .isEquals(); } return false; } @Override public int hashCode() { return new HashCodeBuilder() .append(category) .append(created) .append(description) .append(eTag) .append(modified) .append(name) .append(state) .append(status) .append(type) .append(uri) .toHashCode(); } public String toJsonString() { return System.getProperty("line.separator") + new GsonBuilder() .setPrettyPrinting() .disableHtmlEscaping() .create().toJson(this); } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
/* * 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.thrift.transport; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.Random; import org.apache.thrift.TConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * FileTransport implementation of the TTransport interface. * Currently this is a straightforward port of the cpp implementation * * It may make better sense to provide a basic stream access on top of the framed file format * The FileTransport can then be a user of this framed file format with some additional logic * for chunking. */ public class TFileTransport extends TTransport { private static final Logger LOGGER = LoggerFactory.getLogger(TFileTransport.class.getName()); public static class TruncableBufferedInputStream extends BufferedInputStream { public void trunc() { pos = count = 0; } public TruncableBufferedInputStream(InputStream in) { super(in); } public TruncableBufferedInputStream(InputStream in, int size) { super(in, size); } } public static class Event { private byte[] buf_; private int nread_; private int navailable_; /** * Initialize an event. Initially, it has no valid contents * * @param buf byte array buffer to store event */ public Event(byte[] buf) { buf_ = buf; nread_ = navailable_ = 0; } public byte[] getBuf() { return buf_;} public int getSize() { return buf_.length; } public void setAvailable(int sz) { nread_ = 0; navailable_=sz;} public int getRemaining() { return (navailable_ - nread_); } public int emit(byte[] buf, int offset, int ndesired) { if((ndesired == 0) || (ndesired > getRemaining())) ndesired = getRemaining(); if(ndesired <= 0) return (ndesired); System.arraycopy(buf_, nread_, buf, offset, ndesired); nread_ += ndesired; return(ndesired); } } public static class ChunkState { /** * Chunk Size. Must be same across all implementations */ public static final int DEFAULT_CHUNK_SIZE = 16 * 1024 * 1024; private int chunk_size_ = DEFAULT_CHUNK_SIZE; private long offset_ = 0; public ChunkState() {} public ChunkState(int chunk_size) { chunk_size_ = chunk_size; } public void skip(int size) {offset_ += size; } public void seek(long offset) {offset_ = offset;} public int getChunkSize() { return chunk_size_;} public int getChunkNum() { return ((int)(offset_/chunk_size_));} public int getRemaining() { return (chunk_size_ - ((int)(offset_ % chunk_size_)));} public long getOffset() { return (offset_);} } public enum TailPolicy { NOWAIT(0, 0), WAIT_FOREVER(500, -1); /** * Time in milliseconds to sleep before next read * If 0, no sleep */ public final int timeout_; /** * Number of retries before giving up * if 0, no retries * if -1, retry forever */ public final int retries_; /** * ctor for policy * * @param timeout sleep time for this particular policy * @param retries number of retries */ TailPolicy(int timeout, int retries) { timeout_ = timeout; retries_ = retries; } } /** * Current tailing policy */ TailPolicy currentPolicy_ = TailPolicy.NOWAIT; /** * Underlying file being read */ protected TSeekableFile inputFile_ = null; /** * Underlying outputStream */ protected OutputStream outputStream_ = null; /** * Event currently read in */ Event currentEvent_ = null; /** * InputStream currently being used for reading */ InputStream inputStream_ = null; /** * current Chunk state */ ChunkState cs = null; /** * is read only? */ private boolean readOnly_ = false; /** * Get File Tailing Policy * * @return current read policy */ public TailPolicy getTailPolicy() { return (currentPolicy_); } /** * Set file Tailing Policy * * @param policy New policy to set * @return Old policy */ public TailPolicy setTailPolicy(TailPolicy policy) { TailPolicy old = currentPolicy_; currentPolicy_ = policy; return (old); } /** * Initialize read input stream * * @return input stream to read from file */ private InputStream createInputStream() throws TTransportException { InputStream is; try { if(inputStream_ != null) { ((TruncableBufferedInputStream)inputStream_).trunc(); is = inputStream_; } else { is = new TruncableBufferedInputStream(inputFile_.getInputStream()); } } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } return(is); } /** * Read (potentially tailing) an input stream * * @param is InputStream to read from * @param buf Buffer to read into * @param off Offset in buffer to read into * @param len Number of bytes to read * @param tp policy to use if we hit EOF * * @return number of bytes read */ private int tailRead(InputStream is, byte[] buf, int off, int len, TailPolicy tp) throws TTransportException { int orig_len = len; try { int retries = 0; while(len > 0) { int cnt = is.read(buf, off, len); if(cnt > 0) { off += cnt; len -= cnt; retries = 0; cs.skip(cnt); // remember that we read so many bytes } else if (cnt == -1) { // EOF retries++; if((tp.retries_ != -1) && tp.retries_ < retries) return (orig_len - len); if(tp.timeout_ > 0) { try {Thread.sleep(tp.timeout_);} catch(InterruptedException e) {} } } else { // either non-zero or -1 is what the contract says! throw new TTransportException("Unexpected return from InputStream.read = " + cnt); } } } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } return(orig_len - len); } /** * Event is corrupted. Do recovery * * @return true if recovery could be performed and we can read more data * false is returned only when nothing more can be read */ private boolean performRecovery() throws TTransportException { int numChunks = getNumChunks(); int curChunk = cs.getChunkNum(); if(curChunk >= (numChunks-1)) { return false; } seekToChunk(curChunk+1); return true; } /** * Read event from underlying file * * @return true if event could be read, false otherwise (on EOF) */ private boolean readEvent() throws TTransportException { byte[] ebytes = new byte[4]; int esize; int nread; int nrequested; retry: do { // corner case. read to end of chunk nrequested = cs.getRemaining(); if(nrequested < 4) { nread = tailRead(inputStream_, ebytes, 0, nrequested, currentPolicy_); if(nread != nrequested) { return(false); } } // assuming serialized on little endian machine nread = tailRead(inputStream_, ebytes, 0, 4, currentPolicy_); if(nread != 4) { return(false); } esize=0; for(int i=3; i>=0; i--) { int val = (0x000000ff & (int)ebytes[i]); esize |= (val << (i*8)); } // check if event is corrupted and do recovery as required if(esize > cs.getRemaining()) { throw new TTransportException("FileTransport error: bad event size"); /* if(performRecovery()) { esize=0; } else { return false; } */ } } while (esize == 0); // reset existing event or get a larger one if(currentEvent_.getSize() < esize) currentEvent_ = new Event(new byte [esize]); // populate the event byte[] buf = currentEvent_.getBuf(); nread = tailRead(inputStream_, buf, 0, esize, currentPolicy_); if(nread != esize) { return(false); } currentEvent_.setAvailable(esize); return(true); } /** * open if both input/output open unless readonly * * @return true */ public boolean isOpen() { return ((inputStream_ != null) && (readOnly_ || (outputStream_ != null))); } /** * Diverging from the cpp model and sticking to the TSocket model * Files are not opened in ctor - but in explicit open call */ public void open() throws TTransportException { if (isOpen()) throw new TTransportException(TTransportException.ALREADY_OPEN); try { inputStream_ = createInputStream(); cs = new ChunkState(); currentEvent_ = new Event(new byte [256]); if(!readOnly_) outputStream_ = new BufferedOutputStream(inputFile_.getOutputStream()); } catch (IOException iox) { throw new TTransportException(TTransportException.NOT_OPEN, iox); } } /** * Closes the transport. */ public void close() { if (inputFile_ != null) { try { inputFile_.close(); } catch (IOException iox) { LOGGER.warn("WARNING: Error closing input file: " + iox.getMessage()); } inputFile_ = null; } if (outputStream_ != null) { try { outputStream_.close(); } catch (IOException iox) { LOGGER.warn("WARNING: Error closing output stream: " + iox.getMessage()); } outputStream_ = null; } } /** * File Transport ctor * * @param path File path to read and write from * @param readOnly Whether this is a read-only transport * @throws IOException if there is an error accessing the file. */ public TFileTransport(final String path, boolean readOnly) throws IOException { inputFile_ = new TStandardFile(path); readOnly_ = readOnly; } /** * File Transport ctor * * @param inputFile open TSeekableFile to read/write from * @param readOnly Whether this is a read-only transport */ public TFileTransport(TSeekableFile inputFile, boolean readOnly) { inputFile_ = inputFile; readOnly_ = readOnly; } /** * Cloned from TTransport.java:readAll(). Only difference is throwing an EOF exception * where one is detected. */ public int readAll(byte[] buf, int off, int len) throws TTransportException { int got = 0; int ret = 0; while (got < len) { ret = read(buf, off+got, len-got); if (ret < 0) { throw new TTransportException("Error in reading from file"); } if(ret == 0) { throw new TTransportException(TTransportException.END_OF_FILE, "End of File reached"); } got += ret; } return got; } /** * Reads up to len bytes into buffer buf, starting at offset off. * * @param buf Array to read into * @param off Index to start reading at * @param len Maximum number of bytes to read * @return The number of bytes actually read * @throws TTransportException if there was an error reading data */ public int read(byte[] buf, int off, int len) throws TTransportException { if(!isOpen()) throw new TTransportException(TTransportException.NOT_OPEN, "Must open before reading"); if(currentEvent_.getRemaining() == 0) { if(!readEvent()) return(0); } int nread = currentEvent_.emit(buf, off, len); return nread; } public int getNumChunks() throws TTransportException { if(!isOpen()) throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getNumChunks"); try { long len = inputFile_.length(); if(len == 0) return 0; else return (((int)(len/cs.getChunkSize())) + 1); } catch (IOException iox) { throw new TTransportException(iox.getMessage(), iox); } } public int getCurChunk() throws TTransportException { if(!isOpen()) throw new TTransportException(TTransportException.NOT_OPEN, "Must open before getCurChunk"); return (cs.getChunkNum()); } public void seekToChunk(int chunk) throws TTransportException { if(!isOpen()) throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking"); int numChunks = getNumChunks(); // file is empty, seeking to chunk is pointless if (numChunks == 0) { return; } // negative indicates reverse seek (from the end) if (chunk < 0) { chunk += numChunks; } // too large a value for reverse seek, just seek to beginning if (chunk < 0) { chunk = 0; } long eofOffset=0; boolean seekToEnd = (chunk >= numChunks); if(seekToEnd) { chunk = chunk - 1; try { eofOffset = inputFile_.length(); } catch (IOException iox) {throw new TTransportException(iox.getMessage(), iox);} } if(chunk*cs.getChunkSize() != cs.getOffset()) { try { inputFile_.seek((long)chunk*cs.getChunkSize()); } catch (IOException iox) { throw new TTransportException("Seek to chunk " + chunk + " " +iox.getMessage(), iox); } cs.seek((long)chunk*cs.getChunkSize()); currentEvent_.setAvailable(0); inputStream_ = createInputStream(); } if(seekToEnd) { // waiting forever here - otherwise we can hit EOF and end up // having consumed partial data from the data stream. TailPolicy old = setTailPolicy(TailPolicy.WAIT_FOREVER); while(cs.getOffset() < eofOffset) { readEvent(); } currentEvent_.setAvailable(0); setTailPolicy(old); } } public void seekToEnd() throws TTransportException { if(!isOpen()) throw new TTransportException(TTransportException.NOT_OPEN, "Must open before seeking"); seekToChunk(getNumChunks()); } /** * Writes up to len bytes from the buffer. * * @param buf The output data buffer * @param off The offset to start writing from * @param len The number of bytes to write * @throws TTransportException if there was an error writing data */ public void write(byte[] buf, int off, int len) throws TTransportException { throw new TTransportException("Not Supported"); } /** * Flush any pending data out of a transport buffer. * * @throws TTransportException if there was an error writing out data. */ public void flush() throws TTransportException { throw new TTransportException("Not Supported"); } @Override public TConfiguration getConfiguration() { return null; } @Override public void updateKnownMessageSize(long size) throws TTransportException { } @Override public void checkReadBytesAvailable(long numBytes) throws TTransportException { } /** * test program * */ public static void main(String[] args) throws Exception { int num_chunks = 10; if((args.length < 1) || args[0].equals("--help") || args[0].equals("-h") || args[0].equals("-?")) { printUsage(); } if(args.length > 1) { try { num_chunks = Integer.parseInt(args[1]); } catch (Exception e) { LOGGER.error("Cannot parse " + args[1]); printUsage(); } } TFileTransport t = new TFileTransport(args[0], true); t.open(); LOGGER.info("NumChunks="+t.getNumChunks()); Random r = new Random(); for(int j=0; j<num_chunks; j++) { byte[] buf = new byte[4096]; int cnum = r.nextInt(t.getNumChunks()-1); LOGGER.info("Reading chunk "+cnum); t.seekToChunk(cnum); for(int i=0; i<4096; i++) { t.read(buf, 0, 4096); } } } private static void printUsage() { LOGGER.error("Usage: TFileTransport <filename> [num_chunks]"); LOGGER.error(" (Opens and reads num_chunks chunks from file randomly)"); System.exit(1); } }
package com.github.anno4j.schema_parsing.naming; import com.github.anno4j.model.impl.ResourceObject; import com.github.anno4j.schema.model.rdfs.RDFSSchemaResource; import com.github.anno4j.schema_parsing.building.OntGenerationConfig; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.object.ObjectConnection; import org.openrdf.repository.object.ObjectRepository; import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.regex.Pattern; /** * Utility class for generating Java compliant names for resources. * Provides functionality for deriving a package name from the hostname portion of URIs. * The readability can be enhanced by specifying the rdfs:label of the resource. */ public class IdentifierBuilder { /** * List of reserved keywords in the Java programming language. * Those can not be used as identifiers. */ private static final String JAVA_RESERVED_KEYWORDS[] = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while" }; /** * Regex for validating well-formed URIs as defined in * <a href="https://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a> Appendix B. */ private static final Pattern URI_VALIDATION_REGEX = Pattern.compile("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"); /** * Connection to use for building names, e.g. to disambiguate the identifiers. */ private final ObjectConnection connection; /** * Initializes the builder with a connection to a repository. * @param connection The connection to use later. */ IdentifierBuilder(ObjectConnection connection) { this.connection = connection; } /** * Returns a builder object that operates on the given repository. * @param repository The repository to use, e.g. for name disambiguation. * @return An instance of the builder. * @throws RepositoryException Thrown if an error occurs while opening a connection to the repository. */ public static IdentifierBuilder forObjectRepository(ObjectRepository repository) throws RepositoryException { return forObjectRepository(repository.getConnection()); } /** * Returns a builder object that operates on the connected repository. * @param connection A connection to the repository to use, e.g. for name disambiguation. * @return An instance of the builder. */ public static IdentifierBuilder forObjectRepository(ObjectConnection connection) { return new IdentifierBuilder(connection); } /** * Generates a Java compliant name using the rules and conventions defined at * <a href="https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">Naming a Package</a>. * @param name The name that should be escaped. * @return The escaped name. Returns the name '_' if the given name is empty. * @throws IllegalArgumentException Thrown if <code>name</code> is empty or null. */ private String toJavaName(String name) throws IllegalArgumentException { StringBuilder builder = new StringBuilder(name); if(!name.isEmpty()) { // Remove illegal characters: for(int i = 0; i < builder.length(); i++) { char c = builder.charAt(i); if(!Character.isJavaIdentifierPart(c)) { // Hyphens and whitespaces are not allowed in package names. Replace them by underscore: if(c == '-' || c == ' ') { builder.setCharAt(i, '_'); } else { // All other characters are removed: builder.deleteCharAt(i); i--; } } } // Append underscore to java reserved names to avoid collision: if(Arrays.binarySearch(JAVA_RESERVED_KEYWORDS, builder.toString()) >= 0) { builder.append("_"); } // Names may not start with e.g. a number and must not be empty: if(builder.length() == 0 || !Character.isJavaIdentifierStart(builder.charAt(0))) { builder.insert(0, '_'); } return builder.toString(); } else { // If a empty name is provided: throw new IllegalArgumentException("The provided name must not be null or empty."); } } /** * Returns the filename or fragment of a given URI. * @param resource The resource for which to extract the fragment or filename. * @return The fragment or filename or an deterministically chosen, unique name for the resource. */ private String getFileOrFragmentName(ResourceObject resource) { URI u; try { u = new URI(resource.getResourceAsString()); } catch (URISyntaxException e) { return "Unnamed" + resource.getResourceAsString().hashCode(); } // Handle fragments, i.e. trailing components preceded by "#": if(u.getFragment() != null) { return u.getFragment(); } // Handle URLs with paths. Pick the name of the last folder/file: if(u.getPath() != null) { String[] splits = u.getPath().split("/"); if(!splits[splits.length - 1].isEmpty()) { return splits[splits.length - 1]; } } // Handle URNs: if(u.toString().startsWith("urn:")) { String[] splits = u.toString().split(":"); if(!splits[splits.length - 1].isEmpty()) { return splits[splits.length - 1]; } } return "Unnamed" + resource.getResourceAsString().hashCode(); } /** * Determines a package name for the type generated for a URI by its hostname component. * If a portion of the hostname contains a hyphen or if it is a Java reserved name or * starts with a digit then this portion of the package name is added an underscore * (like suggested in * <a href="https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">Naming a Package</a>). * If a portion of the hostname contains a special character that is not a hyphen then this character is left out * in the package name. * The package structure extracted is appended to the base package defined in {@code config} * * @param object The resource for which to get the package name for. * @param config Configuration for Java class generation. * @return Returns the package name for the given resource. If the hostname is a IP address or the resource is a blank node * then the default package {@link OntGenerationConfig#getBasePackage()} of {@code config} is returned. */ public String packageName(ResourceObject object, OntGenerationConfig config) { URI u; try { u = new URI(object.getResourceAsString()); } catch (URISyntaxException e) { return config.getBasePackage(); } if(u.getHost() != null) { String[] splits = u.getHost().toLowerCase().split("\\."); // Iterate the components in reverse order to generate a package style name: List<String> packageNamePortions = new LinkedList<>(); for (int i = splits.length - 1; i >= 0; i--) { // Package names can't be empty, only numbers (IPv4 addresses) or contain colons (IPv6): if(!splits[i].isEmpty() && !splits[i].matches("[0-9]+") && !splits[i].contains(":")) { String portion; try { portion = toJavaName(splits[i]); // Make Java compliant packageNamePortions.add(portion); } catch (IllegalArgumentException ignored) { } } } if(packageNamePortions.size() > 0) { StringBuilder packageName = new StringBuilder(); // Join the portions of the package name found to a package name separated by '.': ListIterator<String> portionIter = packageNamePortions.listIterator(); while(portionIter.hasNext()) { packageName.append(portionIter.next()); if(portionIter.hasNext()) { packageName.append("."); } } // Append to base package if there is any: if(!config.getBasePackage().isEmpty()) { return config.getBasePackage() + "." + packageName.toString(); } else { return packageName.toString(); } } else { return config.getBasePackage(); } } else { return config.getBasePackage(); } } /** * Returns the RDFS label preferred by the given configuration. * @param resource The resource for which to get a label. * @param config The configuration object specifying the language preference. * @return Returns the RDFS label preferred or null if no label could be found. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ private String getPreferredRDFSLabel(ResourceObject resource, OntGenerationConfig config) throws RepositoryException { try { RDFSSchemaResource schemaResource = connection.findObject(RDFSSchemaResource.class, resource.getResource()); if(schemaResource != null) { CharSequence bestLabel = null; for (CharSequence label : schemaResource.getLabels()) { if (config.isPreferredForIdentifiers(label, bestLabel)) { bestLabel = label; } } if (bestLabel != null) { return bestLabel.toString(); } else { return null; } } else { // Something that is not a RDFS resource has no RDFS label: return null; } } catch (QueryEvaluationException | RepositoryException e) { throw new RepositoryException(); } } /** * Checks whether there is any other resource than the given one which has an {@code rdfs:label} * which would possibly result in the same identifier name by {@link #toJavaName(String)}. * @param resource The resource that has the label. * @param label The label to check for. * @return Returns true iff there is no possibly conflicting label within the repository. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ private boolean isRDFSLabelUnique(ResourceObject resource, String label) throws RepositoryException { // A conflicting label may be lead by some non-alphanumeric characters: StringBuilder regex = new StringBuilder("([^a-zA-Z0-9])*"); for(int i = 0; i < label.length(); i++) { char c = label.charAt(i); if(Character.isJavaIdentifierPart(c)) { regex.append(c); } // Between each char (and at the end) there may be non-alphanumeric chars (would be pruned out by name generation): regex.append("([^0-9a-zA-Z])*"); } try { return !connection.prepareBooleanQuery(QueryLanguage.SPARQL, "ASK {" + " ?s rdfs:label ?l . " + " FILTER( ?s != <" + resource.getResourceAsString() + "> && REGEX(LCASE(str(?l)), \"" + regex + "\") )" + "}" ).evaluate(); } catch (MalformedQueryException | QueryEvaluationException | RepositoryException e) { throw new RepositoryException(e); } } /** * Returns true if there is no suffix found in any other resource than the given one * that would possibly result into the same identifier name when processed by {@link #toJavaName(String)}. * @param resource The resource which suffix should be checked. * @return Returns true iff the no other possibly conflicting IRI is found in the repository. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ private boolean isFileOrFragmentNameUnique(ResourceObject resource) throws RepositoryException { String fragment = getFileOrFragmentName(resource); // A conflicting label may be lead by a separator and some non-alphanumeric characters: StringBuilder regex = new StringBuilder("(.*)(:|/|#)([^a-zA-Z0-9])*"); for(int i = 0; i < fragment.length(); i++) { char c = fragment.charAt(i); if(Character.isJavaIdentifierPart(c)) { regex.append(c); } // Between each char (and at the end) there may be non-alphanumeric chars (would be pruned out by name generation): regex.append("([^a-zA-Z0-9])*"); } regex.append("$"); try { return !connection.prepareBooleanQuery(QueryLanguage.SPARQL, "ASK {" + " ?s ?p ?o . " + " FILTER( ?s != <" + resource.getResourceAsString() + "> && REGEX(LCASE(str(?s)), \"" + regex + "\") )" + "}" ).evaluate(); } catch (MalformedQueryException | QueryEvaluationException | RepositoryException e) { throw new RepositoryException(e); } } /** * Determines a Java compliant identifier for the resource with first character in lowercase (e.g. variable names). * Removes all characters that are not allowed in identifier names and transforms separations by underscore, * hyphen or whitespace to CamelCase. * The name is preferably generated from the rdfs:label if it was set. * @param resource The resource for which to find a name. * @param config The configuration object specifying how names are built. * @return The identifier name that was determined. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ public String lowercaseIdentifier(ResourceObject resource, OntGenerationConfig config) throws RepositoryException { // Prefer the rdfs:label as a basis for the name. If not supplied, try to extract from URI: StringBuilder rawName; String rdfsLabel = getPreferredRDFSLabel(resource, config); if(rdfsLabel != null && (!config.isRDFSLabelAmbiguityChecked() || isRDFSLabelUnique(resource, rdfsLabel))) { rawName = new StringBuilder(rdfsLabel); } else if(!config.isFileOrFragmentAmbiguityChecked() || isFileOrFragmentNameUnique(resource)){ rawName = new StringBuilder(getFileOrFragmentName(resource)); } else { rawName = new StringBuilder(getFileOrFragmentName(resource)).append(resource.getResourceAsString().hashCode()); } // Replace separation with underscore and/or whitespace to camel case: int pivotUnderscore = -1, pivotWhitespace = -1; do { pivotUnderscore = rawName.indexOf("_", pivotUnderscore); pivotWhitespace = rawName.indexOf(" ", pivotWhitespace); if(pivotUnderscore != -1) { if(pivotUnderscore + 1 < rawName.length() && Character.isLowerCase(rawName.charAt(pivotUnderscore + 1))) { rawName.setCharAt(pivotUnderscore + 1, Character.toUpperCase(rawName.charAt(pivotUnderscore + 1))); } rawName.deleteCharAt(pivotUnderscore); // If the pivot for whitespace was ahead set it one back, because one character was deleted: if(pivotUnderscore < pivotWhitespace) { pivotWhitespace--; } } if(pivotWhitespace != -1) { if(pivotWhitespace + 1 < rawName.length() && Character.isLowerCase(rawName.charAt(pivotWhitespace + 1))) { rawName.setCharAt(pivotWhitespace + 1, Character.toUpperCase(rawName.charAt(pivotWhitespace + 1))); } rawName.deleteCharAt(pivotWhitespace); // If the pivot for underscore was ahead set it one back, because one character was deleted: if(pivotUnderscore > pivotWhitespace) { pivotUnderscore--; } } } while (pivotUnderscore != -1 || pivotWhitespace != -1); // Make sure the first character is lowercase: if(rawName.length() > 0) { rawName.setCharAt(0, Character.toLowerCase(rawName.charAt(0))); } return toJavaName(rawName.toString()); } /** * Determines a Java compliant identifier for the resource with first character in uppercase (e.g. class names). * Removes all characters that are not allowed in identifier names and transforms separations by underscore, * hyphen or whitespace to CamelCase. * The name is preferably generated from the rdfs:label if it was set. * @param resource The resource for which to find a name. * @param config The configuration object specifying how names are built. * @return The identifier name that was determined. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ public String capitalizedIdentifier(ResourceObject resource, OntGenerationConfig config) throws RepositoryException { // Prune non allowed characters from the raw name: StringBuilder identifier = new StringBuilder(lowercaseIdentifier(resource, config)); // Capitalize first character as defined by the coding conventions: identifier.setCharAt(0, Character.toUpperCase(identifier.charAt(0))); return identifier.toString(); } /** * Extracts a plural form for this resource. * A trailing "s" is added and some simple grammatical rules (for english) are applied. * @param resource The resource for which to find a name. * @param config The configuration object specifying how names are built. * @return Same as {@link #lowercaseIdentifier(ResourceObject, OntGenerationConfig)}, but in a plural form. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ public String lowercasePluralIdentifier(ResourceObject resource, OntGenerationConfig config) throws RepositoryException { StringBuilder identifier = new StringBuilder(); identifier.append(lowercaseIdentifier(resource, config)); // Replace trailing "y" with "ie". E.g. "capacity" will be transformed to "capacities": if(identifier.charAt(identifier.length() - 1) == 'y') { identifier.deleteCharAt(identifier.length() - 1); identifier.append("ie"); } // Only append trailing "s" if the name does not yet end with one: if(identifier.charAt(identifier.length() - 1) != 's') { identifier.append("s"); } return identifier.toString(); } /** * Extracts a capitalized plural form for this resource. * A trailing "s" is added and some simple grammatical rules (for english) are applied. * @param resource The resource for which to find a name. * @param config The configuration object specifying how names are built. * @return Same as {@link #capitalizedIdentifier(ResourceObject, OntGenerationConfig)}, but in a plural form. * @throws RepositoryException Thrown if an error occurs while querying the repository. */ public String capitalizedPluralIdentifier(ResourceObject resource, OntGenerationConfig config) throws RepositoryException { StringBuilder identifier = new StringBuilder(lowercasePluralIdentifier(resource, config)); if(identifier.length() > 0) { identifier.setCharAt(0, Character.toUpperCase(identifier.charAt(0))); } return identifier.toString(); } }
package 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. */ import java.io.IOException; import java.io.StringReader; import java.io.Writer; import org.apache.velocity.context.EvaluateContext; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.apache.velocity.exception.TemplateInitException; import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.parser.ParseException; import org.apache.velocity.runtime.parser.ParserTreeConstants; import org.apache.velocity.runtime.parser.node.Node; import org.apache.velocity.runtime.parser.node.SimpleNode; import org.apache.velocity.util.introspection.Info; /** * Evaluates the directive argument as a VTL string, using the existing * context. * * @author <a href="mailto:wglass@apache.org">Will Glass-Husain</a> * @version $Id: Evaluate.java 898032 2010-01-11 19:51:03Z nbubna $ * @since 1.6 */ public class Evaluate extends Directive { /** * Return name of this directive. * @return The name of this directive. */ public String getName() { return "evaluate"; } /** * Return type of this directive. * @return The type of this directive. */ public int getType() { return LINE; } /** * Initialize and check arguments. * @param rs * @param context * @param node * @throws TemplateInitException */ public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException { super.init( rs, context, node ); /** * Check that there is exactly one argument and it is a string or reference. */ int argCount = node.jjtGetNumChildren(); if (argCount == 0) { throw new TemplateInitException( "#" + getName() + "() requires exactly one argument", context.getCurrentTemplateName(), node.getColumn(), node.getLine()); } if (argCount > 1) { /* * use line/col of second argument */ throw new TemplateInitException( "#" + getName() + "() requires exactly one argument", context.getCurrentTemplateName(), node.jjtGetChild(1).getColumn(), node.jjtGetChild(1).getLine()); } Node childNode = node.jjtGetChild(0); if ( childNode.getType() != ParserTreeConstants.JJTSTRINGLITERAL && childNode.getType() != ParserTreeConstants.JJTREFERENCE ) { throw new TemplateInitException( "#" + getName() + "() argument must be a string literal or reference", context.getCurrentTemplateName(), childNode.getColumn(), childNode.getLine()); } } /** * Evaluate the argument, convert to a String, and evaluate again * (with the same context). * @param context * @param writer * @param node * @return True if the directive rendered successfully. * @throws IOException * @throws ResourceNotFoundException * @throws ParseErrorException * @throws MethodInvocationException */ public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException { /* * Evaluate the string with the current context. We know there is * exactly one argument and it is a string or reference. */ Object value = node.jjtGetChild(0).value( context ); String sourceText; if ( value != null ) { sourceText = value.toString(); } else { sourceText = ""; } /* * The new string needs to be parsed since the text has been dynamically generated. */ String templateName = context.getCurrentTemplateName(); SimpleNode nodeTree = null; try { nodeTree = rsvc.parse(new StringReader(sourceText), templateName, false); } catch (ParseException pex) { // use the line/column from the template Info info = new Info( templateName, node.getLine(), node.getColumn() ); throw new ParseErrorException( pex.getMessage(), info ); } catch (TemplateInitException pex) { Info info = new Info( templateName, node.getLine(), node.getColumn() ); throw new ParseErrorException( pex.getMessage(), info ); } /* * now we want to init and render. Chain the context * to prevent any changes to the current context. */ if (nodeTree != null) { InternalContextAdapter ica = new EvaluateContext(context, rsvc); ica.pushCurrentTemplateName( templateName ); try { try { nodeTree.init( ica, rsvc ); } catch (TemplateInitException pex) { Info info = new Info( templateName, node.getLine(), node.getColumn() ); throw new ParseErrorException( pex.getMessage(), info ); } try { preRender(ica); /* * now render, and let any exceptions fly */ nodeTree.render( ica, writer ); } catch (StopCommand stop) { if (!stop.isFor(this)) { throw stop; } else if (rsvc.getLog().isDebugEnabled()) { rsvc.getLog().debug(stop.getMessage()); } } catch (ParseErrorException pex) { // convert any parsing errors to the correct line/col Info info = new Info( templateName, node.getLine(), node.getColumn() ); throw new ParseErrorException( pex.getMessage(), info ); } } finally { ica.popCurrentTemplateName(); postRender(ica); } return true; } return false; } }
/** * Copyright 2009 - 2011 Sergio Bossa (sergio.bossa@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package terrastore.partition.impl; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import terrastore.communication.Cluster; import terrastore.communication.Node; import terrastore.router.impl.HashFunction; import terrastore.partition.ClusterPartitioner; import terrastore.store.Key; /** * {@link terrastore.partition.ClusterPartitioner} implementation based on consistent hashing and ordering. * * @author Sergio Bossa */ public class ClusterHashingPartitioner implements ClusterPartitioner { private static final Logger LOG = LoggerFactory.getLogger(ClusterHashingPartitioner.class); // private final int maxPartitions; private final HashFunction hashFunction; private final Map<Cluster, Partitioner> partitioners; private final ReadWriteLock stateLock; public ClusterHashingPartitioner(int maxPartitions, HashFunction hashFunction) { this.maxPartitions = maxPartitions; this.hashFunction = hashFunction; this.partitioners = new HashMap<Cluster, Partitioner>(); this.stateLock = new ReentrantReadWriteLock(); } @Override public int getMaxPartitions() { return maxPartitions; } @Override public void addNode(Cluster cluster, Node node) { stateLock.writeLock().lock(); try { Partitioner partitioner = partitioners.get(cluster); if (partitioner == null) { partitioner = new Partitioner(maxPartitions, hashFunction); partitioners.put(cluster, partitioner); } partitioner.addNode(node); } finally { stateLock.writeLock().unlock(); } } @Override public void removeNode(Cluster cluster, Node node) { stateLock.writeLock().lock(); try { Partitioner partitioner = partitioners.get(cluster); if (partitioner != null) { partitioner.removeNode(node); } } finally { stateLock.writeLock().unlock(); } } @Override public Set<Node> getNodesFor(Cluster cluster) { stateLock.readLock().lock(); try { Partitioner partitioner = partitioners.get(cluster); if (partitioner != null) { return partitioner.getNodes(); } else { return Collections.emptySet(); } } finally { stateLock.readLock().unlock(); } } @Override public Node getNodeFor(Cluster cluster, String bucket) { stateLock.readLock().lock(); try { Partitioner partitioner = partitioners.get(cluster); if (partitioner != null) { return partitioner.getNodeFor(bucket); } else { return null; } } finally { stateLock.readLock().unlock(); } } @Override public Node getNodeFor(Cluster cluster, String bucket, Key key) { stateLock.readLock().lock(); try { Partitioner partitioner = partitioners.get(cluster); if (partitioner != null) { return partitioner.getNodeFor(bucket, key); } else { return null; } } finally { stateLock.readLock().unlock(); } } @Override public void cleanupPartitions() { stateLock.writeLock().lock(); try { for (Partitioner partitioner : partitioners.values()) { partitioner.cleanupPartitions(); } } finally { stateLock.writeLock().unlock(); } } private static class Partitioner { private final int maxPartitions; private final HashFunction hashFunction; private final Node[] ring; private final SortedSet<Node> nodes; private final Map<Node, List<Integer>> nodesToPartitions; public Partitioner(int maxPartitions, HashFunction hashFunction) { this.maxPartitions = maxPartitions; this.hashFunction = hashFunction; this.ring = new Node[maxPartitions]; this.nodes = new TreeSet<Node>(new NodeComparator()); this.nodesToPartitions = new HashMap(); } public void addNode(Node node) { if (nodes.size() == maxPartitions) { // TODO : use proper exception here! throw new IllegalStateException("Reached partitions limit: " + maxPartitions); } else if (!nodes.contains(node)) { nodes.add(node); rebuildPartitions(); } else { // TODO : use proper exception here? throw new IllegalStateException("Duplicated node: " + node.getName()); } } public void removeNode(Node node) { if (nodes.contains(node)) { nodes.remove(node); rebuildPartitions(); } else { // TODO : use proper exception here? throw new IllegalStateException("Not existent node: " + node.getName()); } } public Set<Node> getNodes() { return nodes; } public Node getNodeFor(String bucket) { String toHash = bucket; int hash = hashFunction.hash(toHash, maxPartitions); return selectNodeAtPartition(hash); } public Node getNodeFor(String bucket, Key key) { String toHash = bucket + key; int hash = hashFunction.hash(toHash, maxPartitions); return selectNodeAtPartition(hash); } public void cleanupPartitions() { nodes.clear(); nodesToPartitions.clear(); } private void rebuildPartitions() { int totalNodes = nodes.size(); if (totalNodes > 0) { int optimalPartitionSize = maxPartitions / totalNodes; int ringPosition = 0; int nodePosition = 1; nodesToPartitions.clear(); for (Node node : nodes) { List<Integer> nodePartitions = new ArrayList<Integer>(optimalPartitionSize + (maxPartitions % totalNodes)); for (int i = 0; (i < optimalPartitionSize) || (nodePosition == totalNodes && ringPosition < ring.length); i++) { nodePartitions.add(ringPosition); ring[ringPosition] = node; ringPosition++; } nodesToPartitions.put(node, nodePartitions); nodePosition++; } } else { for (int i = 0; i < maxPartitions; i++) { ring[i] = null; } nodesToPartitions.clear(); } } private Node selectNodeAtPartition(int partition) { if (partition >= 0 && partition < ring.length) { Node selected = ring[partition]; LOG.debug("Getting node {} at partition {}", selected, partition); return selected; } else { // TODO : use proper exception here? throw new IllegalStateException("Wrong partition number: " + partition); } } } private static class NodeComparator implements Comparator<Node> { public int compare(Node n1, Node n2) { return n1.getName().compareTo(n2.getName()); } } }
/* * 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.sling.engine.impl.filter; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import org.apache.sling.commons.osgi.OsgiUtil; import org.apache.sling.engine.EngineConstants; import org.apache.sling.engine.impl.helper.SlingFilterConfig; import org.apache.sling.engine.impl.helper.SlingServletContext; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ServletFilterManager extends ServiceTracker { public static enum FilterChainType { /** * Indicates request level filters. * * @see EngineConstants#FILTER_SCOPE_REQUEST */ REQUEST("Request"), /** * Indicates error level filters. * * @see EngineConstants#FILTER_SCOPE_ERROR */ ERROR("Error"), /** * Indicates include level filters. * * @see EngineConstants#FILTER_SCOPE_INCLUDE */ INCLUDE("Include"), /** * Indicates forward level filters. * * @see EngineConstants#FILTER_SCOPE_FORWARD */ FORWARD("Forward"), /** * Indicates component level filters. * * @see EngineConstants#FILTER_SCOPE_COMPONENT */ COMPONENT("Component"); private final String message; private FilterChainType(final String message) { this.message = message; } @Override public String toString() { return message; } } /** * The service property used by Felix's HttpService whiteboard * implementation. */ private static String FELIX_WHITEBOARD_PATTERN_PROPERTY = "pattern"; // TODO: use filter (&(objectclass=javax.servlet.Filter)(filter.scope=*)) private static final String FILTER_SERVICE_NAME = Filter.class.getName(); /** default log */ private final Logger log = LoggerFactory.getLogger(getClass()); private final SlingServletContext servletContext; private final SlingFilterChainHelper[] filterChains; private final boolean compatMode; public ServletFilterManager(final BundleContext context, final SlingServletContext servletContext, final boolean compatMode) { super(context, FILTER_SERVICE_NAME, null); this.servletContext = servletContext; this.filterChains = new SlingFilterChainHelper[FilterChainType.values().length]; this.filterChains[FilterChainType.REQUEST.ordinal()] = new SlingFilterChainHelper(); this.filterChains[FilterChainType.ERROR.ordinal()] = new SlingFilterChainHelper(); this.filterChains[FilterChainType.INCLUDE.ordinal()] = new SlingFilterChainHelper(); this.filterChains[FilterChainType.FORWARD.ordinal()] = new SlingFilterChainHelper(); this.filterChains[FilterChainType.COMPONENT.ordinal()] = new SlingFilterChainHelper(); this.compatMode = compatMode; } public SlingFilterChainHelper getFilterChain(final FilterChainType chain) { return filterChains[chain.ordinal()]; } public Filter[] getFilters(final FilterChainType chain) { return getFilterChain(chain).getFilters(); } @Override public Object addingService(ServiceReference reference) { Object service = super.addingService(reference); if (service instanceof Filter) { initFilter(reference, (Filter) service); } return service; } @Override public void modifiedService(ServiceReference reference, Object service) { if (service instanceof Filter) { destroyFilter(reference, (Filter) service); initFilter(reference, (Filter) service); } super.modifiedService(reference, service); } @Override public void removedService(ServiceReference reference, Object service) { if (service instanceof Filter) { destroyFilter(reference, (Filter) service); } super.removedService(reference, service); } /** * Check if the filter should be excluded. */ private boolean excludeFilter(final ServiceReference reference) { // if the service has a filter scope property, we include it if ( reference.getProperty(EngineConstants.SLING_FILTER_SCOPE) != null || reference.getProperty(EngineConstants.FILTER_SCOPE) != null ) { return false; } // in compat mode we allow all filters not having the felix pattern prop! if ( this.compatMode ) { // Check if filter will be registered by Felix HttpService Whiteboard if (reference.getProperty(FELIX_WHITEBOARD_PATTERN_PROPERTY) != null) { return true; } return false; } return true; } private void initFilter(final ServiceReference reference, final Filter filter) { if ( this.excludeFilter(reference) ) { return; } final String filterName = SlingFilterConfig.getName(reference); if (filterName == null) { log.error("initFilter: Missing name for filter {}", reference); } else { // initialize the filter first try { final FilterConfig config = new SlingFilterConfig( servletContext, reference, filterName); filter.init(config); // service id Long serviceId = (Long) reference.getProperty(Constants.SERVICE_ID); // get the order, Integer.MAX_VALUE by default Object orderObj = reference.getProperty(Constants.SERVICE_RANKING); if (orderObj == null) { // filter order is defined as lower value has higher priority // while service ranking is the opposite // In addition we allow different types than Integer orderObj = reference.getProperty(EngineConstants.FILTER_ORDER); if ( orderObj != null ) { // we can use 0 as the default as this will be applied in // the next step anyway if this props contains an invalid // value Integer order = OsgiUtil.toInteger(orderObj, 0); order = order * -1; } } final int order = (orderObj instanceof Integer) ? ((Integer) orderObj).intValue() : 0; // register by scope String[] scopes = OsgiUtil.toStringArray( reference.getProperty(EngineConstants.SLING_FILTER_SCOPE), null); if ( scopes == null ) { scopes = OsgiUtil.toStringArray( reference.getProperty(EngineConstants.FILTER_SCOPE), null); } if (scopes != null && scopes.length > 0) { for (String scope : scopes) { scope = scope.toUpperCase(); try { FilterChainType type = FilterChainType.valueOf(scope.toString()); getFilterChain(type).addFilter(filter, serviceId, order); if (type == FilterChainType.COMPONENT) { getFilterChain(FilterChainType.INCLUDE).addFilter( filter, serviceId, order); getFilterChain(FilterChainType.FORWARD).addFilter( filter, serviceId, order); } } catch (IllegalArgumentException iae) { // TODO: log ... } } } else { log.warn(String.format( "A Filter (Service ID %s) has been registered without a filter.scope property.", reference.getProperty(Constants.SERVICE_ID))); getFilterChain(FilterChainType.REQUEST).addFilter(filter, serviceId, order); } } catch (ServletException ce) { log.error("Filter " + filterName + " failed to initialize", ce); } catch (Throwable t) { log.error("Unexpected Problem initializing ComponentFilter " + "", t); } } } private void destroyFilter(final ServiceReference reference, final Filter filter) { // service id Object serviceId = reference.getProperty(Constants.SERVICE_ID); boolean removed = false; for (SlingFilterChainHelper filterChain : filterChains) { removed |= filterChain.removeFilterById(serviceId); } // destroy it if (removed) { try { filter.destroy(); } catch (Throwable t) { log.error("Unexpected problem destroying Filter {}", filter, t); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.dbcp; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; /** * A dummy {@link Statement}, for testing purposes. * * @author Rodney Waldhoff * @author Dirk Verbeeck * @version $Revision$ $Date$ */ public class TesterStatement implements Statement { public TesterStatement(Connection conn) { _connection = conn; } public TesterStatement(Connection conn, int resultSetType, int resultSetConcurrency) { _connection = conn; _resultSetType = resultSetType; _resultSetConcurrency = resultSetConcurrency; } protected Connection _connection = null; protected boolean _open = true; protected int _rowsUpdated = 1; protected boolean _executeResponse = true; protected int _maxFieldSize = 1024; protected int _maxRows = 1024; protected boolean _escapeProcessing = false; protected int _queryTimeout = 1000; protected String _cursorName = null; protected int _fetchDirection = 1; protected int _fetchSize = 1; protected int _resultSetConcurrency = 1; protected int _resultSetType = 1; protected ResultSet _resultSet = null; public ResultSet executeQuery(String sql) throws SQLException { checkOpen(); if("null".equals(sql)) { return null; } if("invalid".equals(sql)) { throw new SQLException("invalid query"); } if ("broken".equals(sql)) { throw new SQLException("broken connection"); } if("select username".equals(sql)) { String username = ((TesterConnection) _connection).getUsername(); Object[][] data = {{username}}; return new TesterResultSet(this, data); } else { // Simulate timeout if queryTimout is set to less than 5 seconds if (_queryTimeout > 0 && _queryTimeout < 5) { throw new SQLException("query timeout"); } return new TesterResultSet(this); } } public int executeUpdate(String sql) throws SQLException { checkOpen(); return _rowsUpdated; } public void close() throws SQLException { // calling close twice has no effect if (!_open) { return; } _open = false; if (_resultSet != null) { _resultSet.close(); _resultSet = null; } } public int getMaxFieldSize() throws SQLException { checkOpen(); return _maxFieldSize; } public void setMaxFieldSize(int max) throws SQLException { checkOpen(); _maxFieldSize = max; } public int getMaxRows() throws SQLException { checkOpen(); return _maxRows; } public void setMaxRows(int max) throws SQLException { checkOpen(); _maxRows = max; } public void setEscapeProcessing(boolean enable) throws SQLException { checkOpen(); _escapeProcessing = enable; } public int getQueryTimeout() throws SQLException { checkOpen(); return _queryTimeout; } public void setQueryTimeout(int seconds) throws SQLException { checkOpen(); _queryTimeout = seconds; } public void cancel() throws SQLException { checkOpen(); } public SQLWarning getWarnings() throws SQLException { checkOpen(); return null; } public void clearWarnings() throws SQLException { checkOpen(); } public void setCursorName(String name) throws SQLException { checkOpen(); _cursorName = name; } public boolean execute(String sql) throws SQLException { checkOpen(); if("invalid".equals(sql)) { throw new SQLException("invalid query"); } return _executeResponse; } public ResultSet getResultSet() throws SQLException { checkOpen(); if (_resultSet == null) { _resultSet = new TesterResultSet(this); } return _resultSet; } public int getUpdateCount() throws SQLException { checkOpen(); return _rowsUpdated; } public boolean getMoreResults() throws SQLException { checkOpen(); return false; } public void setFetchDirection(int direction) throws SQLException { checkOpen(); _fetchDirection = direction; } public int getFetchDirection() throws SQLException { checkOpen(); return _fetchDirection; } public void setFetchSize(int rows) throws SQLException { checkOpen(); _fetchSize = rows; } public int getFetchSize() throws SQLException { checkOpen(); return _fetchSize; } public int getResultSetConcurrency() throws SQLException { checkOpen(); return _resultSetConcurrency; } public int getResultSetType() throws SQLException { checkOpen(); return _resultSetType; } public void addBatch(String sql) throws SQLException { checkOpen(); } public void clearBatch() throws SQLException { checkOpen(); } public int[] executeBatch() throws SQLException { checkOpen(); return new int[0]; } public Connection getConnection() throws SQLException { checkOpen(); return _connection; } protected void checkOpen() throws SQLException { if(!_open) { throw new SQLException("Connection is closed."); } } public boolean getMoreResults(int current) throws SQLException { throw new SQLException("Not implemented."); } public ResultSet getGeneratedKeys() throws SQLException { return new TesterResultSet(this); } public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { throw new SQLException("Not implemented."); } public int executeUpdate(String sql, int columnIndexes[]) throws SQLException { throw new SQLException("Not implemented."); } public int executeUpdate(String sql, String columnNames[]) throws SQLException { throw new SQLException("Not implemented."); } public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { throw new SQLException("Not implemented."); } public boolean execute(String sql, int columnIndexes[]) throws SQLException { throw new SQLException("Not implemented."); } public boolean execute(String sql, String columnNames[]) throws SQLException { throw new SQLException("Not implemented."); } public int getResultSetHoldability() throws SQLException { checkOpen(); throw new SQLException("Not implemented."); } /* JDBC_4_ANT_KEY_BEGIN */ public boolean isWrapperFor(Class<?> iface) throws SQLException { throw new SQLException("Not implemented."); } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("Not implemented."); } public boolean isClosed() throws SQLException { throw new SQLException("Not implemented."); } public void setPoolable(boolean poolable) throws SQLException { throw new SQLException("Not implemented."); } public boolean isPoolable() throws SQLException { throw new SQLException("Not implemented."); } /* JDBC_4_ANT_KEY_END */ }
/* * 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.calcite.sql; import org.apache.calcite.config.CalciteSystemProperty; import org.apache.calcite.sql.parser.SqlParserUtil; import org.apache.calcite.util.Glossary; import org.apache.calcite.util.SerializableCharset; import org.apache.calcite.util.Util; import java.io.Serializable; import java.nio.charset.Charset; import java.util.Locale; import static org.apache.calcite.util.Static.RESOURCE; /** * A <code>SqlCollation</code> is an object representing a <code>Collate</code> * statement. It is immutable. */ public class SqlCollation implements Serializable { public static final SqlCollation COERCIBLE = new SqlCollation(Coercibility.COERCIBLE); public static final SqlCollation IMPLICIT = new SqlCollation(Coercibility.IMPLICIT); //~ Enums ------------------------------------------------------------------ /** * <blockquote>A &lt;character value expression&gt; consisting of a column * reference has the coercibility characteristic Implicit, with collating * sequence as defined when the column was created. A &lt;character value * expression&gt; consisting of a value other than a column (e.g., a host * variable or a literal) has the coercibility characteristic Coercible, * with the default collation for its character repertoire. A &lt;character * value expression&gt; simply containing a &lt;collate clause&gt; has the * coercibility characteristic Explicit, with the collating sequence * specified in the &lt;collate clause&gt;.</blockquote> * * @see Glossary#SQL99 SQL:1999 Part 2 Section 4.2.3 */ public enum Coercibility { /** Strongest coercibility. */ EXPLICIT, IMPLICIT, COERCIBLE, /** Weakest coercibility. */ NONE } //~ Instance fields -------------------------------------------------------- protected final String collationName; protected final SerializableCharset wrappedCharset; protected final Locale locale; protected final String strength; private final Coercibility coercibility; //~ Constructors ----------------------------------------------------------- /** * Creates a Collation by its name and its coercibility * * @param collation Collation specification * @param coercibility Coercibility */ public SqlCollation( String collation, Coercibility coercibility) { this.coercibility = coercibility; SqlParserUtil.ParsedCollation parseValues = SqlParserUtil.parseCollation(collation); Charset charset = parseValues.getCharset(); this.wrappedCharset = SerializableCharset.forCharset(charset); locale = parseValues.getLocale(); strength = parseValues.getStrength(); String c = charset.name().toUpperCase(Locale.ROOT) + "$" + locale.toString(); if ((strength != null) && (strength.length() > 0)) { c += "$" + strength; } collationName = c; } /** * Creates a SqlCollation with the default collation name and the given * coercibility. * * @param coercibility Coercibility */ public SqlCollation(Coercibility coercibility) { this( CalciteSystemProperty.DEFAULT_COLLATION.value(), coercibility); } //~ Methods ---------------------------------------------------------------- public boolean equals(Object o) { return this == o || o instanceof SqlCollation && collationName.equals(((SqlCollation) o).collationName); } @Override public int hashCode() { return collationName.hashCode(); } /** * Returns the collating sequence (the collation name) and the coercibility * for the resulting value of a dyadic operator. * * @param col1 first operand for the dyadic operation * @param col2 second operand for the dyadic operation * @return the resulting collation sequence. The "no collating sequence" * result is returned as null. * * @see Glossary#SQL99 SQL:1999 Part 2 Section 4.2.3 Table 2 */ public static SqlCollation getCoercibilityDyadicOperator( SqlCollation col1, SqlCollation col2) { return getCoercibilityDyadic(col1, col2); } /** * Returns the collating sequence (the collation name) and the coercibility * for the resulting value of a dyadic operator. * * @param col1 first operand for the dyadic operation * @param col2 second operand for the dyadic operation * @return the resulting collation sequence * * @throws org.apache.calcite.runtime.CalciteException from * {@link org.apache.calcite.runtime.CalciteResource#invalidCompare} or * {@link org.apache.calcite.runtime.CalciteResource#differentCollations} * if no collating sequence can be deduced * * @see Glossary#SQL99 SQL:1999 Part 2 Section 4.2.3 Table 2 */ public static SqlCollation getCoercibilityDyadicOperatorThrows( SqlCollation col1, SqlCollation col2) { SqlCollation ret = getCoercibilityDyadic(col1, col2); if (null == ret) { throw RESOURCE.invalidCompare( col1.collationName, "" + col1.coercibility, col2.collationName, "" + col2.coercibility).ex(); } return ret; } /** * Returns the collating sequence (the collation name) to use for the * resulting value of a comparison. * * @param col1 first operand for the dyadic operation * @param col2 second operand for the dyadic operation * * @return the resulting collation sequence. If no collating * sequence could be deduced throws a * {@link org.apache.calcite.runtime.CalciteResource#invalidCompare} * * @see Glossary#SQL99 SQL:1999 Part 2 Section 4.2.3 Table 3 */ public static String getCoercibilityDyadicComparison( SqlCollation col1, SqlCollation col2) { return getCoercibilityDyadicOperatorThrows(col1, col2).collationName; } /** * Returns the result for {@link #getCoercibilityDyadicComparison} and * {@link #getCoercibilityDyadicOperator}. */ protected static SqlCollation getCoercibilityDyadic( SqlCollation col1, SqlCollation col2) { assert null != col1; assert null != col2; final Coercibility coercibility1 = col1.getCoercibility(); final Coercibility coercibility2 = col2.getCoercibility(); switch (coercibility1) { case COERCIBLE: switch (coercibility2) { case COERCIBLE: return col2; case IMPLICIT: return col2; case NONE: return null; case EXPLICIT: return col2; default: throw Util.unexpected(coercibility2); } case IMPLICIT: switch (coercibility2) { case COERCIBLE: return col1; case IMPLICIT: if (col1.collationName.equals(col2.collationName)) { return col2; } return null; case NONE: return null; case EXPLICIT: return col2; default: throw Util.unexpected(coercibility2); } case NONE: switch (coercibility2) { case COERCIBLE: case IMPLICIT: case NONE: return null; case EXPLICIT: return col2; default: throw Util.unexpected(coercibility2); } case EXPLICIT: switch (coercibility2) { case COERCIBLE: case IMPLICIT: case NONE: return col1; case EXPLICIT: if (col1.collationName.equals(col2.collationName)) { return col2; } throw RESOURCE.differentCollations( col1.collationName, col2.collationName).ex(); default: throw Util.unexpected(coercibility2); } default: throw Util.unexpected(coercibility1); } } public String toString() { return "COLLATE " + collationName; } public void unparse( SqlWriter writer) { writer.keyword("COLLATE"); writer.identifier(collationName, false); } public Charset getCharset() { return wrappedCharset.getCharset(); } public final String getCollationName() { return collationName; } public final SqlCollation.Coercibility getCoercibility() { return coercibility; } } // End SqlCollation.java
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.dynamodb; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.*; import com.amazonaws.auth.*; import com.amazonaws.handlers.HandlerChainFactory; import com.amazonaws.handlers.RequestHandler; import com.amazonaws.http.HttpResponseHandler; import com.amazonaws.http.JsonResponseHandler; import com.amazonaws.http.JsonErrorResponseHandler; import com.amazonaws.http.ExecutionContext; import com.amazonaws.util.AWSRequestMetrics; import com.amazonaws.util.AWSRequestMetrics.Field; import com.amazonaws.internal.StaticCredentialsProvider; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.JsonUnmarshallerContext; import com.amazonaws.transform.JsonErrorUnmarshaller; import com.amazonaws.util.json.JSONObject; import com.amazonaws.services.dynamodb.model.*; import com.amazonaws.services.dynamodb.model.transform.*; /** * Client for accessing AmazonDynamoDB. All service calls made * using this client are blocking, and will not return until the service call * completes. * <p> * <p> * Amazon DynamoDB is a fast, highly scalable, highly available, cost-effective non-relational database service. * </p> * <p> * Amazon DynamoDB removes traditional scalability limitations on data storage while maintaining low latency and predictable performance. * </p> */ public class AmazonDynamoDBClient extends AmazonWebServiceClient implements AmazonDynamoDB { /** Provider for AWS credentials. */ private AWSCredentialsProvider awsCredentialsProvider; private static final Log log = LogFactory.getLog(AmazonDynamoDB.class); /** * List of exception unmarshallers for all AmazonDynamoDB exceptions. */ protected List<Unmarshaller<AmazonServiceException, JSONObject>> exceptionUnmarshallers; /** AWS signer for authenticating requests. */ private AWS4Signer signer; /** * Constructs a new client to invoke service methods on * AmazonDynamoDB. A credentials provider chain will be used * that searches for credentials in this order: * <ul> * <li> Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY </li> * <li> Java System Properties - aws.accessKeyId and aws.secretKey </li> * <li> Instance profile credentials delivered through the Amazon EC2 metadata service </li> * </ul> * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @see DefaultAWSCredentialsProvider */ public AmazonDynamoDBClient() { this(new DefaultAWSCredentialsProviderChain(), new ClientConfiguration()); } /** * Constructs a new client to invoke service methods on * AmazonDynamoDB. A credentials provider chain will be used * that searches for credentials in this order: * <ul> * <li> Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY </li> * <li> Java System Properties - aws.accessKeyId and aws.secretKey </li> * <li> Instance profile credentials delivered through the Amazon EC2 metadata service </li> * </ul> * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @param clientConfiguration The client configuration options controlling how this * client connects to AmazonDynamoDB * (ex: proxy settings, retry counts, etc.). * * @see DefaultAWSCredentialsProvider */ public AmazonDynamoDBClient(ClientConfiguration clientConfiguration) { this(new DefaultAWSCredentialsProviderChain(), clientConfiguration); } /** * Constructs a new client to invoke service methods on * AmazonDynamoDB using the specified AWS account credentials. * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @param awsCredentials The AWS credentials (access key ID and secret key) to use * when authenticating with AWS services. */ public AmazonDynamoDBClient(AWSCredentials awsCredentials) { this(awsCredentials, new ClientConfiguration()); } /** * Constructs a new client to invoke service methods on * AmazonDynamoDB using the specified AWS account credentials * and client configuration options. * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @param awsCredentials The AWS credentials (access key ID and secret key) to use * when authenticating with AWS services. * @param clientConfiguration The client configuration options controlling how this * client connects to AmazonDynamoDB * (ex: proxy settings, retry counts, etc.). */ public AmazonDynamoDBClient(AWSCredentials awsCredentials, ClientConfiguration clientConfiguration) { super(clientConfiguration); this.awsCredentialsProvider = new StaticCredentialsProvider(awsCredentials); init(); } /** * Constructs a new client to invoke service methods on * AmazonDynamoDB using the specified AWS account credentials provider. * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials * to authenticate requests with AWS services. */ public AmazonDynamoDBClient(AWSCredentialsProvider awsCredentialsProvider) { this(awsCredentialsProvider, new ClientConfiguration()); } /** * Constructs a new client to invoke service methods on * AmazonDynamoDB using the specified AWS account credentials * provider and client configuration options. * * <p> * All service calls made using this new client object are blocking, and will not * return until the service call completes. * * @param awsCredentialsProvider * The AWS credentials provider which will provide credentials * to authenticate requests with AWS services. * @param clientConfiguration The client configuration options controlling how this * client connects to AmazonDynamoDB * (ex: proxy settings, retry counts, etc.). */ public AmazonDynamoDBClient(AWSCredentialsProvider awsCredentialsProvider, ClientConfiguration clientConfiguration) { super(clientConfiguration); this.awsCredentialsProvider = awsCredentialsProvider; init(); } private void init() { exceptionUnmarshallers = new ArrayList<Unmarshaller<AmazonServiceException, JSONObject>>(); exceptionUnmarshallers.add(new LimitExceededExceptionUnmarshaller()); exceptionUnmarshallers.add(new InternalServerErrorExceptionUnmarshaller()); exceptionUnmarshallers.add(new ProvisionedThroughputExceededExceptionUnmarshaller()); exceptionUnmarshallers.add(new ResourceInUseExceptionUnmarshaller()); exceptionUnmarshallers.add(new ConditionalCheckFailedExceptionUnmarshaller()); exceptionUnmarshallers.add(new ResourceNotFoundExceptionUnmarshaller()); exceptionUnmarshallers.add(new JsonErrorUnmarshaller()); setEndpoint("dynamodb.us-east-1.amazonaws.com/"); signer = new AWS4Signer(); signer.setServiceName("dynamodb"); HandlerChainFactory chainFactory = new HandlerChainFactory(); requestHandlers.addAll(chainFactory.newRequestHandlerChain( "/com/amazonaws/services/dynamodb/request.handlers")); clientConfiguration = new ClientConfiguration(clientConfiguration); if (clientConfiguration.getMaxErrorRetry() == ClientConfiguration.DEFAULT_MAX_RETRIES) { log.debug("Overriding default max error retry value to: " + 10); clientConfiguration.setMaxErrorRetry(10); } setConfiguration(clientConfiguration); } /** * <p> * Retrieves a paginated list of table names created by the AWS Account * of the caller in the AWS Region (e.g. <code>us-east-1</code> ). * </p> * * @param listTablesRequest Container for the necessary parameters to * execute the ListTables service method on AmazonDynamoDB. * * @return The response from the ListTables service method, as returned * by AmazonDynamoDB. * * @throws InternalServerErrorException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public ListTablesResult listTables(ListTablesRequest listTablesRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<ListTablesRequest> request = new ListTablesRequestMarshaller().marshall(listTablesRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<ListTablesResult, JsonUnmarshallerContext> unmarshaller = new ListTablesResultJsonUnmarshaller(); JsonResponseHandler<ListTablesResult> responseHandler = new JsonResponseHandler<ListTablesResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Gets the values of one or more items and its attributes by primary key * (composite primary key, only). * </p> * <p> * Narrow the scope of the query using comparison operators on the * <code>RangeKeyValue</code> of the composite key. Use the * <code>ScanIndexForward</code> parameter to get results in forward or * reverse order by range key. * </p> * * @param queryRequest Container for the necessary parameters to execute * the Query service method on AmazonDynamoDB. * * @return The response from the Query service method, as returned by * AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public QueryResult query(QueryRequest queryRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<QueryRequest> request = new QueryRequestMarshaller().marshall(queryRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<QueryResult, JsonUnmarshallerContext> unmarshaller = new QueryResultJsonUnmarshaller(); JsonResponseHandler<QueryResult> responseHandler = new JsonResponseHandler<QueryResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Allows to execute a batch of Put and/or Delete Requests for many * tables in a single call. A total of 25 requests are allowed. * </p> * <p> * There are no transaction guarantees provided by this API. It does not * allow conditional puts nor does it support return values. * </p> * * @param batchWriteItemRequest Container for the necessary parameters to * execute the BatchWriteItem service method on AmazonDynamoDB. * * @return The response from the BatchWriteItem service method, as * returned by AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public BatchWriteItemResult batchWriteItem(BatchWriteItemRequest batchWriteItemRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<BatchWriteItemRequest> request = new BatchWriteItemRequestMarshaller().marshall(batchWriteItemRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<BatchWriteItemResult, JsonUnmarshallerContext> unmarshaller = new BatchWriteItemResultJsonUnmarshaller(); JsonResponseHandler<BatchWriteItemResult> responseHandler = new JsonResponseHandler<BatchWriteItemResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Edits an existing item's attributes. * </p> * <p> * You can perform a conditional update (insert a new attribute * name-value pair if it doesn't exist, or replace an existing name-value * pair if it has certain expected attribute values). * </p> * * @param updateItemRequest Container for the necessary parameters to * execute the UpdateItem service method on AmazonDynamoDB. * * @return The response from the UpdateItem service method, as returned * by AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws ConditionalCheckFailedException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public UpdateItemResult updateItem(UpdateItemRequest updateItemRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<UpdateItemRequest> request = new UpdateItemRequestMarshaller().marshall(updateItemRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<UpdateItemResult, JsonUnmarshallerContext> unmarshaller = new UpdateItemResultJsonUnmarshaller(); JsonResponseHandler<UpdateItemResult> responseHandler = new JsonResponseHandler<UpdateItemResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Creates a new item, or replaces an old item with a new item (including * all the attributes). * </p> * <p> * If an item already exists in the specified table with the same primary * key, the new item completely replaces the existing item. You can * perform a conditional put (insert a new item if one with the specified * primary key doesn't exist), or replace an existing item if it has * certain attribute values. * </p> * * @param putItemRequest Container for the necessary parameters to * execute the PutItem service method on AmazonDynamoDB. * * @return The response from the PutItem service method, as returned by * AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws ConditionalCheckFailedException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public PutItemResult putItem(PutItemRequest putItemRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<PutItemRequest> request = new PutItemRequestMarshaller().marshall(putItemRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<PutItemResult, JsonUnmarshallerContext> unmarshaller = new PutItemResultJsonUnmarshaller(); JsonResponseHandler<PutItemResult> responseHandler = new JsonResponseHandler<PutItemResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Retrieves information about the table, including the current status of * the table, the primary key schema and when the table was created. * </p> * <p> * If the table does not exist, Amazon DynamoDB returns a * <code>ResourceNotFoundException</code> . * </p> * * @param describeTableRequest Container for the necessary parameters to * execute the DescribeTable service method on AmazonDynamoDB. * * @return The response from the DescribeTable service method, as * returned by AmazonDynamoDB. * * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public DescribeTableResult describeTable(DescribeTableRequest describeTableRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<DescribeTableRequest> request = new DescribeTableRequestMarshaller().marshall(describeTableRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<DescribeTableResult, JsonUnmarshallerContext> unmarshaller = new DescribeTableResultJsonUnmarshaller(); JsonResponseHandler<DescribeTableResult> responseHandler = new JsonResponseHandler<DescribeTableResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Retrieves one or more items and its attributes by performing a full * scan of a table. * </p> * <p> * Provide a <code>ScanFilter</code> to get more specific results. * </p> * * @param scanRequest Container for the necessary parameters to execute * the Scan service method on AmazonDynamoDB. * * @return The response from the Scan service method, as returned by * AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public ScanResult scan(ScanRequest scanRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<ScanRequest> request = new ScanRequestMarshaller().marshall(scanRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<ScanResult, JsonUnmarshallerContext> unmarshaller = new ScanResultJsonUnmarshaller(); JsonResponseHandler<ScanResult> responseHandler = new JsonResponseHandler<ScanResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Adds a new table to your account. * </p> * <p> * The table name must be unique among those associated with the AWS * Account issuing the request, and the AWS Region that receives the * request (e.g. <code>us-east-1</code> ). * </p> * <p> * The <code>CreateTable</code> operation triggers an asynchronous * workflow to begin creating the table. Amazon DynamoDB immediately * returns the state of the table ( <code>CREATING</code> ) until the * table is in the <code>ACTIVE</code> state. Once the table is in the * <code>ACTIVE</code> state, you can perform data plane operations. * </p> * * @param createTableRequest Container for the necessary parameters to * execute the CreateTable service method on AmazonDynamoDB. * * @return The response from the CreateTable service method, as returned * by AmazonDynamoDB. * * @throws ResourceInUseException * @throws LimitExceededException * @throws InternalServerErrorException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public CreateTableResult createTable(CreateTableRequest createTableRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<CreateTableRequest> request = new CreateTableRequestMarshaller().marshall(createTableRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<CreateTableResult, JsonUnmarshallerContext> unmarshaller = new CreateTableResultJsonUnmarshaller(); JsonResponseHandler<CreateTableResult> responseHandler = new JsonResponseHandler<CreateTableResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Updates the provisioned throughput for the given table. * </p> * <p> * Setting the throughput for a table helps you manage performance and is * part of the Provisioned Throughput feature of Amazon DynamoDB. * </p> * * @param updateTableRequest Container for the necessary parameters to * execute the UpdateTable service method on AmazonDynamoDB. * * @return The response from the UpdateTable service method, as returned * by AmazonDynamoDB. * * @throws ResourceInUseException * @throws LimitExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public UpdateTableResult updateTable(UpdateTableRequest updateTableRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<UpdateTableRequest> request = new UpdateTableRequestMarshaller().marshall(updateTableRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<UpdateTableResult, JsonUnmarshallerContext> unmarshaller = new UpdateTableResultJsonUnmarshaller(); JsonResponseHandler<UpdateTableResult> responseHandler = new JsonResponseHandler<UpdateTableResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Deletes a table and all of its items. * </p> * <p> * If the table is in the <code>ACTIVE</code> state, you can delete it. * If a table is in <code>CREATING</code> or <code>UPDATING</code> states * then Amazon DynamoDB returns a <code>ResourceInUseException</code> . * If the specified table does not exist, Amazon DynamoDB returns a * <code>ResourceNotFoundException</code> . * </p> * * @param deleteTableRequest Container for the necessary parameters to * execute the DeleteTable service method on AmazonDynamoDB. * * @return The response from the DeleteTable service method, as returned * by AmazonDynamoDB. * * @throws ResourceInUseException * @throws LimitExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public DeleteTableResult deleteTable(DeleteTableRequest deleteTableRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<DeleteTableRequest> request = new DeleteTableRequestMarshaller().marshall(deleteTableRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<DeleteTableResult, JsonUnmarshallerContext> unmarshaller = new DeleteTableResultJsonUnmarshaller(); JsonResponseHandler<DeleteTableResult> responseHandler = new JsonResponseHandler<DeleteTableResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Deletes a single item in a table by primary key. * </p> * <p> * You can perform a conditional delete operation that deletes the item * if it exists, or if it has an expected attribute value. * </p> * * @param deleteItemRequest Container for the necessary parameters to * execute the DeleteItem service method on AmazonDynamoDB. * * @return The response from the DeleteItem service method, as returned * by AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws ConditionalCheckFailedException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public DeleteItemResult deleteItem(DeleteItemRequest deleteItemRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<DeleteItemRequest> request = new DeleteItemRequestMarshaller().marshall(deleteItemRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<DeleteItemResult, JsonUnmarshallerContext> unmarshaller = new DeleteItemResultJsonUnmarshaller(); JsonResponseHandler<DeleteItemResult> responseHandler = new JsonResponseHandler<DeleteItemResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Retrieves a set of Attributes for an item that matches the primary * key. * </p> * <p> * The <code>GetItem</code> operation provides an eventually-consistent * read by default. If eventually-consistent reads are not acceptable for * your application, use <code>ConsistentRead</code> . Although this * operation might take longer than a standard read, it always returns * the last updated value. * </p> * * @param getItemRequest Container for the necessary parameters to * execute the GetItem service method on AmazonDynamoDB. * * @return The response from the GetItem service method, as returned by * AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public GetItemResult getItem(GetItemRequest getItemRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<GetItemRequest> request = new GetItemRequestMarshaller().marshall(getItemRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<GetItemResult, JsonUnmarshallerContext> unmarshaller = new GetItemResultJsonUnmarshaller(); JsonResponseHandler<GetItemResult> responseHandler = new JsonResponseHandler<GetItemResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Retrieves the attributes for multiple items from multiple tables using * their primary keys. * </p> * <p> * The maximum number of item attributes that can be retrieved for a * single operation is 100. Also, the number of items retrieved is * constrained by a 1 MB the size limit. If the response size limit is * exceeded or a partial result is returned due to an internal processing * failure, Amazon DynamoDB returns an <code>UnprocessedKeys</code> value * so you can retry the operation starting with the next item to get. * </p> * <p> * Amazon DynamoDB automatically adjusts the number of items returned per * page to enforce this limit. For example, even if you ask to retrieve * 100 items, but each individual item is 50k in size, the system returns * 20 items and an appropriate <code>UnprocessedKeys</code> value so you * can get the next page of results. If necessary, your application needs * its own logic to assemble the pages of results into one set. * </p> * * @param batchGetItemRequest Container for the necessary parameters to * execute the BatchGetItem service method on AmazonDynamoDB. * * @return The response from the BatchGetItem service method, as returned * by AmazonDynamoDB. * * @throws ProvisionedThroughputExceededException * @throws InternalServerErrorException * @throws ResourceNotFoundException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public BatchGetItemResult batchGetItem(BatchGetItemRequest batchGetItemRequest) throws AmazonServiceException, AmazonClientException { /* Create execution context */ ExecutionContext executionContext = createExecutionContext(); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.RequestMarshallTime.name()); Request<BatchGetItemRequest> request = new BatchGetItemRequestMarshaller().marshall(batchGetItemRequest); awsRequestMetrics.endEvent(Field.RequestMarshallTime.name()); Unmarshaller<BatchGetItemResult, JsonUnmarshallerContext> unmarshaller = new BatchGetItemResultJsonUnmarshaller(); JsonResponseHandler<BatchGetItemResult> responseHandler = new JsonResponseHandler<BatchGetItemResult>(unmarshaller); return invoke(request, responseHandler, executionContext); } /** * <p> * Retrieves a paginated list of table names created by the AWS Account * of the caller in the AWS Region (e.g. <code>us-east-1</code> ). * </p> * * @return The response from the ListTables service method, as returned * by AmazonDynamoDB. * * @throws InternalServerErrorException * * @throws AmazonClientException * If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example * if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonDynamoDB indicating * either a problem with the data in the request, or a server side issue. */ public ListTablesResult listTables() throws AmazonServiceException, AmazonClientException { return listTables(new ListTablesRequest()); } /** * Overrides the default endpoint for this client and explicitly provides * an AWS region ID and AWS service name to use when the client calculates a signature * for requests. In almost all cases, this region ID and service name * are automatically determined from the endpoint, and callers should use the simpler * one-argument form of setEndpoint instead of this method. * <p> * <b>This method is not threadsafe. Endpoints should be configured when the * client is created and before any service requests are made. Changing it * afterwards creates inevitable race conditions for any service requests in * transit.</b> * <p> * Callers can pass in just the endpoint (ex: "dynamodb.us-east-1.amazonaws.com/") or a full * URL, including the protocol (ex: "http://dynamodb.us-east-1.amazonaws.com/"). If the * protocol is not specified here, the default protocol from this client's * {@link ClientConfiguration} will be used, which by default is HTTPS. * <p> * For more information on using AWS regions with the AWS SDK for Java, and * a complete list of all available endpoints for all AWS services, see: * <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=3912"> * http://developer.amazonwebservices.com/connect/entry.jspa?externalID=3912</a> * * @param endpoint * The endpoint (ex: "dynamodb.us-east-1.amazonaws.com/") or a full URL, * including the protocol (ex: "http://dynamodb.us-east-1.amazonaws.com/") of * the region specific AWS endpoint this client will communicate * with. * @param serviceName * The name of the AWS service to use when signing requests. * @param regionId * The ID of the region in which this service resides. * * @throws IllegalArgumentException * If any problems are detected with the specified endpoint. */ public void setEndpoint(String endpoint, String serviceName, String regionId) throws IllegalArgumentException { setEndpoint(endpoint); signer.setServiceName(serviceName); signer.setRegionName(regionId); } /** * Returns additional metadata for a previously executed successful, request, typically used for * debugging issues where a service isn't acting as expected. This data isn't considered part * of the result data returned by an operation, so it's available through this separate, * diagnostic interface. * <p> * Response metadata is only cached for a limited period of time, so if you need to access * this extra diagnostic information for an executed request, you should use this method * to retrieve it as soon as possible after executing the request. * * @param request * The originally executed request * * @return The response metadata for the specified request, or null if none * is available. */ public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) { return client.getResponseMetadataForRequest(request); } private <X, Y extends AmazonWebServiceRequest> X invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) throws AmazonClientException { request.setEndpoint(endpoint); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.CredentialsRequestTime.name()); AWSCredentials credentials = awsCredentialsProvider.getCredentials(); awsRequestMetrics.endEvent(Field.CredentialsRequestTime.name()); AmazonWebServiceRequest originalRequest = request.getOriginalRequest(); if (originalRequest != null && originalRequest.getRequestCredentials() != null) { credentials = originalRequest.getRequestCredentials(); } executionContext.setSigner(signer); executionContext.setCredentials(credentials); executionContext.setCustomBackoffStrategy(com.amazonaws.internal.DynamoDBBackoffStrategy.DEFAULT); JsonErrorResponseHandler errorResponseHandler = new JsonErrorResponseHandler(exceptionUnmarshallers); awsRequestMetrics.startEvent(Field.ClientExecuteTime.name()); X result = (X) client.execute(request, responseHandler, errorResponseHandler, executionContext); awsRequestMetrics.endEvent(Field.ClientExecuteTime.name()); awsRequestMetrics.log(); return result; } }
package com.blackcj.fitdata.fragment; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.blackcj.fitdata.R; import com.blackcj.fitdata.Utilities; import com.blackcj.fitdata.activity.IMainActivityCallback; import com.blackcj.fitdata.adapter.RecyclerViewAdapter; import com.blackcj.fitdata.animation.ItemAnimator; import com.blackcj.fitdata.database.CacheManager; import com.blackcj.fitdata.model.Workout; import com.blackcj.fitdata.service.CacheResultReceiver; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by Chris Black * * Used to display a page of data within the view pager. */ public class PageFragment extends BaseFragment implements RecyclerViewAdapter.OnItemClickListener, CacheResultReceiver.Receiver { private static final String TAG = "PageFragment"; private static final String ARG_PAGE = "ARG_PAGE"; private static final String ARG_FILTER = "ARG_FILTER"; private SwipeRefreshLayout mSwipeRefreshLayout; private RecyclerViewAdapter adapter; private boolean needsRefresh = true; private int mPage; private String mFilterText = ""; private CacheResultReceiver mReciever; protected IMainActivityCallback mCallback; protected Handler mHandler; protected Runnable mRunnable; @Bind(R.id.recyclerView) RecyclerView mRecyclerView; public static PageFragment create(int page, String filterText) { Bundle args = new Bundle(); args.putInt(ARG_PAGE, page); args.putString(ARG_FILTER, filterText); PageFragment fragment = new PageFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPage = getArguments().getInt(ARG_PAGE); mFilterText = getArguments().getString(ARG_FILTER); mReciever = new CacheResultReceiver(new Handler()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_page, container, false); ButterKnife.bind(this, view); mRecyclerView.setLayoutManager(new GridLayoutManager(this.getActivity(), 2)); List<Workout> items = new ArrayList<>(); adapter = new RecyclerViewAdapter(items, Utilities.getTimeFrameText(Utilities.TimeFrame.values()[mPage - 1])); adapter.setOnItemClickListener(this); filter(); mRecyclerView.setItemAnimator(new ItemAnimator()); mRecyclerView.setAdapter(adapter); mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.contentView); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //CacheManager.getReport(Utilities.TimeFrame.values()[mPage - 1], mReciever, getActivity()); if (mPage < 4) { //UserPreferences.setLastSync(getActivity(), Utilities.getTimeFrameStart(Utilities.TimeFrame.values()[mPage - 1])); } mCallback.quickDataRead(); } }); mSwipeRefreshLayout.setEnabled(false); return view; } @Override public void onAttach(Context activity) { super.onAttach(activity); if(activity instanceof IMainActivityCallback) { mCallback = (IMainActivityCallback)activity; } } /** * Clear callback on detach to prevent null reference errors after the view has been */ @Override public void onDetach() { super.onDetach(); mCallback = null; } public void setFilterText(String text) { if(mFilterText.equals(text)) { return; } mFilterText = text; filter(); } /** * Triggered when data changes in the DataManger by calls to quickDataRead */ public void refreshData() { mReciever.setReceiver(this); mSwipeRefreshLayout.setRefreshing(true); CacheManager.getReport(Utilities.TimeFrame.values()[mPage - 1], mReciever, getActivity()); } public void filter() { adapter.filter(mFilterText); } @Override public void onResume() { super.onResume(); mReciever.setReceiver(this); //mCallback.quickDataRead(); // TODO: Use timeframe instead CacheManager.getReport(Utilities.TimeFrame.values()[mPage - 1], mReciever, getActivity()); } @Override public void onPause() { super.onPause(); mReciever.setReceiver(null); if (mHandler != null && mRunnable != null) { mHandler.removeCallbacks(mRunnable); } if (mSwipeRefreshLayout != null) { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setEnabled(false); mSwipeRefreshLayout.destroyDrawingCache(); mSwipeRefreshLayout.clearAnimation(); } } public void setSwipeToRefreshEnabled(boolean enabled) { mSwipeRefreshLayout.setEnabled(enabled); } @Override public void onItemClick(View view, Workout viewModel) { mCallback.launch(view.findViewById(R.id.image), viewModel); } @Override public void onReceiveResult(int resultCode, Bundle resultData) { final List<Workout> workoutList = resultData.getParcelableArrayList("workoutList"); needsRefresh = true; if (adapter.getItemCount() == 0) { needsRefresh = false; adapter.setItems(workoutList, Utilities.getTimeFrameText(Utilities.TimeFrame.values()[mPage - 1])); filter(); } if (mHandler != null && mRunnable != null) { mHandler.removeCallbacks(mRunnable); } mHandler = new Handler(); mRunnable = new Runnable() { @Override public void run() { if (needsRefresh) { adapter.setItems(workoutList, Utilities.getTimeFrameText(Utilities.TimeFrame.values()[mPage - 1])); filter(); } // Update the UI getActivity().runOnUiThread(new Runnable() { @Override public void run() { mSwipeRefreshLayout.setRefreshing(false); } }); } }; mHandler.postDelayed(mRunnable, 1000); } }
package gnu.kawa.lispexpr; import gnu.bytecode.*; import gnu.mapping.*; import gnu.expr.*; import gnu.math.*; import gnu.kawa.io.FilePath; import gnu.kawa.io.Path; import gnu.kawa.io.URIPath; import gnu.kawa.functions.Arithmetic; import gnu.kawa.functions.LProcess; import gnu.kawa.functions.MakeDynamic; import gnu.kawa.reflect.CompileBuildObject; import gnu.kawa.reflect.CompileInvoke; import gnu.kawa.reflect.Invoke; import gnu.kawa.reflect.LazyType; import gnu.lists.Blob; import gnu.lists.FVector; import gnu.lists.Sequences; import gnu.lists.U8Vector; import java.util.*; /** A wrapper around a class type. * A LangObjType is implemented using some class type, * but may have a custom (language-specific) coercion method, * constructor, and name. */ public class LangObjType extends SpecialObjectType implements TypeValue { final int typeCode; private static final int PATH_TYPE_CODE = 1; private static final int FILEPATH_TYPE_CODE = 2; private static final int URI_TYPE_CODE = 3; private static final int CLASS_TYPE_CODE = 4; private static final int TYPE_TYPE_CODE = 5; private static final int CLASSTYPE_TYPE_CODE = 6; private static final int INTEGER_TYPE_CODE = 7; private static final int RATIONAL_TYPE_CODE = 8; private static final int REAL_TYPE_CODE = 9; private static final int NUMERIC_TYPE_CODE = 10; private static final int LIST_TYPE_CODE = 11; private static final int VECTOR_TYPE_CODE = 12; private static final int CONST_VECTOR_TYPE_CODE = 13; private static final int STRING_TYPE_CODE = 14; private static final int REGEX_TYPE_CODE = 15; private static final int DFLONUM_TYPE_CODE = 16; private static final int S8VECTOR_TYPE_CODE = 17; private static final int U8VECTOR_TYPE_CODE = 18; private static final int S16VECTOR_TYPE_CODE = 19; private static final int U16VECTOR_TYPE_CODE = 20; private static final int S32VECTOR_TYPE_CODE = 21; private static final int U32VECTOR_TYPE_CODE = 22; private static final int S64VECTOR_TYPE_CODE = 23; private static final int U64VECTOR_TYPE_CODE = 24; private static final int F32VECTOR_TYPE_CODE = 25; private static final int F64VECTOR_TYPE_CODE = 26; private static final int PROCEDURE_TYPE_CODE = 27; private static final int PROMISE_TYPE_CODE = 28; private static final int SEQUENCE_TYPE_CODE = 29; private static final int DYNAMIC_TYPE_CODE = 30; public static final LangObjType pathType = new LangObjType("path", "gnu.kawa.io.Path", PATH_TYPE_CODE); public static final LangObjType filepathType = new LangObjType("filepath", "gnu.kawa.io.FilePath", FILEPATH_TYPE_CODE); public static final LangObjType URIType = new LangObjType("URI", "gnu.kawa.io.URIPath", URI_TYPE_CODE); public static final LangObjType typeClass = new LangObjType("class", "java.lang.Class", CLASS_TYPE_CODE); public static final LangObjType typeType = new LangObjType("type", "gnu.bytecode.Type", TYPE_TYPE_CODE); public static final LangObjType typeClassType = new LangObjType("class-type", "gnu.bytecode.ClassType", CLASSTYPE_TYPE_CODE); public static final LangObjType numericType = new LangObjType("number", "gnu.math.Numeric", NUMERIC_TYPE_CODE); public static final LangObjType realType = new LangObjType("real", "gnu.math.RealNum", REAL_TYPE_CODE); public static final LangObjType rationalType = new LangObjType("rational", "gnu.math.RatNum", RATIONAL_TYPE_CODE); public static final LangObjType integerType = new LangObjType("integer", "gnu.math.IntNum", INTEGER_TYPE_CODE); public static final LangObjType dflonumType = new LangObjType("DFloNum", "gnu.math.DFloNum", DFLONUM_TYPE_CODE); public static final LangObjType vectorType = new LangObjType("vector", "gnu.lists.FVector", VECTOR_TYPE_CODE); public static final LangObjType constVectorType = new LangObjType("constant-vector", "gnu.lists.FVector", CONST_VECTOR_TYPE_CODE); public static final LangObjType s8vectorType = new LangObjType("s8vector", "gnu.lists.S8Vector", S8VECTOR_TYPE_CODE); public static final LangObjType u8vectorType = new LangObjType("u8vector", "gnu.lists.U8Vector", U8VECTOR_TYPE_CODE); public static final LangObjType s16vectorType = new LangObjType("s16vector", "gnu.lists.S16Vector", S16VECTOR_TYPE_CODE); public static final LangObjType u16vectorType = new LangObjType("u16vector", "gnu.lists.U16Vector", U16VECTOR_TYPE_CODE); public static final LangObjType s32vectorType = new LangObjType("s32vector", "gnu.lists.S32Vector", S32VECTOR_TYPE_CODE); public static final LangObjType u32vectorType = new LangObjType("u32vector", "gnu.lists.U32Vector", U32VECTOR_TYPE_CODE); public static final LangObjType s64vectorType = new LangObjType("s64vector", "gnu.lists.S64Vector", S64VECTOR_TYPE_CODE); public static final LangObjType u64vectorType = new LangObjType("u64vector", "gnu.lists.U64Vector", U64VECTOR_TYPE_CODE); public static final LangObjType f32vectorType = new LangObjType("f32vector", "gnu.lists.F32Vector", F32VECTOR_TYPE_CODE); public static final LangObjType f64vectorType = new LangObjType("f64vector", "gnu.lists.F64Vector", F64VECTOR_TYPE_CODE); public static final LangObjType regexType = new LangObjType("regex", "java.util.regex.Pattern", REGEX_TYPE_CODE); public static final LangObjType stringType = new LangObjType("string", "java.lang.CharSequence", STRING_TYPE_CODE); public static final LangObjType listType = new LangObjType("list", "gnu.lists.LList", LIST_TYPE_CODE); static final ClassType typeArithmetic = ClassType.make("gnu.kawa.functions.Arithmetic"); public static final LangObjType procedureType = new LangObjType("procedure", "gnu.mapping.Procedure", PROCEDURE_TYPE_CODE); public static final LangObjType promiseType = new LangObjType("promise", "gnu.mapping.Lazy", PROMISE_TYPE_CODE); public static final LangObjType sequenceType = new LangObjType("sequence", "java.util.List", SEQUENCE_TYPE_CODE); public static final LangObjType dynamicType = new LangObjType("dynamic", "java.lang.Object", DYNAMIC_TYPE_CODE); LangObjType(String name, String implClass, int typeCode) { super(name, ClassType.make(implClass)); this.typeCode = typeCode; } public static LangObjType getInstanceFromClass(String name) { if ("gnu.math.IntNum".equals(name)) return LangObjType.integerType; if ("gnu.math.DFloNum".equals(name)) return LangObjType.dflonumType; if ("gnu.math.RatNum".equals(name)) return LangObjType.rationalType; if ("gnu.math.RealNum".equals(name)) return LangObjType.realType; if ("gnu.math.Numeric".equals(name)) return LangObjType.numericType; if ("gnu.lists.FVector".equals(name)) return LangObjType.vectorType; if ("gnu.lists.LList".equals(name)) return LangObjType.listType; if ("gnu.kawa.io.Path".equals(name)) return LangObjType.pathType; if ("gnu.kawa.io.URIPath".equals(name)) return LangObjType.URIType; if ("gnu.kawa.io.FilePath".equals(name)) return LangObjType.filepathType; if ("java.lang.Class".equals(name)) return LangObjType.typeClass; if ("gnu.bytecode.Type".equals(name)) return LangObjType.typeType; if ("gnu.bytecode.ClassType".equals(name)) return LangObjType.typeClassType; if ("gnu.lists.F64Vector".equals(name)) return LangObjType.f64vectorType; if ("gnu.lists.F32Vector".equals(name)) return LangObjType.f32vectorType; if ("gnu.lists.S64Vector".equals(name)) return LangObjType.s64vectorType; if ("gnu.lists.S32Vector".equals(name)) return LangObjType.s32vectorType; if ("gnu.lists.S16Vector".equals(name)) return LangObjType.s16vectorType; if ("gnu.lists.S8Vector".equals(name)) return LangObjType.s8vectorType; if ("gnu.lists.U64Vector".equals(name)) return LangObjType.u64vectorType; if ("gnu.lists.U32Vector".equals(name)) return LangObjType.u32vectorType; if ("gnu.lists.U16Vector".equals(name)) return LangObjType.u16vectorType; if ("gnu.lists.U8Vector".equals(name)) return LangObjType.u8vectorType; return null; } @Override public int isCompatibleWithValue(Type valueType) { if (this == valueType) return 2; switch (typeCode) { case SEQUENCE_TYPE_CODE: if (valueType instanceof ArrayType) return 1; if (stringType.isCompatibleWithValue(valueType) > 0) return 1; break; case DYNAMIC_TYPE_CODE: return 2; } return getImplementationType().isCompatibleWithValue(valueType); } public int compare(Type other) { if (other instanceof LazyType) other = ((LazyType) other).getValueType(); if (other == nullType) return 1; switch (typeCode) { case CLASS_TYPE_CODE: if (other == typeType || other == typeClassType || other == typeType.implementationType || other == typeClassType.implementationType) return -1; break; case TYPE_TYPE_CODE: if (other == typeClass || other == typeClassType || other == typeClass.implementationType || other == typeClassType.implementationType) return 1; case CLASSTYPE_TYPE_CODE: if (other == typeClass || other == typeClass.implementationType) return 1; if (other == typeType || other == typeClass.implementationType || other == procedureType) return -1; break; case PROCEDURE_TYPE_CODE: if (other == typeClassType) return 1; break; case SEQUENCE_TYPE_CODE: if (other instanceof ArrayType || isCompatibleWithValue(stringType, other) > 0) return 1; } return getImplementationType().compare(other); } public void emitIsInstance(Variable incoming, Compilation comp, Target target) { switch (typeCode) { case STRING_TYPE_CODE: case LIST_TYPE_CODE: case VECTOR_TYPE_CODE: case S8VECTOR_TYPE_CODE: case U8VECTOR_TYPE_CODE: case S16VECTOR_TYPE_CODE: case U16VECTOR_TYPE_CODE: case S32VECTOR_TYPE_CODE: case U32VECTOR_TYPE_CODE: case S64VECTOR_TYPE_CODE: case U64VECTOR_TYPE_CODE: case F32VECTOR_TYPE_CODE: case F64VECTOR_TYPE_CODE: case REGEX_TYPE_CODE: implementationType.emitIsInstance(comp.getCode()); target.compileFromStack(comp, comp.getLanguage().getTypeFor(Boolean.TYPE)); break; default: gnu.kawa.reflect.InstanceOf.emitIsInstance(this, incoming, comp, target); } } public static Numeric coerceNumeric (Object value) { value = Promise.force(value); Numeric rval = Numeric.asNumericOrNull(value); if (rval == null && value != null) throw new WrongType(WrongType.ARG_CAST, value, numericType); return rval; } public static RealNum coerceRealNum (Object value) { value = Promise.force(value); RealNum rval = RealNum.asRealNumOrNull(value); if (rval == null && value != null) throw new WrongType(WrongType.ARG_CAST, value, realType); return rval; } public static DFloNum coerceDFloNum (Object value) { value = Promise.force(value); DFloNum rval = DFloNum.asDFloNumOrNull(value); if (rval == null && value != null) throw new WrongType(WrongType.ARG_CAST, value, dflonumType); return rval; } public static RatNum coerceRatNum (Object value) { value = Promise.force(value); RatNum rval = RatNum.asRatNumOrNull(value); if (rval == null && value != null) throw new WrongType(WrongType.ARG_CAST, value, rationalType); return rval; } public static IntNum coerceIntNum (Object value) { value = Promise.force(value); IntNum ival = IntNum.asIntNumOrNull(value); if (ival == null && value != null) throw new WrongType(WrongType.ARG_CAST, value, integerType); return ival; } public static Class coerceToClassOrNull (Object type) { type = Promise.force(type); if (type instanceof Class) return (Class) type; if (type instanceof Type) { if (type instanceof ClassType && ! (type instanceof PairClassType)) return ((ClassType) type).getReflectClass(); // FIXME: Handle ArrayType and PrimType. } return null; } public static Class coerceToClass (Object obj) { Class coerced = coerceToClassOrNull(obj); if (coerced == null && obj != null) throw new ClassCastException("cannot cast "+obj+" to type"); return coerced; } public static ClassType coerceToClassTypeOrNull (Object type) { if (type instanceof ClassType) return (ClassType) type; if (type instanceof Class) { Language language = Language.getDefaultLanguage(); Type t = language.getTypeFor((Class) type); if (t instanceof ClassType) return (ClassType) t; } return null; } public static ClassType coerceToClassType (Object obj) { obj = Promise.force(obj); ClassType coerced = coerceToClassTypeOrNull(obj); if (coerced == null && obj != null) throw new ClassCastException("cannot cast "+obj+" to class-type"); return coerced; } public static Type coerceToTypeOrNull (Object type) { type = Promise.force(type); if (type instanceof Type) return (Type) type; if (type instanceof Class) { Language language = Language.getDefaultLanguage(); return language.getTypeFor((Class) type); } return null; } public static Type coerceToType (Object obj) { Type coerced = coerceToTypeOrNull(obj); if (coerced == null && obj != null) throw new ClassCastException("cannot cast "+obj+" to type"); return coerced; } public static FVector coerceToConstVector(Object obj) { obj = Promise.force(obj); if (obj instanceof FVector) { FVector vec = (FVector) obj; if (vec.isReadOnly()) return vec; throw new ClassCastException("vector is not constant-vector"); } throw new ClassCastException("cannot cast "+obj+" to constant-vector"); } public static Procedure coerceToProcedureOrNull(Object value) { final Object obj = Promise.force(value); if (obj instanceof Procedure) return (Procedure) obj; if (obj instanceof LangObjType) { Procedure cons = ((LangObjType) obj).getConstructor(); if (cons != null) return cons; return new ProcedureN () { public Object applyN (Object[] args) throws Throwable { int nargs = args.length; Object[] xargs = new Object[nargs+1]; System.arraycopy(args, 0, xargs, 1, nargs); xargs[0] = obj; return Invoke.make.applyN(xargs); } }; } return null; } public static Procedure coerceToProcedure (Object obj) { obj = Promise.force(obj); Procedure coerced = coerceToProcedureOrNull(obj); if (coerced == null && obj != null) throw new ClassCastException("cannot cast "+obj+" to procedure"); return coerced; } public static U8Vector coerceToU8Vector(Object obj) { if (obj instanceof LProcess) return ((LProcess) obj).getValue().asPlainBytevector(); if (obj instanceof Blob) return ((Blob) obj).asPlainBytevector(); return (U8Vector) obj; } Method coercionMethod () { switch (typeCode) { case CLASS_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceToClass", 1); case CLASSTYPE_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceToClassType", 1); case TYPE_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceToType", 1); case PROCEDURE_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceToProcedure", 1); case NUMERIC_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceNumeric", 1); case REAL_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceRealNum", 1); case RATIONAL_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceRatNum", 1); case INTEGER_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceIntNum", 1); case DFLONUM_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceDFloNum", 1); case U8VECTOR_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceToU8Vector", 1); case CONST_VECTOR_TYPE_CODE: return typeLangObjType.getDeclaredMethod("coerceToConstVector", 1); case VECTOR_TYPE_CODE: case S8VECTOR_TYPE_CODE: case S16VECTOR_TYPE_CODE: case U16VECTOR_TYPE_CODE: case S32VECTOR_TYPE_CODE: case U32VECTOR_TYPE_CODE: case S64VECTOR_TYPE_CODE: case U64VECTOR_TYPE_CODE: case F32VECTOR_TYPE_CODE: case F64VECTOR_TYPE_CODE: case STRING_TYPE_CODE: case LIST_TYPE_CODE: case REGEX_TYPE_CODE: return null; case SEQUENCE_TYPE_CODE: return ClassType.make("gnu.lists.Sequences").getDeclaredMethod("coerceToSequence", 1); default: Procedure cons = getConstructor(); if (cons == null) return null; return ((PrimProcedure) cons).getMethod(); } } protected Method coercionOrNullMethod() { ClassType methodDeclaringClass = implementationType; String mname; switch (typeCode) { case PATH_TYPE_CODE: mname = "coerceToPathOrNull"; break; case FILEPATH_TYPE_CODE: mname = "coerceToFilePathOrNull"; break; case URI_TYPE_CODE: mname = "coerceToURIPathOrNull"; break; case CLASS_TYPE_CODE: methodDeclaringClass = typeLangObjType; mname = "coerceToClassOrNull"; break; case CLASSTYPE_TYPE_CODE: methodDeclaringClass = typeLangObjType; mname = "coerceToClassTypeOrNull"; break; case TYPE_TYPE_CODE: methodDeclaringClass = typeLangObjType; mname = "coerceToTypeOrNull"; break; case PROCEDURE_TYPE_CODE: methodDeclaringClass = typeLangObjType; mname = "coerceToProcedureOrNull"; break; case NUMERIC_TYPE_CODE: methodDeclaringClass = implementationType; mname = "asNumericOrNull"; break; case DFLONUM_TYPE_CODE: methodDeclaringClass = implementationType; mname = "asDFloNumOrNull"; break; case REAL_TYPE_CODE: methodDeclaringClass = implementationType; mname = "asRealNumOrNull"; break; case RATIONAL_TYPE_CODE: methodDeclaringClass = implementationType; mname = "asRatNumOrNull"; break; case INTEGER_TYPE_CODE: methodDeclaringClass = implementationType; mname = "asIntNumOrNull"; break; case SEQUENCE_TYPE_CODE: methodDeclaringClass = ClassType.make("gnu.lists.Sequences"); mname = "asSequenceOrNull"; break; default: return null; } return methodDeclaringClass.getDeclaredMethod(mname, 1); } public boolean emitCoercionOrNull(CodeAttr code) { Method method = coercionOrNullMethod(); if (method == null) return false; code.emitInvokeStatic(method); return true; } public void emitTestIf(Variable incoming, Declaration decl, Compilation comp) { CodeAttr code = comp.getCode(); if (incoming != null) code.emitLoad(incoming); if (emitCoercionOrNull(code)) { if (decl != null) { code.emitDup(); decl.compileStore(comp); } code.emitIfNotNull(); } else { implementationType.emitIsInstance(code); code.emitIfIntNotZero(); if (decl != null) { code.emitLoad(incoming); emitCoerceFromObject(code); decl.compileStore(comp); } } } public Object coerceFromObject (Object obj) { switch (typeCode) { case PATH_TYPE_CODE: return Path.valueOf(obj); case FILEPATH_TYPE_CODE: return FilePath.makeFilePath(obj); case URI_TYPE_CODE: return URIPath.makeURI(obj); case CLASS_TYPE_CODE: return coerceToClass(obj); case CLASSTYPE_TYPE_CODE: return coerceToClassType(obj); case TYPE_TYPE_CODE: return coerceToType(obj); case PROCEDURE_TYPE_CODE: return coerceToProcedure(obj); case NUMERIC_TYPE_CODE: return coerceNumeric(obj); case REAL_TYPE_CODE: return coerceRealNum(obj); case RATIONAL_TYPE_CODE: return coerceRatNum(obj); case INTEGER_TYPE_CODE: return coerceIntNum(obj); case DFLONUM_TYPE_CODE: return coerceDFloNum(obj); case SEQUENCE_TYPE_CODE: return Sequences.coerceToSequence(obj); case CONST_VECTOR_TYPE_CODE: return coerceToConstVector(obj); case VECTOR_TYPE_CODE: case S8VECTOR_TYPE_CODE: case U8VECTOR_TYPE_CODE: case S16VECTOR_TYPE_CODE: case U16VECTOR_TYPE_CODE: case S32VECTOR_TYPE_CODE: case U32VECTOR_TYPE_CODE: case S64VECTOR_TYPE_CODE: case U64VECTOR_TYPE_CODE: case F32VECTOR_TYPE_CODE: case F64VECTOR_TYPE_CODE: case LIST_TYPE_CODE: case REGEX_TYPE_CODE: // optimize? default: return super.coerceFromObject(obj); } } public void emitConvertFromPrimitive (Type stackType, CodeAttr code) { Type argType = null; String cname = null; String mname = "make"; switch (typeCode) { case DFLONUM_TYPE_CODE: if (stackType instanceof PrimType) { char sig1 = stackType.getSignature().charAt(0); if (sig1 == 'I' || sig1 == 'B' || sig1 == 'S' || sig1 == 'J' || sig1 == 'F') { code.emitConvert((PrimType) stackType, Type.doubleType); stackType = Type.doubleType; } if (stackType == Type.doubleType) { cname = "gnu.math.DFloNum"; argType = stackType; } } break; case INTEGER_TYPE_CODE: case RATIONAL_TYPE_CODE: case REAL_TYPE_CODE: case NUMERIC_TYPE_CODE: if (stackType instanceof PrimType) { if (stackType == Type.intType || stackType == Type.byteType || stackType == Type.shortType || stackType == LangPrimType.unsignedByteType || stackType == LangPrimType.unsignedShortType) { cname = "gnu.math.IntNum"; argType = Type.int_type; } else if (stackType == Type.longType || stackType == LangPrimType.unsignedIntType || stackType == LangPrimType.unsignedLongType) { cname = "gnu.math.IntNum"; mname = stackType == Type.longType ? "valueOf" : "valueOfUnsigned"; argType = stackType.getImplementationType(); } else if (typeCode == REAL_TYPE_CODE || typeCode == NUMERIC_TYPE_CODE) { if (stackType == Type.floatType) { code.emitConvert(Type.float_type, Type.double_type); stackType = Type.doubleType; } if (stackType == Type.doubleType) { cname = "gnu.math.DFloNum"; argType = Type.doubleType; } } } break; } if (cname != null) { ClassType clas = ClassType.make(cname); Type[] args = { argType }; code.emitInvokeStatic(clas.getDeclaredMethod(mname, args)); } else super.emitConvertFromPrimitive(stackType, code); } public Expression convertValue (Expression value) { // In these cases, using the coercion metod would by-pass // the static type-checking in InlineCalls#checkType, to no benefit. if (typeCode == INTEGER_TYPE_CODE || typeCode == NUMERIC_TYPE_CODE || typeCode == REAL_TYPE_CODE || typeCode == RATIONAL_TYPE_CODE || typeCode == DFLONUM_TYPE_CODE) return null; Method method = coercionMethod(); if (method == null) return null; ApplyExp aexp = new ApplyExp(method, new Expression[] { value }); aexp.setType(this); return aexp; } public void emitCoerceFromObject (CodeAttr code) { switch (typeCode) { case VECTOR_TYPE_CODE: case S8VECTOR_TYPE_CODE: case S16VECTOR_TYPE_CODE: case U16VECTOR_TYPE_CODE: case S32VECTOR_TYPE_CODE: case U32VECTOR_TYPE_CODE: case S64VECTOR_TYPE_CODE: case U64VECTOR_TYPE_CODE: case F32VECTOR_TYPE_CODE: case F64VECTOR_TYPE_CODE: case STRING_TYPE_CODE: case LIST_TYPE_CODE: case REGEX_TYPE_CODE: case PROMISE_TYPE_CODE: code.emitCheckcast(implementationType); break; default: code.emitInvoke(coercionMethod()); } } /* #ifdef JAVA5 */ static final String VARARGS_SUFFIX = ""; /* #else */ // static final String VARARGS_SUFFIX = "$V"; /* #endif */ public ObjectType getConstructorType() { switch (typeCode) { case PROMISE_TYPE_CODE: return LazyType.promiseType; default: return this; } } public Procedure getConstructor () { switch (typeCode) { case PATH_TYPE_CODE: return new PrimProcedure("gnu.kawa.io.Path", "valueOf", 1); case FILEPATH_TYPE_CODE: return new PrimProcedure("gnu.kawa.io.FilePath", "makeFilePath", 1); case URI_TYPE_CODE: return new PrimProcedure("gnu.kawa.io.URIPath", "makeURI", 1); case VECTOR_TYPE_CODE: return new PrimProcedure("gnu.lists.FVector", "make", 1); case CONST_VECTOR_TYPE_CODE: return new PrimProcedure("gnu.lists.FVector", "makeConstant", 1); case LIST_TYPE_CODE: return gnu.kawa.functions.MakeList.list; case STRING_TYPE_CODE: return new PrimProcedure("kawa.lib.strings", "$make$string$"+VARARGS_SUFFIX, 1); case REGEX_TYPE_CODE: return new PrimProcedure("java.util.regex.Pattern", "compile", 1); case DYNAMIC_TYPE_CODE: return MakeDynamic.instance; default: return null; } } public String encodeType(Language language) { if (this == sequenceType) return "sequence"; return null; } public Type getElementType() { switch (typeCode) { case S8VECTOR_TYPE_CODE: return LangPrimType.byteType; case S16VECTOR_TYPE_CODE: return LangPrimType.shortType; case S32VECTOR_TYPE_CODE: return LangPrimType.intType; case S64VECTOR_TYPE_CODE: return LangPrimType.longType; case U8VECTOR_TYPE_CODE: return LangPrimType.unsignedByteType; case U16VECTOR_TYPE_CODE: return LangPrimType.unsignedShortType; case U32VECTOR_TYPE_CODE: return LangPrimType.unsignedIntType; case U64VECTOR_TYPE_CODE: return LangPrimType.unsignedLongType; case F32VECTOR_TYPE_CODE: return LangPrimType.floatType; case F64VECTOR_TYPE_CODE: return LangPrimType.doubleType; } return null; } public String elementGetterMethodName() { switch (typeCode) { case S8VECTOR_TYPE_CODE: case U8VECTOR_TYPE_CODE: return "getByte"; case S16VECTOR_TYPE_CODE: case U16VECTOR_TYPE_CODE: return "getShort"; case S32VECTOR_TYPE_CODE: case U32VECTOR_TYPE_CODE: return "getInt"; case S64VECTOR_TYPE_CODE: case U64VECTOR_TYPE_CODE: return "getLong"; case F32VECTOR_TYPE_CODE: return "getFloat"; case F64VECTOR_TYPE_CODE: return "getDouble"; } return null; } public String elementSetterMethodName() { String gname = elementGetterMethodName(); if (gname == null) return null; return "set" + gname.substring(3); } public static final ClassType typeLangObjType = ClassType.make("gnu.kawa.lispexpr.LangObjType"); public CompileBuildObject getBuildObject() { switch (typeCode) { case S8VECTOR_TYPE_CODE: case S16VECTOR_TYPE_CODE: case S32VECTOR_TYPE_CODE: case S64VECTOR_TYPE_CODE: case U8VECTOR_TYPE_CODE: case U16VECTOR_TYPE_CODE: case U32VECTOR_TYPE_CODE: case U64VECTOR_TYPE_CODE: case F32VECTOR_TYPE_CODE: case F64VECTOR_TYPE_CODE: return new SimpleVectorBuilder(this); default: return new CompileBuildObject(); } } public static class SimpleVectorBuilder extends CompileBuildObject { Type elementType; PrimProcedure addProc; public SimpleVectorBuilder(LangObjType vectorType) { this.elementType = vectorType.getElementType(); Method addMethod = ((ClassType) vectorType.getImplementationType()) .getMethod("add", new Type[] { elementType.getImplementationType() }); addProc = new PrimProcedure(addMethod, Type.voidType, new Type[] {elementType}); } @Override public boolean useBuilder(int numCode, InlineCalls visitor) { return (numKeywordArgs() == 0 && hasDefaultConstructor()) || super.useBuilder(numCode, visitor); } @Override public Expression buildAddChild(Declaration target, Expression child) { return new ApplyExp(addProc, new ReferenceExp(target), child); } } }
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.job; import org.pentaho.di.base.BaseHopMeta; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.job.entry.JobEntryCopy; import org.w3c.dom.Node; /** * This class defines a hop from one job entry copy to another. * * @author Matt * @since 19-06-2003 * */ public class JobHopMeta extends BaseHopMeta<JobEntryCopy> { private static Class<?> PKG = JobHopMeta.class; // for i18n purposes, needed by Translator2!! private boolean evaluation; private boolean unconditional; public JobHopMeta() { this( (JobEntryCopy) null, (JobEntryCopy) null ); } public JobHopMeta( JobEntryCopy from, JobEntryCopy to ) { this.from = from; this.to = to; enabled = true; split = false; evaluation = true; unconditional = false; id = null; if ( from != null && from.isStart() ) { setUnconditional(); } } public JobHopMeta( Node hopnode, JobMeta job ) throws KettleXMLException { try { String from_name = XMLHandler.getTagValue( hopnode, "from" ); String to_name = XMLHandler.getTagValue( hopnode, "to" ); String sfrom_nr = XMLHandler.getTagValue( hopnode, "from_nr" ); String sto_nr = XMLHandler.getTagValue( hopnode, "to_nr" ); String senabled = XMLHandler.getTagValue( hopnode, "enabled" ); String sevaluation = XMLHandler.getTagValue( hopnode, "evaluation" ); String sunconditional = XMLHandler.getTagValue( hopnode, "unconditional" ); int from_nr, to_nr; from_nr = Const.toInt( sfrom_nr, 0 ); to_nr = Const.toInt( sto_nr, 0 ); this.from = job.findJobEntry( from_name, from_nr, true ); this.to = job.findJobEntry( to_name, to_nr, true ); if ( senabled == null ) { enabled = true; } else { enabled = "Y".equalsIgnoreCase( senabled ); } if ( sevaluation == null ) { evaluation = true; } else { evaluation = "Y".equalsIgnoreCase( sevaluation ); } unconditional = "Y".equalsIgnoreCase( sunconditional ); } catch ( Exception e ) { throw new KettleXMLException( BaseMessages.getString( PKG, "JobHopMeta.Exception.UnableToLoadHopInfoXML" ), e ); } } public String getXML() { StringBuilder retval = new StringBuilder( 200 ); if ( ( null != this.from ) && ( null != this.to ) ) { retval.append( " " ).append( XMLHandler.openTag( XML_TAG ) ).append( Const.CR ); retval.append( " " ).append( XMLHandler.addTagValue( "from", this.from.getName() ) ); retval.append( " " ).append( XMLHandler.addTagValue( "to", this.to.getName() ) ); retval.append( " " ).append( XMLHandler.addTagValue( "from_nr", this.from.getNr() ) ); retval.append( " " ).append( XMLHandler.addTagValue( "to_nr", this.to.getNr() ) ); retval.append( " " ).append( XMLHandler.addTagValue( "enabled", enabled ) ); retval.append( " " ).append( XMLHandler.addTagValue( "evaluation", evaluation ) ); retval.append( " " ).append( XMLHandler.addTagValue( "unconditional", unconditional ) ); retval.append( " " ).append( XMLHandler.closeTag( XML_TAG ) ).append( Const.CR ); } return retval.toString(); } public boolean getEvaluation() { return evaluation; } public void setEvaluation() { if ( !evaluation ) { setChanged(); } setEvaluation( true ); } public void setEvaluation( boolean e ) { if ( evaluation != e ) { setChanged(); } evaluation = e; } public void setUnconditional() { if ( !unconditional ) { setChanged(); } unconditional = true; } public void setConditional() { if ( unconditional ) { setChanged(); } unconditional = false; } public boolean isUnconditional() { return unconditional; } public void setSplit( boolean split ) { if ( this.split != split ) { setChanged(); } this.split = split; } public boolean isSplit() { return split; } public String getDescription() { if ( isUnconditional() ) { return BaseMessages.getString( PKG, "JobHopMeta.Msg.ExecNextJobEntryUncondition" ); } else { if ( getEvaluation() ) { return BaseMessages.getString( PKG, "JobHopMeta.Msg.ExecNextJobEntryFlawLess" ); } else { return BaseMessages.getString( PKG, "JobHopMeta.Msg.ExecNextJobEntryFailed" ); } } } public String toString() { return getDescription(); // return from_entry.getName()+"."+from_entry.getNr()+" --> "+to_entry.getName()+"."+to_entry.getNr(); } public JobEntryCopy getFromEntry() { return this.from; } public void setFromEntry( JobEntryCopy fromEntry ) { this.from = fromEntry; changed = true; } public JobEntryCopy getToEntry() { return this.to; } public void setToEntry( JobEntryCopy toEntry ) { this.to = toEntry; changed = true; } /** * @param unconditional * the unconditional to set */ public void setUnconditional( boolean unconditional ) { if ( this.unconditional != unconditional ) { setChanged(); } this.unconditional = unconditional; } }
package org.mellowtech.core.io.impl; import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; import org.mellowtech.core.TestUtils; import org.mellowtech.core.io.*; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Path; import java.util.Iterator; /** * Created by msvens on 24/10/15. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class RecordFileTemplate { RecordFile rf; abstract String fname(); abstract String fnameMoved(); static String dir = "rftests"; static int maxBlocks = 10; static int blockSize = 1024; static int reserve = 1024; static String testString = "01234567ABCDEFGH"; static byte[] testBlock; static { StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < 64; i++){ stringBuilder.append(testString); } testBlock = stringBuilder.toString().getBytes(); } abstract long blocksOffset(); abstract RecordFile init(int blockSize, int reserve, int maxBlocks, Path fname) throws Exception; abstract RecordFile reopen(Path fname) throws Exception; protected void fillFile() throws Exception { for(int i = 0; i < maxBlocks; i++) rf.insert(testBlock); } @BeforeAll public static void createDir(){ TestUtils.deleteTempDir(dir); TestUtils.createTempDir(dir); } @AfterAll public static void rmDir(){ TestUtils.createTempDir(dir); } @BeforeEach public void setup() throws Exception{ rf = init(blockSize,reserve,maxBlocks, TestUtils.getAbsolutePath(dir+"/"+fname())); } @AfterEach public void after() throws Exception{ rf.remove(); } /**COMMON TEST CASES**/ @Test public void blockSize(){ assertEquals(blockSize, rf.getBlockSize()); } @Test public void reserveSize() throws IOException{ assertEquals(reserve, rf.getReserve().length); } @Test public void move() throws Exception { fillFile(); RecordFile rf1 = rf.move(TestUtils.getAbsolutePath(dir+"/"+fname())); assertFalse(rf.isOpen()); for(int i = 0; i < maxBlocks; i++) { assertEquals(new String(testBlock), new String(rf1.get(i))); } rf = rf1; } /****TESTS WITH ZERO ELEMENTS*********/ @Nested @DisplayName("An empty recordfile ") class Empty { @Test @DisplayName("has zero blocks") void zeroSize() { assertEquals(0, rf.size()); } @Test @DisplayName("has all free blocks") void zeroFree() { assertTrue(maxBlocks <= rf.getFreeBlocks()); } @Test @DisplayName("has an empty iterator") void zeroIterator() { assertFalse(rf.iterator().hasNext()); } @Test @DisplayName("when cleared has a file size of 0") void zeroClear() throws IOException { rf.clear(); assertEquals(0, rf.size()); } @Test @DisplayName("contains no blocks") void zeroContains() throws Exception { assertFalse(rf.contains(0)); } @Test @DisplayName("has no first record") void zeroFirstRecord() throws Exception { assertEquals(-1, rf.getFirstRecord()); } @Test @DisplayName("returns null when getting block 0") void zeroGet() throws Exception { assertNull(rf.get(0)); } @Test @DisplayName("returns null when getting a mapped block") void zeroGetMapped() throws Exception { try { assertNull(rf.getMapped(0)); } catch (UnsupportedOperationException uoe) { ; } } @Test @DisplayName("returns false when trying to read into a block") void zeroGetBoolean() throws Exception { byte b[] = new byte[blockSize]; assertFalse(rf.get(0, b)); } @Test @DisplayName("remains empty after reopen") void zeroReopen() throws Exception { rf.close(); rf = reopen(TestUtils.getAbsolutePath(dir + "/" + fname())); assertEquals(0, rf.size()); assertNull(rf.get(0)); } @Test @DisplayName("cannot update a block") void zeroUpdate() throws Exception { byte b[] = new byte[blockSize]; assertFalse(rf.update(0, b)); } @Test @DisplayName("cannot delete a block") public void zeroDelete() throws Exception { assertFalse(rf.delete(0)); assertEquals(0, rf.size()); } } /****TESTS WITH 1 ELEMENT*************/ @Nested @DisplayName("A RecordFile with only the first record used") class First { @Test @DisplayName("should have a size of 1") void oneSize() throws Exception { rf.insert(testBlock); assertEquals(1, rf.size()); } @Test @DisplayName("should have maxBlocks - 1 free blocks") void oneFree() throws Exception { rf.insert(testBlock); assertTrue(maxBlocks - 1 <= rf.getFreeBlocks()); } @Test @DisplayName("should have an iterator with only record 0") void oneIterator() throws Exception { rf.insert(testBlock); Iterator<Record> iter = rf.iterator(); assertEquals(0, iter.next().record); assertFalse(iter.hasNext()); } @Test @DisplayName("when cleared should have zero blocks") void oneClear() throws IOException { rf.insert(testBlock); rf.clear(); assertEquals(0, rf.size()); } @Test @DisplayName("should contain 1 block") void oneContains() throws Exception { rf.insert(testBlock); assertTrue(rf.contains(0)); } @Test @DisplayName("Should returon 0 as its first record") void oneFirstRecord() throws Exception { rf.insert(testBlock); assertEquals(0, rf.getFirstRecord()); } @Test @DisplayName("Contents of record 0 should be correct") void oneGet() throws Exception { rf.insert(testBlock); assertEquals(new String(testBlock), new String(rf.get(0))); } @Test @DisplayName("If mapped blocks are support should be able to map block 0") void oneGetMapped() throws Exception { try { rf.insert(testBlock); byte[] b = new byte[1024]; ByteBuffer bb = rf.getMapped(0); assertEquals(blockSize, bb.limit() - bb.position()); bb.get(b); assertEquals(new String(testBlock), new String(b)); } catch (UnsupportedOperationException e) { ; } } @Test @DisplayName("Should return true when reading record 0") void oneGetBoolean() throws Exception { rf.insert(testBlock); byte b[] = new byte[blockSize]; assertTrue(rf.get(0, b)); assertEquals(new String(testBlock), new String(b)); } @Test @DisplayName("When reopened should contain 1 record") void oneReopen() throws Exception { rf.insert(testBlock); rf.save(); rf.close(); rf = reopen(TestUtils.getAbsolutePath(dir + "/" + fname())); assertEquals(1, rf.size()); assertEquals(new String(testBlock), new String(rf.get(0))); } @Test @DisplayName("Should return true when updating the first record") void oneUpdate() throws Exception { rf.insert(testBlock); byte b[] = new byte[blockSize]; b[0] = 1; assertTrue(rf.update(0, b)); } @Test @DisplayName("Should have size 0 after deleting the first record") void oneDelete() throws Exception { rf.insert(testBlock); assertTrue(rf.delete(0)); assertEquals(0, rf.size()); } } @Nested @DisplayName("A RecordFile with only the last record used") class Last { @Test @DisplayName("should have a size of 1") public void lastSize() throws Exception { rf.insert(maxBlocks - 1, testBlock); assertEquals(1, rf.size()); } @Test @DisplayName("should have maxBlocks - 1 free blocks") void lastFree() throws Exception { rf.insert(maxBlocks - 1, testBlock); assertEquals(maxBlocks - 1, rf.getFreeBlocks()); } @Test @DisplayName("should have a single record iterator") void lastIterator() throws Exception { rf.insert(maxBlocks - 1, testBlock); Iterator<Record> iter = rf.iterator(); assertEquals(maxBlocks - 1, iter.next().record); assertFalse(iter.hasNext()); } @Test @DisplayName("should have size 0 after clear") void lastClear() throws IOException { rf.insert(maxBlocks - 1, testBlock); rf.clear(); assertEquals(0, rf.size()); } @Test @DisplayName("should contain a record in its last position") void lastContains() throws Exception { rf.insert(maxBlocks - 1, testBlock); assertTrue(rf.contains(maxBlocks - 1)); } @Test @DisplayName("its first record should be in the last position") void lastFirstRecord() throws Exception { rf.insert(maxBlocks - 1, testBlock); assertEquals(maxBlocks - 1, rf.getFirstRecord()); } @Test @DisplayName("should contain the correct record") public void lastGet() throws Exception { rf.insert(maxBlocks - 1, testBlock); assertEquals(new String(testBlock), new String(rf.get(maxBlocks - 1))); } @Test @DisplayName("should be able to map the last record") void lastGetMapped() throws Exception { rf.insert(maxBlocks - 1, testBlock); ByteBuffer bb = null; try { bb = rf.getMapped(maxBlocks - 1); } catch (UnsupportedOperationException e) { return; } byte[] b = new byte[blockSize]; assertEquals(blockSize, bb.limit() - bb.position()); bb.get(b); assertEquals(new String(testBlock), new String(b)); } @Test @DisplayName("should return true when reading the last record") void lastGetBoolean() throws Exception { rf.insert(maxBlocks - 1, testBlock); byte b[] = new byte[blockSize]; assertTrue(rf.get(maxBlocks - 1, b)); assertEquals(new String(testBlock), new String(b)); } @Test @DisplayName("should be able to reopen") void lastReopen() throws Exception { rf.insert(maxBlocks - 1, testBlock); rf.close(); rf = reopen(TestUtils.getAbsolutePath(dir + "/" + fname())); assertEquals(new String(testBlock), new String(rf.get(maxBlocks - 1))); } @Test @DisplayName("should return true when update the last record") public void lastUpdate() throws Exception { rf.insert(maxBlocks - 1, testBlock); byte b[] = new byte[blockSize]; b[0] = 1; assertTrue(rf.update(maxBlocks - 1, b)); } @Test @DisplayName("should have size 0 when deleting the last record") void lastDelete() throws Exception { rf.insert(maxBlocks - 1, testBlock); assertTrue(rf.delete(maxBlocks - 1)); assertEquals(0, rf.size()); } } @Nested @DisplayName("A full RecordFile ") class All { @Test @DisplayName("should have a size equal to max records") void allSize() throws Exception { fillFile(); assertEquals(maxBlocks, rf.size()); } @Test @DisplayName("should have 0 free blocks") void allFree() throws Exception { fillFile(); assertEquals(0, rf.getFreeBlocks()); } @Test @DisplayName("should have an iterator over all records") public void allIterator() throws Exception { fillFile(); int i = 0; Iterator<org.mellowtech.core.io.Record> iter = rf.iterator(); while (iter.hasNext()) { i++; iter.next(); } assertEquals(maxBlocks, i); } @Test @DisplayName("when cleared should have 0 records") void allClear() throws Exception { fillFile(); rf.clear(); assertEquals(0, rf.size()); } @Test @DisplayName("should contain all records") void allContains() throws Exception { fillFile(); for (int i = 0; i < maxBlocks; i++) { assertTrue(rf.contains(i)); } } @Test @DisplayName("first record is 0") void allFirstRecord() throws Exception { fillFile(); assertEquals(0, rf.getFirstRecord()); } @Test @DisplayName("should get all blocks") void allGet() throws Exception { fillFile(); for (int i = 0; i < maxBlocks; i++) { assertEquals(new String(testBlock), new String(rf.get(i))); } } @Test @DisplayName("should get all records mapped") void allGetMapped() throws Exception { fillFile(); for (int i = 0; i < maxBlocks; i++) { ByteBuffer bb = null; try { bb = rf.getMapped(i); } catch (UnsupportedOperationException e) { return; } byte[] b = new byte[blockSize]; assertEquals(blockSize, bb.limit() - bb.position()); bb.get(b); assertEquals(new String(testBlock), new String(b)); } } @Test @DisplayName("should be able to read all records") void allGetBoolean() throws Exception { fillFile(); for (int i = 0; i < maxBlocks; i++) { byte b[] = new byte[blockSize]; assertTrue(rf.get(i, b)); assertEquals(new String(testBlock), new String(b)); } } @Test @DisplayName("should be able to reopen") void allReopen() throws Exception { fillFile(); rf.close(); rf = reopen(TestUtils.getAbsolutePath(dir + "/" + fname())); for (int i = 0; i < maxBlocks; i++) { assertEquals(new String(testBlock), new String(rf.get(i))); } } @Test @DisplayName("should be able to update all records") void allUpdate() throws Exception { fillFile(); for (int i = 0; i < maxBlocks; i++) { byte b[] = new byte[blockSize]; b[0] = 1; assertTrue(rf.update(i, b)); } } @Test @DisplayName("should be able to delete all records") void allDelete() throws Exception { fillFile(); for (int i = 0; i < maxBlocks; i++) { assertTrue(rf.delete(i)); assertEquals(maxBlocks - 1 - i, rf.size()); } } } @Nested @DisplayName("Hanlding wrong input ") class ErrorPath { @Test @DisplayName("should allow to insert a record that is too big") void insertLargeBlock() throws Exception { byte b[] = new byte[blockSize + 1]; rf.insert(b); assertEquals(1, rf.size()); } @Test @DisplayName("should allow to insert a null record") void insertNull() throws Exception { rf.insert(null); assertEquals(1, rf.size()); } @Test @DisplayName("Inserting into a full file throws an exception") void insertInFull() throws Exception { fillFile(); assertThrows(Exception.class, () -> { rf.insert(testBlock); }); } @Test @DisplayName("Inserting out of range throws an exception") void insertOutOfRange() throws Exception { assertThrows(Exception.class, () -> { rf.insert(maxBlocks, testBlock); }); } } }
/* * Copyright 2013 Guidewire Software, Inc. */ package gw.internal.gosu.ir.nodes; import gw.internal.gosu.parser.ReducedParameterizedDynamicFunctionSymbol; import gw.lang.parser.IReducedDynamicFunctionSymbol; import gw.lang.reflect.IAspectMethodInfoDelegate; import gw.lang.reflect.IRelativeTypeInfo; import gw.lang.reflect.IMethodInfo; import gw.lang.reflect.IType; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.IMethodInfoDelegate; import gw.lang.reflect.IMetaType; import gw.lang.reflect.ITypeVariableType; import gw.lang.reflect.IFunctionType; import gw.lang.reflect.gs.IGosuMethodInfo; import gw.lang.reflect.gs.IGosuClass; import gw.lang.reflect.gs.IGosuEnhancement; import gw.lang.reflect.gs.IGenericTypeVariable; import gw.lang.reflect.java.IJavaMethodInfo; import gw.lang.reflect.java.IJavaType; import gw.lang.reflect.java.JavaTypes; import gw.lang.reflect.java.IJavaClassMethod; import gw.lang.reflect.java.IJavaClassInfo; import gw.lang.ir.IRType; import gw.internal.gosu.ir.transform.util.AccessibilityUtil; import gw.internal.gosu.ir.transform.util.IRTypeResolver; import gw.internal.gosu.parser.TypeLord; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class IRMethodFromMethodInfo extends IRFeatureBase implements IRMethod { private IMethodInfo _originalMethod; private IMethodInfo _terminalMethod; private IFunctionType _functionType; public IRMethodFromMethodInfo(IMethodInfo originalMethod, IFunctionType functionType) { _originalMethod = originalMethod; _terminalMethod = originalMethod; while (_terminalMethod instanceof IMethodInfoDelegate && !(_terminalMethod instanceof IAspectMethodInfoDelegate)) { _terminalMethod = ((IMethodInfoDelegate) _terminalMethod).getSource(); } _functionType = functionType; } public IMethodInfo getOriginalMethod() { return _originalMethod; } public IMethodInfo getTerminalMethod() { return _terminalMethod; } @Override public IRType getReturnType() { return getBoundedReturnType(_terminalMethod); } @Override public List<IRType> getExplicitParameterTypes() { return getBoundedParameterTypeDescriptors(_terminalMethod); } @Override public List<IRType> getAllParameterTypes() { return getMethodDescriptor(_terminalMethod); } @Override public String getName() { return getActualMethodName(_terminalMethod); } @Override public IRType getOwningIRType() { return getTrueOwningType(_terminalMethod); } @Override public IType getOwningIType() { IType owningType; if( _terminalMethod instanceof IJavaMethodInfo ) { // We have to get the owner type from the method because it may be different from the owning type e.g., entity aspects see ContactGosuAspect.AllAdresses IJavaClassMethod m = ((IJavaMethodInfo)_terminalMethod).getMethod(); if( m != null ) { owningType = TypeSystem.get( m.getEnclosingClass() ); } else { owningType = _terminalMethod.getOwnersType(); } } else { owningType = _terminalMethod.getOwnersType(); } if( owningType instanceof IMetaType) { owningType = ((IMetaType)owningType).getType(); } return owningType; } /*if( rootType instanceof IMetaType ) { rootType = ((IMetaType)rootType).getType(); } return rootType;*/ @Override public IRelativeTypeInfo.Accessibility getAccessibility() { return AccessibilityUtil.forFeatureInfo(_terminalMethod); } @Override public boolean isStatic() { return _terminalMethod.isStatic(); } public IRType getTargetRootIRType( ) { IRType owner = getOwningIRType(); if( owner instanceof GosuClassIRType && ((GosuClassIRType)owner).getType() instanceof IGosuEnhancement) { return IRTypeResolver.getDescriptor( ((IGosuEnhancement)((GosuClassIRType)owner).getType()).getEnhancedType() ); } else { return owner; } } @Override public IGenericTypeVariable[] getTypeVariables() { if (_terminalMethod instanceof IGosuMethodInfo && !IGosuClass.ProxyUtil.isProxy(_terminalMethod.getOwnersType())) { return ((IGosuMethodInfo) _terminalMethod).getTypeVariables(); } else { return null; } } @Override public IFunctionType getFunctionType() { return _functionType; } @Override protected boolean isImplicitMethod() { return isGeneratedEnumMethod(); } @Override public boolean isGeneratedEnumMethod() { return getOwningIType().isEnum() && isStatic() && (hasSignature( "getAllValues" ) || hasSignature( "values" ) || hasSignature( "valueOf", JavaTypes.STRING() )); } private boolean hasSignature( String name, IType... argTypes ) { if( getName().equals( name ) && _originalMethod.getParameters().length == argTypes.length ) { for( int i = 0; i < argTypes.length; i++ ) { if( !_originalMethod.getParameters()[i].getFeatureType().equals( argTypes[i] ) ) { return false; } } return true; } return false; } @Override public boolean isBytecodeMethod() { return (_terminalMethod instanceof IGosuMethodInfo || _terminalMethod instanceof IJavaMethodInfo) && !IRFeatureBase.isExternalEntityJavaType( _terminalMethod ); } private static IRType getTrueOwningType( IMethodInfo mi ) { if( mi instanceof IJavaMethodInfo) { // We have to get the owner type from the method because it may be different from the owning type e.g., entity aspects see ContactGosuAspect.AllAdresses IJavaClassMethod m = ((IJavaMethodInfo)mi).getMethod(); if( m != null ) { return IRTypeResolver.getDescriptor( m.getEnclosingClass() ); } } return IRTypeResolver.getDescriptor( mi.getOwnersType() ); } @Override public boolean couldHaveTypeVariables() { return _terminalMethod instanceof IGosuMethodInfo && !IGosuClass.ProxyUtil.isProxy(_terminalMethod.getOwnersType()); } private String getActualMethodName(IMethodInfo methodInfo) { if( methodInfo instanceof IJavaMethodInfo) { // Get the name from the Java method in case a PublishedName attr was used in typeinfo return ((IJavaMethodInfo)methodInfo).getMethod().getName(); } else { return methodInfo.getDisplayName(); } } private IRType getBoundedReturnType( IMethodInfo mi ) { if( mi instanceof IJavaMethodInfo ) { return IRTypeResolver.getDescriptor( ((IJavaMethodInfo)mi).getMethod().getReturnClassInfo() ); } else if( mi instanceof IGosuMethodInfo) { IReducedDynamicFunctionSymbol dfs = ((IGosuMethodInfo)mi).getDfs(); while( dfs instanceof ReducedParameterizedDynamicFunctionSymbol) { ReducedParameterizedDynamicFunctionSymbol pdfs = (ReducedParameterizedDynamicFunctionSymbol)dfs; dfs = pdfs.getBackingDfs(); } if( IGosuClass.ProxyUtil.isProxy( dfs.getGosuClass() ) ) { return getBoundedReturnTypeFromProxiedClass( dfs ); } return IRTypeResolver.getDescriptor( TypeLord.getDefaultParameterizedTypeWithTypeVars( dfs.getReturnType() ) ); } else { return IRTypeResolver.getDescriptor( mi.getReturnType() ); } } private IRType getBoundedReturnTypeFromProxiedClass( IReducedDynamicFunctionSymbol dfs ) { IJavaClassMethod m = getJavaMethodFromProxy( dfs ); return JavaClassIRType.get( m.getReturnClassInfo() ); } public List<IRType> getMethodDescriptor( IMethodInfo mi ) { List<IRType> paramTypes = new ArrayList<IRType>(); IFunctionType functionType = null; if (mi instanceof IGosuMethodInfo && !IGosuClass.ProxyUtil.isProxy( mi.getOwnersType() )) { functionType = (IFunctionType) ((IGosuMethodInfo) mi).getDfs().getType(); } addImplicitParameters( getOwningIType(), functionType, isStatic(), paramTypes ); paramTypes.addAll( getBoundedParameterTypeDescriptors( mi ) ); return paramTypes; } private List<IRType> getBoundedParameterTypeDescriptors( IMethodInfo mi ) { if( mi.getParameters().length == 0 ) { return Collections.emptyList(); } if( mi instanceof IJavaMethodInfo ) { return IRTypeResolver.getDescriptors( ((IJavaMethodInfo)mi).getMethod().getParameterTypes() ); } else if( mi instanceof IGosuMethodInfo ) { IReducedDynamicFunctionSymbol dfs = ((IGosuMethodInfo)mi).getDfs(); while( dfs instanceof ReducedParameterizedDynamicFunctionSymbol ) { ReducedParameterizedDynamicFunctionSymbol pdfs = (ReducedParameterizedDynamicFunctionSymbol)dfs; dfs = pdfs.getBackingDfs(); } List<IRType> boundedTypes = new ArrayList<IRType>( dfs.getArgs().size() ); if( IGosuClass.ProxyUtil.isProxy( dfs.getGosuClass() ) ) { return getBoundedParamTypesFromProxiedClass( dfs ); } for( int i = 0; i < dfs.getArgs().size(); i++ ) { boundedTypes.add( IRTypeResolver.getDescriptor( TypeLord.getDefaultParameterizedTypeWithTypeVars( dfs.getArgs().get(i).getType() ) ) ); } return boundedTypes; } else { return getTypeDescriptors( mi.getParameters() ); } } private List<IRType> getBoundedParamTypesFromProxiedClass( IReducedDynamicFunctionSymbol dfs ) { IJavaClassMethod m = getJavaMethodFromProxy( dfs ); IJavaClassInfo[] paramClasses = m.getParameterTypes(); List<IRType> paramTypes = new ArrayList<IRType>( paramClasses.length ); for( int i = 0; i < paramClasses.length; i++ ) { paramTypes.add( JavaClassIRType.get( paramClasses[i] ) ); } return paramTypes; } private IJavaClassMethod getJavaMethodFromProxy( IReducedDynamicFunctionSymbol dfs ) { IType proxyType = dfs.getGosuClass(); IJavaType javaType = (IJavaType)IGosuClass.ProxyUtil.getProxiedType( proxyType ); IType[] boundedDfsParams = new IType[dfs.getArgs().size()]; for( int i = 0; i < boundedDfsParams.length; i++ ) { IType param = dfs.getArgs().get(i).getType(); if( param instanceof ITypeVariableType && (param.getEnclosingType() instanceof IGosuClass || TypeLord.isRecursiveType( javaType )) ) { param = ((ITypeVariableType)param).getBoundingType(); } boundedDfsParams[i] = TypeLord.getPureGenericType( param ); } javaType = (IJavaType)TypeLord.getDefaultParameterizedType( javaType ); IJavaMethodInfo jmi = (IJavaMethodInfo)((IRelativeTypeInfo)javaType.getTypeInfo()).getMethod( javaType, dfs.getDisplayName(), boundedDfsParams ); return jmi.getMethod(); } }
package org.ripple.bouncycastle.pqc.crypto.ntru; import java.security.SecureRandom; import org.ripple.bouncycastle.crypto.AsymmetricBlockCipher; import org.ripple.bouncycastle.crypto.CipherParameters; import org.ripple.bouncycastle.crypto.DataLengthException; import org.ripple.bouncycastle.crypto.Digest; import org.ripple.bouncycastle.crypto.InvalidCipherTextException; import org.ripple.bouncycastle.crypto.params.ParametersWithRandom; import org.ripple.bouncycastle.pqc.math.ntru.polynomial.DenseTernaryPolynomial; import org.ripple.bouncycastle.pqc.math.ntru.polynomial.IntegerPolynomial; import org.ripple.bouncycastle.pqc.math.ntru.polynomial.Polynomial; import org.ripple.bouncycastle.pqc.math.ntru.polynomial.ProductFormPolynomial; import org.ripple.bouncycastle.pqc.math.ntru.polynomial.SparseTernaryPolynomial; import org.ripple.bouncycastle.pqc.math.ntru.polynomial.TernaryPolynomial; import org.ripple.bouncycastle.util.Arrays; /** * Encrypts, decrypts data and generates key pairs.<br> * The parameter p is hardcoded to 3. */ public class NTRUEngine implements AsymmetricBlockCipher { private boolean forEncryption; private NTRUEncryptionParameters params; private NTRUEncryptionPublicKeyParameters pubKey; private NTRUEncryptionPrivateKeyParameters privKey; private SecureRandom random; /** * Constructs a new instance with a set of encryption parameters. * */ public NTRUEngine() { } public void init(boolean forEncryption, CipherParameters parameters) { this.forEncryption = forEncryption; if (forEncryption) { if (parameters instanceof ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom)parameters; this.random = p.getRandom(); this.pubKey = (NTRUEncryptionPublicKeyParameters)p.getParameters(); } else { this.random = new SecureRandom(); this.pubKey = (NTRUEncryptionPublicKeyParameters)parameters; } this.params = pubKey.getParameters(); } else { this.privKey = (NTRUEncryptionPrivateKeyParameters)parameters; this.params = privKey.getParameters(); } } public int getInputBlockSize() { return params.maxMsgLenBytes; } public int getOutputBlockSize() { return ((params.N * log2(params.q)) + 7) / 8; } public byte[] processBlock(byte[] in, int inOff, int len) throws InvalidCipherTextException { byte[] tmp = new byte[len]; System.arraycopy(in, inOff, tmp, 0, len); if (forEncryption) { return encrypt(tmp, pubKey); } else { return decrypt(tmp, privKey); } } /** * Encrypts a message.<br/> * See P1363.1 section 9.2.2. * * @param m The message to encrypt * @param pubKey the public key to encrypt the message with * @return the encrypted message */ private byte[] encrypt(byte[] m, NTRUEncryptionPublicKeyParameters pubKey) { IntegerPolynomial pub = pubKey.h; int N = params.N; int q = params.q; int maxLenBytes = params.maxMsgLenBytes; int db = params.db; int bufferLenBits = params.bufferLenBits; int dm0 = params.dm0; int pkLen = params.pkLen; int minCallsMask = params.minCallsMask; boolean hashSeed = params.hashSeed; byte[] oid = params.oid; int l = m.length; if (maxLenBytes > 255) { throw new IllegalArgumentException("llen values bigger than 1 are not supported"); } if (l > maxLenBytes) { throw new DataLengthException("Message too long: " + l + ">" + maxLenBytes); } while (true) { // M = b|octL|m|p0 byte[] b = new byte[db / 8]; random.nextBytes(b); byte[] p0 = new byte[maxLenBytes + 1 - l]; byte[] M = new byte[bufferLenBits / 8]; System.arraycopy(b, 0, M, 0, b.length); M[b.length] = (byte)l; System.arraycopy(m, 0, M, b.length + 1, m.length); System.arraycopy(p0, 0, M, b.length + 1 + m.length, p0.length); IntegerPolynomial mTrin = IntegerPolynomial.fromBinary3Sves(M, N); // sData = OID|m|b|hTrunc byte[] bh = pub.toBinary(q); byte[] hTrunc = copyOf(bh, pkLen / 8); byte[] sData = buildSData(oid, m, l, b, hTrunc); Polynomial r = generateBlindingPoly(sData, M); IntegerPolynomial R = r.mult(pub, q); IntegerPolynomial R4 = (IntegerPolynomial)R.clone(); R4.modPositive(4); byte[] oR4 = R4.toBinary(4); IntegerPolynomial mask = MGF(oR4, N, minCallsMask, hashSeed); mTrin.add(mask); mTrin.mod3(); if (mTrin.count(-1) < dm0) { continue; } if (mTrin.count(0) < dm0) { continue; } if (mTrin.count(1) < dm0) { continue; } R.add(mTrin, q); R.ensurePositive(q); return R.toBinary(q); } } private byte[] buildSData(byte[] oid, byte[] m, int l, byte[] b, byte[] hTrunc) { byte[] sData = new byte[oid.length + l + b.length + hTrunc.length]; System.arraycopy(oid, 0, sData, 0, oid.length); System.arraycopy(m, 0, sData, oid.length, m.length); System.arraycopy(b, 0, sData, oid.length + m.length, b.length); System.arraycopy(hTrunc, 0, sData, oid.length + m.length + b.length, hTrunc.length); return sData; } protected IntegerPolynomial encrypt(IntegerPolynomial m, TernaryPolynomial r, IntegerPolynomial pubKey) { IntegerPolynomial e = r.mult(pubKey, params.q); e.add(m, params.q); e.ensurePositive(params.q); return e; } /** * Deterministically generates a blinding polynomial from a seed and a message representative. * * @param seed * @param M message representative * @return a blinding polynomial */ private Polynomial generateBlindingPoly(byte[] seed, byte[] M) { IndexGenerator ig = new IndexGenerator(seed, params); if (params.polyType == NTRUParameters.TERNARY_POLYNOMIAL_TYPE_PRODUCT) { SparseTernaryPolynomial r1 = new SparseTernaryPolynomial(generateBlindingCoeffs(ig, params.dr1)); SparseTernaryPolynomial r2 = new SparseTernaryPolynomial(generateBlindingCoeffs(ig, params.dr2)); SparseTernaryPolynomial r3 = new SparseTernaryPolynomial(generateBlindingCoeffs(ig, params.dr3)); return new ProductFormPolynomial(r1, r2, r3); } else { int dr = params.dr; boolean sparse = params.sparse; int[] r = generateBlindingCoeffs(ig, dr); if (sparse) { return new SparseTernaryPolynomial(r); } else { return new DenseTernaryPolynomial(r); } } } /** * Generates an <code>int</code> array containing <code>dr</code> elements equal to <code>1</code> * and <code>dr</code> elements equal to <code>-1</code> using an index generator. * * @param ig an index generator * @param dr number of ones / negative ones * @return an array containing numbers between <code>-1</code> and <code>1</code> */ private int[] generateBlindingCoeffs(IndexGenerator ig, int dr) { int N = params.N; int[] r = new int[N]; for (int coeff = -1; coeff <= 1; coeff += 2) { int t = 0; while (t < dr) { int i = ig.nextIndex(); if (r[i] == 0) { r[i] = coeff; t++; } } } return r; } /** * An implementation of MGF-TP-1 from P1363.1 section 8.4.1.1. * * @param seed * @param N * @param minCallsR * @param hashSeed whether to hash the seed * @return */ private IntegerPolynomial MGF(byte[] seed, int N, int minCallsR, boolean hashSeed) { Digest hashAlg = params.hashAlg; int hashLen = hashAlg.getDigestSize(); byte[] buf = new byte[minCallsR * hashLen]; byte[] Z = hashSeed ? calcHash(hashAlg, seed) : seed; int counter = 0; while (counter < minCallsR) { hashAlg.update(Z, 0, Z.length); putInt(hashAlg, counter); byte[] hash = calcHash(hashAlg); System.arraycopy(hash, 0, buf, counter * hashLen, hashLen); counter++; } IntegerPolynomial i = new IntegerPolynomial(N); while (true) { int cur = 0; for (int index = 0; index != buf.length; index++) { int O = (int)buf[index] & 0xFF; if (O >= 243) // 243 = 3^5 { continue; } for (int terIdx = 0; terIdx < 4; terIdx++) { int rem3 = O % 3; i.coeffs[cur] = rem3 - 1; cur++; if (cur == N) { return i; } O = (O - rem3) / 3; } i.coeffs[cur] = O - 1; cur++; if (cur == N) { return i; } } if (cur >= N) { return i; } hashAlg.update(Z, 0, Z.length); putInt(hashAlg, counter); byte[] hash = calcHash(hashAlg); buf = hash; counter++; } } private void putInt(Digest hashAlg, int counter) { hashAlg.update((byte)(counter >> 24)); hashAlg.update((byte)(counter >> 16)); hashAlg.update((byte)(counter >> 8)); hashAlg.update((byte)counter); } private byte[] calcHash(Digest hashAlg) { byte[] tmp = new byte[hashAlg.getDigestSize()]; hashAlg.doFinal(tmp, 0); return tmp; } private byte[] calcHash(Digest hashAlg, byte[] input) { byte[] tmp = new byte[hashAlg.getDigestSize()]; hashAlg.update(input, 0, input.length); hashAlg.doFinal(tmp, 0); return tmp; } /** * Decrypts a message.<br/> * See P1363.1 section 9.2.3. * * @param data The message to decrypt * @param privKey the corresponding private key * @return the decrypted message * @throws InvalidCipherTextException if the encrypted data is invalid, or <code>maxLenBytes</code> is greater than 255 */ private byte[] decrypt(byte[] data, NTRUEncryptionPrivateKeyParameters privKey) throws InvalidCipherTextException { Polynomial priv_t = privKey.t; IntegerPolynomial priv_fp = privKey.fp; IntegerPolynomial pub = privKey.h; int N = params.N; int q = params.q; int db = params.db; int maxMsgLenBytes = params.maxMsgLenBytes; int dm0 = params.dm0; int pkLen = params.pkLen; int minCallsMask = params.minCallsMask; boolean hashSeed = params.hashSeed; byte[] oid = params.oid; if (maxMsgLenBytes > 255) { throw new DataLengthException("maxMsgLenBytes values bigger than 255 are not supported"); } int bLen = db / 8; IntegerPolynomial e = IntegerPolynomial.fromBinary(data, N, q); IntegerPolynomial ci = decrypt(e, priv_t, priv_fp); if (ci.count(-1) < dm0) { throw new InvalidCipherTextException("Less than dm0 coefficients equal -1"); } if (ci.count(0) < dm0) { throw new InvalidCipherTextException("Less than dm0 coefficients equal 0"); } if (ci.count(1) < dm0) { throw new InvalidCipherTextException("Less than dm0 coefficients equal 1"); } IntegerPolynomial cR = (IntegerPolynomial)e.clone(); cR.sub(ci); cR.modPositive(q); IntegerPolynomial cR4 = (IntegerPolynomial)cR.clone(); cR4.modPositive(4); byte[] coR4 = cR4.toBinary(4); IntegerPolynomial mask = MGF(coR4, N, minCallsMask, hashSeed); IntegerPolynomial cMTrin = ci; cMTrin.sub(mask); cMTrin.mod3(); byte[] cM = cMTrin.toBinary3Sves(); byte[] cb = new byte[bLen]; System.arraycopy(cM, 0, cb, 0, bLen); int cl = cM[bLen] & 0xFF; // llen=1, so read one byte if (cl > maxMsgLenBytes) { throw new InvalidCipherTextException("Message too long: " + cl + ">" + maxMsgLenBytes); } byte[] cm = new byte[cl]; System.arraycopy(cM, bLen + 1, cm, 0, cl); byte[] p0 = new byte[cM.length - (bLen + 1 + cl)]; System.arraycopy(cM, bLen + 1 + cl, p0, 0, p0.length); if (!Arrays.constantTimeAreEqual(p0, new byte[p0.length])) { throw new InvalidCipherTextException("The message is not followed by zeroes"); } // sData = OID|m|b|hTrunc byte[] bh = pub.toBinary(q); byte[] hTrunc = copyOf(bh, pkLen / 8); byte[] sData = buildSData(oid, cm, cl, cb, hTrunc); Polynomial cr = generateBlindingPoly(sData, cm); IntegerPolynomial cRPrime = cr.mult(pub); cRPrime.modPositive(q); if (!cRPrime.equals(cR)) { throw new InvalidCipherTextException("Invalid message encoding"); } return cm; } /** * @param e * @param priv_t a polynomial such that if <code>fastFp=true</code>, <code>f=1+3*priv_t</code>; otherwise, <code>f=priv_t</code> * @param priv_fp * @return */ protected IntegerPolynomial decrypt(IntegerPolynomial e, Polynomial priv_t, IntegerPolynomial priv_fp) { IntegerPolynomial a; if (params.fastFp) { a = priv_t.mult(e, params.q); a.mult(3); a.add(e); } else { a = priv_t.mult(e, params.q); } a.center0(params.q); a.mod3(); IntegerPolynomial c = params.fastFp ? a : new DenseTernaryPolynomial(a).mult(priv_fp, 3); c.center0(3); return c; } private byte[] copyOf(byte[] src, int len) { byte[] tmp = new byte[len]; System.arraycopy(src, 0, tmp, 0, len < src.length ? len : src.length); return tmp; } private int log2(int value) { if (value == 2048) { return 11; } throw new IllegalStateException("log2 not fully implemented"); } }
package org.onosproject.cli.athena; import com.google.common.base.Splitter; import org.apache.karaf.shell.commands.Argument; import org.apache.karaf.shell.commands.Command; import org.onosproject.athena.database.AdvancedFeatureConstraint; import org.onosproject.athena.database.AdvancedFeatureConstraintType; import org.onosproject.athena.database.AdvancedFeatureConstraintValue; import org.onosproject.athena.database.AthenaFeatureField; import org.onosproject.athena.database.AthenaFeatureRequester; import org.onosproject.athena.database.AthenaFeatureRequestrType; import org.onosproject.athena.database.AthenaIndexField; import org.onosproject.athena.database.AthenaValueGenerator; import org.onosproject.athena.database.FeatureConstraint; import org.onosproject.athena.database.FeatureConstraintOperator; import org.onosproject.athena.database.FeatureConstraintOperatorType; import org.onosproject.athena.database.FeatureConstraintType; import org.onosproject.athena.database.FeatureDatabaseService; import org.onosproject.athena.database.TargetAthenaValue; import org.onosproject.cli.AbstractShellCommand; import org.slf4j.Logger; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import static org.slf4j.LoggerFactory.getLogger; /** * Created by seunghyeon on 01/05/16. * The basic CLI command for athena. * This works for querying to athena distributed storage with constraints and options. * athena-query feature:comparator:value,... option:param1:param2,... */ @Command(scope = "onos", name = "athena-query", description = "Athena debugging CLI") public class AthenaQueryCommand extends AbstractShellCommand { private final Logger log = getLogger(getClass()); public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; public static final String ANSI_YELLOW = "\u001B[33m"; public static final String ANSI_BLUE = "\u001B[34m"; public static final String ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN = "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m"; @Argument(index = 0, name = "queryArguments", description = "arguments for range query", required = true, multiValued = false) String queryArguments = null; @Argument(index = 1, name = "options", description = "Advanced options", required = false, multiValued = false) String options = null; @Override protected void execute() { FeatureDatabaseService featureDatabaseService = get(FeatureDatabaseService.class); if (queryArguments.startsWith("?")) { printUsage(); return; } if (queryArguments.startsWith("view")) { printFeatures(); return; } //generate dataRequestobj FeatureConstraint dataRequestobject = generateDataRequestObject(); //generate dataRequestAdvancedOps AdvancedFeatureConstraint dataRequestAdvancedOptions = null; if (options != null) { dataRequestAdvancedOptions = dataRequestAdvancedOptions(); } AthenaFeatureRequester athenaFeatureRequester = new AthenaFeatureRequester( AthenaFeatureRequestrType.REQUEST_FEATURES, dataRequestobject, dataRequestAdvancedOptions, null); featureDatabaseService.requestFeatures(null, athenaFeatureRequester); } public AdvancedFeatureConstraint dataRequestAdvancedOptions() { AdvancedFeatureConstraint dataRequestAdvancedOptions = new AdvancedFeatureConstraint(); Iterable<String> ops; ops = Splitter.on(",").split(options); String[] param = new String[3]; String sb; for (String params : ops) { //LIMIT_FEATURE_COUNTS if (params.startsWith("L")) { param[0] = params.substring(2); dataRequestAdvancedOptions.addAdvancedOptions(AdvancedFeatureConstraintType.LIMIT_FEATURE_COUNTS, new AdvancedFeatureConstraintValue(param[0])); //SORTING_RAW_FEATURES } else if (params.startsWith("S")) { param[0] = params.substring(2); dataRequestAdvancedOptions.addAdvancedOptions(AdvancedFeatureConstraintType.SORTING, new AdvancedFeatureConstraintValue(param[0])); //SORTING_AGGREGATED_INDEX_FEATURES } else if (params.startsWith("A")) { sb = params.substring(2); dataRequestAdvancedOptions.addAdvancedOptions(AdvancedFeatureConstraintType.AGGREGATE, new AdvancedFeatureConstraintValue(splitConstraintsAdvanced(sb))); } } return dataRequestAdvancedOptions; } public List<String> splitConstraintsAdvanced(String params) { List<String> returnValue = new ArrayList<>(); Iterable<String> value; value = Splitter.on(":").split(params); for (String v : value) { returnValue.add(v); } return returnValue; } public String[] splitConstraints(String params) { String comparator = null; String[] param = null; String[] returnValue = new String[3]; String[] compratorSet = {"=", ">", "<", ">=", "<="}; for (int i = 0; i < compratorSet.length; i++) { param = params.split(compratorSet[i]); if (param[0].length() != params.length()) { returnValue[0] = param[0]; returnValue[1] = compratorSet[i]; returnValue[2] = param[1]; break; } } return returnValue; } //generate DataRequestObjects. private FeatureConstraint generateDataRequestObject() { AthenaFeatureField athenaFeatureField = new AthenaFeatureField(); AthenaIndexField athenaIndexField = new AthenaIndexField(); FeatureConstraintType featureConstraintType; FeatureConstraintOperator featureConstraintOperator = null; Object value = null; String type; FeatureConstraint completeDataRequestobject = new FeatureConstraint(FeatureConstraintOperatorType.LOGICAL, new FeatureConstraintOperator(FeatureConstraintOperator.LOGICAL_AND)); Iterable<String> constraints; constraints = Splitter.on(",").split(queryArguments); String[] param; for (String params : constraints) { param = splitConstraints(params); if (param[1].startsWith("=")) { featureConstraintOperator = new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_EQ); } else if (param[1].startsWith(">")) { featureConstraintOperator = new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_GT); } else if (param[1].startsWith(">=")) { featureConstraintOperator = new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_GTE); } else if (param[1].startsWith("<")) { featureConstraintOperator = new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_LT); } else if (param[1].startsWith("<=")) { featureConstraintOperator = new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_LTE); } else { System.out.println("Not support operator : " + param[1]); } type = athenaIndexField.getTypeOnDatabase(param[0]); if (type == null) { type = athenaFeatureField.getTypeOnDatabase(param[0]); } if (type.startsWith(athenaFeatureField.varintType)) { value = new BigInteger(param[2]); } else if (type.startsWith(athenaFeatureField.bigintType)) { value = new Long(param[2]); } else if (type.startsWith(athenaFeatureField.boolType)) { value = Boolean.valueOf(param[2]); } else if (type.startsWith(athenaFeatureField.stringType)) { value = param[2]; } else if (type.startsWith(athenaFeatureField.doubleType)) { value = new Double(param[2]); } else if (type.startsWith(athenaFeatureField.timestampType)) { value = AthenaValueGenerator.parseDataToAthenaValue(param[2]); } else { System.out.println("Not supported feature : " + param[2]); } FeatureConstraint featureConstraint = null; if (athenaIndexField.getListOfFeatures().contains(param[0])) { featureConstraintType = FeatureConstraintType.INDEX; athenaIndexField = new AthenaIndexField(); athenaIndexField.setValue(param[0]); featureConstraint = new FeatureConstraint(featureConstraintType, FeatureConstraintOperatorType.COMPARABLE, featureConstraintOperator, athenaIndexField, new TargetAthenaValue(value)); } else if (athenaFeatureField.getListOfFeatures().contains(param[0])) { featureConstraintType = FeatureConstraintType.FEATURE; athenaFeatureField = new AthenaFeatureField(); athenaFeatureField.setValue(param[0]); featureConstraint = new FeatureConstraint(featureConstraintType, FeatureConstraintOperatorType.COMPARABLE, featureConstraintOperator, athenaFeatureField, new TargetAthenaValue(value)); } else { System.out.println("Not support feature : " + param[0]); } if (featureConstraint == null) { System.out.println("Cannot create datareuqestObject! "); } completeDataRequestobject.appenValue(new TargetAthenaValue(featureConstraint)); } return completeDataRequestobject; } public void printUsage() { System.out.println("athena-query FeatureComaratorValue Ops:Pramgs"); System.out.println("Timestamp format: yyyy-MM-dd-HH:mm"); System.out.println("Available advanced options are :"); System.out.println(" L - Limit features (param1 = number of entires"); System.out.println(" S - Sorting with a certain feature (param1 = name of feature "); System.out.println(" A - Sorting entires with a certain condition by an index"); System.out.println("ex) athena-query FSSdurationNSec>10,timestamp>2016-01-03-11:45,FSSactionOutput=true," + "AappName=org.onosproject.fwd" + " L:100,S:FSSbyteCount,A:Feature1:Feature2"); } public void printFeatures() { AthenaIndexField in = new AthenaIndexField(); AthenaFeatureField fn = new AthenaFeatureField(); System.out.print(ANSI_PURPLE + "Index: "); List<String> features = in.getListOfFeatures(); for (int i = 0; i < features.size(); i++) { System.out.print(features.get(i)); if (i != (features.size() - 1)) { System.out.print(", "); } } System.out.println(ANSI_RESET + ""); System.out.print(ANSI_GREEN + "Feature: "); features = fn.getListOfFeatures(); for (int i = 0; i < features.size(); i++) { if (!fn.isElementofTables(features.get(i))) { System.out.print(features.get(i)); } if (i != (features.size() - 1)) { System.out.print(", "); } } System.out.println("" + ANSI_RESET); } }
package org.intellij.ibatis.provider; import com.intellij.codeInsight.completion.CompletionVariant; import com.intellij.codeInsight.completion.XmlCompletionData; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.Pair; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiLanguageInjectionHost; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.filters.TextFilter; import com.intellij.psi.filters.TrueFilter; import com.intellij.psi.filters.position.LeftNeighbour; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlFile; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomFileElement; import com.intellij.util.xml.DomManager; import org.intellij.ibatis.model.JdbcType; import org.intellij.ibatis.dom.sqlMap.SqlMap; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * completion data for SQL map symbol */ public class SqlMapSymbolCompletionData extends XmlCompletionData { public static String OPEN_TAG = "#"; public static String CLOSE_TAG = "#"; private static List<String> sentenceNames = new ArrayList<String>(); private XmlCompletionData parentCompletionData; static { sentenceNames.add("select"); sentenceNames.add("insert"); sentenceNames.add("update"); sentenceNames.add("delete"); sentenceNames.add("procedue"); sentenceNames.add("statement"); sentenceNames.add("sql"); } public SqlMapSymbolCompletionData(XmlCompletionData parentCompletionData) { this.parentCompletionData = parentCompletionData; } public String findPrefix(PsiElement psiElement, int offsetInFile) { if (getXmlTagForSQLCompletion(psiElement, psiElement.getContainingFile()) != null) { return psiElement.getText().substring(0, offsetInFile - psiElement.getTextRange().getStartOffset()); } else return super.findPrefix(psiElement, offsetInFile); } @Override public CompletionVariant[] findVariants(PsiElement psiElement, PsiFile psiFile) { XmlTag tag = getXmlTagForSQLCompletion(psiElement, psiFile); if (tag != null) { // String prefix = findPrefix(psiElement, psiElement.getTextOffset()); String prefix2 = prefix.substring(0, prefix.indexOf("#") + 1); if (prefix.contains("#")) { //# is necessary LeftNeighbour left = new LeftNeighbour(new TextFilter(OPEN_TAG)); CompletionVariant variant = new CompletionVariant(left); variant.includeScopeClass(PsiElement.class, true); variant.addCompletionFilter(TrueFilter.INSTANCE); variant.setInsertHandler(new SqlMapSymbolnsertHandler()); if (!prefix.contains(":")) { //just clear in line parameter name if (!prefix.contains(".")) { //root field List<String> parameterNames = getParameterNamesForXmlTag(tag, prefix2); for (String parameterName : parameterNames) { variant.addCompletion(parameterName); } } else //recursion field { String parameterClass = tag.getAttributeValue("parameterClass"); if (IbatisClassShortcutsReferenceProvider.isDomain(parameterClass)) //domain class { PsiClass psiClass = IbatisClassShortcutsReferenceProvider.getPsiClass(psiElement, parameterClass); if (psiClass != null) { //find Map<String, String> methodMap = FieldAccessMethodReferenceProvider.getAllSetterMethods(psiClass, prefix.replace("#", "")); for (Map.Entry<String, String> entry : methodMap.entrySet()) { variant.addCompletion(prefix2 + entry.getKey()); } } } } } else //jdbc type will be added { if ((prefix + " ").split(":").length == 2) { //only one ':' included prefix = prefix.substring(0, prefix.indexOf(':')); for (String typeName : JdbcType.TYPES.keySet()) { variant.addCompletion(prefix + ":" + typeName); } } else //two ':' include { } } return new CompletionVariant[]{variant}; } } if (parentCompletionData != null) return parentCompletionData.findVariants(psiElement, psiFile); return super.findVariants(psiElement, psiFile); } /** * get xml tag for code completion * * @param psiElement psiElement * @param psiFile current file * @return xml tag */ @Nullable public static XmlTag getXmlTagForSQLCompletion(PsiElement psiElement, PsiFile psiFile) { if (!psiFile.isPhysical()) { if (psiElement.getParent().getClass().getName().contains("com.intellij.sql.psi")) { // text only if (!psiElement.isPhysical()) { //injected sql mode //todo jacky resolve parameter code completion in sql List<Pair<PsiElement,TextRange>> files = InjectedLanguageUtil.getInjectedPsiFiles(psiElement); InjectedLanguageManager manager = InjectedLanguageManager.getInstance(psiElement.getProject()); PsiLanguageInjectionHost psiLanguageInjectionHost = manager.getInjectionHost(psiElement); if (psiElement.getContainingFile() instanceof XmlFile) { XmlFile xmlFile = (XmlFile) psiElement.getContainingFile(); final DomFileElement fileElement = DomManager.getDomManager(psiFile.getProject()).getFileElement(xmlFile, DomElement.class); if (fileElement != null && fileElement.getRootElement() instanceof SqlMap) { return getParentSentence(psiElement); } } } } } return null; } /** * get parameter name list * * @param xmlTag xmlTag * @param prefix prefix for name * @return name list */ public List<String> getParameterNamesForXmlTag(XmlTag xmlTag, String prefix) { List<String> nameList = new ArrayList<String>(); String parameterClass = xmlTag.getAttributeValue("parameterClass"); List<String> symbolNames = getAllSymbolsInXmlTag(xmlTag); if (parameterClass == null) //if parameterClass and parameterMap absent, use #value# as default { symbolNames.add("value"); } for (String symbolName : symbolNames) { nameList.add(prefix + symbolName + CLOSE_TAG); } return nameList; } /** * get all symbols for xml tag * * @param xmlTag Xml Tag * @return symbol name list */ public static List<String> getAllSymbolsInXmlTag(XmlTag xmlTag) { String parameterClass = xmlTag.getAttributeValue("parameterClass"); List<String> nameList = new ArrayList<String>(); if (StringUtil.isNotEmpty(parameterClass)) { PsiClass psiClass = IbatisClassShortcutsReferenceProvider.getPsiClass(xmlTag, parameterClass); if (psiClass != null && !"Map".equals(psiClass.getName())) { if (IbatisClassShortcutsReferenceProvider.isDomain(psiClass.getName())) { //domain class Set<String> methodNames = FieldAccessMethodReferenceProvider.getAllGetterMethods(psiClass, "").keySet(); for (String methodName : methodNames) { nameList.add(methodName); } } else //internal class { nameList.add("value"); } } } return nameList; } /** * add default symbol * * @param nameList name list * @param prefix prefix */ public void addDefaultSymbol(List<String> nameList, String prefix) { nameList.add(prefix + "value" + CLOSE_TAG); } /** * get SQL sentence tag for psiElement * * @param psiElement psiElement object * @return XmlTag object */ @Nullable public static XmlTag getParentSentence(PsiElement psiElement) { XmlTag tag = PsiTreeUtil.getParentOfType(psiElement, XmlTag.class); if (tag != null) { if (sentenceNames.contains(tag.getName())) { return tag; } else { return getParentSentence(tag); } } return null; } }
// Copyright 2014 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.native_test; import android.app.Activity; import android.app.ActivityManager; import android.app.Instrumentation; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Process; import android.util.SparseArray; import org.chromium.base.Log; import org.chromium.test.reporter.TestStatusReceiver; import org.chromium.test.support.ResultsBundleGenerator; import org.chromium.test.support.RobotiumBundleGenerator; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * An Instrumentation that runs tests based on NativeTestActivity. */ public class NativeTestInstrumentationTestRunner extends Instrumentation { public static final String EXTRA_NATIVE_TEST_ACTIVITY = "org.chromium.native_test.NativeTestInstrumentationTestRunner.NativeTestActivity"; public static final String EXTRA_SHARD_NANO_TIMEOUT = "org.chromium.native_test.NativeTestInstrumentationTestRunner.ShardNanoTimeout"; public static final String EXTRA_SHARD_SIZE_LIMIT = "org.chromium.native_test.NativeTestInstrumentationTestRunner.ShardSizeLimit"; public static final String EXTRA_TEST_LIST_FILE = "org.chromium.native_test.NativeTestInstrumentationTestRunner.TestList"; public static final String EXTRA_TEST = "org.chromium.native_test.NativeTestInstrumentationTestRunner.Test"; private static final String TAG = "cr_NativeTest"; private static final long DEFAULT_SHARD_NANO_TIMEOUT = 60 * 1000000000L; // Default to no size limit. private static final int DEFAULT_SHARD_SIZE_LIMIT = 0; private static final String DEFAULT_NATIVE_TEST_ACTIVITY = "org.chromium.native_test.NativeUnitTestActivity"; private static final Pattern RE_TEST_OUTPUT = Pattern.compile("\\[ *([^ ]*) *\\] ?([^ ]+)( .*)?$"); private ResultsBundleGenerator mBundleGenerator = new RobotiumBundleGenerator(); private Handler mHandler = new Handler(); private Bundle mLogBundle = new Bundle(); private SparseArray<ShardMonitor> mMonitors = new SparseArray<ShardMonitor>(); private String mNativeTestActivity; private TestStatusReceiver mReceiver; private Map<String, ResultsBundleGenerator.TestResult> mResults = new HashMap<String, ResultsBundleGenerator.TestResult>(); private Queue<ArrayList<String>> mShards = new ArrayDeque<ArrayList<String>>(); private long mShardNanoTimeout = DEFAULT_SHARD_NANO_TIMEOUT; private int mShardSizeLimit = DEFAULT_SHARD_SIZE_LIMIT; private File mStdoutFile; private Bundle mTransparentArguments; @Override public void onCreate(Bundle arguments) { mTransparentArguments = new Bundle(arguments); mNativeTestActivity = arguments.getString(EXTRA_NATIVE_TEST_ACTIVITY); if (mNativeTestActivity == null) mNativeTestActivity = DEFAULT_NATIVE_TEST_ACTIVITY; mTransparentArguments.remove(EXTRA_NATIVE_TEST_ACTIVITY); String shardNanoTimeout = arguments.getString(EXTRA_SHARD_NANO_TIMEOUT); if (shardNanoTimeout != null) mShardNanoTimeout = Long.parseLong(shardNanoTimeout); mTransparentArguments.remove(EXTRA_SHARD_NANO_TIMEOUT); String shardSizeLimit = arguments.getString(EXTRA_SHARD_SIZE_LIMIT); if (shardSizeLimit != null) mShardSizeLimit = Integer.parseInt(shardSizeLimit); mTransparentArguments.remove(EXTRA_SHARD_SIZE_LIMIT); String singleTest = arguments.getString(EXTRA_TEST); if (singleTest != null) { ArrayList<String> shard = new ArrayList<>(1); shard.add(singleTest); mShards.add(shard); } String testListFilePath = arguments.getString(EXTRA_TEST_LIST_FILE); if (testListFilePath != null) { File testListFile = new File(testListFilePath); try { BufferedReader testListFileReader = new BufferedReader(new FileReader(testListFile)); String test; ArrayList<String> workingShard = new ArrayList<String>(); while ((test = testListFileReader.readLine()) != null) { workingShard.add(test); if (workingShard.size() == mShardSizeLimit) { mShards.add(workingShard); workingShard = new ArrayList<String>(); } } if (!workingShard.isEmpty()) { mShards.add(workingShard); } testListFileReader.close(); } catch (IOException e) { Log.e(TAG, "Error reading %s", testListFile.getAbsolutePath(), e); } } mTransparentArguments.remove(EXTRA_TEST_LIST_FILE); try { mStdoutFile = File.createTempFile( ".temp_stdout_", ".txt", Environment.getExternalStorageDirectory()); Log.i(TAG, "stdout file created: %s", mStdoutFile.getAbsolutePath()); } catch (IOException e) { Log.e(TAG, "Unable to create temporary stdout file.", e); finish(Activity.RESULT_CANCELED, new Bundle()); return; } start(); } @Override public void onStart() { super.onStart(); mReceiver = new TestStatusReceiver(); mReceiver.register(getContext()); mReceiver.registerCallback(new TestStatusReceiver.TestRunCallback() { @Override public void testRunStarted(int pid) { if (pid != Process.myPid()) { ShardMonitor m = new ShardMonitor( pid, System.nanoTime() + mShardNanoTimeout); mMonitors.put(pid, m); mHandler.post(m); } } @Override public void testRunFinished(int pid) { ShardMonitor m = mMonitors.get(pid); if (m != null) { m.stopped(); mMonitors.remove(pid); } mHandler.post(new ShardEnder(pid)); } }); mHandler.post(new ShardStarter()); } /** Monitors a test shard's execution. */ private class ShardMonitor implements Runnable { private static final int MONITOR_FREQUENCY_MS = 1000; private long mExpirationNanoTime; private int mPid; private AtomicBoolean mStopped; public ShardMonitor(int pid, long expirationNanoTime) { mPid = pid; mExpirationNanoTime = expirationNanoTime; mStopped = new AtomicBoolean(false); } public void stopped() { mStopped.set(true); } @Override public void run() { if (mStopped.get()) { return; } if (isAppProcessAlive(getContext(), mPid)) { if (System.nanoTime() > mExpirationNanoTime) { Log.e(TAG, "Test process %d timed out.", mPid); mHandler.post(new ShardEnder(mPid)); return; } else { mHandler.postDelayed(this, MONITOR_FREQUENCY_MS); return; } } Log.e(TAG, "Test process %d died unexpectedly.", mPid); mHandler.post(new ShardEnder(mPid)); } } private static boolean isAppProcessAlive(Context context, int pid) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo processInfo : activityManager.getRunningAppProcesses()) { if (processInfo.pid == pid) return true; } return false; } /** Starts the NativeTestActivty. */ private class ShardStarter implements Runnable { @Override public void run() { Intent i = new Intent(Intent.ACTION_MAIN); i.setComponent(new ComponentName(getContext().getPackageName(), mNativeTestActivity)); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtras(mTransparentArguments); if (mShards != null && !mShards.isEmpty()) { ArrayList<String> shard = mShards.remove(); i.putStringArrayListExtra(NativeTestActivity.EXTRA_SHARD, shard); } i.putExtra(NativeTestActivity.EXTRA_STDOUT_FILE, mStdoutFile.getAbsolutePath()); getContext().startActivity(i); } } private class ShardEnder implements Runnable { private static final int WAIT_FOR_DEATH_MILLIS = 10; private int mPid; public ShardEnder(int pid) { mPid = pid; } @Override public void run() { if (mPid != Process.myPid()) { Process.killProcess(mPid); try { while (isAppProcessAlive(getContext(), mPid)) { Thread.sleep(WAIT_FOR_DEATH_MILLIS); } } catch (InterruptedException e) { Log.e(TAG, "%d may still be alive.", mPid, e); } } mResults.putAll(parseResults()); if (mShards != null && !mShards.isEmpty()) { mHandler.post(new ShardStarter()); } else { finish(Activity.RESULT_OK, mBundleGenerator.generate(mResults)); } } } /** * Generates a map between test names and test results from the instrumented Activity's * output. */ private Map<String, ResultsBundleGenerator.TestResult> parseResults() { Map<String, ResultsBundleGenerator.TestResult> results = new HashMap<String, ResultsBundleGenerator.TestResult>(); BufferedReader r = null; try { if (mStdoutFile == null || !mStdoutFile.exists()) { Log.e(TAG, "Unable to find stdout file."); return results; } r = new BufferedReader(new InputStreamReader( new BufferedInputStream(new FileInputStream(mStdoutFile)))); for (String l = r.readLine(); l != null && !l.equals("<<ScopedMainEntryLogger"); l = r.readLine()) { Matcher m = RE_TEST_OUTPUT.matcher(l); if (m.matches()) { if (m.group(1).equals("RUN")) { results.put(m.group(2), ResultsBundleGenerator.TestResult.UNKNOWN); } else if (m.group(1).equals("FAILED")) { results.put(m.group(2), ResultsBundleGenerator.TestResult.FAILED); } else if (m.group(1).equals("OK")) { results.put(m.group(2), ResultsBundleGenerator.TestResult.PASSED); } } mLogBundle.putString(Instrumentation.REPORT_KEY_STREAMRESULT, l + "\n"); sendStatus(0, mLogBundle); Log.i(TAG, l); } } catch (FileNotFoundException e) { Log.e(TAG, "Couldn't find stdout file: ", e); } catch (IOException e) { Log.e(TAG, "Error handling stdout file: ", e); } finally { if (r != null) { try { r.close(); } catch (IOException e) { Log.e(TAG, "Error while closing stdout reader.", e); } } if (mStdoutFile != null) { if (!mStdoutFile.delete()) { Log.e(TAG, "Unable to delete %s", mStdoutFile.getAbsolutePath()); } } } return results; } }
/* * Copyright 2014, Appyvet, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or 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.appyvet.rangebar; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.LightingColorFilter; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.TypedValue; import android.view.View; /** * Represents a thumb in the RangeBar slider. This is the handle for the slider * that is pressed and slid. */ class PinView extends View { // Private Constants /////////////////////////////////////////////////////// // The radius (in dp) of the touchable area around the thumb. We are basing // this value off of the recommended 48dp Rhythm. See: // http://developer.android.com/design/style/metrics-grids.html#48dp-rhythm private static final float MINIMUM_TARGET_RADIUS_DP = 24; // Sets the default values for radius, normal, pressed if circle is to be // drawn but no value is given. private static final float DEFAULT_THUMB_RADIUS_DP = 14; // Member Variables //////////////////////////////////////////////////////// // Radius (in pixels) of the touch area of the thumb. private float mTargetRadiusPx; // Indicates whether this thumb is currently pressed and active. private boolean mIsPressed = false; // The y-position of the thumb in the parent view. This should not change. private float mY; // The current x-position of the thumb in the parent view. private float mX; // mPaint to draw the thumbs if attributes are selected private Paint mTextPaint; private Drawable mPin; private String mValue; // Radius of the new thumb if selected private int mPinRadiusPx; private ColorFilter mPinFilter; private float mPinPadding; private float mTextYPadding; private Rect mBounds = new Rect(); private Resources mRes; private float mDensity; private Paint mCirclePaint; private float mCircleRadiusPx; private IRangeBarFormatter formatter; private float mMinPinFont = RangeBar.DEFAULT_MIN_PIN_FONT_SP; private float mMaxPinFont = RangeBar.DEFAULT_MAX_PIN_FONT_SP; private boolean mPinsAreTemporary; private boolean mHasBeenPressed = false; // Constructors //////////////////////////////////////////////////////////// public PinView(Context context) { super(context); } // Initialization ////////////////////////////////////////////////////////// public void setFormatter(IRangeBarFormatter mFormatter) { this.formatter = mFormatter; } /** * The view is created empty with a default constructor. Use init to set all the initial * variables for the pin * * @param ctx Context * @param y The y coordinate to raw the pin (i.e. the bar location) * @param pinRadiusDP the initial size of the pin * @param pinColor the color of the pin * @param textColor the color of the value text in the pin * @param circleRadius the radius of the selector circle * @param minFont the minimum font size for the pin text * @param maxFont the maximum font size for the pin text * @param pinsAreTemporary whether to show the pin initially or just the circle */ public void init(Context ctx, float y, float pinRadiusDP, int pinColor, int textColor, float circleRadius, int circleColor, float minFont, float maxFont, boolean pinsAreTemporary) { mRes = ctx.getResources(); mPin = ContextCompat.getDrawable(ctx, R.drawable.rotate); mDensity = getResources().getDisplayMetrics().density; mMinPinFont = minFont / mDensity; mMaxPinFont = maxFont / mDensity; mPinsAreTemporary = pinsAreTemporary; mPinPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, mRes.getDisplayMetrics()); mCircleRadiusPx = circleRadius; mTextYPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3.5f, mRes.getDisplayMetrics()); // If one of the attributes are set, but the others aren't, set the // attributes to default if (pinRadiusDP == -1) { mPinRadiusPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_THUMB_RADIUS_DP, mRes.getDisplayMetrics()); } else { mPinRadiusPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pinRadiusDP, mRes.getDisplayMetrics()); } //Set text size in px from dp int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 15, mRes.getDisplayMetrics()); // Creates the paint and sets the Paint values mTextPaint = new Paint(); mTextPaint.setColor(textColor); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(textSize); // Creates the paint and sets the Paint values mCirclePaint = new Paint(); mCirclePaint.setColor(circleColor); mCirclePaint.setAntiAlias(true); //Color filter for the selection pin mPinFilter = new LightingColorFilter(pinColor, pinColor); // Sets the minimum touchable area, but allows it to expand based on // image size int targetRadius = (int) Math.max(MINIMUM_TARGET_RADIUS_DP, mPinRadiusPx); mTargetRadiusPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, targetRadius, mRes.getDisplayMetrics()); mY = y; } /** * Set the x value of the pin * * @param x set x value of the pin */ @Override public void setX(float x) { mX = x; } /** * Get the x value of the pin * * @return x float value of the pin */ @Override public float getX() { return mX; } /** * Set the value of the pin * * @param x String value of the pin */ public void setXValue(String x) { mValue = x; } /** * Determine if the pin is pressed * * @return true if is in pressed state * false otherwise */ @Override public boolean isPressed() { return mIsPressed; } /** * Sets the state of the pin to pressed */ public void press() { mIsPressed = true; mHasBeenPressed = true; } /** * Set size of the pin and padding for use when animating pin enlargement on press * * @param size the size of the pin radius * @param padding the size of the padding */ public void setSize(float size, float padding) { mPinPadding = (int) padding; mPinRadiusPx = (int) size; invalidate(); } /** * Release the pin, sets pressed state to false */ public void release() { mIsPressed = false; } /** * Determines if the input coordinate is close enough to this thumb to * consider it a press. * * @param x the x-coordinate of the user touch * @param y the y-coordinate of the user touch * @return true if the coordinates are within this thumb's target area; * false otherwise */ public boolean isInTargetZone(float x, float y) { return (Math.abs(x - mX) <= mTargetRadiusPx && Math.abs(y - mY + mPinPadding) <= mTargetRadiusPx); } //Draw the circle regardless of pressed state. If pin size is >0 then also draw the pin and text @Override public void draw(Canvas canvas) { canvas.drawCircle(mX, mY, mCircleRadiusPx, mCirclePaint); //Draw pin if pressed if (mPinRadiusPx > 0 && (mHasBeenPressed || !mPinsAreTemporary)) { mBounds.set((int) mX - mPinRadiusPx, (int) mY - (mPinRadiusPx * 2) - (int) mPinPadding, (int) mX + mPinRadiusPx, (int) mY - (int) mPinPadding); mPin.setBounds(mBounds); String text = mValue; if (this.formatter != null) { text = formatter.format(text); } calibrateTextSize(mTextPaint, text, mBounds.width()); mTextPaint.getTextBounds(text, 0, text.length(), mBounds); mTextPaint.setTextAlign(Paint.Align.CENTER); mPin.setColorFilter(mPinFilter); mPin.draw(canvas); canvas.drawText(text, mX, mY - mPinRadiusPx - mPinPadding + mTextYPadding, mTextPaint); } super.draw(canvas); } // Private Methods ///////////////////////////////////////////////////////////////// //Set text size based on available pin width. private void calibrateTextSize(Paint paint, String text, float boxWidth) { paint.setTextSize(10); float textSize = paint.measureText(text); float estimatedFontSize = boxWidth * 8 / textSize / mDensity; if (estimatedFontSize < mMinPinFont) { estimatedFontSize = mMinPinFont; } else if (estimatedFontSize > mMaxPinFont) { estimatedFontSize = mMaxPinFont; } paint.setTextSize(estimatedFontSize * mDensity); } }
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.macho; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.equalToObject; import static org.junit.Assert.assertThat; import com.facebook.buck.charset.NulTerminatedCharsetDecoder; import com.google.common.primitives.UnsignedInteger; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import org.junit.Test; public class SymTabCommandUtilsTest { @Test public void testGettingNlistAtIndex64BitBigEndian() throws Exception { checkWithBytes(NlistTestData.getBigEndian64Bit(), true, false); } @Test public void testGettingNlistAtIndex32BitBigEndian() throws Exception { checkWithBytes(NlistTestData.getBigEndian32Bit(), false, false); } @Test public void testGettingNlistAtIndex64BitLittleEndian() throws Exception { checkWithBytes(NlistTestData.getLittleEndian64Bit(), true, true); } @Test public void testGettingNlistAtIndex32BitLittleEndian() throws Exception { checkWithBytes(NlistTestData.getLittleEndian32Bit(), false, true); } private void checkWithBytes(byte[] nlistTemplateBytes, boolean is64Bit, boolean isSwapped) throws IOException { byte[] nlistBytes1 = Arrays.copyOf(nlistTemplateBytes, nlistTemplateBytes.length); if (isSwapped) { nlistBytes1[0] = (byte) 0x01; // strx } else { nlistBytes1[3] = (byte) 0x01; // strx } nlistBytes1[4] = (byte) 0x11; // type byte[] nlistBytes2 = Arrays.copyOf(nlistTemplateBytes, nlistTemplateBytes.length); if (isSwapped) { nlistBytes2[0] = (byte) 0x02; // strx } else { nlistBytes2[3] = (byte) 0x02; // strx } nlistBytes2[4] = (byte) 0x22; // type byte[] commandBytes; if (isSwapped) { commandBytes = SymTabCommandTestData.getLittleEndian(); } else { commandBytes = SymTabCommandTestData.getBigEndian(); } final int cmdSize = commandBytes.length; if (isSwapped) { commandBytes[8] = (byte) cmdSize; // symoff commandBytes[12] = (byte) 2; // nsyms } else { commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 2; // nsyms } ByteBuffer commandBuffer = ByteBuffer.wrap(commandBytes) .order(isSwapped ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN); SymTabCommand symTabCommand = SymTabCommandUtils.createFromBuffer(commandBuffer); assertThat(symTabCommand.getSymoff(), equalToObject(UnsignedInteger.fromIntBits(cmdSize))); assertThat(symTabCommand.getNsyms(), equalToObject(UnsignedInteger.fromIntBits(2))); ByteBuffer byteBuffer = ByteBuffer.allocate(cmdSize + nlistTemplateBytes.length * 2) .order(commandBuffer.order()) .put(commandBytes) .put(nlistBytes1) .put(nlistBytes2); Nlist entry1 = SymTabCommandUtils.getNlistAtIndex(byteBuffer, symTabCommand, 0, is64Bit); assertThat(entry1.getN_strx(), equalToObject(UnsignedInteger.fromIntBits(0x01))); assertThat(entry1.getN_type(), equalToObject(UnsignedInteger.fromIntBits(0x11))); Nlist entry2 = SymTabCommandUtils.getNlistAtIndex(byteBuffer, symTabCommand, 1, is64Bit); assertThat(entry2.getN_strx(), equalToObject(UnsignedInteger.fromIntBits(0x02))); assertThat(entry2.getN_type(), equalToObject(UnsignedInteger.fromIntBits(0x22))); } @Test public void testGettingStringTableValueForNlist() throws Exception { final String stringTableEntry = "string_table_entry"; byte[] nlistBytes = NlistTestData.getBigEndian64Bit(); nlistBytes[3] = (byte) (0x01); // strx - first entry byte[] commandBytes = SymTabCommandTestData.getBigEndian(); final int cmdSize = commandBytes.length; commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 1; // nsyms commandBytes[19] = (byte) (cmdSize + nlistBytes.length); // stroff commandBytes[23] = (byte) (stringTableEntry.length() + 1); // strsize ByteBuffer byteBuffer = ByteBuffer.allocate( commandBytes.length + nlistBytes.length + 1 + stringTableEntry.length() + 1) .order(ByteOrder.BIG_ENDIAN) .put(commandBytes) .put(nlistBytes) .put((byte) 0x00) .put(stringTableEntry.getBytes(StandardCharsets.UTF_8)) .put((byte) 0x00); byteBuffer.position(0); SymTabCommand symTabCommand = SymTabCommandUtils.createFromBuffer(byteBuffer); assertThat(symTabCommand.getSymoff(), equalToObject(UnsignedInteger.fromIntBits(cmdSize))); assertThat(symTabCommand.getNsyms(), equalToObject(UnsignedInteger.fromIntBits(1))); byteBuffer.position(cmdSize); Nlist nlist = NlistUtils.createFromBuffer(byteBuffer, true); assertThat(nlist.getN_strx(), equalToObject(UnsignedInteger.fromIntBits(1))); String result = SymTabCommandUtils.getStringTableEntryForNlist( byteBuffer, symTabCommand, nlist, new NulTerminatedCharsetDecoder(StandardCharsets.UTF_8.newDecoder())); assertThat(result, equalToObject(stringTableEntry)); } @Test public void testGettingStringTableEntrySize() throws Exception { assertThat(SymTabCommandUtils.sizeOfStringTableEntryWithContents("abc"), equalTo(4)); } @Test public void testInsertingNewStringTableEntry() throws Exception { byte[] commandBytes = SymTabCommandTestData.getBigEndian(); final int cmdSize = commandBytes.length; commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 0; // nsyms commandBytes[19] = (byte) cmdSize; // stroff commandBytes[23] = (byte) 20; // strsize final String content = "new_entry"; ByteBuffer byteBuffer = ByteBuffer.allocate( cmdSize + 20 + SymTabCommandUtils.sizeOfStringTableEntryWithContents(content)) .order(ByteOrder.BIG_ENDIAN) .put(commandBytes) .put(new byte[20]); byteBuffer.position(0); SymTabCommand symTabCommand = SymTabCommandUtils.createFromBuffer(byteBuffer); UnsignedInteger offset = SymTabCommandUtils.insertNewStringTableEntry(byteBuffer, symTabCommand, content); assertThat(offset, equalToObject(UnsignedInteger.fromIntBits(20))); byteBuffer.position(symTabCommand.getStroff().plus(offset).intValue()); byte[] entryBytes = new byte[content.length()]; byteBuffer.get(entryBytes, 0, content.length()); assertThat(entryBytes, equalTo(content.getBytes(StandardCharsets.UTF_8))); } @Test public void testUpdatingSymTabCommand() throws Exception { byte[] commandBytes = SymTabCommandTestData.getBigEndian(); final int cmdSize = commandBytes.length; commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 3; // nsyms commandBytes[18] = (byte) cmdSize; // stroff commandBytes[23] = (byte) 20; // strsize SymTabCommand symTabCommand = SymTabCommandUtils.createFromBuffer( ByteBuffer.wrap(commandBytes).order(ByteOrder.BIG_ENDIAN)); final String content = "new_entry"; ByteBuffer byteBuffer = ByteBuffer.allocate( cmdSize + 20 + SymTabCommandUtils.sizeOfStringTableEntryWithContents(content)) .order(ByteOrder.BIG_ENDIAN) .putInt(SymTabCommand.LC_SYMTAB.intValue()) .putInt(cmdSize) .put(commandBytes); SymTabCommand updated = SymTabCommandUtils.updateSymTabCommand(byteBuffer, symTabCommand, content); assertThat( updated.getStrsize(), equalToObject( symTabCommand .getStrsize() .plus( UnsignedInteger.fromIntBits( SymTabCommandUtils.sizeOfStringTableEntryWithContents(content))))); byteBuffer.position(updated.getLoadCommandCommonFields().getOffsetInBinary()); byte[] updatedBytes = new byte[commandBytes.length]; byteBuffer.get(updatedBytes, 0, updatedBytes.length); SymTabCommand commandFromBuffer = SymTabCommandUtils.createFromBuffer( ByteBuffer.wrap(updatedBytes).order(ByteOrder.BIG_ENDIAN)); assertThat(commandFromBuffer.getSymoff(), equalToObject(updated.getSymoff())); assertThat(commandFromBuffer.getNsyms(), equalToObject(updated.getNsyms())); assertThat(commandFromBuffer.getStroff(), equalToObject(updated.getStroff())); assertThat(commandFromBuffer.getStrsize(), equalToObject(updated.getStrsize())); } @Test public void testCheckingForNulValue() throws Exception { byte[] nlistBytes = NlistTestData.getBigEndian64Bit(); nlistBytes[3] = (byte) 0x00; // strx - first entry byte[] commandBytes = SymTabCommandTestData.getBigEndian(); final int cmdSize = commandBytes.length; commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 1; // nsyms commandBytes[19] = (byte) (cmdSize + nlistBytes.length); // stroff commandBytes[23] = (byte) 0x00; // strsize ByteBuffer byteBuffer = ByteBuffer.allocate(cmdSize + nlistBytes.length) .order(ByteOrder.BIG_ENDIAN) .put(commandBytes) .put(nlistBytes); byteBuffer.position(cmdSize); Nlist nlist = NlistUtils.createFromBuffer(byteBuffer, false); assertThat(SymTabCommandUtils.stringTableEntryIsNull(nlist), equalTo(true)); } @Test public void testCheckingSlashesAtStartAndEnd() throws Exception { byte[] nlistBytes = NlistTestData.getBigEndian64Bit(); nlistBytes[3] = (byte) 0x01; // strx String entryContents = "/some/path/"; byte[] commandBytes = SymTabCommandTestData.getBigEndian(); final int cmdSize = commandBytes.length; commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 1; // nsyms commandBytes[19] = (byte) (cmdSize + nlistBytes.length); // stroff commandBytes[23] = (byte) (1 + entryContents.length() + 1); // strsize - nul + contents + nul ByteBuffer byteBuffer = ByteBuffer.allocate(cmdSize + nlistBytes.length + 1 + entryContents.length() + 1) .order(ByteOrder.BIG_ENDIAN) .put(commandBytes) .put(nlistBytes) .put((byte) 0x00) .put(entryContents.getBytes(StandardCharsets.UTF_8)) .put((byte) 0x00); byteBuffer.position(0); SymTabCommand symTabCommand = SymTabCommandUtils.createFromBuffer(byteBuffer); byteBuffer.position(cmdSize); Nlist nlist = NlistUtils.createFromBuffer(byteBuffer, false); assertThat( SymTabCommandUtils.stringTableEntryStartsWithSlash(byteBuffer, symTabCommand, nlist), equalTo(true)); assertThat( SymTabCommandUtils.stringTableEntryEndsWithSlash(byteBuffer, symTabCommand, nlist), equalTo(true)); } @Test public void testCheckingForEmptyString() throws Exception { byte[] nlistBytes = NlistTestData.getBigEndian64Bit(); nlistBytes[3] = (byte) 0x01; // strx byte[] commandBytes = SymTabCommandTestData.getBigEndian(); final int cmdSize = commandBytes.length; commandBytes[11] = (byte) cmdSize; // symoff commandBytes[15] = (byte) 1; // nsyms commandBytes[19] = (byte) (cmdSize + nlistBytes.length); // stroff commandBytes[23] = (byte) (1 + 1); // strsize - nul + nul ByteBuffer byteBuffer = ByteBuffer.allocate(cmdSize + nlistBytes.length + 1 + 1) .order(ByteOrder.BIG_ENDIAN) .put(commandBytes) .put(nlistBytes) .put((byte) 0x00) .put((byte) 0x00); byteBuffer.position(0); SymTabCommand symTabCommand = SymTabCommandUtils.createFromBuffer(byteBuffer); byteBuffer.position(cmdSize); Nlist nlist = NlistUtils.createFromBuffer(byteBuffer, false); assertThat( SymTabCommandUtils.stringTableEntryIsEmptyString(byteBuffer, symTabCommand, nlist), equalTo(true)); } }
/* * 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.distributed.dht.preloader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReadWriteLock; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.IgniteSystemProperties; import org.apache.ignite.cache.affinity.AffinityCentralizedFunction; import org.apache.ignite.cache.affinity.AffinityFunction; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.events.CacheEvent; import org.apache.ignite.events.DiscoveryEvent; import org.apache.ignite.events.Event; import org.apache.ignite.events.EventType; import org.apache.ignite.internal.IgniteFutureTimeoutCheckedException; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.IgniteInterruptedCheckedException; import org.apache.ignite.internal.cluster.ClusterTopologyCheckedException; import org.apache.ignite.internal.managers.discovery.GridDiscoveryTopologySnapshot; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.DynamicCacheChangeRequest; import org.apache.ignite.internal.processors.cache.GridCacheContext; import org.apache.ignite.internal.processors.cache.GridCacheMvccCandidate; import org.apache.ignite.internal.processors.cache.GridCacheSharedContext; import org.apache.ignite.internal.processors.cache.distributed.dht.GridClientPartitionTopology; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtAssignmentFetchFuture; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionTopology; import org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtTopologyFuture; import org.apache.ignite.internal.processors.cache.transactions.IgniteTxKey; import org.apache.ignite.internal.processors.cache.version.GridCacheVersion; import org.apache.ignite.internal.processors.timeout.GridTimeoutObject; import org.apache.ignite.internal.processors.timeout.GridTimeoutObjectAdapter; import org.apache.ignite.internal.util.GridConcurrentHashSet; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.CI1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.X; import org.apache.ignite.internal.util.typedef.internal.CU; import org.apache.ignite.internal.util.typedef.internal.LT; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgnitePredicate; import org.jetbrains.annotations.Nullable; import org.jsr166.ConcurrentHashMap8; import static org.apache.ignite.events.EventType.EVT_NODE_FAILED; import static org.apache.ignite.events.EventType.EVT_NODE_JOINED; import static org.apache.ignite.events.EventType.EVT_NODE_LEFT; import static org.apache.ignite.internal.events.DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT; import static org.apache.ignite.internal.managers.communication.GridIoPolicy.SYSTEM_POOL; /** * Future for exchanging partition maps. */ public class GridDhtPartitionsExchangeFuture extends GridFutureAdapter<AffinityTopologyVersion> implements Comparable<GridDhtPartitionsExchangeFuture>, GridDhtTopologyFuture { /** */ private static final int DUMP_PENDING_OBJECTS_THRESHOLD = IgniteSystemProperties.getInteger(IgniteSystemProperties.IGNITE_DUMP_PENDING_OBJECTS_THRESHOLD, 10); /** */ private static final long serialVersionUID = 0L; /** Dummy flag. */ private final boolean dummy; /** Force preload flag. */ private final boolean forcePreload; /** Dummy reassign flag. */ private final boolean reassign; /** Discovery event. */ private volatile DiscoveryEvent discoEvt; /** */ @GridToStringInclude private final Collection<UUID> rcvdIds = new GridConcurrentHashSet<>(); /** Remote nodes. */ private volatile Collection<ClusterNode> rmtNodes; /** Remote nodes. */ @GridToStringInclude private volatile Collection<UUID> rmtIds; /** Oldest node. */ @GridToStringExclude private final AtomicReference<ClusterNode> oldestNode = new AtomicReference<>(); /** ExchangeFuture id. */ private final GridDhtPartitionExchangeId exchId; /** Init flag. */ @GridToStringInclude private final AtomicBoolean init = new AtomicBoolean(false); /** Ready for reply flag. */ @GridToStringInclude private final AtomicBoolean ready = new AtomicBoolean(false); /** Replied flag. */ @GridToStringInclude private final AtomicBoolean replied = new AtomicBoolean(false); /** Timeout object. */ @GridToStringExclude private volatile GridTimeoutObject timeoutObj; /** Cache context. */ private final GridCacheSharedContext<?, ?> cctx; /** Busy lock to prevent activities from accessing exchanger while it's stopping. */ private ReadWriteLock busyLock; /** */ private AtomicBoolean added = new AtomicBoolean(false); /** Event latch. */ @GridToStringExclude private CountDownLatch evtLatch = new CountDownLatch(1); /** */ private GridFutureAdapter<Boolean> initFut; /** Topology snapshot. */ private AtomicReference<GridDiscoveryTopologySnapshot> topSnapshot = new AtomicReference<>(); /** Last committed cache version before next topology version use. */ private AtomicReference<GridCacheVersion> lastVer = new AtomicReference<>(); /** * Messages received on non-coordinator are stored in case if this node * becomes coordinator. */ private final Map<UUID, GridDhtPartitionsSingleMessage> singleMsgs = new ConcurrentHashMap8<>(); /** Messages received from new coordinator. */ private final Map<UUID, GridDhtPartitionsFullMessage> fullMsgs = new ConcurrentHashMap8<>(); /** */ @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) @GridToStringInclude private volatile IgniteInternalFuture<?> partReleaseFut; /** */ private final Object mux = new Object(); /** Logger. */ private IgniteLogger log; /** Dynamic cache change requests. */ private Collection<DynamicCacheChangeRequest> reqs; /** Cache validation results. */ private volatile Map<Integer, Boolean> cacheValidRes; /** Skip preload flag. */ private boolean skipPreload; /** */ private boolean clientOnlyExchange; /** Init timestamp. Used to track the amount of time spent to complete the future. */ private long initTs; /** * Dummy future created to trigger reassignments if partition * topology changed while preloading. * * @param cctx Cache context. * @param reassign Dummy reassign flag. * @param discoEvt Discovery event. * @param exchId Exchange id. */ public GridDhtPartitionsExchangeFuture( GridCacheSharedContext cctx, boolean reassign, DiscoveryEvent discoEvt, GridDhtPartitionExchangeId exchId ) { dummy = true; forcePreload = false; this.exchId = exchId; this.reassign = reassign; this.discoEvt = discoEvt; this.cctx = cctx; onDone(exchId.topologyVersion()); } /** * Force preload future created to trigger reassignments if partition * topology changed while preloading. * * @param cctx Cache context. * @param discoEvt Discovery event. * @param exchId Exchange id. */ public GridDhtPartitionsExchangeFuture(GridCacheSharedContext cctx, DiscoveryEvent discoEvt, GridDhtPartitionExchangeId exchId) { dummy = false; forcePreload = true; this.exchId = exchId; this.discoEvt = discoEvt; this.cctx = cctx; reassign = true; onDone(exchId.topologyVersion()); } /** * @param cctx Cache context. * @param busyLock Busy lock. * @param exchId Exchange ID. * @param reqs Cache change requests. */ public GridDhtPartitionsExchangeFuture( GridCacheSharedContext cctx, ReadWriteLock busyLock, GridDhtPartitionExchangeId exchId, Collection<DynamicCacheChangeRequest> reqs ) { assert busyLock != null; assert exchId != null; dummy = false; forcePreload = false; reassign = false; this.cctx = cctx; this.busyLock = busyLock; this.exchId = exchId; this.reqs = reqs; log = cctx.logger(getClass()); initFut = new GridFutureAdapter<>(); if (log.isDebugEnabled()) log.debug("Creating exchange future [localNode=" + cctx.localNodeId() + ", fut=" + this + ']'); } /** * @param reqs Cache change requests. */ public void cacheChangeRequests(Collection<DynamicCacheChangeRequest> reqs) { this.reqs = reqs; } /** {@inheritDoc} */ @Override public AffinityTopologyVersion topologyVersion() { return exchId.topologyVersion(); } /** * @return Skip preload flag. */ public boolean skipPreload() { return skipPreload; } /** * @return Dummy flag. */ public boolean dummy() { return dummy; } /** * @return Force preload flag. */ public boolean forcePreload() { return forcePreload; } /** * @return Dummy reassign flag. */ public boolean reassign() { return reassign; } /** * @return {@code True} if dummy reassign. */ public boolean dummyReassign() { return (dummy() || forcePreload()) && reassign(); } /** * @param cacheId Cache ID to check. * @param topVer Topology version. * @return {@code True} if cache was added during this exchange. */ public boolean isCacheAdded(int cacheId, AffinityTopologyVersion topVer) { if (!F.isEmpty(reqs)) { for (DynamicCacheChangeRequest req : reqs) { if (req.start() && !req.clientStartOnly()) { if (CU.cacheId(req.cacheName()) == cacheId) return true; } } } GridCacheContext<?, ?> cacheCtx = cctx.cacheContext(cacheId); return cacheCtx != null && F.eq(cacheCtx.startTopologyVersion(), topVer); } /** * @param cacheId Cache ID. * @return {@code True} if local client has been added. */ public boolean isLocalClientAdded(int cacheId) { if (!F.isEmpty(reqs)) { for (DynamicCacheChangeRequest req : reqs) { if (req.start() && F.eq(req.initiatingNodeId(), cctx.localNodeId())) { if (CU.cacheId(req.cacheName()) == cacheId) return true; } } } return false; } /** * @param cacheCtx Cache context. * @throws IgniteCheckedException If failed. */ private void initTopology(GridCacheContext cacheCtx) throws IgniteCheckedException { if (stopping(cacheCtx.cacheId())) return; if (canCalculateAffinity(cacheCtx)) { if (log.isDebugEnabled()) log.debug("Will recalculate affinity [locNodeId=" + cctx.localNodeId() + ", exchId=" + exchId + ']'); cacheCtx.affinity().calculateAffinity(exchId.topologyVersion(), discoEvt); } else { if (log.isDebugEnabled()) log.debug("Will request affinity from remote node [locNodeId=" + cctx.localNodeId() + ", exchId=" + exchId + ']'); // Fetch affinity assignment from remote node. GridDhtAssignmentFetchFuture fetchFut = new GridDhtAssignmentFetchFuture(cacheCtx, exchId.topologyVersion(), CU.affinityNodes(cacheCtx, exchId.topologyVersion())); fetchFut.init(); List<List<ClusterNode>> affAssignment = fetchFut.get(); if (log.isDebugEnabled()) log.debug("Fetched affinity from remote node, initializing affinity assignment [locNodeId=" + cctx.localNodeId() + ", topVer=" + exchId.topologyVersion() + ']'); if (affAssignment == null) { affAssignment = new ArrayList<>(cacheCtx.affinity().partitions()); List<ClusterNode> empty = Collections.emptyList(); for (int i = 0; i < cacheCtx.affinity().partitions(); i++) affAssignment.add(empty); } cacheCtx.affinity().initializeAffinity(exchId.topologyVersion(), affAssignment); } } /** * @param cacheCtx Cache context. * @return {@code True} if local node can calculate affinity on it's own for this partition map exchange. */ private boolean canCalculateAffinity(GridCacheContext cacheCtx) { AffinityFunction affFunc = cacheCtx.config().getAffinity(); // Do not request affinity from remote nodes if affinity function is not centralized. if (!U.hasAnnotation(affFunc, AffinityCentralizedFunction.class)) return true; // If local node did not initiate exchange or local node is the only cache node in grid. Collection<ClusterNode> affNodes = CU.affinityNodes(cacheCtx, exchId.topologyVersion()); return !exchId.nodeId().equals(cctx.localNodeId()) || (affNodes.size() == 1 && affNodes.contains(cctx.localNode())); } /** * @return {@code True} */ public boolean onAdded() { return added.compareAndSet(false, true); } /** * Event callback. * * @param exchId Exchange ID. * @param discoEvt Discovery event. */ public void onEvent(GridDhtPartitionExchangeId exchId, DiscoveryEvent discoEvt) { assert exchId.equals(this.exchId); this.discoEvt = discoEvt; evtLatch.countDown(); } /** * @return Discovery event. */ public DiscoveryEvent discoveryEvent() { return discoEvt; } /** * @return Exchange ID. */ public GridDhtPartitionExchangeId exchangeId() { return exchId; } /** * @return {@code true} if entered to busy state. */ private boolean enterBusy() { if (busyLock.readLock().tryLock()) return true; if (log.isDebugEnabled()) log.debug("Failed to enter busy state (exchanger is stopping): " + this); return false; } /** * */ private void leaveBusy() { busyLock.readLock().unlock(); } /** * Starts activity. * * @throws IgniteInterruptedCheckedException If interrupted. */ public void init() throws IgniteInterruptedCheckedException { if (isDone()) return; if (init.compareAndSet(false, true)) { if (isDone()) return; initTs = U.currentTimeMillis(); try { // Wait for event to occur to make sure that discovery // will return corresponding nodes. U.await(evtLatch); assert discoEvt != null : this; assert !dummy && !forcePreload : this; ClusterNode oldest = CU.oldestAliveCacheServerNode(cctx, exchId.topologyVersion()); oldestNode.set(oldest); if (!F.isEmpty(reqs)) blockGateways(); startCaches(); // True if client node joined or failed. boolean clientNodeEvt; if (F.isEmpty(reqs)) { int type = discoEvt.type(); assert type == EVT_NODE_JOINED || type == EVT_NODE_LEFT || type == EVT_NODE_FAILED : discoEvt; clientNodeEvt = CU.clientNode(discoEvt.eventNode()); } else { assert discoEvt.type() == EVT_DISCOVERY_CUSTOM_EVT : discoEvt; boolean clientOnlyCacheEvt = true; for (DynamicCacheChangeRequest req : reqs) { if (req.clientStartOnly() || req.close()) continue; clientOnlyCacheEvt = false; break; } clientNodeEvt = clientOnlyCacheEvt; } if (clientNodeEvt) { ClusterNode node = discoEvt.eventNode(); // Client need to initialize affinity for local join event or for stated client caches. if (!node.isLocal() || clientCacheClose()) { for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (cacheCtx.isLocal()) continue; GridDhtPartitionTopology top = cacheCtx.topology(); top.updateTopologyVersion(exchId, this, -1, stopping(cacheCtx.cacheId())); if (cacheCtx.affinity().affinityTopologyVersion() == AffinityTopologyVersion.NONE) { initTopology(cacheCtx); top.beforeExchange(this); } else cacheCtx.affinity().clientEventTopologyChange(discoEvt, exchId.topologyVersion()); } if (exchId.isLeft()) cctx.mvcc().removeExplicitNodeLocks(exchId.nodeId(), exchId.topologyVersion()); rmtIds = Collections.emptyList(); rmtNodes = Collections.emptyList(); onDone(exchId.topologyVersion()); skipPreload = cctx.kernalContext().clientNode(); return; } } clientOnlyExchange = clientNodeEvt || cctx.kernalContext().clientNode(); if (clientOnlyExchange) { skipPreload = cctx.kernalContext().clientNode(); for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (cacheCtx.isLocal()) continue; GridDhtPartitionTopology top = cacheCtx.topology(); top.updateTopologyVersion(exchId, this, -1, stopping(cacheCtx.cacheId())); } for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (cacheCtx.isLocal()) continue; initTopology(cacheCtx); } if (oldest != null) { rmtNodes = new ConcurrentLinkedQueue<>(CU.aliveRemoteServerNodesWithCaches(cctx, exchId.topologyVersion())); rmtIds = Collections.unmodifiableSet(new HashSet<>(F.nodeIds(rmtNodes))); initFut.onDone(true); if (log.isDebugEnabled()) log.debug("Initialized future: " + this); if (cctx.localNode().equals(oldest)) { for (GridCacheContext cacheCtx : cctx.cacheContexts()) { boolean updateTop = !cacheCtx.isLocal() && exchId.topologyVersion().equals(cacheCtx.startTopologyVersion()); if (updateTop) { for (GridClientPartitionTopology top : cctx.exchange().clientTopologies()) { if (top.cacheId() == cacheCtx.cacheId()) { cacheCtx.topology().update(exchId, top.partitionMap(true)); break; } } } } onDone(exchId.topologyVersion()); } else sendPartitions(oldest); } else { rmtIds = Collections.emptyList(); rmtNodes = Collections.emptyList(); onDone(exchId.topologyVersion()); } return; } assert oldestNode.get() != null; for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (isCacheAdded(cacheCtx.cacheId(), exchId.topologyVersion())) { if (cacheCtx.discovery().cacheAffinityNodes(cacheCtx.name(), topologyVersion()).isEmpty()) U.quietAndWarn(log, "No server nodes found for cache client: " + cacheCtx.namex()); } cacheCtx.preloader().onExchangeFutureAdded(); } List<String> cachesWithoutNodes = null; if (exchId.isLeft()) { for (String name : cctx.cache().cacheNames()) { if (cctx.discovery().cacheAffinityNodes(name, topologyVersion()).isEmpty()) { if (cachesWithoutNodes == null) cachesWithoutNodes = new ArrayList<>(); cachesWithoutNodes.add(name); // Fire event even if there is no client cache started. if (cctx.gridEvents().isRecordable(EventType.EVT_CACHE_NODES_LEFT)) { Event evt = new CacheEvent( name, cctx.localNode(), cctx.localNode(), "All server nodes have left the cluster.", EventType.EVT_CACHE_NODES_LEFT, 0, false, null, null, null, null, false, null, false, null, null, null ); cctx.gridEvents().record(evt); } } } } if (cachesWithoutNodes != null) { StringBuilder sb = new StringBuilder("All server nodes for the following caches have left the cluster: "); for (int i = 0; i < cachesWithoutNodes.size(); i++) { String cache = cachesWithoutNodes.get(i); sb.append('\'').append(cache).append('\''); if (i != cachesWithoutNodes.size() - 1) sb.append(", "); } U.quietAndWarn(log, sb.toString()); U.quietAndWarn(log, "Must have server nodes for caches to operate."); } assert discoEvt != null; assert exchId.nodeId().equals(discoEvt.eventNode().id()); for (GridCacheContext cacheCtx : cctx.cacheContexts()) { GridClientPartitionTopology clientTop = cctx.exchange().clearClientTopology( cacheCtx.cacheId()); long updSeq = clientTop == null ? -1 : clientTop.lastUpdateSequence(); // Update before waiting for locks. if (!cacheCtx.isLocal()) cacheCtx.topology().updateTopologyVersion(exchId, this, updSeq, stopping(cacheCtx.cacheId())); } // Grab all alive remote nodes with order of equal or less than last joined node. rmtNodes = new ConcurrentLinkedQueue<>(CU.aliveRemoteServerNodesWithCaches(cctx, exchId.topologyVersion())); rmtIds = Collections.unmodifiableSet(new HashSet<>(F.nodeIds(rmtNodes))); for (Map.Entry<UUID, GridDhtPartitionsSingleMessage> m : singleMsgs.entrySet()) // If received any messages, process them. onReceive(m.getKey(), m.getValue()); for (Map.Entry<UUID, GridDhtPartitionsFullMessage> m : fullMsgs.entrySet()) // If received any messages, process them. onReceive(m.getKey(), m.getValue()); AffinityTopologyVersion topVer = exchId.topologyVersion(); for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (cacheCtx.isLocal()) continue; // Must initialize topology after we get discovery event. initTopology(cacheCtx); cacheCtx.preloader().onTopologyChanged(exchId.topologyVersion()); cacheCtx.preloader().updateLastExchangeFuture(this); } IgniteInternalFuture<?> partReleaseFut = cctx.partitionReleaseFuture(topVer); // Assign to class variable so it will be included into toString() method. this.partReleaseFut = partReleaseFut; if (log.isDebugEnabled()) log.debug("Before waiting for partition release future: " + this); int dumpedObjects = 0; while (true) { try { partReleaseFut.get(2 * cctx.gridConfig().getNetworkTimeout(), TimeUnit.MILLISECONDS); break; } catch (IgniteFutureTimeoutCheckedException ignored) { // Print pending transactions and locks that might have led to hang. if (dumpedObjects < DUMP_PENDING_OBJECTS_THRESHOLD) { dumpPendingObjects(); dumpedObjects++; } } } if (log.isDebugEnabled()) log.debug("After waiting for partition release future: " + this); if (exchId.isLeft()) cctx.mvcc().removeExplicitNodeLocks(exchId.nodeId(), exchId.topologyVersion()); IgniteInternalFuture<?> locksFut = cctx.mvcc().finishLocks(exchId.topologyVersion()); dumpedObjects = 0; while (true) { try { locksFut.get(2 * cctx.gridConfig().getNetworkTimeout(), TimeUnit.MILLISECONDS); break; } catch (IgniteFutureTimeoutCheckedException ignored) { if (dumpedObjects < DUMP_PENDING_OBJECTS_THRESHOLD) { U.warn(log, "Failed to wait for locks release future. " + "Dumping pending objects that might be the cause: " + cctx.localNodeId()); U.warn(log, "Locked keys:"); for (IgniteTxKey key : cctx.mvcc().lockedKeys()) U.warn(log, "Locked key: " + key); for (IgniteTxKey key : cctx.mvcc().nearLockedKeys()) U.warn(log, "Locked near key: " + key); Map<IgniteTxKey, Collection<GridCacheMvccCandidate>> locks = cctx.mvcc().unfinishedLocks(exchId.topologyVersion()); for (Map.Entry<IgniteTxKey, Collection<GridCacheMvccCandidate>> e : locks.entrySet()) U.warn(log, "Awaited locked entry [key=" + e.getKey() + ", mvcc=" + e.getValue() + ']'); dumpedObjects++; } } } for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (cacheCtx.isLocal()) continue; // Notify replication manager. GridCacheContext drCacheCtx = cacheCtx.isNear() ? cacheCtx.near().dht().context() : cacheCtx; if (drCacheCtx.isDrEnabled()) drCacheCtx.dr().beforeExchange(topVer, exchId.isLeft()); // Partition release future is done so we can flush the write-behind store. cacheCtx.store().forceFlush(); // Process queued undeploys prior to sending/spreading map. cacheCtx.preloader().unwindUndeploys(); GridDhtPartitionTopology top = cacheCtx.topology(); assert topVer.equals(top.topologyVersion()) : "Topology version is updated only in this class instances inside single ExchangeWorker thread."; top.beforeExchange(this); } for (GridClientPartitionTopology top : cctx.exchange().clientTopologies()) { top.updateTopologyVersion(exchId, this, -1, stopping(top.cacheId())); top.beforeExchange(this); } } catch (IgniteInterruptedCheckedException e) { onDone(e); throw e; } catch (Throwable e) { U.error(log, "Failed to reinitialize local partitions (preloading will be stopped): " + exchId, e); onDone(e); if (e instanceof Error) throw (Error)e; return; } if (F.isEmpty(rmtIds)) { onDone(exchId.topologyVersion()); return; } ready.set(true); initFut.onDone(true); if (log.isDebugEnabled()) log.debug("Initialized future: " + this); ClusterNode oldest = oldestNode.get(); // If this node is not oldest. if (!oldest.id().equals(cctx.localNodeId())) sendPartitions(oldest); else { boolean allReceived = allReceived(); if (allReceived && replied.compareAndSet(false, true)) { if (spreadPartitions()) onDone(exchId.topologyVersion()); } } scheduleRecheck(); } else assert false : "Skipped init future: " + this; } /** * @return {@code True} if exchange initiated for client cache close. */ private boolean clientCacheClose() { return reqs != null && reqs.size() == 1 && reqs.iterator().next().close(); } /** * */ private void dumpPendingObjects() { U.warn(log, "Failed to wait for partition release future. Dumping pending objects that might be the cause: " + cctx.localNodeId()); cctx.exchange().dumpPendingObjects(); } /** * @param cacheId Cache ID to check. * @return {@code True} if cache is stopping by this exchange. */ private boolean stopping(int cacheId) { boolean stopping = false; if (!F.isEmpty(reqs)) { for (DynamicCacheChangeRequest req : reqs) { if (cacheId == CU.cacheId(req.cacheName())) { stopping = req.stop(); break; } } } return stopping; } /** * Starts dynamic caches. * @throws IgniteCheckedException If failed. */ private void startCaches() throws IgniteCheckedException { cctx.cache().prepareCachesStart(F.view(reqs, new IgnitePredicate<DynamicCacheChangeRequest>() { @Override public boolean apply(DynamicCacheChangeRequest req) { return req.start(); } }), exchId.topologyVersion()); } /** * */ private void blockGateways() { for (DynamicCacheChangeRequest req : reqs) { if (req.stop() || req.close()) cctx.cache().blockGateway(req); } } /** * @param node Node. * @param id ID. * @throws IgniteCheckedException If failed. */ private void sendLocalPartitions(ClusterNode node, @Nullable GridDhtPartitionExchangeId id) throws IgniteCheckedException { GridDhtPartitionsSingleMessage m = new GridDhtPartitionsSingleMessage(id, clientOnlyExchange, cctx.versions().last()); for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (!cacheCtx.isLocal()) m.addLocalPartitionMap(cacheCtx.cacheId(), cacheCtx.topology().localPartitionMap()); } if (log.isDebugEnabled()) log.debug("Sending local partitions [nodeId=" + node.id() + ", exchId=" + exchId + ", msg=" + m + ']'); cctx.io().send(node, m, SYSTEM_POOL); } /** * @param nodes Nodes. * @param id ID. * @throws IgniteCheckedException If failed. */ private void sendAllPartitions(Collection<? extends ClusterNode> nodes, GridDhtPartitionExchangeId id) throws IgniteCheckedException { GridDhtPartitionsFullMessage m = new GridDhtPartitionsFullMessage(id, lastVer.get(), id.topologyVersion()); for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (!cacheCtx.isLocal()) { AffinityTopologyVersion startTopVer = cacheCtx.startTopologyVersion(); boolean ready = startTopVer == null || startTopVer.compareTo(id.topologyVersion()) <= 0; if (ready) m.addFullPartitionsMap(cacheCtx.cacheId(), cacheCtx.topology().partitionMap(true)); } } // It is important that client topologies be added after contexts. for (GridClientPartitionTopology top : cctx.exchange().clientTopologies()) m.addFullPartitionsMap(top.cacheId(), top.partitionMap(true)); if (log.isDebugEnabled()) log.debug("Sending full partition map [nodeIds=" + F.viewReadOnly(nodes, F.node2id()) + ", exchId=" + exchId + ", msg=" + m + ']'); cctx.io().safeSend(nodes, m, SYSTEM_POOL, null); } /** * @param oldestNode Oldest node. */ private void sendPartitions(ClusterNode oldestNode) { try { sendLocalPartitions(oldestNode, exchId); } catch (ClusterTopologyCheckedException ignore) { if (log.isDebugEnabled()) log.debug("Oldest node left during partition exchange [nodeId=" + oldestNode.id() + ", exchId=" + exchId + ']'); } catch (IgniteCheckedException e) { scheduleRecheck(); U.error(log, "Failed to send local partitions to oldest node (will retry after timeout) [oldestNodeId=" + oldestNode.id() + ", exchId=" + exchId + ']', e); } } /** * @return {@code True} if succeeded. */ private boolean spreadPartitions() { try { sendAllPartitions(rmtNodes, exchId); return true; } catch (IgniteCheckedException e) { scheduleRecheck(); if (!X.hasCause(e, InterruptedException.class)) U.error(log, "Failed to send full partition map to nodes (will retry after timeout) [nodes=" + F.nodeId8s(rmtNodes) + ", exchangeId=" + exchId + ']', e); return false; } } /** {@inheritDoc} */ @Override public boolean onDone(AffinityTopologyVersion res, Throwable err) { Map<Integer, Boolean> m = null; for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (cacheCtx.config().getTopologyValidator() != null && !CU.isSystemCache(cacheCtx.name())) { if (m == null) m = new HashMap<>(); m.put(cacheCtx.cacheId(), cacheCtx.config().getTopologyValidator().validate(discoEvt.topologyNodes())); } } cacheValidRes = m != null ? m : Collections.<Integer, Boolean>emptyMap(); cctx.cache().onExchangeDone(exchId.topologyVersion(), reqs, err); cctx.exchange().onExchangeDone(this, err); if (super.onDone(res, err) && !dummy && !forcePreload) { if (log.isDebugEnabled()) log.debug("Completed partition exchange [localNode=" + cctx.localNodeId() + ", exchange= " + this + "duration=" + duration() + ", durationFromInit=" + (U.currentTimeMillis() - initTs) + ']'); initFut.onDone(err == null); GridTimeoutObject timeoutObj = this.timeoutObj; // Deschedule timeout object. if (timeoutObj != null) cctx.kernalContext().timeout().removeTimeoutObject(timeoutObj); if (exchId.isLeft()) { for (GridCacheContext cacheCtx : cctx.cacheContexts()) cacheCtx.config().getAffinity().removeNode(exchId.nodeId()); } return true; } return dummy; } /** {@inheritDoc} */ @Override public Throwable validateCache(GridCacheContext cctx) { Throwable err = error(); if (err != null) return err; if (cctx.config().getTopologyValidator() != null) { Boolean res = cacheValidRes.get(cctx.cacheId()); if (res != null && !res) { return new IgniteCheckedException("Failed to perform cache operation " + "(cache topology is not valid): " + cctx.name()); } } return null; } /** * Cleans up resources to avoid excessive memory usage. */ public void cleanUp() { topSnapshot.set(null); singleMsgs.clear(); fullMsgs.clear(); rcvdIds.clear(); oldestNode.set(null); partReleaseFut = null; Collection<ClusterNode> rmtNodes = this.rmtNodes; if (rmtNodes != null) rmtNodes.clear(); } /** * @return {@code True} if all replies are received. */ private boolean allReceived() { Collection<UUID> rmtIds = this.rmtIds; assert rmtIds != null : "Remote Ids can't be null: " + this; synchronized (rcvdIds) { return rcvdIds.containsAll(rmtIds); } } /** * @param nodeId Sender node id. * @param msg Single partition info. */ public void onReceive(final UUID nodeId, final GridDhtPartitionsSingleMessage msg) { assert msg != null; assert msg.exchangeId().equals(exchId); // Update last seen version. while (true) { GridCacheVersion old = lastVer.get(); if (old == null || old.compareTo(msg.lastVersion()) < 0) { if (lastVer.compareAndSet(old, msg.lastVersion())) break; } else break; } if (isDone()) { if (log.isDebugEnabled()) log.debug("Received message for finished future (will reply only to sender) [msg=" + msg + ", fut=" + this + ']'); sendAllPartitions(nodeId, cctx.gridConfig().getNetworkSendRetryCount()); } else { initFut.listen(new CI1<IgniteInternalFuture<Boolean>>() { @Override public void apply(IgniteInternalFuture<Boolean> f) { try { if (!f.get()) return; } catch (IgniteCheckedException e) { U.error(log, "Failed to initialize exchange future: " + this, e); return; } ClusterNode loc = cctx.localNode(); singleMsgs.put(nodeId, msg); boolean match = true; // Check if oldest node has changed. if (!oldestNode.get().equals(loc)) { match = false; synchronized (mux) { // Double check. if (oldestNode.get().equals(loc)) match = true; } } if (match) { boolean allReceived; synchronized (rcvdIds) { if (rcvdIds.add(nodeId)) updatePartitionSingleMap(msg); allReceived = allReceived(); } // If got all replies, and initialization finished, and reply has not been sent yet. if (allReceived && ready.get() && replied.compareAndSet(false, true)) { spreadPartitions(); onDone(exchId.topologyVersion()); } else if (log.isDebugEnabled()) log.debug("Exchange future full map is not sent [allReceived=" + allReceived() + ", ready=" + ready + ", replied=" + replied.get() + ", init=" + init.get() + ", fut=" + GridDhtPartitionsExchangeFuture.this + ']'); } } }); } } /** * @param nodeId Node ID. * @param retryCnt Number of retries. */ private void sendAllPartitions(final UUID nodeId, final int retryCnt) { ClusterNode n = cctx.node(nodeId); try { if (n != null) sendAllPartitions(F.asList(n), exchId); } catch (IgniteCheckedException e) { if (e instanceof ClusterTopologyCheckedException || !cctx.discovery().alive(n)) { log.debug("Failed to send full partition map to node, node left grid " + "[rmtNode=" + nodeId + ", exchangeId=" + exchId + ']'); return; } if (retryCnt > 0) { long timeout = cctx.gridConfig().getNetworkSendRetryDelay(); LT.error(log, e, "Failed to send full partition map to node (will retry after timeout) " + "[node=" + nodeId + ", exchangeId=" + exchId + ", timeout=" + timeout + ']'); cctx.time().addTimeoutObject(new GridTimeoutObjectAdapter(timeout) { @Override public void onTimeout() { sendAllPartitions(nodeId, retryCnt - 1); } }); } else U.error(log, "Failed to send full partition map [node=" + n + ", exchangeId=" + exchId + ']', e); } } /** * @param nodeId Sender node ID. * @param msg Full partition info. */ public void onReceive(final UUID nodeId, final GridDhtPartitionsFullMessage msg) { assert msg != null; if (isDone()) { if (log.isDebugEnabled()) log.debug("Received message for finished future [msg=" + msg + ", fut=" + this + ']'); return; } if (log.isDebugEnabled()) log.debug("Received full partition map from node [nodeId=" + nodeId + ", msg=" + msg + ']'); assert exchId.topologyVersion().equals(msg.topologyVersion()); initFut.listen(new CI1<IgniteInternalFuture<Boolean>>() { @Override public void apply(IgniteInternalFuture<Boolean> f) { try { if (!f.get()) return; } catch (IgniteCheckedException e) { U.error(log, "Failed to initialize exchange future: " + this, e); return; } ClusterNode curOldest = oldestNode.get(); if (!nodeId.equals(curOldest.id())) { if (log.isDebugEnabled()) log.debug("Received full partition map from unexpected node [oldest=" + curOldest.id() + ", unexpectedNodeId=" + nodeId + ']'); ClusterNode snd = cctx.discovery().node(nodeId); if (snd == null) { if (log.isDebugEnabled()) log.debug("Sender node left grid, will ignore message from unexpected node [nodeId=" + nodeId + ", exchId=" + msg.exchangeId() + ']'); return; } // Will process message later if sender node becomes oldest node. if (snd.order() > curOldest.order()) fullMsgs.put(nodeId, msg); return; } assert msg.exchangeId().equals(exchId); assert msg.lastVersion() != null; cctx.versions().onReceived(nodeId, msg.lastVersion()); updatePartitionFullMap(msg); onDone(exchId.topologyVersion()); } }); } /** * Updates partition map in all caches. * * @param msg Partitions full messages. */ private void updatePartitionFullMap(GridDhtPartitionsFullMessage msg) { for (Map.Entry<Integer, GridDhtPartitionFullMap> entry : msg.partitions().entrySet()) { Integer cacheId = entry.getKey(); GridCacheContext cacheCtx = cctx.cacheContext(cacheId); if (cacheCtx != null) cacheCtx.topology().update(exchId, entry.getValue()); else { ClusterNode oldest = CU.oldestAliveCacheServerNode(cctx, AffinityTopologyVersion.NONE); if (oldest != null && oldest.isLocal()) cctx.exchange().clientTopology(cacheId, this).update(exchId, entry.getValue()); } } } /** * Updates partition map in all caches. * * @param msg Partitions single message. */ private void updatePartitionSingleMap(GridDhtPartitionsSingleMessage msg) { for (Map.Entry<Integer, GridDhtPartitionMap> entry : msg.partitions().entrySet()) { Integer cacheId = entry.getKey(); GridCacheContext cacheCtx = cctx.cacheContext(cacheId); GridDhtPartitionTopology top = cacheCtx != null ? cacheCtx.topology() : cctx.exchange().clientTopology(cacheId, this); top.update(exchId, entry.getValue()); } } /** * @param nodeId Left node id. */ public void onNodeLeft(final UUID nodeId) { if (isDone()) return; if (!enterBusy()) return; try { // Wait for initialization part of this future to complete. initFut.listen(new CI1<IgniteInternalFuture<Boolean>>() { @Override public void apply(IgniteInternalFuture<Boolean> f) { try { if (!f.get()) return; } catch (IgniteCheckedException e) { U.error(log, "Failed to initialize exchange future: " + this, e); return; } if (isDone()) return; if (!enterBusy()) return; try { // Pretend to have received message from this node. rcvdIds.add(nodeId); Collection<UUID> rmtIds = GridDhtPartitionsExchangeFuture.this.rmtIds; assert rmtIds != null; ClusterNode oldest = oldestNode.get(); if (oldest.id().equals(nodeId)) { if (log.isDebugEnabled()) log.debug("Oldest node left or failed on partition exchange " + "(will restart exchange process)) [oldestNodeId=" + oldest.id() + ", exchangeId=" + exchId + ']'); boolean set = false; ClusterNode newOldest = CU.oldestAliveCacheServerNode(cctx, exchId.topologyVersion()); if (newOldest != null) { // If local node is now oldest. if (newOldest.id().equals(cctx.localNodeId())) { synchronized (mux) { if (oldestNode.compareAndSet(oldest, newOldest)) { // If local node is just joining. if (exchId.nodeId().equals(cctx.localNodeId())) { try { for (GridCacheContext cacheCtx : cctx.cacheContexts()) { if (!cacheCtx.isLocal()) cacheCtx.topology().beforeExchange( GridDhtPartitionsExchangeFuture.this); } } catch (IgniteCheckedException e) { onDone(e); return; } } set = true; } } } else { synchronized (mux) { set = oldestNode.compareAndSet(oldest, newOldest); } if (set && log.isDebugEnabled()) log.debug("Reassigned oldest node [this=" + cctx.localNodeId() + ", old=" + oldest.id() + ", new=" + newOldest.id() + ']'); } } else { ClusterTopologyCheckedException err = new ClusterTopologyCheckedException("Failed to " + "wait for exchange future, all server nodes left."); onDone(err); } if (set) { // If received any messages, process them. for (Map.Entry<UUID, GridDhtPartitionsSingleMessage> m : singleMsgs.entrySet()) onReceive(m.getKey(), m.getValue()); for (Map.Entry<UUID, GridDhtPartitionsFullMessage> m : fullMsgs.entrySet()) onReceive(m.getKey(), m.getValue()); // Reassign oldest node and resend. recheck(); } } else if (rmtIds.contains(nodeId)) { if (log.isDebugEnabled()) log.debug("Remote node left of failed during partition exchange (will ignore) " + "[rmtNode=" + nodeId + ", exchangeId=" + exchId + ']'); assert rmtNodes != null; for (Iterator<ClusterNode> it = rmtNodes.iterator(); it.hasNext(); ) { if (it.next().id().equals(nodeId)) it.remove(); } if (allReceived() && ready.get() && replied.compareAndSet(false, true)) if (spreadPartitions()) onDone(exchId.topologyVersion()); } } finally { leaveBusy(); } } }); } finally { leaveBusy(); } } /** * */ private void recheck() { ClusterNode oldest = oldestNode.get(); // If this is the oldest node. if (oldest.id().equals(cctx.localNodeId())) { Collection<UUID> remaining = remaining(); if (!remaining.isEmpty()) { try { cctx.io().safeSend(cctx.discovery().nodes(remaining), new GridDhtPartitionsSingleRequest(exchId), SYSTEM_POOL, null); } catch (IgniteCheckedException e) { U.error(log, "Failed to request partitions from nodes [exchangeId=" + exchId + ", nodes=" + remaining + ']', e); } } // Resend full partition map because last attempt failed. else { if (spreadPartitions()) onDone(exchId.topologyVersion()); } } else sendPartitions(oldest); // Schedule another send. scheduleRecheck(); } /** * */ private void scheduleRecheck() { if (!isDone()) { GridTimeoutObject old = timeoutObj; if (old != null) cctx.kernalContext().timeout().removeTimeoutObject(old); GridTimeoutObject timeoutObj = new GridTimeoutObjectAdapter( cctx.gridConfig().getNetworkTimeout() * Math.max(1, cctx.gridConfig().getCacheConfiguration().length)) { @Override public void onTimeout() { cctx.kernalContext().closure().runLocalSafe(new Runnable() { @Override public void run() { if (isDone()) return; if (!enterBusy()) return; try { U.warn(log, "Retrying preload partition exchange due to timeout [done=" + isDone() + ", dummy=" + dummy + ", exchId=" + exchId + ", rcvdIds=" + F.id8s(rcvdIds) + ", rmtIds=" + F.id8s(rmtIds) + ", remaining=" + F.id8s(remaining()) + ", init=" + init + ", initFut=" + initFut.isDone() + ", ready=" + ready + ", replied=" + replied + ", added=" + added + ", oldest=" + U.id8(oldestNode.get().id()) + ", oldestOrder=" + oldestNode.get().order() + ", evtLatch=" + evtLatch.getCount() + ", locNodeOrder=" + cctx.localNode().order() + ", locNodeId=" + cctx.localNode().id() + ']', "Retrying preload partition exchange due to timeout."); recheck(); } finally { leaveBusy(); } } }); } }; this.timeoutObj = timeoutObj; cctx.kernalContext().timeout().addTimeoutObject(timeoutObj); } } /** * @return Remaining node IDs. */ Collection<UUID> remaining() { if (rmtIds == null) return Collections.emptyList(); return F.lose(rmtIds, true, rcvdIds); } /** {@inheritDoc} */ @Override public int compareTo(GridDhtPartitionsExchangeFuture fut) { return exchId.compareTo(fut.exchId); } /** {@inheritDoc} */ @Override public boolean equals(Object o) { if (this == o) return true; GridDhtPartitionsExchangeFuture fut = (GridDhtPartitionsExchangeFuture)o; return exchId.equals(fut.exchId); } /** {@inheritDoc} */ @Override public int hashCode() { return exchId.hashCode(); } /** {@inheritDoc} */ @Override public String toString() { ClusterNode oldestNode = this.oldestNode.get(); return S.toString(GridDhtPartitionsExchangeFuture.class, this, "oldest", oldestNode == null ? "null" : oldestNode.id(), "oldestOrder", oldestNode == null ? "null" : oldestNode.order(), "evtLatch", evtLatch == null ? "null" : evtLatch.getCount(), "remaining", remaining(), "super", super.toString()); } }
package suadb.server; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import suadb.parse.BadSyntaxException; import suadb.parse.InputArrayData; import suadb.parse.Parser; import suadb.planner.BasicUpdatePlanner; import suadb.planner.Planner; import suadb.query.Plan; import suadb.query.Scan; import suadb.record.ArrayInfo; import suadb.record.Schema; import suadb.test.DummyData; import suadb.test.SuaDBExeTestBase; import suadb.test.SuaDBTestBase; import suadb.tx.Transaction; import static org.junit.Assert.*; /** * Created by Rony on 2016-11-28. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SuaDBTest extends SuaDBExeTestBase { @Test public void test_01_list() { Transaction tx = new Transaction(); Scan s = list(tx); assertFalse("Check empty database", s.next()); tx.commit(); } @Test public void test_10_create_1D_array() { String ARRAY_NAME = "TD1"; String ATTR_01 = "a"; String ATTR_02 = "b"; String DIM_01 = "x"; Transaction tx = new Transaction(); String query = "CREATE ARRAY TD1" + "<" + " a : int," + " b : int" + ">" + "[x = 0:100,10]"; SuaDB.planner().executeUpdate(query, tx); ArrayInfo ai = SuaDB.mdMgr().getArrayInfo(ARRAY_NAME, tx); assertEquals(ai.arrayName(), ARRAY_NAME); // Check Attributes assertEquals(ai.schema().attributes().size(), 2); assertTrue(ai.schema().hasAttribute(ATTR_01)); assertTrue(ai.schema().hasAttribute(ATTR_02)); // Check Dimensions assertEquals(ai.schema().dimensions().size(), 1); assertTrue(ai.schema().hasDimension(DIM_01)); tx.commit(); } @Test public void test_10_create_1D_array_with_underbar() { String ARRAY_NAME = "T_D2"; String ATTR_01 = "c"; String ATTR_02 = "d"; String DIM_01 = "z"; Transaction tx = new Transaction(); String query = String.format( "CREATE ARRAY %s" + "<" + " %s : int," + " %s : int" + ">" + "[%s = 0:100,10]", ARRAY_NAME, ATTR_01, ATTR_02, DIM_01); SuaDB.planner().executeUpdate(query, tx); ArrayInfo ai = SuaDB.mdMgr().getArrayInfo(ARRAY_NAME, tx); assertEquals(ai.arrayName(), ARRAY_NAME); // Check Attributes assertEquals(ai.schema().attributes().size(), 2); assertTrue(ai.schema().hasAttribute(ATTR_01)); assertTrue(ai.schema().hasAttribute(ATTR_02)); // Check Dimensions assertEquals(ai.schema().dimensions().size(), 1); assertTrue(ai.schema().hasDimension(DIM_01)); tx.commit(); } @Test public void test_10_create_1D_array_attributes_with_underbar() { String ARRAY_NAME = "T_D3"; String ATTR_01 = "a_a"; String ATTR_02 = "b_b"; String DIM_01 = "x"; Transaction tx = new Transaction(); String query = String.format( "CREATE ARRAY %s" + "<" + " %s : int," + " %s : int" + ">" + "[%s = 0:100,10]", ARRAY_NAME, ATTR_01, ATTR_02, DIM_01); SuaDB.planner().executeUpdate(query, tx); ArrayInfo ai = SuaDB.mdMgr().getArrayInfo(ARRAY_NAME, tx); assertEquals(ai.arrayName(), ARRAY_NAME); // Check Attributes assertEquals(ai.schema().attributes().size(), 2); assertTrue(ai.schema().hasAttribute(ATTR_01)); assertTrue(ai.schema().hasAttribute(ATTR_02)); // Check Dimensions assertEquals(ai.schema().dimensions().size(), 1); assertTrue(ai.schema().hasDimension(DIM_01)); tx.commit(); } @Test(expected = BadSyntaxException.class) public void test_10_create_2D_array_with_duplicate_attributename() { Transaction tx = new Transaction(); try { String query = "CREATE ARRAY TD3" + "<" + " a : int," + " b : int," + " a : int" + ">" + "[x = 0:100,10, y = 0:30,6]"; SuaDB.planner().executeUpdate(query, tx); }catch (Exception e) { throw e; }finally { tx.commit(); } } @Test(expected = BadSyntaxException.class) public void test_10_create_3D_array_with_duplicate_dimensionname() { Transaction tx = new Transaction(); try { String query = "CREATE ARRAY TD4" + "<" + " a : int," + " b : int" + ">" + "[x = 0:100,10, y = 0:30,6, x = 0:50,2]"; SuaDB.planner().executeUpdate(query, tx); }catch (Exception e) { throw e; }finally { tx.commit(); } } @Test public void test_80_remove_1D_array() { Transaction tx = new Transaction(); String query = "REMOVE(TD1)"; SuaDB.planner().executeUpdate(query, tx); tx.commit(); } }
/* * Copyright 2015 ctakesoft.com<hal1000@ctakesoft.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ctakesoft.ctassistant; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.support.annotation.AnimRes; import android.support.annotation.ColorInt; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.customtabs.CustomTabsIntent; import android.support.customtabs.CustomTabsSession; import android.util.TypedValue; import org.chromium.customtabsclient.shared.CustomTabsHelper; /** * Class holding the {@link Intent} and start bundle for a Custom Tabs Activity. * * <p> * <strong>Note:</strong> The constants below are public for the browser implementation's benefit. * You are strongly encouraged to use {@link AssistantIntent.Builder}.</p> */ public final class AssistantIntent { @SuppressWarnings("unused") private static final String TAG = AssistantIntent.class.getSimpleName(); @SuppressWarnings("unused") private final AssistantIntent self = this; /** * Builder class for {@link AssistantIntent} objects. */ public static final class Builder { private Context mContext; private CustomTabsIntent.Builder mBuilder; private boolean mIsDefaultToolbarColor = true; private boolean mEnableUrlBarHiding = false; Builder(Context context, CustomTabsSession session) { mContext = context; mBuilder = new CustomTabsIntent.Builder(session); } /** * Sets the toolbar color. * * @param color {@link Color} */ public Builder setToolbarColor(@ColorInt int color) { mBuilder.setToolbarColor(color); mIsDefaultToolbarColor = false; return this; } /** * Enables the url bar to hide as the user scrolls down on the page. */ public Builder enableUrlBarHiding() { mEnableUrlBarHiding = true; return this; } /** * Sets the Close button icon for the custom tab. * * @param iconRes The icon drawable ID {@link android.graphics.drawable.Drawable} */ public Builder setCloseButtonIcon(@DrawableRes int iconRes) { mBuilder.setCloseButtonIcon(BitmapFactory.decodeResource(mContext.getResources(), iconRes)); return this; } /** * Sets the Close button icon to ArrowBack icon. */ public Builder setCloseButtonIconToArrowBack() { mBuilder.setCloseButtonIcon(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_arrow_back)); return this; } /** * Sets whether the title should be shown in the custom tab. * * @param showTitle Whether the title should be shown. */ public Builder setShowTitle(boolean showTitle) { mBuilder.setShowTitle(showTitle); return this; } /** * Sets the start animations, * * @param enterResId Resource ID of the "enter" animation for the browser. * @param exitResId Resource ID of the "exit" animation for the application. */ public Builder setStartAnimations(@AnimRes int enterResId, @AnimRes int exitResId) { mBuilder.setStartAnimations(mContext, enterResId, exitResId); return this; } /** * Sets the start animations to slide in right / slide out left, */ public Builder setStartAnimationsRightToLeft() { mBuilder.setStartAnimations(mContext, R.anim.slide_in_right, R.anim.slide_out_left); return this; } /** * Sets the exit animations, * * @param enterResId Resource ID of the "enter" animation for the application. * @param exitResId Resource ID of the "exit" animation for the browser. */ public Builder setExitAnimations(@AnimRes int enterResId, @AnimRes int exitResId) { mBuilder.setExitAnimations(mContext, enterResId, exitResId); return this; } /** * Sets the exit animations to slide in left / slide out right, */ public Builder setExitAnimationsLeftToRight() { mBuilder.setExitAnimations(mContext, R.anim.slide_in_left, R.anim.slide_out_right); return this; } /** * Adds a menu item. * * @param label Menu label. * @param pendingIntent Pending intent delivered when the menu item is clicked. */ public Builder addMenuItem(@NonNull String label, @NonNull PendingIntent pendingIntent) { mBuilder.addMenuItem(label, pendingIntent); return this; } /** * Adds a menu item for starting activity. * * @param label Menu label. * @param activityCls Activity started when the menu item is clicked. */ public Builder addMenuItemForStartActivity(@NonNull String label, @NonNull Class<?> activityCls) { Intent menuIntent = new Intent(); menuIntent.setClass(mContext.getApplicationContext(), activityCls); // Optional animation configuration when the user clicks menu items. // Bundle menuBundle = ActivityOptions.makeCustomAnimation(mContext, android.R.anim.slide_in_left, // android.R.anim.slide_out_right).toBundle(); // PendingIntent pi = PendingIntent.getActivity(mContext.getApplicationContext(), 0, menuIntent, 0, // menuBundle); PendingIntent pi = PendingIntent.getActivity(mContext.getApplicationContext(), 0, menuIntent, 0, null); addMenuItem(label, pi); return this; } /** * Sets the action button. * * @param iconRes The icon drawable ID {@link android.graphics.drawable.Drawable} * @param description The description for the button. To be used for accessibility. * @param pendingIntent pending intent delivered when the button is clicked. * @param shouldTint Whether the action button should be tinted. */ public Builder setActionButton(@DrawableRes int iconRes, @NonNull String description, @NonNull PendingIntent pendingIntent, boolean shouldTint) { Bitmap icon = BitmapFactory.decodeResource(mContext.getResources(), iconRes); mBuilder.setActionButton(icon, description, pendingIntent, shouldTint); return this; } /** * See {@link #setActionButton(int, String, PendingIntent, boolean)} */ public Builder setActionButton(@DrawableRes int iconRes, @NonNull String description, @NonNull PendingIntent pendingIntent) { return setActionButton(iconRes, description, pendingIntent, false); } /** * Sets the action button for sharing url. * * See {@link #setActionButton(int, String, PendingIntent, boolean)} */ public Builder setActionButtonForShareUrl() { String shareLabel = mContext.getString(R.string.label_action_share); PendingIntent pendingIntent = createPendingIntent(); return setActionButton(android.R.drawable.ic_menu_share, shareLabel, pendingIntent, false); } private PendingIntent createPendingIntent() { Intent actionIntent = new Intent(mContext.getApplicationContext(), ShareBroadcastReceiver.class); return PendingIntent.getBroadcast(mContext.getApplicationContext(), 0, actionIntent, 0); } /** * Combines all the options that have been set and returns a new {@link CustomTabsIntent} * object. */ public AssistantIntent build() { if (mIsDefaultToolbarColor) { TypedValue outValue = new TypedValue(); mContext.getTheme().resolveAttribute(R.attr.colorPrimary, outValue, true); int color = outValue.data; if (color != 0) { mBuilder.setToolbarColor(color); } } CustomTabsIntent customTabsIntent = mBuilder.build(); customTabsIntent.intent.putExtra(CustomTabsIntent.EXTRA_ENABLE_URLBAR_HIDING, mEnableUrlBarHiding); CustomTabsHelper.addKeepAliveExtra(mContext, customTabsIntent.intent); return new AssistantIntent(customTabsIntent); } } /* ----- internals ----- */ private CustomTabsIntent mCustomTabsIntent; private AssistantIntent(CustomTabsIntent customTabsIntent) { mCustomTabsIntent = customTabsIntent; } void setPackage(String packageName) { mCustomTabsIntent.intent.setPackage(packageName); } void launchUrl(Activity context, Uri uri) { mCustomTabsIntent.launchUrl(context, uri); } }
/* * 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.core.ml.dataframe.analyses; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.Version; import org.elasticsearch.common.Strings; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.mapper.BooleanFieldMapper; import org.elasticsearch.index.mapper.KeywordFieldMapper; import org.elasticsearch.index.mapper.NumberFieldMapper; import org.elasticsearch.xpack.core.ml.AbstractBWCSerializationTestCase; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; public class ClassificationTests extends AbstractBWCSerializationTestCase<Classification> { private static final BoostedTreeParams BOOSTED_TREE_PARAMS = BoostedTreeParams.builder().build(); @Override protected Classification doParseInstance(XContentParser parser) throws IOException { return Classification.fromXContent(parser, false); } @Override protected Classification createTestInstance() { return createRandom(); } public static Classification createRandom() { String dependentVariableName = randomAlphaOfLength(10); BoostedTreeParams boostedTreeParams = BoostedTreeParamsTests.createRandom(); String predictionFieldName = randomBoolean() ? null : randomAlphaOfLength(10); Classification.ClassAssignmentObjective classAssignmentObjective = randomBoolean() ? null : randomFrom(Classification.ClassAssignmentObjective.values()); Integer numTopClasses = randomBoolean() ? null : randomIntBetween(0, 1000); Double trainingPercent = randomBoolean() ? null : randomDoubleBetween(1.0, 100.0, true); Long randomizeSeed = randomBoolean() ? null : randomLong(); return new Classification(dependentVariableName, boostedTreeParams, predictionFieldName, classAssignmentObjective, numTopClasses, trainingPercent, randomizeSeed); } public static Classification mutateForVersion(Classification instance, Version version) { return new Classification(instance.getDependentVariable(), BoostedTreeParamsTests.mutateForVersion(instance.getBoostedTreeParams(), version), instance.getPredictionFieldName(), version.onOrAfter(Version.V_7_7_0) ? instance.getClassAssignmentObjective() : null, instance.getNumTopClasses(), instance.getTrainingPercent(), instance.getRandomizeSeed()); } @Override protected void assertOnBWCObject(Classification bwcSerializedObject, Classification testInstance, Version version) { if (version.onOrAfter(Version.V_7_6_0)) { super.assertOnBWCObject(bwcSerializedObject, testInstance, version); return; } Classification newBwc = new Classification(bwcSerializedObject.getDependentVariable(), bwcSerializedObject.getBoostedTreeParams(), bwcSerializedObject.getPredictionFieldName(), bwcSerializedObject.getClassAssignmentObjective(), bwcSerializedObject.getNumTopClasses(), bwcSerializedObject.getTrainingPercent(), 42L); Classification newInstance = new Classification(testInstance.getDependentVariable(), testInstance.getBoostedTreeParams(), testInstance.getPredictionFieldName(), testInstance.getClassAssignmentObjective(), testInstance.getNumTopClasses(), testInstance.getTrainingPercent(), 42L); super.assertOnBWCObject(newBwc, newInstance, version); } @Override protected Writeable.Reader<Classification> instanceReader() { return Classification::new; } public void testConstructor_GivenTrainingPercentIsLessThanOne() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, 0.999, randomLong())); assertThat(e.getMessage(), equalTo("[training_percent] must be a double in [1, 100]")); } public void testConstructor_GivenTrainingPercentIsGreaterThan100() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, 100.0001, randomLong())); assertThat(e.getMessage(), equalTo("[training_percent] must be a double in [1, 100]")); } public void testConstructor_GivenNumTopClassesIsLessThanZero() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, -1, 1.0, randomLong())); assertThat(e.getMessage(), equalTo("[num_top_classes] must be an integer in [0, 1000]")); } public void testConstructor_GivenNumTopClassesIsGreaterThan1000() { ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 1001, 1.0, randomLong())); assertThat(e.getMessage(), equalTo("[num_top_classes] must be an integer in [0, 1000]")); } public void testGetPredictionFieldName() { Classification classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, 50.0, randomLong()); assertThat(classification.getPredictionFieldName(), equalTo("result")); classification = new Classification("foo", BOOSTED_TREE_PARAMS, null, null, 3, 50.0, randomLong()); assertThat(classification.getPredictionFieldName(), equalTo("foo_prediction")); } public void testClassAssignmentObjective() { Classification classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", Classification.ClassAssignmentObjective.MAXIMIZE_ACCURACY, 7, 1.0, randomLong()); assertThat(classification.getClassAssignmentObjective(), equalTo(Classification.ClassAssignmentObjective.MAXIMIZE_ACCURACY)); classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", Classification.ClassAssignmentObjective.MAXIMIZE_MINIMUM_RECALL, 7, 1.0, randomLong()); assertThat(classification.getClassAssignmentObjective(), equalTo(Classification.ClassAssignmentObjective.MAXIMIZE_MINIMUM_RECALL)); // class_assignment_objective == null, default applied classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 7, 1.0, randomLong()); assertThat(classification.getClassAssignmentObjective(), equalTo(Classification.ClassAssignmentObjective.MAXIMIZE_MINIMUM_RECALL)); } public void testGetNumTopClasses() { Classification classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 7, 1.0, randomLong()); assertThat(classification.getNumTopClasses(), equalTo(7)); // Boundary condition: num_top_classes == 0 classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 0, 1.0, randomLong()); assertThat(classification.getNumTopClasses(), equalTo(0)); // Boundary condition: num_top_classes == 1000 classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 1000, 1.0, randomLong()); assertThat(classification.getNumTopClasses(), equalTo(1000)); // num_top_classes == null, default applied classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, null, 1.0, randomLong()); assertThat(classification.getNumTopClasses(), equalTo(2)); } public void testGetTrainingPercent() { Classification classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, 50.0, randomLong()); assertThat(classification.getTrainingPercent(), equalTo(50.0)); // Boundary condition: training_percent == 1.0 classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, 1.0, randomLong()); assertThat(classification.getTrainingPercent(), equalTo(1.0)); // Boundary condition: training_percent == 100.0 classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, 100.0, randomLong()); assertThat(classification.getTrainingPercent(), equalTo(100.0)); // training_percent == null, default applied classification = new Classification("foo", BOOSTED_TREE_PARAMS, "result", null, 3, null, randomLong()); assertThat(classification.getTrainingPercent(), equalTo(100.0)); } public void testGetParams() { DataFrameAnalysis.FieldInfo fieldInfo = new TestFieldInfo( Map.of( "foo", Set.of(BooleanFieldMapper.CONTENT_TYPE), "bar", Set.of(NumberFieldMapper.NumberType.LONG.typeName()), "baz", Set.of(KeywordFieldMapper.CONTENT_TYPE)), Map.of( "foo", 10L, "bar", 20L, "baz", 30L) ); assertThat( new Classification("foo").getParams(fieldInfo), equalTo( Map.of( "dependent_variable", "foo", "class_assignment_objective", Classification.ClassAssignmentObjective.MAXIMIZE_MINIMUM_RECALL, "num_top_classes", 2, "prediction_field_name", "foo_prediction", "prediction_field_type", "bool", "num_classes", 10L, "training_percent", 100.0))); assertThat( new Classification("bar").getParams(fieldInfo), equalTo( Map.of( "dependent_variable", "bar", "class_assignment_objective", Classification.ClassAssignmentObjective.MAXIMIZE_MINIMUM_RECALL, "num_top_classes", 2, "prediction_field_name", "bar_prediction", "prediction_field_type", "int", "num_classes", 20L, "training_percent", 100.0))); assertThat( new Classification("baz", BoostedTreeParams.builder().build() , null, null, null, 50.0, null).getParams(fieldInfo), equalTo( Map.of( "dependent_variable", "baz", "class_assignment_objective", Classification.ClassAssignmentObjective.MAXIMIZE_MINIMUM_RECALL, "num_top_classes", 2, "prediction_field_name", "baz_prediction", "prediction_field_type", "string", "num_classes", 30L, "training_percent", 50.0))); } public void testRequiredFieldsIsNonEmpty() { assertThat(createTestInstance().getRequiredFields(), is(not(empty()))); } public void testFieldCardinalityLimitsIsNonEmpty() { Classification classification = createTestInstance(); List<FieldCardinalityConstraint> constraints = classification.getFieldCardinalityConstraints(); assertThat(constraints.size(), equalTo(1)); assertThat(constraints.get(0).getField(), equalTo(classification.getDependentVariable())); assertThat(constraints.get(0).getLowerBound(), equalTo(2L)); assertThat(constraints.get(0).getUpperBound(), equalTo(30L)); } public void testGetExplicitlyMappedFields() { assertThat(new Classification("foo").getExplicitlyMappedFields(null, "results"), equalTo(Collections.singletonMap("results.feature_importance", MapUtils.featureImportanceMapping()))); assertThat(new Classification("foo").getExplicitlyMappedFields(Collections.emptyMap(), "results"), equalTo(Collections.singletonMap("results.feature_importance", MapUtils.featureImportanceMapping()))); assertThat( new Classification("foo").getExplicitlyMappedFields(Collections.singletonMap("foo", "not_a_map"), "results"), equalTo(Collections.singletonMap("results.feature_importance", MapUtils.featureImportanceMapping()))); Map<String, Object> explicitlyMappedFields = new Classification("foo").getExplicitlyMappedFields( Collections.singletonMap("foo", Collections.singletonMap("bar", "baz")), "results"); assertThat(explicitlyMappedFields, allOf( hasEntry("results.foo_prediction", Collections.singletonMap("bar", "baz")), hasEntry("results.top_classes.class_name", Collections.singletonMap("bar", "baz")))); assertThat(explicitlyMappedFields, hasEntry("results.feature_importance", MapUtils.featureImportanceMapping())); explicitlyMappedFields = new Classification("foo").getExplicitlyMappedFields( new HashMap<>() {{ put("foo", new HashMap<>() {{ put("type", "alias"); put("path", "bar"); }}); put("bar", Collections.singletonMap("type", "long")); }}, "results"); assertThat(explicitlyMappedFields, allOf( hasEntry("results.foo_prediction", Collections.singletonMap("type", "long")), hasEntry("results.top_classes.class_name", Collections.singletonMap("type", "long")))); assertThat(explicitlyMappedFields, hasEntry("results.feature_importance", MapUtils.featureImportanceMapping())); assertThat( new Classification("foo").getExplicitlyMappedFields( Collections.singletonMap("foo", new HashMap<>() {{ put("type", "alias"); put("path", "missing"); }}), "results"), equalTo(Collections.singletonMap("results.feature_importance", MapUtils.featureImportanceMapping()))); } public void testToXContent_GivenVersionBeforeRandomizeSeedWasIntroduced() throws IOException { Classification classification = createRandom(); assertThat(classification.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { classification.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", "7.5.0"))); String json = Strings.toString(builder); assertThat(json, not(containsString("randomize_seed"))); } } public void testToXContent_GivenVersionAfterRandomizeSeedWasIntroduced() throws IOException { Classification classification = createRandom(); assertThat(classification.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { classification.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", Version.CURRENT.toString()))); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testToXContent_GivenVersionIsNull() throws IOException { Classification classification = createRandom(); assertThat(classification.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { classification.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("version", null))); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testToXContent_GivenEmptyParams() throws IOException { Classification classification = createRandom(); assertThat(classification.getRandomizeSeed(), is(notNullValue())); try (XContentBuilder builder = JsonXContent.contentBuilder()) { classification.toXContent(builder, ToXContent.EMPTY_PARAMS); String json = Strings.toString(builder); assertThat(json, containsString("randomize_seed")); } } public void testGetStateDocId() { Classification classification = createRandom(); assertThat(classification.persistsState(), is(true)); String randomId = randomAlphaOfLength(10); assertThat(classification.getStateDocId(randomId), equalTo(randomId + "_classification_state#1")); } public void testExtractJobIdFromStateDoc() { assertThat(Classification.extractJobIdFromStateDoc("foo_bar-1_classification_state#1"), equalTo("foo_bar-1")); assertThat(Classification.extractJobIdFromStateDoc("noop"), is(nullValue())); } @Override protected Classification mutateInstanceForVersion(Classification instance, Version version) { return mutateForVersion(instance, version); } private static class TestFieldInfo implements DataFrameAnalysis.FieldInfo { private final Map<String, Set<String>> fieldTypes; private final Map<String, Long> fieldCardinalities; private TestFieldInfo(Map<String, Set<String>> fieldTypes, Map<String, Long> fieldCardinalities) { this.fieldTypes = fieldTypes; this.fieldCardinalities = fieldCardinalities; } @Override public Set<String> getTypes(String field) { return fieldTypes.get(field); } @Override public Long getCardinality(String field) { return fieldCardinalities.get(field); } } }