repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
variacode/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/QuotedStringTokenizer.java
7149
/* * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.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.dtolabs.rundeck.core.utils; import org.apache.commons.lang.text.StrMatcher; import java.util.*; /** * Tokenizer for strings delimited by spaces, allowing quoted strings with either single or double quotes, and escaped * quote values within those strings by doubling the quote character. Delimiters are not returned in the tokens, and * runs of delimiters can be quelled. All chars in a quoted section are returned, even blanks. * Implements {@link Iterable} and {@link Iterator}. * */ public class QuotedStringTokenizer implements Iterator<String>, Iterable<String> { private char[] string; private int pos; private Queue<String> buffer; private StrMatcher delimiterMatcher; private StrMatcher quoteMatcher; private StrMatcher whitespaceMatcher; private boolean quashDelimiters; public QuotedStringTokenizer(String string) { this(string.toCharArray(), 0); } public QuotedStringTokenizer(char[] chars, int pos) { this.string = chars; this.pos = pos; buffer = new ArrayDeque<String>(); delimiterMatcher = StrMatcher.trimMatcher(); quoteMatcher = StrMatcher.quoteMatcher(); whitespaceMatcher = StrMatcher.trimMatcher(); quashDelimiters=true; readNext(); } public static String[] tokenizeToArray(String string) { List<String> strings = collectTokens(string); return strings.toArray(new String[strings.size()]); } public static List<String> tokenizeToList(String string) { return collectTokens(string); } public static Iterable<String> tokenize(String string) { return new QuotedStringTokenizer(string); } private static List<String> collectTokens(String string) { ArrayList<String> strings = new ArrayList<String>(); for (String s : new QuotedStringTokenizer(string)) { strings.add(s); } return strings; } @Override public boolean hasNext() { return !buffer.isEmpty(); } @Override public String next() { String remove = buffer.remove(); readNext(); return remove; } private void readNext() { pos = readNextToken(string, pos, buffer); } private int readNextToken(char[] chars, int pos, Collection<String> tokens) { if (pos >= chars.length) { return -1; } int ws = whitespaceMatcher.isMatch(chars, pos); if (ws > 0) { pos += ws; } if (pos >= chars.length) { return -1; } int delim = delimiterMatcher.isMatch(chars, pos); if (delim > 0) { if (quashDelimiters) { pos = consumeDelimiters(chars, pos, delim); } else { addToken(buffer, ""); return pos + delim; } } int quote = quoteMatcher.isMatch(chars, pos); return readQuotedToken(chars, pos, tokens, quote); } private int consumeDelimiters(char[] chars, int start, int delim) { while (delim > 0 && start < chars.length - delim) { start += delim; delim = delimiterMatcher.isMatch(chars, start); } return start; } private int readQuotedToken(char[] chars, int start, Collection<String> tokens, int quotesize) { int pos = start; StringBuilder tchars = new StringBuilder(); boolean quoting = quotesize > 0; if (quoting) { pos += quotesize; } while (pos < chars.length) { if (quoting) { if (charsMatch(chars, start, pos, quotesize)) { //matches the quoting char //if next token is the same quote, it is an escaped quote if (charsMatch(chars, start, pos + quotesize, quotesize)) { //token the quote tchars.append(new String(chars, pos, quotesize)); pos += 2 * quotesize; continue; } //end of quoting quoting = false; pos += quotesize; continue; } //append char tchars.append(chars[pos++]); } else { int delim = delimiterMatcher.isMatch(chars, pos); if (delim > 0) { if (quashDelimiters) { pos = consumeDelimiters(chars, pos, delim); addToken(tokens, tchars.toString()); return pos; } else { addToken(tokens, tchars.toString()); return pos + delim; } } if (quotesize > 0 && charsMatch(chars, start, pos, quotesize)) { //new quote quoting = true; pos += quotesize; continue; } //append char tchars.append(chars[pos++]); } } addToken(tokens, tchars.toString()); return pos; } /** * @return true if two sequences of chars match within the array. * * @param chars char set * @param pos1 position 1 * @param pos2 position 2 * @param len2 length to compare * */ private boolean charsMatch(char[] chars, int pos1, int pos2, int len2) { return charsMatch(chars, pos1, len2, pos2, len2); } /** * @return true if two sequences of chars match within the array. * * @param chars char set * @param pos1 pos 1 * @param len1 length 1 * @param pos2 pos 2 * @param len2 length 2 * */ private boolean charsMatch(char[] chars, int pos1, int len1, int pos2, int len2) { if (len1 != len2) { return false; } if (pos1 + len1 > chars.length || pos2 + len2 > chars.length) { return false; } for (int i = 0; i < len1; i++) { if (chars[pos1 + i] != chars[pos2 + i]) { return false; } } return true; } private void addToken(Collection<String> buffer, String token) { buffer.add(token); } @Override public void remove() { } @Override public Iterator<String> iterator() { return this; } }
apache-2.0
maichler/izpack
izpack-panel/src/main/java/com/izforge/izpack/panels/userinput/console/title/ConsoleTitleField.java
1665
/* * IzPack - Copyright 2001-2013 Julien Ponge, All Rights Reserved. * * http://izpack.org/ * http://izpack.codehaus.org/ * * Copyright 2013 Tim Anderson * * 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.izforge.izpack.panels.userinput.console.title; import com.izforge.izpack.api.handler.Prompt; import com.izforge.izpack.panels.userinput.console.ConsoleField; import com.izforge.izpack.panels.userinput.field.Field; import com.izforge.izpack.util.Console; /** * Console title field. * * @author Tim Anderson */ public class ConsoleTitleField extends ConsoleField { /** * Constructs a {@code ConsoleTitleField}. * * @param field the field * @param console the console */ public ConsoleTitleField(Field field, Console console, Prompt prompt) { super(field, console, prompt); } /** * Displays the field. * * @return {@code true} */ @Override public boolean display() { String title = getField().getLabel(true); if (title != null) { println(title); println(""); } return true; } }
apache-2.0
dgutierr/uberfire-extensions
uberfire-wires/uberfire-wires-bpmn/uberfire-wires-bpmn-client/src/main/java/org/uberfire/ext/wires/bpmn/client/resources/i18n/BpmnEditorConstants.java
1180
/* * Copyright 2015 JBoss, by Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uberfire.ext.wires.bpmn.client.resources.i18n; import com.google.gwt.core.client.GWT; import com.google.gwt.i18n.client.Messages; public interface BpmnEditorConstants extends Messages { public static final BpmnEditorConstants INSTANCE = GWT.create( BpmnEditorConstants.class ); String bpmnResourceTypeDescription(); String bpmnPerspectiveTitle(); String bpmnExplorerTitle(); String bpmnExplorerNoFilesFound(); String bpmnExplorerNoFilesOpen(); String bpmnExplorerFileUrl(); String bpmnEditorTitle(); }
apache-2.0
johnnywale/drill
exec/java-exec/src/test/java/org/apache/drill/exec/physical/impl/common/HashPartitionTest.java
13922
/* * 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.drill.exec.physical.impl.common; import org.apache.drill.shaded.guava.com.google.common.collect.Lists; import org.apache.calcite.rel.core.JoinRelType; import org.apache.drill.common.config.DrillConfig; import org.apache.drill.common.expression.FieldReference; import org.apache.drill.common.expression.LogicalExpression; import org.apache.drill.common.expression.SchemaPath; import org.apache.drill.common.logical.data.JoinCondition; import org.apache.drill.common.logical.data.NamedExpression; import org.apache.drill.common.types.TypeProtos; import org.apache.drill.common.types.Types; import org.apache.drill.exec.ExecConstants; import org.apache.drill.exec.memory.BufferAllocator; import org.apache.drill.exec.ops.FragmentContext; import org.apache.drill.exec.ops.OperatorContext; import org.apache.drill.exec.physical.config.HashJoinPOP; import org.apache.drill.exec.physical.impl.MockRecordBatch; import org.apache.drill.exec.physical.impl.aggregate.SpilledRecordBatch; import org.apache.drill.exec.physical.impl.join.HashJoinMemoryCalculator; import org.apache.drill.exec.physical.impl.join.HashJoinMemoryCalculatorImpl; import org.apache.drill.exec.physical.impl.join.JoinUtils; import org.apache.drill.exec.physical.impl.spill.SpillSet; import org.apache.drill.exec.planner.logical.DrillJoinRel; import org.apache.drill.exec.proto.ExecProtos; import org.apache.drill.exec.proto.UserBitShared; import org.apache.drill.exec.record.BatchSchema; import org.apache.drill.exec.record.CloseableRecordBatch; import org.apache.drill.exec.record.MaterializedField; import org.apache.drill.exec.record.RecordBatch; import org.apache.drill.test.BaseDirTestWatcher; import org.apache.drill.test.BaseTest; import org.apache.drill.test.OperatorFixture; import org.apache.drill.exec.physical.rowSet.DirectRowSet; import org.apache.drill.exec.physical.rowSet.RowSet; import org.apache.drill.exec.physical.rowSet.RowSetBuilder; import org.apache.drill.test.rowSet.RowSetComparison; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import java.util.List; public class HashPartitionTest extends BaseTest { @Rule public final BaseDirTestWatcher dirTestWatcher = new BaseDirTestWatcher(); @Test public void noSpillBuildSideTest() throws Exception { new HashPartitionFixture().run(new HashPartitionTestCase() { private RowSet buildRowSet; private RowSet probeRowSet; @Override public CloseableRecordBatch createBuildBatch(BatchSchema schema, FragmentContext context) { buildRowSet = new RowSetBuilder(context.getAllocator(), schema) .addRow(1, "green") .addRow(3, "red") .addRow(2, "blue") .build(); return new MockRecordBatch.Builder(). sendData(buildRowSet). build(context); } @Override public void createResultBuildBatch(BatchSchema schema, FragmentContext context) { } @Override public CloseableRecordBatch createProbeBatch(BatchSchema schema, FragmentContext context) { probeRowSet = new RowSetBuilder(context.getAllocator(), schema) .addRow(.5f, "yellow") .addRow(1.5f, "blue") .addRow(2.5f, "black") .build(); return new MockRecordBatch.Builder(). sendData(probeRowSet). build(context); } @Override public void run(SpillSet spillSet, BatchSchema buildSchema, BatchSchema probeSchema, RecordBatch buildBatch, RecordBatch probeBatch, ChainedHashTable baseHashTable, FragmentContext context, OperatorContext operatorContext) throws Exception { final HashPartition hashPartition = new HashPartition(context, context.getAllocator(), baseHashTable, buildBatch, probeBatch, false, 10, spillSet, 0, 0, 2); // only '1' has a special treatment final HashJoinMemoryCalculator.BuildSidePartitioning noopCalc = new HashJoinMemoryCalculatorImpl.NoopBuildSidePartitioningImpl(); hashPartition.appendInnerRow(buildBatch.getContainer(), 0, 10, noopCalc); hashPartition.appendInnerRow(buildBatch.getContainer(), 1, 11, noopCalc); hashPartition.appendInnerRow(buildBatch.getContainer(), 2, 12, noopCalc); hashPartition.completeAnInnerBatch(false, false); hashPartition.buildContainersHashTableAndHelper(); { int compositeIndex = hashPartition.probeForKey(0, 16); Assert.assertEquals(-1, compositeIndex); } { int compositeIndex = hashPartition.probeForKey(1, 12); int startIndex = hashPartition.getStartIndex(compositeIndex).getLeft(); int nextIndex = hashPartition.getNextIndex(startIndex); Assert.assertEquals(2, startIndex); Assert.assertEquals(-1, nextIndex); } { int compositeIndex = hashPartition.probeForKey(2, 15); Assert.assertEquals(-1, compositeIndex); } buildRowSet.clear(); probeRowSet.clear(); hashPartition.close(); } }); } @Test public void spillSingleIncompleteBatchBuildSideTest() throws Exception { new HashPartitionFixture().run(new HashPartitionTestCase() { private RowSet buildRowSet; private RowSet probeRowSet; private RowSet actualBuildRowSet; @Override public CloseableRecordBatch createBuildBatch(BatchSchema schema, FragmentContext context) { buildRowSet = new RowSetBuilder(context.getAllocator(), schema) .addRow(1, "green") .addRow(3, "red") .addRow(2, "blue") .build(); return new MockRecordBatch.Builder(). sendData(buildRowSet). build(context); } @Override public void createResultBuildBatch(BatchSchema schema, FragmentContext context) { final BatchSchema newSchema = BatchSchema.newBuilder() .addFields(schema) .addField(MaterializedField.create(HashPartition.HASH_VALUE_COLUMN_NAME, HashPartition.HVtype)) .build(); actualBuildRowSet = new RowSetBuilder(context.getAllocator(), newSchema) .addRow(1, "green", 10) .addRow(3, "red", 11) .addRow(2, "blue", 12) .build(); } @Override public CloseableRecordBatch createProbeBatch(BatchSchema schema, FragmentContext context) { probeRowSet = new RowSetBuilder(context.getAllocator(), schema) .addRow(.5f, "yellow") .addRow(1.5f, "blue") .addRow(2.5f, "black") .build(); return new MockRecordBatch.Builder(). sendData(probeRowSet). build(context); } @Override public void run(SpillSet spillSet, BatchSchema buildSchema, BatchSchema probeSchema, RecordBatch buildBatch, RecordBatch probeBatch, ChainedHashTable baseHashTable, FragmentContext context, OperatorContext operatorContext) { final HashPartition hashPartition = new HashPartition(context, context.getAllocator(), baseHashTable, buildBatch, probeBatch, false, 10, spillSet, 0, 0, 2); final HashJoinMemoryCalculator.BuildSidePartitioning noopCalc = new HashJoinMemoryCalculatorImpl.NoopBuildSidePartitioningImpl(); hashPartition.appendInnerRow(buildBatch.getContainer(), 0, 10, noopCalc); hashPartition.appendInnerRow(buildBatch.getContainer(), 1, 11, noopCalc); hashPartition.appendInnerRow(buildBatch.getContainer(), 2, 12, noopCalc); hashPartition.completeAnInnerBatch(false, false); hashPartition.spillThisPartition(); final String spillFile = hashPartition.getSpillFile(); final int batchesCount = hashPartition.getPartitionBatchesCount(); hashPartition.closeWriter(); SpilledRecordBatch spilledBuildBatch = new SpilledRecordBatch(spillFile, batchesCount, context, buildSchema, operatorContext, spillSet); final RowSet actual = DirectRowSet.fromContainer(spilledBuildBatch.getContainer()); new RowSetComparison(actualBuildRowSet).verify(actual); spilledBuildBatch.close(); buildRowSet.clear(); actualBuildRowSet.clear(); probeRowSet.clear(); hashPartition.close(); } }); } public class HashPartitionFixture { public void run(HashPartitionTestCase testCase) throws Exception { try (OperatorFixture operatorFixture = new OperatorFixture.Builder(HashPartitionTest.this.dirTestWatcher).build()) { final FragmentContext context = operatorFixture.getFragmentContext(); final HashJoinPOP pop = new HashJoinPOP(null, null, null, JoinRelType.FULL, null); final OperatorContext operatorContext = operatorFixture.operatorContext(pop); final DrillConfig config = context.getConfig(); final BufferAllocator allocator = operatorFixture.allocator(); final UserBitShared.QueryId queryId = UserBitShared.QueryId.newBuilder() .setPart1(1L) .setPart2(2L) .build(); final ExecProtos.FragmentHandle fragmentHandle = ExecProtos.FragmentHandle.newBuilder() .setQueryId(queryId) .setMinorFragmentId(1) .setMajorFragmentId(2) .build(); final SpillSet spillSet = new SpillSet(config, fragmentHandle, pop); // Create build batch MaterializedField buildColA = MaterializedField.create("buildColA", Types.required(TypeProtos.MinorType.INT)); MaterializedField buildColB = MaterializedField.create("buildColB", Types.required(TypeProtos.MinorType.VARCHAR)); List<MaterializedField> buildCols = Lists.newArrayList(buildColA, buildColB); final BatchSchema buildSchema = new BatchSchema(BatchSchema.SelectionVectorMode.NONE, buildCols); final CloseableRecordBatch buildBatch = testCase.createBuildBatch(buildSchema, operatorContext.getFragmentContext()); buildBatch.next(); testCase.createResultBuildBatch(buildSchema, operatorContext.getFragmentContext()); // Create probe batch MaterializedField probeColA = MaterializedField.create("probeColA", Types.required(TypeProtos.MinorType.FLOAT4)); MaterializedField probeColB = MaterializedField.create("probeColB", Types.required(TypeProtos.MinorType.VARCHAR)); List<MaterializedField> probeCols = Lists.newArrayList(probeColA, probeColB); final BatchSchema probeSchema = new BatchSchema(BatchSchema.SelectionVectorMode.NONE, probeCols); final CloseableRecordBatch probeBatch = testCase.createProbeBatch(probeSchema, operatorContext.getFragmentContext()); probeBatch.next(); final LogicalExpression buildColExpression = SchemaPath.getSimplePath(buildColB.getName()); final LogicalExpression probeColExpression = SchemaPath.getSimplePath(probeColB.getName()); final JoinCondition condition = new JoinCondition(DrillJoinRel.EQUALITY_CONDITION, probeColExpression, buildColExpression); final List<Comparator> comparators = Lists.newArrayList(JoinUtils.checkAndReturnSupportedJoinComparator(condition)); final List<NamedExpression> buildExpressions = Lists.newArrayList(new NamedExpression(buildColExpression, new FieldReference("build_side_0"))); final List<NamedExpression> probeExpressions = Lists.newArrayList(new NamedExpression(probeColExpression, new FieldReference("probe_side_0"))); final int hashTableSize = (int) context.getOptions().getOption(ExecConstants.MIN_HASH_TABLE_SIZE); final HashTableConfig htConfig = new HashTableConfig(hashTableSize, HashTable.DEFAULT_LOAD_FACTOR, buildExpressions, probeExpressions, comparators); final ChainedHashTable baseHashTable = new ChainedHashTable(htConfig, context, allocator, buildBatch, probeBatch, null); baseHashTable.updateIncoming(buildBatch, probeBatch); testCase.run(spillSet, buildSchema, probeSchema, buildBatch, probeBatch, baseHashTable, context, operatorContext); buildBatch.close(); probeBatch.close(); } } } interface HashPartitionTestCase { CloseableRecordBatch createBuildBatch(BatchSchema schema, FragmentContext context); void createResultBuildBatch(BatchSchema schema, FragmentContext context); CloseableRecordBatch createProbeBatch(BatchSchema schema, FragmentContext context); void run(SpillSet spillSet, BatchSchema buildSchema, BatchSchema probeSchema, RecordBatch buildBatch, RecordBatch probeBatch, ChainedHashTable baseHashTable, FragmentContext context, OperatorContext operatorContext) throws Exception; } }
apache-2.0
hastef88/carbon-business-messaging
components/andes/org.wso2.carbon.andes/src/main/java/org/wso2/carbon/andes/listeners/BrokerLifecycleListener.java
1101
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wso2.carbon.andes.listeners; /** * This is an interface that declares the method where external parties * can define andes server pre-shutdown work that needs to be done by extending this. */ public interface BrokerLifecycleListener { /** * Method declaration for pre-shutdown work * */ public void onShuttingdown(); /** * Method declaration for post-shutdown work * */ public void onShutdown(); }
apache-2.0
mztaylor/rice-git
rice-middleware/kim/kim-impl/src/main/java/org/kuali/rice/kim/impl/group/GroupMemberBo.java
2735
/** * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kim.impl.group; import java.sql.Timestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.kuali.rice.kim.api.group.GroupMember; import org.kuali.rice.kim.api.group.GroupMemberContract; import org.kuali.rice.kim.impl.membership.AbstractMemberBo; import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator; import javax.persistence.Cacheable; @Entity @Cacheable(false) @Table(name = "KRIM_GRP_MBR_T") public class GroupMemberBo extends AbstractMemberBo implements GroupMemberContract { private static final long serialVersionUID = 6773749266062306217L; @PortableSequenceGenerator(name = "KRIM_GRP_MBR_ID_S") @GeneratedValue(generator = "KRIM_GRP_MBR_ID_S") @Id @Column(name = "GRP_MBR_ID") private String id; @Column(name = "GRP_ID") private String groupId; public static GroupMember to(GroupMemberBo bo) { if (bo == null) { return null; } return GroupMember.Builder.create(bo).build(); } public static GroupMemberBo from(GroupMember im) { if (im == null) { return null; } GroupMemberBo bo = new GroupMemberBo(); bo.setId(im.getId()); bo.setGroupId(im.getGroupId()); bo.setMemberId(im.getMemberId()); bo.setTypeCode(im.getType().getCode()); bo.setActiveFromDateValue(im.getActiveFromDate() == null ? null : new Timestamp(im.getActiveFromDate().getMillis())); bo.setActiveToDateValue(im.getActiveToDate() == null ? null : new Timestamp(im.getActiveToDate().getMillis())); bo.setVersionNumber(im.getVersionNumber()); bo.setObjectId(im.getObjectId()); return bo; } @Override public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } }
apache-2.0
zdary/intellij-community
platform/util/src/com/intellij/util/io/keyStorage/InlinedKeyStorage.java
1695
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.io.keyStorage; import com.intellij.util.Processor; import com.intellij.util.io.InlineKeyDescriptor; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class InlinedKeyStorage<Data> implements AppendableObjectStorage<Data> { private final InlineKeyDescriptor<Data> myDescriptor; public InlinedKeyStorage(@NotNull InlineKeyDescriptor<Data> descriptor) { myDescriptor = descriptor; } @Override public Data read(int addr) throws IOException { return myDescriptor.fromInt(addr); } @Override public boolean processAll(@NotNull Processor<? super Data> processor) throws IOException { throw new UnsupportedOperationException(); } @Override public int append(Data value) throws IOException { return myDescriptor.toInt(value); } @Override public boolean checkBytesAreTheSame(int addr, Data value) { return false; } @Override public void lockRead() { throw new UnsupportedOperationException(); } @Override public void unlockRead() { throw new UnsupportedOperationException(); } @Override public void lockWrite() { throw new UnsupportedOperationException(); } @Override public void unlockWrite() { throw new UnsupportedOperationException(); } @Override public int getCurrentLength() { throw new UnsupportedOperationException(); } @Override public boolean isDirty() { return false; } @Override public void force() { } @Override public void close() throws IOException { } }
apache-2.0
wjw465150/jodd
jodd-petite/src/test/java/jodd/petite/ManualTest.java
7696
// Copyright (c) 2003-present, Jodd Team (http://jodd.org) // 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 jodd.petite; import jodd.petite.data.PojoAnnBean; import jodd.petite.data.PojoBean; import jodd.petite.data.SomeService; import org.junit.Test; import java.util.Set; import static jodd.petite.PetiteRegistry.petite; import static jodd.petite.meta.InitMethodInvocationStrategy.POST_INITIALIZE; import static org.junit.Assert.*; public class ManualTest { @Test public void testManualRegistration() { PetiteContainer pc = new PetiteContainer(); pc.registerPetiteBean(SomeService.class, null, null, null, false); pc.registerPetiteBean(PojoBean.class, "pojo", null, null, false); assertEquals(2, pc.getTotalBeans()); Set<String> names = pc.getBeanNames(); assertEquals(2, names.size()); assertTrue(names.contains("pojo")); assertTrue(names.contains("someService")); pc.registerPetiteCtorInjectionPoint("pojo", null, null); pc.registerPetitePropertyInjectionPoint("pojo", "service", "someService"); pc.registerPetiteMethodInjectionPoint("pojo", "injectService", null, new String[]{"someService"}); pc.registerPetiteInitMethods("pojo", POST_INITIALIZE, "init"); PojoBean pojoBean = (PojoBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertSame(ss, pojoBean.service); assertSame(ss, pojoBean.service2); assertEquals(1, pojoBean.count); } @Test public void testManualRegistration2() { PetiteContainer pc = new PetiteContainer(); petite(pc).bean(SomeService.class).register(); petite(pc).bean(PojoBean.class).name("pojo").register(); assertEquals(2, pc.getTotalBeans()); petite(pc).wire("pojo").ctor().bind(); petite(pc).wire("pojo").property("service").ref("someService").bind(); petite(pc).wire("pojo").method("injectService").ref("someService").bind(); petite(pc).init("pojo").invoke(POST_INITIALIZE).methods("init").register(); PojoBean pojoBean = (PojoBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertSame(ss, pojoBean.service); assertSame(ss, pojoBean.service2); assertEquals(1, pojoBean.count); } @Test public void testManualRegistrationUsingAnnotations() { PetiteContainer pc = new PetiteContainer(); pc.registerPetiteBean(SomeService.class, null, null, null, false); pc.registerPetiteBean(PojoAnnBean.class, "pojo", null, null, false); assertEquals(2, pc.getTotalBeans()); PojoAnnBean pojoBean = (PojoAnnBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertSame(ss, pojoBean.service); assertSame(ss, pojoBean.service2); assertEquals(1, pojoBean.count); } @Test public void testManualRegistrationUsingAnnotations2() { PetiteContainer pc = new PetiteContainer(); petite(pc).bean(SomeService.class).register(); petite(pc).bean(PojoAnnBean.class).name("pojo").register(); assertEquals(2, pc.getTotalBeans()); PojoAnnBean pojoBean = (PojoAnnBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertSame(ss, pojoBean.service); assertSame(ss, pojoBean.service2); assertEquals(1, pojoBean.count); } @Test public void testManualDefinitionUsingAnnotations() { PetiteContainer pc = new PetiteContainer(); pc.registerPetiteBean(SomeService.class, null, null, null, false); pc.registerPetiteBean(PojoAnnBean.class, "pojo", null, null, true); assertEquals(2, pc.getTotalBeans()); PojoAnnBean pojoBean = (PojoAnnBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertNull(pojoBean.service); assertNull(pojoBean.service2); assertEquals(0, pojoBean.count); } @Test public void testManualDefinitionUsingAnnotations2() { PetiteContainer pc = new PetiteContainer(); petite(pc).bean(SomeService.class).register(); petite(pc).bean(PojoAnnBean.class).name("pojo").define().register(); assertEquals(2, pc.getTotalBeans()); PojoAnnBean pojoBean = (PojoAnnBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertNull(pojoBean.service); assertNull(pojoBean.service2); assertEquals(0, pojoBean.count); } @Test public void testManualDefinition() { PetiteContainer pc = new PetiteContainer(); pc.registerPetiteBean(SomeService.class, null, null, null, false); pc.registerPetiteBean(PojoBean.class, "pojo", null, null, true); assertEquals(2, pc.getTotalBeans()); pc.registerPetiteCtorInjectionPoint("pojo", null, null); pc.registerPetitePropertyInjectionPoint("pojo", "service", "someService"); pc.registerPetiteMethodInjectionPoint("pojo", "injectService", null, new String[] {"someService"}); pc.registerPetiteInitMethods("pojo", POST_INITIALIZE, "init"); PojoBean pojoBean = (PojoBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertSame(ss, pojoBean.service); assertSame(ss, pojoBean.service2); assertEquals(1, pojoBean.count); } @Test public void testManualDefinition2() { PetiteContainer pc = new PetiteContainer(); petite(pc).bean(SomeService.class).register(); petite(pc).bean(PojoBean.class).name("pojo").define().register(); assertEquals(2, pc.getTotalBeans()); petite(pc).wire("pojo").ctor().bind(); petite(pc).wire("pojo").property("service").ref("someService").bind(); petite(pc).wire("pojo").method("injectService").ref("someService").bind(); petite(pc).init("pojo").invoke(POST_INITIALIZE).methods("init").register(); PojoBean pojoBean = (PojoBean) pc.getBean("pojo"); SomeService ss = (SomeService) pc.getBean("someService"); assertNotNull(pojoBean); assertNotNull(ss); assertSame(ss, pojoBean.fservice); assertSame(ss, pojoBean.service); assertSame(ss, pojoBean.service2); assertEquals(1, pojoBean.count); } }
bsd-2-clause
kerwinxu/barcodeManager
zxing/android/src/com/google/zxing/client/android/result/AddressBookResultHandler.java
7135
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.client.android.result; import com.google.zxing.client.android.R; import com.google.zxing.client.result.AddressBookParsedResult; import com.google.zxing.client.result.ParsedResult; import android.app.Activity; import android.telephony.PhoneNumberUtils; import android.text.Spannable; import android.text.SpannableString; import android.text.style.StyleSpan; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * Handles address book entries. * * @author dswitkin@google.com (Daniel Switkin) */ public final class AddressBookResultHandler extends ResultHandler { private static final DateFormat[] DATE_FORMATS = { new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH), new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH), new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH), }; static { for (DateFormat format : DATE_FORMATS) { format.setLenient(false); } } private static final int[] BUTTON_TEXTS = { R.string.button_add_contact, R.string.button_show_map, R.string.button_dial, R.string.button_email, }; private final boolean[] fields; private int buttonCount; // This takes all the work out of figuring out which buttons/actions should be in which // positions, based on which fields are present in this barcode. private int mapIndexToAction(int index) { if (index < buttonCount) { int count = -1; for (int x = 0; x < MAX_BUTTON_COUNT; x++) { if (fields[x]) { count++; } if (count == index) { return x; } } } return -1; } public AddressBookResultHandler(Activity activity, ParsedResult result) { super(activity, result); AddressBookParsedResult addressResult = (AddressBookParsedResult) result; String[] addresses = addressResult.getAddresses(); boolean hasAddress = addresses != null && addresses.length > 0 && addresses[0].length() > 0; String[] phoneNumbers = addressResult.getPhoneNumbers(); boolean hasPhoneNumber = phoneNumbers != null && phoneNumbers.length > 0; String[] emails = addressResult.getEmails(); boolean hasEmailAddress = emails != null && emails.length > 0; fields = new boolean[MAX_BUTTON_COUNT]; fields[0] = true; // Add contact is always available fields[1] = hasAddress; fields[2] = hasPhoneNumber; fields[3] = hasEmailAddress; buttonCount = 0; for (int x = 0; x < MAX_BUTTON_COUNT; x++) { if (fields[x]) { buttonCount++; } } } @Override public int getButtonCount() { return buttonCount; } @Override public int getButtonText(int index) { return BUTTON_TEXTS[mapIndexToAction(index)]; } @Override public void handleButtonPress(int index) { AddressBookParsedResult addressResult = (AddressBookParsedResult) getResult(); String[] addresses = addressResult.getAddresses(); String address1 = addresses == null || addresses.length < 1 ? null : addresses[0]; String[] addressTypes = addressResult.getAddressTypes(); String address1Type = addressTypes == null || addressTypes.length < 1 ? null : addressTypes[0]; int action = mapIndexToAction(index); switch (action) { case 0: addContact(addressResult.getNames(), addressResult.getPronunciation(), addressResult.getPhoneNumbers(), addressResult.getPhoneTypes(), addressResult.getEmails(), addressResult.getEmailTypes(), addressResult.getNote(), addressResult.getInstantMessenger(), address1, address1Type, addressResult.getOrg(), addressResult.getTitle(), addressResult.getURL(), addressResult.getBirthday()); break; case 1: String[] names = addressResult.getNames(); String title = names != null ? names[0] : null; searchMap(address1, title); break; case 2: dialPhone(addressResult.getPhoneNumbers()[0]); break; case 3: sendEmail(addressResult.getEmails()[0], null, null); break; default: break; } } private static Date parseDate(String s) { for (DateFormat currentFormat : DATE_FORMATS) { try { return currentFormat.parse(s); } catch (ParseException e) { // continue } } return null; } // Overriden so we can hyphenate phone numbers, format birthdays, and bold the name. @Override public CharSequence getDisplayContents() { AddressBookParsedResult result = (AddressBookParsedResult) getResult(); StringBuilder contents = new StringBuilder(100); ParsedResult.maybeAppend(result.getNames(), contents); int namesLength = contents.length(); String pronunciation = result.getPronunciation(); if (pronunciation != null && pronunciation.length() > 0) { contents.append("\n("); contents.append(pronunciation); contents.append(')'); } ParsedResult.maybeAppend(result.getTitle(), contents); ParsedResult.maybeAppend(result.getOrg(), contents); ParsedResult.maybeAppend(result.getAddresses(), contents); String[] numbers = result.getPhoneNumbers(); if (numbers != null) { for (String number : numbers) { ParsedResult.maybeAppend(PhoneNumberUtils.formatNumber(number), contents); } } ParsedResult.maybeAppend(result.getEmails(), contents); ParsedResult.maybeAppend(result.getURL(), contents); String birthday = result.getBirthday(); if (birthday != null && birthday.length() > 0) { Date date = parseDate(birthday); if (date != null) { ParsedResult.maybeAppend(DateFormat.getDateInstance(DateFormat.MEDIUM).format(date.getTime()), contents); } } ParsedResult.maybeAppend(result.getNote(), contents); if (namesLength > 0) { // Bold the full name to make it stand out a bit. Spannable styled = new SpannableString(contents.toString()); styled.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, namesLength, 0); return styled; } else { return contents.toString(); } } @Override public int getDisplayTitle() { return R.string.result_address_book; } }
bsd-2-clause
Snickermicker/smarthome
extensions/binding/org.eclipse.smarthome.binding.mqtt/src/main/java/org/eclipse/smarthome/binding/mqtt/discovery/MQTTTopicDiscoveryParticipant.java
1646
/** * Copyright (c) 2014,2019 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.eclipse.smarthome.binding.mqtt.discovery; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.thing.ThingUID; import org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection; /** * Implement this interface to get notified of received values and vanished topics. * * @author David Graeff - Initial contribution */ @NonNullByDefault public interface MQTTTopicDiscoveryParticipant { /** * Called whenever a message on the subscribed topic got published or a retained message was received. * * @param thingUID The MQTT thing UID of the Thing that established/created the given broker connection. * @param connection The broker connection * @param topic The topic * @param payload The topic payload */ void receivedMessage(ThingUID thingUID, MqttBrokerConnection connection, String topic, byte[] payload); /** * A MQTT topic vanished. * * @param thingUID The MQTT thing UID of the Thing that established/created the given broker connection. * @param connection The broker connection * @param topic The topic */ void topicVanished(ThingUID thingUID, MqttBrokerConnection connection, String topic); }
epl-1.0
renatoathaydes/checker-framework
checker/src/org/checkerframework/checker/regex/qual/Var.java
1075
package org.checkerframework.checker.regex.qual; import org.checkerframework.qualframework.poly.SimpleQualifierParameterAnnotationConverter; import org.checkerframework.qualframework.poly.qual.Wildcard; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Var is a qualifier parameter use. * * @see org.checkerframework.checker.tainting.qual.Var */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) @Repeatable(MultiVar.class) public @interface Var { /** * Which parameter this @Var is a use of. */ String arg() default SimpleQualifierParameterAnnotationConverter.PRIMARY_TARGET; /** * The name of the parameter to set. */ String param() default SimpleQualifierParameterAnnotationConverter.PRIMARY_TARGET; /** * Specify that this use is a wildcard with a bound. */ Wildcard wildcard() default Wildcard.NONE; }
gpl-2.0
robertoandrade/cyclos
src/nl/strohalm/cyclos/controls/access/transactionpassword/ManageTransactionPasswordAction.java
5153
/* This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Cyclos is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package nl.strohalm.cyclos.controls.access.transactionpassword; import javax.servlet.http.HttpServletRequest; import nl.strohalm.cyclos.controls.ActionContext; import nl.strohalm.cyclos.controls.BaseFormAction; import nl.strohalm.cyclos.entities.access.OperatorUser; import nl.strohalm.cyclos.entities.access.TransactionPassword; import nl.strohalm.cyclos.entities.access.User; import nl.strohalm.cyclos.entities.members.Element; import nl.strohalm.cyclos.entities.members.Operator; import nl.strohalm.cyclos.services.elements.ResetTransactionPasswordDTO; import nl.strohalm.cyclos.utils.ActionHelper; import nl.strohalm.cyclos.utils.RelationshipHelper; import nl.strohalm.cyclos.utils.RequestHelper; import nl.strohalm.cyclos.utils.validation.ValidationException; import org.apache.struts.action.ActionForward; /** * Action used to reset a member's transaction password * @author luis */ public class ManageTransactionPasswordAction extends BaseFormAction { @Override protected ActionForward handleDisplay(final ActionContext context) throws Exception { final HttpServletRequest request = context.getRequest(); final ManageTransactionPasswordForm form = context.getForm(); final User user = retrieveUser(context); boolean canReset = false; boolean canBlock = false; switch (user.getTransactionPasswordStatus()) { case ACTIVE: canReset = true; canBlock = true; break; case BLOCKED: canReset = true; break; case PENDING: canBlock = true; break; case NEVER_CREATED: if (user.getElement().getGroup().getBasicSettings().getTransactionPassword() == TransactionPassword.MANUAL) { canReset = true; } break; } request.setAttribute("groupStatus", user.getElement().getGroup().getBasicSettings().getTransactionPassword()); request.setAttribute("user", user); request.setAttribute("canReset", canReset); request.setAttribute("canBlock", canBlock); RequestHelper.storeEnum(request, TransactionPassword.class, "globalTransactionPasswordStatus"); RequestHelper.storeEnum(request, User.TransactionPasswordStatus.class, "userTransactionPasswordStatus"); if (form.isEmbed()) { return new ActionForward("/pages/access/transactionPassword/manageTransactionPassword.jsp"); } else { return context.getInputForward(); } } @Override protected ActionForward handleSubmit(final ActionContext context) throws Exception { final ManageTransactionPasswordForm form = context.getForm(); User user = retrieveUser(context); final boolean block = form.isBlock(); final ResetTransactionPasswordDTO dto = new ResetTransactionPasswordDTO(); dto.setUser(user); dto.setAllowGeneration(!block); user = accessService.resetTransactionPassword(dto); context.sendMessage(block ? "transactionPassword.blocked" : "transactionPassword.reset"); return ActionHelper.redirectWithParam(context.getRequest(), context.getSuccessForward(), "userId", user.getId()); } private User retrieveUser(final ActionContext context) { final HttpServletRequest request = context.getRequest(); if (request.getAttribute("element") != null) { // The element may be already retrieved on the manage passwords action return ((Element) request.getAttribute("element")).getUser(); } final ManageTransactionPasswordForm form = context.getForm(); User user; final long userId = form.getUserId(); try { user = elementService.loadUser(userId, RelationshipHelper.nested(User.Relationships.ELEMENT, Element.Relationships.GROUP)); if (user instanceof OperatorUser) { Element element = user.getElement(); element = elementService.load(element.getId(), RelationshipHelper.nested(Operator.Relationships.MEMBER, Element.Relationships.GROUP)); } } catch (final Exception e) { throw new ValidationException(); } return user; } }
gpl-2.0
cheshirekow/codebase
third_party/lcm/lcm-java/jchart2d-code/src/info/monitorenter/gui/chart/demos/StaticChartXAxisInverse.java
3599
/* * StaticChartXAxisInverse.java of project jchart2d, a demonstration * of the minimal code to set up a chart with static data and an * inverse x axis. * Copyright (C) 2007 - 2011 Achim Westermann, created on 10.12.2004, 13:48:55 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * If you modify or optimize the code in a useful way please let me know. * Achim.Westermann@gmx.de * */ package info.monitorenter.gui.chart.demos; import info.monitorenter.gui.chart.Chart2D; import info.monitorenter.gui.chart.IAxisScalePolicy; import info.monitorenter.gui.chart.ITrace2D; import info.monitorenter.gui.chart.axis.AAxis; import info.monitorenter.gui.chart.axis.AxisInverse; import info.monitorenter.gui.chart.traces.Trace2DSimple; import info.monitorenter.gui.chart.views.ChartPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JPanel; /** * Title: StaticChartXAxisInverse. * <p> * * Description: A demonstration of the minimal code to set up a chart with * static data and an inverse x axis (<code>{@link AxisInverse}</code>). * * @author Achim Westermann * * @version $Revision: 1.7 $ */ public final class StaticChartXAxisInverse extends JPanel { /** * Generated for <code>serialVersionUID</code>. */ private static final long serialVersionUID = -7965444904622492209L; /** * Main entry. * <p> * * @param args * ignored. */ public static void main(final String[] args) { for (int i = 0; i < 1; i++) { JFrame frame = new JFrame("Static Chart x inverted"); frame.getContentPane().add(new StaticChartXAxisInverse()); frame.addWindowListener(new WindowAdapter() { /** * @see java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent) */ @Override public void windowClosing(final WindowEvent e) { System.exit(0); } }); frame.setSize(600, 600); frame.setLocation(i % 3 * 200, i / 3 * 100); frame.setVisible(true); } } /** * Defcon. */ private StaticChartXAxisInverse() { this.setLayout(new BorderLayout()); Chart2D chart = new Chart2D(); AAxis<?> axisXinverted = new AxisInverse<IAxisScalePolicy>(); chart.setAxisXBottom(axisXinverted, 0); // Create an ITrace: // Note that dynamic charts need limited amount of values!!! // ITrace2D trace = new Trace2DLtd(200); ITrace2D trace = new Trace2DSimple(); // Add the trace to the chart: chart.addTrace(trace); trace.setColor(Color.RED); // Add all points, as it is static: double xValue = 0; for (int i = 0; i < 120; i++) { trace.addPoint(xValue + i, i); } // Make it visible: this.add(new ChartPanel(chart), BorderLayout.CENTER); } }
gpl-3.0
OhmGeek/ThanCue
src/org/zeroturnaround/zip/extra/ZipShort.java
4527
/* * 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.zeroturnaround.zip.extra; import static org.zeroturnaround.zip.extra.ZipConstants.BYTE_MASK; /** * This is a class that has been made significantly smaller (deleted a bunch of methods) and originally * is from the Apache Ant Project (http://ant.apache.org), org.apache.tools.zip package. * All license and other documentation is intact. * * Utility class that represents a two byte integer with conversion * rules for the big endian byte order of ZIP files. * */ public final class ZipShort implements Cloneable { private static final int BYTE_1_MASK = 0xFF00; private static final int BYTE_1_SHIFT = 8; private final int value; /** * Create instance from a number. * * @param value the int to store as a ZipShort * @since 1.1 */ public ZipShort(int value) { this.value = value; } /** * Create instance from bytes. * * @param bytes the bytes to store as a ZipShort * @since 1.1 */ public ZipShort(byte[] bytes) { this(bytes, 0); } /** * Create instance from the two bytes starting at offset. * * @param bytes the bytes to store as a ZipShort * @param offset the offset to start * @since 1.1 */ public ZipShort(byte[] bytes, int offset) { value = ZipShort.getValue(bytes, offset); } /** * Get value as two bytes in big endian byte order. * * @return the value as a a two byte array in big endian byte order * @since 1.1 */ public byte[] getBytes() { byte[] result = new byte[2]; result[0] = (byte) (value & BYTE_MASK); result[1] = (byte) ((value & BYTE_1_MASK) >> BYTE_1_SHIFT); return result; } /** * Get value as Java int. * * @return value as a Java int * @since 1.1 */ public int getValue() { return value; } /** * Get value as two bytes in big endian byte order. * * @param value the Java int to convert to bytes * @return the converted int as a byte array in big endian byte order */ public static byte[] getBytes(int value) { byte[] result = new byte[2]; result[0] = (byte) (value & BYTE_MASK); result[1] = (byte) ((value & BYTE_1_MASK) >> BYTE_1_SHIFT); return result; } /** * Helper method to get the value as a java int from two bytes starting at given array offset * * @param bytes the array of bytes * @param offset the offset to start * @return the corresponding java int value */ public static int getValue(byte[] bytes, int offset) { int value = (bytes[offset + 1] << BYTE_1_SHIFT) & BYTE_1_MASK; value += (bytes[offset] & BYTE_MASK); return value; } /** * Helper method to get the value as a java int from a two-byte array * * @param bytes the array of bytes * @return the corresponding java int value */ public static int getValue(byte[] bytes) { return getValue(bytes, 0); } /** * Override to make two instances with same value equal. * * @param o an object to compare * @return true if the objects are equal * @since 1.1 */ @Override public boolean equals(Object o) { if (o == null || !(o instanceof ZipShort)) { return false; } return value == ((ZipShort) o).getValue(); } /** * Override to make two instances with same value equal. * * @return the value stored in the ZipShort * @since 1.1 */ @Override public int hashCode() { return value; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException cnfe) { // impossible throw new RuntimeException(cnfe); } } @Override public String toString() { return "ZipShort value: " + value; } }
gpl-3.0
5AMW3155/shattered-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/ui/Tag.java
1948
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.ui; import com.watabou.noosa.Game; import com.watabou.noosa.NinePatch; import com.watabou.noosa.ui.Button; import com.shatteredpixel.shatteredpixeldungeon.Chrome; public class Tag extends Button { private float r; private float g; private float b; protected NinePatch bg; protected float lightness = 0; public Tag( int color ) { super(); this.r = (color >> 16) / 255f; this.g = ((color >> 8) & 0xFF) / 255f; this.b = (color & 0xFF) / 255f; } @Override protected void createChildren() { super.createChildren(); bg = Chrome.get( Chrome.Type.TAG ); add( bg ); } @Override protected void layout() { super.layout(); bg.x = x; bg.y = y; bg.size( width, height ); } public void flash() { lightness = 1f; } @Override public void update() { super.update(); if (visible && lightness > 0.5) { if ((lightness -= Game.elapsed) > 0.5) { bg.ra = bg.ga = bg.ba = 2 * lightness - 1; bg.rm = 2 * r * (1 - lightness); bg.gm = 2 * g * (1 - lightness); bg.bm = 2 * b * (1 - lightness); } else { bg.hardlight( r, g, b ); } } } }
gpl-3.0
Lobz/reforged-pixel-dungeon
src/com/shatteredpixel/shatteredpixeldungeon/ui/CheckBox.java
1771
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.shatteredpixeldungeon.ui; import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene; public class CheckBox extends RedButton { private boolean checked = false; public CheckBox( String label ) { super( label ); icon( Icons.get( Icons.UNCHECKED ) ); } @Override protected void layout() { super.layout(); float margin = (height - text.baseLine()) / 2; text.x = PixelScene.align( PixelScene.uiCamera, x + margin ); text.y = PixelScene.align( PixelScene.uiCamera, y + margin ); margin = (height - icon.height) / 2; icon.x = PixelScene.align( PixelScene.uiCamera, x + width - margin - icon.width ); icon.y = PixelScene.align( PixelScene.uiCamera, y + margin ); } public boolean checked() { return checked; } public void checked( boolean value ) { if (checked != value) { checked = value; icon.copy( Icons.get( checked ? Icons.CHECKED : Icons.UNCHECKED ) ); } } @Override protected void onClick() { super.onClick(); checked( !checked ); } }
gpl-3.0
roskens/opennms-pre-github
opennms-tools/ireport-resource-query-provider/src/test/java/org/opennms/netmgt/jasper/resource/ResourceQueryFieldsProviderTest.java
6860
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.jasper.resource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRField; import net.sf.jasperreports.engine.JRQuery; import net.sf.jasperreports.engine.JRQueryChunk; import net.sf.jasperreports.engine.base.JRBaseQuery; import net.sf.jasperreports.engine.design.JRDesignDataset; import org.junit.Test; public class ResourceQueryFieldsProviderTest { private class TestDatasetImpl extends JRDesignDataset{ /** * */ private static final long serialVersionUID = 1L; public TestDatasetImpl() { super(true); } private String m_queryText = ""; public JRQuery getQuery() { JRQuery query = new JRBaseQuery() { /** * */ private static final long serialVersionUID = 1L; public JRQueryChunk[] getChunks() { return null; } public String getLanguage() { return "resourceQuery"; } public String getText() { return getQueryText(); } }; return query; } public String getQueryText() { return m_queryText; } public void setQueryText(String queryText) { m_queryText = queryText; } } @Test public void testQueryWithDsNames() throws UnsupportedOperationException, JRException { TestDatasetImpl reportDataset = new TestDatasetImpl(); reportDataset.setQueryText("--rrdDir share/rrd/snmp --nodeId 47 --resourceName opennms-jvm --dsName TotalMemory"); ResourceQueryFieldsProvider provider = new ResourceQueryFieldsProvider(); JRField[] fields = provider.getFields(null, reportDataset, null); assertNotNull(fields); assertEquals(2, fields.length); assertEquals("Path", fields[0].getName()); assertEquals("TotalMemory", fields[1].getName()); } @Test public void testQueryWithManyDsNames() throws UnsupportedOperationException, JRException { TestDatasetImpl reportDataset = new TestDatasetImpl(); reportDataset.setQueryText("--rrdDir share/rrd/snmp --nodeId 47 --resourceName opennms-jvm --dsName TotalMemory,DsName1,DsName2,DsName3"); ResourceQueryFieldsProvider provider = new ResourceQueryFieldsProvider(); JRField[] fields = provider.getFields(null, reportDataset, null); assertNotNull(fields); assertEquals(5, fields.length); assertEquals("Path", fields[0].getName()); assertEquals("TotalMemory", fields[1].getName()); assertEquals("DsName1", fields[2].getName()); assertEquals("DsName2", fields[3].getName()); assertEquals("DsName3", fields[4].getName()); } @Test public void testQueryWithStringProperties() throws UnsupportedOperationException, JRException { TestDatasetImpl reportDataset = new TestDatasetImpl(); reportDataset.setQueryText("--rrdDir share/rrd/snmp --nodeId 47 --resourceName opennms-jvm --dsName TotalMemory,DsName1,DsName2,DsName3 --string nsVpnMonVpnName"); ResourceQueryFieldsProvider provider = new ResourceQueryFieldsProvider(); JRField[] fields = provider.getFields(null, reportDataset, null); assertNotNull(fields); assertEquals(6, fields.length); assertEquals("Path", fields[0].getName()); assertEquals("TotalMemory", fields[1].getName()); assertEquals("DsName1", fields[2].getName()); assertEquals("DsName2", fields[3].getName()); assertEquals("DsName3", fields[4].getName()); assertEquals("nsVpnMonVpnName", fields[5].getName()); } @Test public void testQueryWithMultipleStringProperties() throws UnsupportedOperationException, JRException { TestDatasetImpl reportDataset = new TestDatasetImpl(); reportDataset.setQueryText("--rrdDir share/rrd/snmp --nodeId 47 --resourceName opennms-jvm --dsName TotalMemory,DsName1,DsName2,DsName3 --string nsVpnMonVpnName,name2,name3"); ResourceQueryFieldsProvider provider = new ResourceQueryFieldsProvider(); JRField[] fields = provider.getFields(null, reportDataset, null); assertNotNull(fields); assertEquals(8, fields.length); assertEquals("Path", fields[0].getName()); assertEquals("TotalMemory", fields[1].getName()); assertEquals("DsName1", fields[2].getName()); assertEquals("DsName2", fields[3].getName()); assertEquals("DsName3", fields[4].getName()); assertEquals("nsVpnMonVpnName", fields[5].getName()); assertEquals("name2", fields[6].getName()); assertEquals("name3", fields[7].getName()); } @Test public void testQueryWithoutDsNames() throws UnsupportedOperationException, JRException { TestDatasetImpl reportDataset = new TestDatasetImpl(); reportDataset.setQueryText("--rrdDir share/rrd/snmp --nodeId 47 --resourceName opennms-jvm"); ResourceQueryFieldsProvider provider = new ResourceQueryFieldsProvider(); JRField[] fields = provider.getFields(null, reportDataset, null); assertNotNull(fields); assertEquals(1, fields.length); assertEquals("Path", fields[0].getName()); } }
agpl-3.0
bhutchinson/kfs
kfs-tem/src/main/java/org/kuali/kfs/module/tem/document/web/struts/TravelStrutsObservable.java
2543
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.module.tem.document.web.struts; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import org.kuali.kfs.module.tem.document.web.bean.TravelMvcWrapperBean; public class TravelStrutsObservable extends Observable { public Map<String, List<Observer>> observers; /** * deprecating this since the best practice is to use Spring */ @Override @Deprecated public void addObserver(final Observer observer) { super.addObserver(observer); } @SuppressWarnings("null") @Override public void notifyObservers(final Object arg) { TravelMvcWrapperBean wrapper = null; if (arg instanceof TravelMvcWrapperBean) { wrapper = (TravelMvcWrapperBean) arg; } else if (arg instanceof Object[]) { final Object[] args = (Object[]) arg; if (args != null && args.length > 0 && args[0] instanceof TravelMvcWrapperBean) { wrapper = (TravelMvcWrapperBean) args[0]; } } final String eventName = wrapper.getMethodToCall(); for (final Observer observer : getObservers().get(eventName)) { observer.update(this, arg); } clearChanged(); } /** * Gets the observers attribute. * * @return Returns the observers. */ public Map<String, List<Observer>> getObservers() { return observers; } /** * Sets the observers attribute value. * * @param observers The observers to set. */ public void setObservers(final Map<String,List<Observer>> observers) { this.observers = observers; } }
agpl-3.0
siosio/intellij-community
java/java-tests/testData/refactoring/makeClassStatic/IDEADEV12762_after.java
340
class Test18 { String str; static class A { private final Test18 anObject; boolean flag; public A(Test18 anObject, boolean flag) { this.flag = flag; this.anObject = anObject; } void foo() { System.out.println("str = " + anObject.str); } } }
apache-2.0
ekoi/DANS-DVN-4.6.1
src/main/java/edu/harvard/iq/dataverse/authorization/providers/oauth2/impl/GoogleOAuth2AP.java
2685
package edu.harvard.iq.dataverse.authorization.providers.oauth2.impl; import com.github.scribejava.apis.GoogleApi20; import com.github.scribejava.core.builder.api.BaseApi; import edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo; import edu.harvard.iq.dataverse.authorization.providers.oauth2.AbstractOAuth2AuthenticationProvider; import edu.harvard.iq.dataverse.util.BundleUtil; import java.io.StringReader; import java.util.UUID; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; /** * * @author michael */ public class GoogleOAuth2AP extends AbstractOAuth2AuthenticationProvider { public GoogleOAuth2AP(String aClientId, String aClientSecret) { id = "google"; title = BundleUtil.getStringFromBundle("auth.providers.title.google"); clientId = aClientId; clientSecret = aClientSecret; scope = "https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email"; baseUserEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo"; } @Override public BaseApi getApiInstance() { return GoogleApi20.instance(); } @Override protected ParsedUserResponse parseUserResponse(String responseBody) { try ( StringReader rdr = new StringReader(responseBody); JsonReader jrdr = Json.createReader(rdr) ) { JsonObject response = jrdr.readObject(); AuthenticatedUserDisplayInfo displayInfo = new AuthenticatedUserDisplayInfo( response.getString("given_name",""), response.getString("family_name",""), response.getString("email",""), "", "" ); String persistentUserId = response.getString("id"); String username = response.getString("email"); if ( username != null ) { username = username.split("@")[0].trim(); } else { // compose a username from given and family names username = response.getString("given_name","") + "." + response.getString("family_name",""); username = username.trim(); if ( username.isEmpty() ) { username = UUID.randomUUID().toString(); } else { username = username.replaceAll(" ", "-"); } } return new ParsedUserResponse(displayInfo, persistentUserId, username); } } @Override public boolean isDisplayIdentifier() { return false; } }
apache-2.0
Guavus/hbase
hbase-client/src/main/java/org/apache/hadoop/hbase/ipc/MasterCoprocessorRpcChannel.java
3362
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.ipc; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.client.HConnection; import org.apache.hadoop.hbase.protobuf.ProtobufUtil; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos; import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse; import org.apache.hadoop.hbase.util.ByteStringer; import com.google.protobuf.Descriptors; import com.google.protobuf.Message; /** * Provides clients with an RPC connection to call coprocessor endpoint {@link com.google.protobuf.Service}s * against the active master. An instance of this class may be obtained * by calling {@link org.apache.hadoop.hbase.client.HBaseAdmin#coprocessorService()}, * but should normally only be used in creating a new {@link com.google.protobuf.Service} stub to call the endpoint * methods. * @see org.apache.hadoop.hbase.client.HBaseAdmin#coprocessorService() */ @InterfaceAudience.Private public class MasterCoprocessorRpcChannel extends CoprocessorRpcChannel{ private static Log LOG = LogFactory.getLog(MasterCoprocessorRpcChannel.class); private final HConnection connection; public MasterCoprocessorRpcChannel(HConnection conn) { this.connection = conn; } @Override protected Message callExecService(Descriptors.MethodDescriptor method, Message request, Message responsePrototype) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Call: "+method.getName()+", "+request.toString()); } final ClientProtos.CoprocessorServiceCall call = ClientProtos.CoprocessorServiceCall.newBuilder() .setRow(ByteStringer.wrap(HConstants.EMPTY_BYTE_ARRAY)) .setServiceName(method.getService().getFullName()) .setMethodName(method.getName()) .setRequest(request.toByteString()).build(); CoprocessorServiceResponse result = ProtobufUtil.execService(connection.getMaster(), call); Message response = null; if (result.getValue().hasValue()) { response = responsePrototype.newBuilderForType() .mergeFrom(result.getValue().getValue()).build(); } else { response = responsePrototype.getDefaultInstanceForType(); } if (LOG.isTraceEnabled()) { LOG.trace("Master Result is value=" + response); } return response; } }
apache-2.0
tinkerstudent/playn
robovm/src/playn/robovm/RoboCanvasState.java
978
/** * Copyright 2014 The PlayN 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 playn.robovm; /** * Maintains canvas state that is not maintained via CGContext. */ public class RoboCanvasState { RoboGradient gradient; public RoboCanvasState() { this((RoboGradient)null); } public RoboCanvasState(RoboCanvasState toCopy) { this(toCopy.gradient); } public RoboCanvasState(RoboGradient gradient) { this.gradient = gradient; } }
apache-2.0
haonaturel/DataflowJavaSDK
sdk/src/test/java/com/google/cloud/dataflow/sdk/util/GroupAlsoByWindowsDoFnTest.java
13007
/* * Copyright (C) 2015 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.google.cloud.dataflow.sdk.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import com.google.cloud.dataflow.sdk.coders.BigEndianLongCoder; import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.transforms.Combine.CombineFn; import com.google.cloud.dataflow.sdk.transforms.Combine.KeyedCombineFn; import com.google.cloud.dataflow.sdk.transforms.Sum; import com.google.cloud.dataflow.sdk.transforms.windowing.BoundedWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.FixedWindows; import com.google.cloud.dataflow.sdk.transforms.windowing.IntervalWindow; import com.google.cloud.dataflow.sdk.transforms.windowing.Sessions; import com.google.cloud.dataflow.sdk.transforms.windowing.SlidingWindows; import com.google.cloud.dataflow.sdk.util.common.CounterSet; import com.google.cloud.dataflow.sdk.values.KV; import com.google.cloud.dataflow.sdk.values.TupleTag; import org.hamcrest.Matchers; import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** Unit tests for {@link GroupAlsoByWindowsDoFn}. */ @RunWith(JUnit4.class) @SuppressWarnings({"rawtypes", "unchecked"}) public class GroupAlsoByWindowsDoFnTest { ExecutionContext execContext; CounterSet counters; TupleTag<KV<String, Iterable<String>>> outputTag; @Before public void setUp() { execContext = new DirectModeExecutionContext(); counters = new CounterSet(); outputTag = new TupleTag<>(); } @Test public void testEmpty() throws Exception { DoFnRunner<KV<String, Iterable<WindowedValue<String>>>, KV<String, Iterable<String>>, List> runner = makeRunner(WindowingStrategy.of(FixedWindows.<String>of(Duration.millis(10)))); runner.startBundle(); runner.finishBundle(); List<KV<String, Iterable<String>>> result = runner.getReceiver(outputTag); assertEquals(0, result.size()); } @Test public void testFixedWindows() throws Exception { DoFnRunner<KV<String, Iterable<WindowedValue<String>>>, KV<String, Iterable<String>>, List> runner = makeRunner(WindowingStrategy.of(FixedWindows.<String>of(Duration.millis(10)))); runner.startBundle(); runner.processElement(WindowedValue.valueInEmptyWindows( KV.of("k", (Iterable<WindowedValue<String>>) Arrays.asList( WindowedValue.of( "v1", new Instant(1), Arrays.asList(window(0, 10))), WindowedValue.of( "v2", new Instant(2), Arrays.asList(window(0, 10))), WindowedValue.of( "v3", new Instant(13), Arrays.asList(window(10, 20))))))); runner.finishBundle(); List<WindowedValue<KV<String, Iterable<String>>>> result = runner.getReceiver(outputTag); assertEquals(2, result.size()); WindowedValue<KV<String, Iterable<String>>> item0 = result.get(0); assertEquals("k", item0.getValue().getKey()); assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v1", "v2")); assertEquals(new Instant(1), item0.getTimestamp()); assertThat(item0.getWindows(), Matchers.contains(window(0, 10))); WindowedValue<KV<String, Iterable<String>>> item1 = result.get(1); assertEquals("k", item1.getValue().getKey()); assertThat(item1.getValue().getValue(), Matchers.contains("v3")); assertEquals(new Instant(13), item1.getTimestamp()); assertThat(item1.getWindows(), Matchers.contains(window(10, 20))); } @Test public void testSlidingWindows() throws Exception { DoFnRunner<KV<String, Iterable<WindowedValue<String>>>, KV<String, Iterable<String>>, List> runner = makeRunner(WindowingStrategy.of( SlidingWindows.<String>of(Duration.millis(20)).every(Duration.millis(10)))); runner.startBundle(); runner.processElement(WindowedValue.valueInEmptyWindows( KV.of("k", (Iterable<WindowedValue<String>>) Arrays.asList( WindowedValue.of( "v1", new Instant(5), Arrays.asList(window(-10, 10), window(0, 20))), WindowedValue.of( "v2", new Instant(15), Arrays.asList(window(0, 20), window(10, 30))))))); runner.finishBundle(); List<WindowedValue<KV<String, Iterable<String>>>> result = runner.getReceiver(outputTag); assertEquals(3, result.size()); WindowedValue<KV<String, Iterable<String>>> item0 = result.get(0); assertEquals("k", item0.getValue().getKey()); assertThat(item0.getValue().getValue(), Matchers.contains("v1")); assertEquals(new Instant(5), item0.getTimestamp()); assertThat(item0.getWindows(), Matchers.contains(window(-10, 10))); WindowedValue<KV<String, Iterable<String>>> item1 = result.get(1); assertEquals("k", item1.getValue().getKey()); assertThat(item1.getValue().getValue(), Matchers.containsInAnyOrder("v1", "v2")); assertEquals(new Instant(5), item1.getTimestamp()); assertThat(item1.getWindows(), Matchers.contains(window(0, 20))); WindowedValue<KV<String, Iterable<String>>> item2 = result.get(2); assertEquals("k", item2.getValue().getKey()); assertThat(item2.getValue().getValue(), Matchers.contains("v2")); assertEquals(new Instant(15), item2.getTimestamp()); assertThat(item2.getWindows(), Matchers.contains(window(10, 30))); } @Test public void testDiscontiguousWindows() throws Exception { DoFnRunner<KV<String, Iterable<WindowedValue<String>>>, KV<String, Iterable<String>>, List> runner = makeRunner(WindowingStrategy.of(FixedWindows.<String>of(Duration.millis(10)))); runner.startBundle(); runner.processElement(WindowedValue.valueInEmptyWindows( KV.of("k", (Iterable<WindowedValue<String>>) Arrays.asList( WindowedValue.of( "v1", new Instant(1), Arrays.asList(window(0, 5))), WindowedValue.of( "v2", new Instant(4), Arrays.asList(window(1, 5))), WindowedValue.of( "v3", new Instant(4), Arrays.asList(window(0, 5))))))); runner.finishBundle(); List<WindowedValue<KV<String, Iterable<String>>>> result = runner.getReceiver(outputTag); assertEquals(2, result.size()); WindowedValue<KV<String, Iterable<String>>> item0 = result.get(0); assertEquals("k", item0.getValue().getKey()); assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v1", "v3")); assertEquals(new Instant(1), item0.getTimestamp()); assertThat(item0.getWindows(), Matchers.contains(window(0, 5))); WindowedValue<KV<String, Iterable<String>>> item1 = result.get(1); assertEquals("k", item1.getValue().getKey()); assertThat(item1.getValue().getValue(), Matchers.contains("v2")); assertEquals(new Instant(4), item1.getTimestamp()); assertThat(item1.getWindows(), Matchers.contains(window(1, 5))); } @Test public void testSessions() throws Exception { DoFnRunner<KV<String, Iterable<WindowedValue<String>>>, KV<String, Iterable<String>>, List> runner = makeRunner(WindowingStrategy.of(Sessions.<String>withGapDuration(Duration.millis(10)))); runner.startBundle(); runner.processElement(WindowedValue.valueInEmptyWindows( KV.of("k", (Iterable<WindowedValue<String>>) Arrays.asList( WindowedValue.of( "v1", new Instant(0), Arrays.asList(window(0, 10))), WindowedValue.of( "v2", new Instant(5), Arrays.asList(window(5, 15))), WindowedValue.of( "v3", new Instant(15), Arrays.asList(window(15, 25))))))); runner.finishBundle(); List<WindowedValue<KV<String, Iterable<String>>>> result = runner.getReceiver(outputTag); assertEquals(2, result.size()); WindowedValue<KV<String, Iterable<String>>> item0 = result.get(0); assertEquals("k", item0.getValue().getKey()); assertThat(item0.getValue().getValue(), Matchers.containsInAnyOrder("v1", "v2")); assertEquals(new Instant(0), item0.getTimestamp()); assertThat(item0.getWindows(), Matchers.contains(window(0, 15))); WindowedValue<KV<String, Iterable<String>>> item1 = result.get(1); assertEquals("k", item1.getValue().getKey()); assertThat(item1.getValue().getValue(), Matchers.contains("v3")); assertEquals(new Instant(15), item1.getTimestamp()); assertThat(item1.getWindows(), Matchers.contains(window(15, 25))); } @Test public void testSessionsCombine() throws Exception { CombineFn<Long, ?, Long> combineFn = new Sum.SumLongFn(); DoFnRunner<KV<String, Iterable<WindowedValue<Long>>>, KV<String, Long>, List> runner = makeRunner(WindowingStrategy.of(Sessions.<String>withGapDuration(Duration.millis(10))), combineFn.<String>asKeyedFn()); runner.startBundle(); runner.processElement(WindowedValue.valueInEmptyWindows( KV.of("k", (Iterable<WindowedValue<Long>>) Arrays.asList( WindowedValue.of( 1L, new Instant(0), Arrays.asList(window(0, 10))), WindowedValue.of( 2L, new Instant(5), Arrays.asList(window(5, 15))), WindowedValue.of( 4L, new Instant(15), Arrays.asList(window(15, 25))))))); runner.finishBundle(); List<WindowedValue<KV<String, Long>>> result = runner.getReceiver(outputTag); assertEquals(2, result.size()); WindowedValue<KV<String, Long>> item0 = result.get(0); assertEquals("k", item0.getValue().getKey()); assertEquals(3L, item0.getValue().getValue().longValue()); assertEquals(new Instant(0), item0.getTimestamp()); assertThat(item0.getWindows(), Matchers.contains(window(0, 15))); WindowedValue<KV<String, Long>> item1 = result.get(1); assertEquals("k", item1.getValue().getKey()); assertEquals(4L, item1.getValue().getValue().longValue()); assertEquals(new Instant(15), item1.getTimestamp()); assertThat(item1.getWindows(), Matchers.contains(window(15, 25))); } private DoFnRunner<KV<String, Iterable<WindowedValue<String>>>, KV<String, Iterable<String>>, List> makeRunner( WindowingStrategy<? super String, IntervalWindow> windowingStrategy) { GroupAlsoByWindowsDoFn<String, String, Iterable<String>, IntervalWindow> fn = GroupAlsoByWindowsDoFn.createForIterable(windowingStrategy, StringUtf8Coder.of()); return makeRunner(windowingStrategy, fn); } private DoFnRunner<KV<String, Iterable<WindowedValue<Long>>>, KV<String, Long>, List> makeRunner( WindowingStrategy<? super String, IntervalWindow> windowingStrategy, KeyedCombineFn<String, Long, ?, Long> combineFn) { GroupAlsoByWindowsDoFn<String, Long, Long, IntervalWindow> fn = GroupAlsoByWindowsDoFn.create( windowingStrategy, combineFn, StringUtf8Coder.of(), BigEndianLongCoder.of()); return makeRunner(windowingStrategy, fn); } private <VI, VO> DoFnRunner<KV<String, Iterable<WindowedValue<VI>>>, KV<String, VO>, List> makeRunner( WindowingStrategy<? super String, IntervalWindow> windowingStrategy, GroupAlsoByWindowsDoFn<String, VI, VO, IntervalWindow> fn) { return DoFnRunner.createWithListOutputs( PipelineOptionsFactory.create(), fn, PTuple.empty(), (TupleTag<KV<String, VO>>) (TupleTag) outputTag, new ArrayList<TupleTag<?>>(), execContext.createStepContext("merge"), counters.getAddCounterMutator(), windowingStrategy); } private BoundedWindow window(long start, long end) { return new IntervalWindow(new Instant(start), new Instant(end)); } }
apache-2.0
AliaksandrShuhayeu/pentaho-kettle
plugins/repositories/core/src/main/java/org/pentaho/di/ui/repo/model/LoginModel.java
1351
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.repo.model; /** * Created by bmorrise on 10/20/16. */ public class LoginModel { private String username; private String password; public String getUsername() { return username; } public void setUsername( String username ) { this.username = username; } public String getPassword() { return password; } public void setPassword( String password ) { this.password = password; } }
apache-2.0
Nimco/sling
tooling/ide/eclipse-core/src/org/apache/sling/ide/eclipse/core/internal/SlingLaunchpadBehaviour.java
25793
/* * 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.ide.eclipse.core.internal; import static org.apache.sling.ide.artifacts.EmbeddedArtifactLocator.SUPPORT_BUNDLE_SYMBOLIC_NAME; import static org.apache.sling.ide.artifacts.EmbeddedArtifactLocator.SUPPORT_SOURCE_BUNDLE_SYMBOLIC_NAME; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.sling.ide.artifacts.EmbeddedArtifact; import org.apache.sling.ide.artifacts.EmbeddedArtifactLocator; import org.apache.sling.ide.eclipse.core.ISlingLaunchpadServer; import org.apache.sling.ide.eclipse.core.ServerUtil; import org.apache.sling.ide.log.Logger; import org.apache.sling.ide.osgi.OsgiClient; import org.apache.sling.ide.osgi.OsgiClientException; import org.apache.sling.ide.serialization.SerializationException; import org.apache.sling.ide.transport.Batcher; import org.apache.sling.ide.transport.Command; import org.apache.sling.ide.transport.Repository; import org.apache.sling.ide.transport.RepositoryInfo; import org.apache.sling.ide.transport.ResourceProxy; import org.apache.sling.ide.transport.Result; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.model.IModuleResource; import org.eclipse.wst.server.core.model.IModuleResourceDelta; import org.eclipse.wst.server.core.model.ServerBehaviourDelegate; import org.osgi.framework.Version; public class SlingLaunchpadBehaviour extends ServerBehaviourDelegateWithModulePublishSupport { private ResourceChangeCommandFactory commandFactory; private ILaunch launch; private JVMDebuggerConnection debuggerConnection; @Override public void stop(boolean force) { if (debuggerConnection!=null) { debuggerConnection.stop(force); } setServerState(IServer.STATE_STOPPED); try { ServerUtil.stopRepository(getServer(), new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().getPluginLogger().warn("Failed to stop repository", e); } } public void start(IProgressMonitor monitor) throws CoreException { boolean success = false; Result<ResourceProxy> result = null; monitor = SubMonitor.convert(monitor, "Starting server", 10).setWorkRemaining(50); Repository repository; RepositoryInfo repositoryInfo; OsgiClient client; try { repository = ServerUtil.connectRepository(getServer(), monitor); repositoryInfo = ServerUtil.getRepositoryInfo(getServer(), monitor); client = Activator.getDefault().getOsgiClientFactory().createOsgiClient(repositoryInfo); } catch (CoreException e) { setServerState(IServer.STATE_STOPPED); throw e; } catch (URISyntaxException e) { setServerState(IServer.STATE_STOPPED); throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e)); } monitor.worked(10); // 10/50 done try { EmbeddedArtifactLocator artifactLocator = Activator.getDefault().getArtifactLocator(); installBundle(monitor,client, artifactLocator.loadSourceSupportBundle(), SUPPORT_SOURCE_BUNDLE_SYMBOLIC_NAME); // 15/50 done installBundle(monitor,client, artifactLocator.loadToolingSupportBundle(), SUPPORT_BUNDLE_SYMBOLIC_NAME); // 20/50 done } catch ( IOException | OsgiClientException e) { Activator.getDefault().getPluginLogger() .warn("Failed reading the installation support bundle", e); } try { if (getServer().getMode().equals(ILaunchManager.DEBUG_MODE)) { debuggerConnection = new JVMDebuggerConnection(client); success = debuggerConnection.connectInDebugMode(launch, getServer(), SubMonitor.convert(monitor, 30)); // 50/50 done } else { Command<ResourceProxy> command = repository.newListChildrenNodeCommand("/"); result = command.execute(); success = result.isSuccess(); monitor.worked(30); // 50/50 done } if (success) { setServerState(IServer.STATE_STARTED); } else { setServerState(IServer.STATE_STOPPED); String message = "Unable to connect to the Server. Please make sure a server instance is running "; if (result != null) { message += " (" + result.toString() + ")"; } throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, message)); } } catch ( CoreException | RuntimeException e ) { setServerState(IServer.STATE_STOPPED); throw e; } finally { monitor.done(); } } private void installBundle(IProgressMonitor monitor, OsgiClient client, final EmbeddedArtifact bundle, String bundleSymbolicName) throws OsgiClientException, IOException { Version embeddedVersion = new Version(bundle.getOsgiFriendlyVersion()); monitor.setTaskName("Installing " + bundleSymbolicName + " " + embeddedVersion); Version remoteVersion = client.getBundleVersion(bundleSymbolicName); monitor.worked(2); ISlingLaunchpadServer launchpadServer = (ISlingLaunchpadServer) getServer().loadAdapter(SlingLaunchpadServer.class, monitor); if (remoteVersion == null || remoteVersion.compareTo(embeddedVersion) < 0 || ( remoteVersion.equals(embeddedVersion) || "SNAPSHOT".equals(embeddedVersion.getQualifier()))) { try ( InputStream contents = bundle.openInputStream() ){ client.installBundle(contents, bundle.getName()); } remoteVersion = embeddedVersion; } launchpadServer.setBundleVersion(bundleSymbolicName, remoteVersion, monitor); monitor.worked(3); } // TODO refine signature public void setupLaunch(ILaunch launch, String launchMode, IProgressMonitor monitor) throws CoreException { // TODO check that ports are free this.launch = launch; setServerRestartState(false); setServerState(IServer.STATE_STARTING); setMode(launchMode); } @Override protected void publishModule(int kind, int deltaKind, IModule[] module, IProgressMonitor monitor) throws CoreException { Logger logger = Activator.getDefault().getPluginLogger(); if (commandFactory == null) { commandFactory = new ResourceChangeCommandFactory(Activator.getDefault().getSerializationManager()); } logger.trace(traceOperation(kind, deltaKind, module)); if (getServer().getServerState() == IServer.STATE_STOPPED) { logger.trace("Ignoring request to publish module when the server is stopped"); setModulePublishState(module, IServer.PUBLISH_STATE_NONE); return; } if ((kind == IServer.PUBLISH_AUTO || kind == IServer.PUBLISH_INCREMENTAL) && deltaKind == ServerBehaviourDelegate.NO_CHANGE) { logger.trace("Ignoring request to publish the module when no resources have changed; most likely another module has changed"); setModulePublishState(module, IServer.PUBLISH_STATE_NONE); return; } if (kind == IServer.PUBLISH_FULL && deltaKind == ServerBehaviourDelegate.REMOVED) { logger.trace("Ignoring request to unpublish all of the module resources"); setModulePublishState(module, IServer.PUBLISH_STATE_NONE); return; } if (ProjectHelper.isBundleProject(module[0].getProject())) { String serverMode = getServer().getMode(); if (!serverMode.equals(ILaunchManager.DEBUG_MODE) || kind==IServer.PUBLISH_CLEAN) { // in debug mode, we rely on the hotcode replacement feature of eclipse/jvm // otherwise, for run and profile modes we explicitly publish the bundle module // TODO: make this configurable as part of the server config // SLING-3655 : when doing PUBLISH_CLEAN, the bundle deployment mechanism should // still be triggered publishBundleModule(module, monitor); } } else if (ProjectHelper.isContentProject(module[0].getProject())) { try { publishContentModule(kind, deltaKind, module, monitor); } catch (SerializationException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Serialization error for " + traceOperation(kind, deltaKind, module).toString(), e)); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "IO error for " + traceOperation(kind, deltaKind, module).toString(), e)); } } } private String traceOperation(int kind, int deltaKind, IModule[] module) { StringBuilder trace = new StringBuilder(); trace.append("SlingLaunchpadBehaviour.publishModule("); switch (kind) { case IServer.PUBLISH_CLEAN: trace.append("PUBLISH_CLEAN, "); break; case IServer.PUBLISH_INCREMENTAL: trace.append("PUBLISH_INCREMENTAL, "); break; case IServer.PUBLISH_AUTO: trace.append("PUBLISH_AUTO, "); break; case IServer.PUBLISH_FULL: trace.append("PUBLISH_FULL, "); break; default: trace.append("UNKNOWN - ").append(kind).append(", "); } switch (deltaKind) { case ServerBehaviourDelegate.ADDED: trace.append("ADDED, "); break; case ServerBehaviourDelegate.CHANGED: trace.append("CHANGED, "); break; case ServerBehaviourDelegate.NO_CHANGE: trace.append("NO_CHANGE, "); break; case ServerBehaviourDelegate.REMOVED: trace.append("REMOVED, "); break; default: trace.append("UNKONWN - ").append(deltaKind).append(", "); break; } switch (getServer().getServerState()) { case IServer.STATE_STARTED: trace.append("STARTED, "); break; case IServer.STATE_STARTING: trace.append("STARTING, "); break; case IServer.STATE_STOPPED: trace.append("STOPPED, "); break; case IServer.STATE_STOPPING: trace.append("STOPPING, "); break; default: trace.append("UNKONWN - ").append(getServer().getServerState()).append(", "); break; } trace.append(Arrays.toString(module)).append(")"); return trace.toString(); } private void publishBundleModule(IModule[] module, IProgressMonitor monitor) throws CoreException { final IProject project = module[0].getProject(); boolean installLocally = getServer().getAttribute(ISlingLaunchpadServer.PROP_INSTALL_LOCALLY, true); monitor.beginTask("deploying via local install", 5); try { OsgiClient osgiClient = Activator.getDefault().getOsgiClientFactory() .createOsgiClient(ServerUtil.getRepositoryInfo(getServer(), monitor)); Version supportBundleVersion = osgiClient .getBundleVersion(EmbeddedArtifactLocator.SUPPORT_BUNDLE_SYMBOLIC_NAME); monitor.worked(1); if (supportBundleVersion == null) { throw new CoreException(new Status(Status.ERROR, Activator.PLUGIN_ID, "The support bundle was not found, please install it via the server properties page.")); } IJavaProject javaProject = ProjectHelper.asJavaProject(project); IFolder outputFolder = (IFolder) project.getWorkspace().getRoot().findMember(javaProject.getOutputLocation()); IPath outputLocation = outputFolder.getLocation(); //ensure the MANIFEST.MF exists - if it doesn't then let the publish fail with a warn (instead of an error) IResource manifest = outputFolder.findMember("META-INF/MANIFEST.MF"); if (manifest==null) { Activator.getDefault().getPluginLogger().warn("Project "+project+" does not have a META-INF/MANIFEST.MF (yet) - not publishing this time"); Activator.getDefault().issueConsoleLog("InstallBundle", outputFolder.getLocation().toOSString(), "Project "+project+" does not have a META-INF/MANIFEST.MF (yet) - not publishing this time"); monitor.done(); setModulePublishState(module, IServer.PUBLISH_STATE_FULL); return; } monitor.worked(1); //TODO SLING-3767: //osgiClient must have a timeout!!! if ( installLocally ) { osgiClient.installLocalBundle(outputLocation.toOSString()); monitor.worked(3); } else { JarBuilder builder = new JarBuilder(); InputStream bundle = builder.buildJar(outputFolder); monitor.worked(1); osgiClient.installLocalBundle(bundle, outputFolder.getLocation().toOSString()); monitor.worked(2); } setModulePublishState(module, IServer.PUBLISH_STATE_NONE); } catch (URISyntaxException e1) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e1.getMessage(), e1)); } catch (OsgiClientException e1) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed installing bundle : " + e1.getMessage(), e1)); } finally { monitor.done(); } } private void publishContentModule(int kind, int deltaKind, IModule[] module, IProgressMonitor monitor) throws CoreException, SerializationException, IOException { Logger logger = Activator.getDefault().getPluginLogger(); Repository repository = ServerUtil.getConnectedRepository(getServer(), monitor); if (repository == null) { throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Unable to find a repository for server " + getServer())); } Batcher batcher = Activator.getDefault().getBatcherFactory().createBatcher(); // TODO it would be more efficient to have a module -> filter mapping // it would be simpler to implement this in SlingContentModuleAdapter, but // the behaviour for resources being filtered out is deletion, and that // would be an incorrect ( or at least suprising ) behaviour at development time List<IModuleResource> addedOrUpdatedResources = new ArrayList<>(); IModuleResource[] allResources = getResources(module); Set<IPath> handledPaths = new HashSet<>(); switch (deltaKind) { case ServerBehaviourDelegate.CHANGED: for (IModuleResourceDelta resourceDelta : getPublishedResourceDelta(module)) { StringBuilder deltaTrace = new StringBuilder(); deltaTrace.append("- processing delta kind "); switch (resourceDelta.getKind()) { case IModuleResourceDelta.ADDED: deltaTrace.append("ADDED "); break; case IModuleResourceDelta.CHANGED: deltaTrace.append("CHANGED "); break; case IModuleResourceDelta.NO_CHANGE: deltaTrace.append("NO_CHANGE "); break; case IModuleResourceDelta.REMOVED: deltaTrace.append("REMOVED "); break; default: deltaTrace.append("UNKNOWN - ").append(resourceDelta.getKind()); } deltaTrace.append("for resource ").append(resourceDelta.getModuleResource()); logger.trace(deltaTrace.toString()); switch (resourceDelta.getKind()) { case IModuleResourceDelta.ADDED: case IModuleResourceDelta.CHANGED: case IModuleResourceDelta.NO_CHANGE: // TODO is this needed? Command<?> command = addFileCommand(repository, resourceDelta.getModuleResource()); if (command != null) { ensureParentIsPublished(resourceDelta.getModuleResource(), repository, allResources, handledPaths, batcher); addedOrUpdatedResources.add(resourceDelta.getModuleResource()); } enqueue(batcher, command); break; case IModuleResourceDelta.REMOVED: enqueue(batcher, removeFileCommand(repository, resourceDelta.getModuleResource())); break; } } break; case ServerBehaviourDelegate.ADDED: case ServerBehaviourDelegate.NO_CHANGE: // TODO is this correct ? for (IModuleResource resource : getResources(module)) { Command<?> command = addFileCommand(repository, resource); enqueue(batcher, command); if (command != null) { addedOrUpdatedResources.add(resource); } } break; case ServerBehaviourDelegate.REMOVED: for (IModuleResource resource : getResources(module)) { enqueue(batcher, removeFileCommand(repository, resource)); } break; } // reorder the child nodes at the end, when all create/update/deletes have been processed for (IModuleResource resource : addedOrUpdatedResources) { enqueue(batcher, reorderChildNodesCommand(repository, resource)); } execute(batcher); // set state to published super.publishModule(kind, deltaKind, module, monitor); setModulePublishState(module, IServer.PUBLISH_STATE_NONE); // setServerPublishState(IServer.PUBLISH_STATE_NONE); } private void execute(Batcher batcher) throws CoreException { for ( Command<?> command : batcher.get()) { Result<?> result = command.execute(); if (!result.isSuccess()) { // TODO - proper error logging throw new CoreException(new Status(Status.ERROR, Activator.PLUGIN_ID, "Failed publishing path=" + command.getPath() + ", result=" + result.toString())); } } } /** * Ensures that the parent of this resource has been published to the repository * * <p> * Note that the parents explicitly do not have their child nodes reordered, this will happen when they are * published due to a resource change * </p> * * @param moduleResource the current resource * @param repository the repository to publish to * @param allResources all of the module's resources * @param handledPaths the paths that have been handled already in this publish operation, but possibly not * registered as published * @param batcher * @throws IOException * @throws SerializationException * @throws CoreException */ private void ensureParentIsPublished(IModuleResource moduleResource, Repository repository, IModuleResource[] allResources, Set<IPath> handledPaths, Batcher batcher) throws CoreException, SerializationException, IOException { Logger logger = Activator.getDefault().getPluginLogger(); IPath currentPath = moduleResource.getModuleRelativePath(); logger.trace("Ensuring that parent of path {0} is published", currentPath); // we assume the root is always published if (currentPath.segmentCount() == 0) { logger.trace("Path {0} can not have a parent, skipping", currentPath); return; } IPath parentPath = currentPath.removeLastSegments(1); // already published by us, a parent of another resource that was published in this execution if (handledPaths.contains(parentPath)) { logger.trace("Parent path {0} was already handled, skipping", parentPath); return; } for (IModuleResource maybeParent : allResources) { if (maybeParent.getModuleRelativePath().equals(parentPath)) { // handle the parent's parent first, if needed ensureParentIsPublished(maybeParent, repository, allResources, handledPaths, batcher); // create this resource enqueue(batcher, addFileCommand(repository, maybeParent)); handledPaths.add(maybeParent.getModuleRelativePath()); logger.trace("Ensured that resource at path {0} is published", parentPath); return; } } throw new IllegalArgumentException("Resource at " + moduleResource.getModuleRelativePath() + " has parent path " + parentPath + " but no resource with that path is in the module's resources."); } private void enqueue(Batcher batcher, Command<?> command) { if (command == null) { return; } batcher.add(command); } private Command<?> addFileCommand(Repository repository, IModuleResource resource) throws CoreException, SerializationException, IOException { IResource res = getResource(resource); if (res == null) { return null; } return commandFactory.newCommandForAddedOrUpdated(repository, res); } private Command<?> reorderChildNodesCommand(Repository repository, IModuleResource resource) throws CoreException, SerializationException, IOException { IResource res = getResource(resource); if (res == null) { return null; } return commandFactory.newReorderChildNodesCommand(repository, res); } private IResource getResource(IModuleResource resource) { IResource file = (IFile) resource.getAdapter(IFile.class); if (file == null) { file = (IFolder) resource.getAdapter(IFolder.class); } if (file == null) { // Usually happens on server startup, it seems to be safe to ignore for now Activator.getDefault().getPluginLogger() .trace("Got null {0} and {1} for {2}", IFile.class.getSimpleName(), IFolder.class.getSimpleName(), resource); return null; } return file; } private Command<?> removeFileCommand(Repository repository, IModuleResource resource) throws SerializationException, IOException, CoreException { IResource deletedResource = getResource(resource); if (deletedResource == null) { return null; } return commandFactory.newCommandForRemovedResources(repository, deletedResource); } }
apache-2.0
rmulvey/bridgepoint
src/org.xtuml.bp.debug.ui/src/org/xtuml/bp/debug/ui/model/BPBreakpoint.java
10881
//======================================================================== // 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.xtuml.bp.debug.ui.model; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.model.Breakpoint; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.model.IWorkbenchAdapter; import org.xtuml.bp.core.Breakpoint_c; import org.xtuml.bp.core.Condition_c; import org.xtuml.bp.core.Gd_c; import org.xtuml.bp.core.Instance_c; import org.xtuml.bp.core.ModelClass_c; import org.xtuml.bp.core.Ooaofooa; import org.xtuml.bp.core.ProvidedOperation_c; import org.xtuml.bp.core.ProvidedSignal_c; import org.xtuml.bp.core.RequiredOperation_c; import org.xtuml.bp.core.RequiredSignal_c; import org.xtuml.bp.core.common.NonRootModelElement; import org.xtuml.bp.debug.ui.IBPDebugUIPluginConstants; import org.xtuml.bp.debug.ui.ModelElementLocation; public abstract class BPBreakpoint extends Breakpoint implements IBPBreakpoint, IWorkbenchAdapter { /** * List of active instance filters for this breakpoint * (list of <code>Instance_c</code>). */ protected List fInstanceFilters = null; /** * Empty instance filters array. */ protected static final Instance_c[] fgEmptyInstanceFilters = new Instance_c[0]; /** * Default constructor is required for the breakpoint manager * to re-create persisted breakpoints. After instantiating a breakpoint, * the <code>setMarker(...)</code> method is called to restore * this breakpoint's attributes. */ public BPBreakpoint() { } /** * @param resource file on which to set the breakpoint * @throws CoreException if unable to create the breakpoint */ public BPBreakpoint(final String markerType, NonRootModelElement nrme, final int flags_all) throws CoreException { IResource resource = (IResource)nrme.getModelRoot().getPersistenceFile(); init(resource, markerType, nrme, flags_all, "", 0); //$NON-NLS-1$ setHitCount(0); } protected void init(final IResource resource, final String markerType, NonRootModelElement nrme, final int flags_all, final String optionalAttribute, final int optionalAttrValue) throws DebugException { final String mr_id = nrme.getModelRoot().getId(); final String location = ModelElementLocation.getModelElementLocation(nrme); String ooa_id = String.valueOf(nrme.Get_ooa_id()); if(ooa_id.equals(Gd_c.Null_unique_id().toString())) { if(nrme instanceof RequiredOperation_c) { ooa_id = ((RequiredOperation_c) nrme).getId().toString(); } else if (nrme instanceof RequiredSignal_c) { ooa_id = ((RequiredSignal_c) nrme).getId().toString(); } else if (nrme instanceof ProvidedOperation_c) { ooa_id = ((ProvidedOperation_c) nrme).getId().toString(); } else if (nrme instanceof ProvidedSignal_c) { ooa_id = ((ProvidedSignal_c) nrme).getId().toString(); } } final String final_id = ooa_id; //final ModelElementID modelElementID = ModelAdapter.getModelElementAdapter(nrme).createModelElementID(nrme); IWorkspaceRunnable runnable = new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { IMarker marker = resource.createMarker(markerType); setMarker(marker); marker.setAttribute(IBreakpoint.ENABLED, true); marker.setAttribute(IBreakpoint.ID, getModelIdentifier()+"/" + location); marker.setAttribute(MODELROOT_ID, mr_id); marker.setAttribute(MODELELEMENT_ID, final_id); marker.setAttribute(LOCATION, location); marker.setAttribute(CONDITION, ""); marker.setAttribute(CONDITION_ENABLED, false); marker.setAttribute(FLAGS, flags_all); if ( !optionalAttribute.equals("") ) { //$NON-NLS-1$ marker.setAttribute(optionalAttribute, optionalAttrValue); } setHitCount(0); } }; run(getMarkerRule(resource), runnable); } public String getModelIdentifier() { return IBPDebugUIPluginConstants.PLUGIN_ID; } /* (non-Javadoc) * @see org.xtuml.bp.debug.ui.model.IBPBreakpoint#getTypeName() */ public String getTypeName() throws CoreException { return "Class:"; } public void setLocation(String location) throws CoreException { if (!location.equals(getCondition())) { setAttribute(LOCATION, location); } } public String getLocation() throws CoreException { return ensureMarker().getAttribute(LOCATION, ""); } /* (non-Javadoc) * @see org.xtuml.bp.debug.ui.model.IBPBreakpoint#setHitCount(int) */ public void setHitCount(int hitCount) throws CoreException { if (hitCount != getHitCount()) { setAttribute(HIT_COUNT, hitCount); if ( hitCount > 0 ) { String message = getLocation() + " [hit count: " + hitCount + "]"; ensureMarker().setAttribute(IMarker.MESSAGE, message); } else { String message = getLocation(); ensureMarker().setAttribute(IMarker.MESSAGE, message); } } } /* (non-Javadoc) * @see org.xtuml.bp.debug.ui.model.IBPBreakpoint#getHitCount() */ public int getHitCount() throws CoreException { return ensureMarker().getAttribute(HIT_COUNT, -1); } public void setCondition(String condition) throws CoreException { if (!condition.equals(getCondition())) { setAttribute(CONDITION, condition); } } public String getCondition() throws CoreException { return ensureMarker().getAttribute(CONDITION, ""); } public boolean isConditionEnabled() throws CoreException { return ensureMarker().getAttribute(CONDITION_ENABLED, false); } public void setConditionEnabled(boolean enableCondition) throws CoreException { if ( isConditionEnabled() != enableCondition ) { setAttribute(CONDITION_ENABLED, enableCondition); } } public boolean supportsCondition() { return false; } public boolean supportsHitCount() { return true; } public boolean getFlag(int flag, int all_flags, boolean defaultValue) { IMarker m = getMarker(); if (m != null) { int flags = m.getAttribute(FLAGS, all_flags); return (flags & flag) != 0; } return defaultValue; } public void setFlag(boolean condition, int flag, int all_flags) throws CoreException { IMarker m = getMarker(); if (m != null) { int flags = m.getAttribute(FLAGS, all_flags); if ( condition ) { flags = flags | flag; } else { flags = flags & ~flag; } m.setAttribute(FLAGS, flags); } } public String getText() { IMarker m = getMarker(); if (m != null) { return getTextDetail() + " " + m.getAttribute(IMarker.MESSAGE, ""); } return ""; } public boolean supportsInstanceFilters() { return false; } public Instance_c[] getInstanceFilters() { if (fInstanceFilters == null || fInstanceFilters.isEmpty()) { return fgEmptyInstanceFilters; } return (Instance_c[])fInstanceFilters.toArray(new Instance_c[fInstanceFilters.size()]); } public void clearInstanceFilters() { if (fInstanceFilters != null) { fInstanceFilters.clear(); fInstanceFilters = null; fireChanged(); } } public void addInstanceFilter(Instance_c object) { if (fInstanceFilters == null) { fInstanceFilters = new ArrayList(); } fInstanceFilters.add(object); fireChanged(); } /** * Change notification when there are no marker changes. If the marker * does not exist, do not fire a change notification (the marker may not * exist if the associated project was closed). */ protected void fireChanged() { if (markerExists()) { DebugPlugin.getDefault().getBreakpointManager().fireBreakpointChanged(this); } } public ModelClass_c[] getAllClasses() { IMarker m = getMarker(); if (m != null) { String mr_id = m.getAttribute(MODELROOT_ID, ""); //$NON_NLS-1$ Ooaofooa x = Ooaofooa.getInstance(mr_id); ModelClass_c [] ret_val = ModelClass_c.ModelClassInstances(x); return ret_val; } return new ModelClass_c[0]; } public Object[] getChildren(Object o) { return null; } public ImageDescriptor getImageDescriptor(Object object) { return null; } public String getLabel(Object o) { // more specific labels will be supplied by overrides in subtypes return "Breakpoint"; } public Object getParent(Object o) { return null; } protected boolean managerEnabled() { return DebugPlugin.getDefault().getBreakpointManager().isEnabled(); } public void modifyTargetBreakpoint(Breakpoint_c bp, String string, Object newAttr) { if ( string.equals(ENABLED) ) { boolean newValue = ((Boolean)newAttr).booleanValue(); if (!managerEnabled()) { newValue = false; } bp.setEnabled(newValue); } else if ( string.equals(HIT_COUNT) ) { int newValue = ((Integer)newAttr).intValue(); bp.setTarget_hit_count(newValue); } else if ( string.equals(CONDITION_ENABLED) ) { boolean newValue = ((Boolean)newAttr).booleanValue(); bp.setCondition_enabled(newValue); } else if ( string.equals(CONDITION) ) { String newValue = (String)newAttr; Condition_c cond = Condition_c.getOneBP_CONOnR3100(bp); if ( cond == null ) { cond = new Condition_c(bp.getModelRoot()); cond.relateAcrossR3100To(bp); } cond.setExpression(newValue); } } protected String getTextDetail() { // Subtypes should override this to provide more // detail than just the data stored in the Marker return ""; } /** * Deletes this breakpoint's underlying marker, and removes * this breakpoint from the breakpoint manager. * * @override * @exception CoreException if unable to delete this breakpoint's * underlying marker */ public void delete() throws CoreException { deleteTargetBreakpoint(); super.delete(); } }
apache-2.0
wso2/siddhi
modules/siddhi-core/src/main/java/io/siddhi/core/query/processor/SchedulingProcessor.java
980
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.core.query.processor; import io.siddhi.core.util.Scheduler; /** * Parent interface for Processors which need access to Siddhi {@link Scheduler} */ public interface SchedulingProcessor extends Processor { Scheduler getScheduler(); void setScheduler(Scheduler scheduler); }
apache-2.0
droolsjbpm/drools
drools-ruleunit/src/test/java/org/drools/ruleunit/SimpleFact.java
887
/* * Copyright 2018 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.ruleunit; public class SimpleFact { private final String stringValue; public SimpleFact(final String stringValue) { this.stringValue = stringValue; } public String getStringValue() { return stringValue; } }
apache-2.0
gretchiemoran/pentaho-kettle
ui/src/org/pentaho/di/ui/trans/steps/mapping/MappingDialog.java
70861
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2013 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.trans.steps.mapping; import org.apache.commons.vfs2.FileObject; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabFolder2Adapter; import org.eclipse.swt.custom.CTabFolderEvent; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; 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.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; 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.ObjectLocationSpecificationMethod; import org.pentaho.di.core.Props; import org.pentaho.di.core.SourceToTargetMapping; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.core.gui.SpoonInterface; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.RepositoryDirectoryInterface; import org.pentaho.di.repository.RepositoryElementMetaInterface; import org.pentaho.di.repository.RepositoryObject; import org.pentaho.di.repository.RepositoryObjectType; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.mapping.MappingIODefinition; import org.pentaho.di.trans.steps.mapping.MappingMeta; import org.pentaho.di.trans.steps.mapping.MappingParameters; import org.pentaho.di.trans.steps.mapping.MappingValueRename; import org.pentaho.di.trans.steps.mappinginput.MappingInputMeta; import org.pentaho.di.trans.steps.mappingoutput.MappingOutputMeta; import org.pentaho.di.ui.core.dialog.EnterMappingDialog; import org.pentaho.di.ui.core.dialog.EnterSelectionDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.gui.GUIResource; 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.repository.dialog.SelectObjectDialog; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.trans.dialog.TransDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.vfs.ui.VfsFileChooserDialog; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MappingDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = MappingMeta.class; // for i18n purposes, needed by Translator2!! private MappingMeta mappingMeta; // File // private Button radioFilename; private Button wbbFilename; private TextVar wFilename; // Repository by name // private Button radioByName; private TextVar wTransname, wDirectory; private Button wbTrans; // Repository by reference // private Button radioByReference; private Button wbByReference; private TextVar wByReference; private CTabFolder wTabFolder; private TransMeta mappingTransMeta = null; protected boolean transModified; private ModifyListener lsMod; private int middle; private int margin; private MappingParameters mappingParameters; private List<MappingIODefinition> inputMappings; private List<MappingIODefinition> outputMappings; private Button wAddInput; private Button wAddOutput; private ObjectId referenceObjectId; private ObjectLocationSpecificationMethod specificationMethod; private Button wMultiInput, wMultiOutput; private interface ApplyChanges { public void applyChanges(); } private class MappingParametersTab implements ApplyChanges { private TableView wMappingParameters; private MappingParameters parameters; private Button wInheritAll; public MappingParametersTab( TableView wMappingParameters, Button wInheritAll, MappingParameters parameters ) { this.wMappingParameters = wMappingParameters; this.wInheritAll = wInheritAll; this.parameters = parameters; } public void applyChanges() { int nrLines = wMappingParameters.nrNonEmpty(); String[] variables = new String[ nrLines ]; String[] inputFields = new String[ nrLines ]; parameters.setVariable( variables ); parameters.setInputField( inputFields ); //CHECKSTYLE:Indentation:OFF for ( int i = 0; i < nrLines; i++ ) { TableItem item = wMappingParameters.getNonEmpty( i ); parameters.getVariable()[ i ] = item.getText( 1 ); parameters.getInputField()[ i ] = item.getText( 2 ); } parameters.setInheritingAllVariables( wInheritAll.getSelection() ); } } private class MappingDefinitionTab implements ApplyChanges { private MappingIODefinition definition; private Text wInputStep; private Text wOutputStep; private Button wMainPath; private Text wDescription; private TableView wFieldMappings; public MappingDefinitionTab( MappingIODefinition definition, Text inputStep, Text outputStep, Button mainPath, Text description, TableView fieldMappings ) { super(); this.definition = definition; wInputStep = inputStep; wOutputStep = outputStep; wMainPath = mainPath; wDescription = description; wFieldMappings = fieldMappings; } public void applyChanges() { // The input step definition.setInputStepname( wInputStep.getText() ); // The output step definition.setOutputStepname( wOutputStep.getText() ); // The description definition.setDescription( wDescription.getText() ); // The main path flag definition.setMainDataPath( wMainPath.getSelection() ); // The grid // int nrLines = wFieldMappings.nrNonEmpty(); definition.getValueRenames().clear(); for ( int i = 0; i < nrLines; i++ ) { TableItem item = wFieldMappings.getNonEmpty( i ); definition.getValueRenames().add( new MappingValueRename( item.getText( 1 ), item.getText( 2 ) ) ); } } } private List<ApplyChanges> changeList; public MappingDialog( Shell parent, Object in, TransMeta tr, String sname ) { super( parent, (BaseStepMeta) in, tr, sname ); mappingMeta = (MappingMeta) in; transModified = false; // Make a copy for our own purposes... // This allows us to change everything directly in the classes with // listeners. // Later we need to copy it to the input class on ok() // mappingParameters = (MappingParameters) mappingMeta.getMappingParameters().clone(); inputMappings = new ArrayList<MappingIODefinition>(); outputMappings = new ArrayList<MappingIODefinition>(); for ( int i = 0; i < mappingMeta.getInputMappings().size(); i++ ) { inputMappings.add( (MappingIODefinition) mappingMeta.getInputMappings().get( i ).clone() ); } for ( int i = 0; i < mappingMeta.getOutputMappings().size(); i++ ) { outputMappings.add( (MappingIODefinition) mappingMeta.getOutputMappings().get( i ).clone() ); } changeList = new ArrayList<ApplyChanges>(); } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX ); props.setLook( shell ); setShellImage( shell, mappingMeta ); lsMod = new ModifyListener() { public void modifyText( ModifyEvent e ) { mappingMeta.setChanged(); } }; changed = mappingMeta.hasChanged(); FormLayout formLayout = new FormLayout(); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout( formLayout ); shell.setText( BaseMessages.getString( PKG, "MappingDialog.Shell.Title" ) ); middle = props.getMiddlePct(); margin = Const.MARGIN; // Stepname line wlStepname = new Label( shell, SWT.RIGHT ); wlStepname.setText( BaseMessages.getString( PKG, "MappingDialog.Stepname.Label" ) ); props.setLook( wlStepname ); fdlStepname = new FormData(); fdlStepname.left = new FormAttachment( 0, 0 ); fdlStepname.right = new FormAttachment( middle, -margin ); fdlStepname.top = new FormAttachment( 0, margin ); wlStepname.setLayoutData( fdlStepname ); wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); wStepname.setText( stepname ); props.setLook( wStepname ); wStepname.addModifyListener( lsMod ); fdStepname = new FormData(); fdStepname.left = new FormAttachment( middle, 0 ); fdStepname.top = new FormAttachment( 0, margin ); fdStepname.right = new FormAttachment( 100, 0 ); wStepname.setLayoutData( fdStepname ); // Show a group with 2 main options: a transformation in the repository // or on file // // ////////////////////////////////////////////////// // The key creation box // ////////////////////////////////////////////////// // Group gTransGroup = new Group( shell, SWT.SHADOW_ETCHED_IN ); gTransGroup.setText( BaseMessages.getString( PKG, "MappingDialog.TransGroup.Label" ) ); gTransGroup.setBackground( shell.getBackground() ); // the default looks // ugly FormLayout transGroupLayout = new FormLayout(); transGroupLayout.marginLeft = margin * 2; transGroupLayout.marginTop = margin * 2; transGroupLayout.marginRight = margin * 2; transGroupLayout.marginBottom = margin * 2; gTransGroup.setLayout( transGroupLayout ); // Radio button: The mapping is in a file // radioFilename = new Button( gTransGroup, SWT.RADIO ); props.setLook( radioFilename ); radioFilename.setSelection( false ); radioFilename.setText( BaseMessages.getString( PKG, "MappingDialog.RadioFile.Label" ) ); radioFilename.setToolTipText( BaseMessages.getString( PKG, "MappingDialog.RadioFile.Tooltip", Const.CR ) ); FormData fdFileRadio = new FormData(); fdFileRadio.left = new FormAttachment( 0, 0 ); fdFileRadio.right = new FormAttachment( 100, 0 ); fdFileRadio.top = new FormAttachment( 0, 0 ); radioFilename.setLayoutData( fdFileRadio ); radioFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME ); setRadioButtons(); } } ); wbbFilename = new Button( gTransGroup, SWT.PUSH | SWT.CENTER ); // Browse props.setLook( wbbFilename ); wbbFilename.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) ); wbbFilename.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForFileOrDirAndAdd" ) ); FormData fdbFilename = new FormData(); fdbFilename.right = new FormAttachment( 100, 0 ); fdbFilename.top = new FormAttachment( radioFilename, margin ); wbbFilename.setLayoutData( fdbFilename ); wbbFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { selectFileTrans(); } } ); wFilename = new TextVar( transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wFilename ); wFilename.addModifyListener( lsMod ); FormData fdFilename = new FormData(); fdFilename.left = new FormAttachment( 0, 25 ); fdFilename.right = new FormAttachment( wbbFilename, -margin ); fdFilename.top = new FormAttachment( wbbFilename, 0, SWT.CENTER ); wFilename.setLayoutData( fdFilename ); wFilename.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME ); setRadioButtons(); } } ); // Radio button: The mapping is in the repository // radioByName = new Button( gTransGroup, SWT.RADIO ); props.setLook( radioByName ); radioByName.setSelection( false ); radioByName.setText( BaseMessages.getString( PKG, "MappingDialog.RadioRep.Label" ) ); radioByName.setToolTipText( BaseMessages.getString( PKG, "MappingDialog.RadioRep.Tooltip", Const.CR ) ); FormData fdRepRadio = new FormData(); fdRepRadio.left = new FormAttachment( 0, 0 ); fdRepRadio.right = new FormAttachment( 100, 0 ); fdRepRadio.top = new FormAttachment( wbbFilename, 2 * margin ); radioByName.setLayoutData( fdRepRadio ); radioByName.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); setRadioButtons(); } } ); wbTrans = new Button( gTransGroup, SWT.PUSH | SWT.CENTER ); // Browse props.setLook( wbTrans ); wbTrans.setText( BaseMessages.getString( PKG, "MappingDialog.Select.Button" ) ); wbTrans.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForFileOrDirAndAdd" ) ); FormData fdbTrans = new FormData(); fdbTrans.right = new FormAttachment( 100, 0 ); fdbTrans.top = new FormAttachment( radioByName, 2 * margin ); wbTrans.setLayoutData( fdbTrans ); wbTrans.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { selectRepositoryTrans(); } } ); wDirectory = new TextVar( transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wDirectory ); wDirectory.addModifyListener( lsMod ); FormData fdTransDir = new FormData(); fdTransDir.left = new FormAttachment( middle + ( 100 - middle ) / 2, 0 ); fdTransDir.right = new FormAttachment( wbTrans, -margin ); fdTransDir.top = new FormAttachment( wbTrans, 0, SWT.CENTER ); wDirectory.setLayoutData( fdTransDir ); wDirectory.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); setRadioButtons(); } } ); wTransname = new TextVar( transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wTransname ); wTransname.addModifyListener( lsMod ); FormData fdTransName = new FormData(); fdTransName.left = new FormAttachment( 0, 25 ); fdTransName.right = new FormAttachment( wDirectory, -margin ); fdTransName.top = new FormAttachment( wbTrans, 0, SWT.CENTER ); wTransname.setLayoutData( fdTransName ); wTransname.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); setRadioButtons(); } } ); // Radio button: The mapping is in the repository // radioByReference = new Button( gTransGroup, SWT.RADIO ); props.setLook( radioByReference ); radioByReference.setSelection( false ); radioByReference.setText( BaseMessages.getString( PKG, "MappingDialog.RadioRepByReference.Label" ) ); radioByReference.setToolTipText( BaseMessages.getString( PKG, "MappingDialog.RadioRepByReference.Tooltip", Const.CR ) ); FormData fdRadioByReference = new FormData(); fdRadioByReference.left = new FormAttachment( 0, 0 ); fdRadioByReference.right = new FormAttachment( 100, 0 ); fdRadioByReference.top = new FormAttachment( wTransname, 2 * margin ); radioByReference.setLayoutData( fdRadioByReference ); radioByReference.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE ); setRadioButtons(); } } ); wbByReference = new Button( gTransGroup, SWT.PUSH | SWT.CENTER ); props.setLook( wbByReference ); wbByReference.setImage( GUIResource.getInstance().getImageTransGraph() ); wbByReference.setToolTipText( BaseMessages.getString( PKG, "MappingDialog.SelectTrans.Tooltip" ) ); FormData fdbByReference = new FormData(); fdbByReference.top = new FormAttachment( radioByReference, margin ); fdbByReference.right = new FormAttachment( 100, 0 ); wbByReference.setLayoutData( fdbByReference ); wbByReference.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { selectTransformationByReference(); } } ); wByReference = new TextVar( transMeta, gTransGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.READ_ONLY ); props.setLook( wByReference ); wByReference.addModifyListener( lsMod ); FormData fdByReference = new FormData(); fdByReference.top = new FormAttachment( radioByReference, margin ); fdByReference.left = new FormAttachment( 0, 25 ); fdByReference.right = new FormAttachment( wbByReference, -margin ); wByReference.setLayoutData( fdByReference ); wByReference.addModifyListener( new ModifyListener() { public void modifyText( ModifyEvent e ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE ); setRadioButtons(); } } ); Button wNewTrans = new Button( gTransGroup, SWT.PUSH | SWT.CENTER ); props.setLook( wNewTrans ); wNewTrans.setText( BaseMessages.getString( PKG, "MappingDialog.New.Button" ) ); FormData fdNewTrans = new FormData(); fdNewTrans.left = new FormAttachment( 0, 0 ); fdNewTrans.top = new FormAttachment( wByReference, 3 * margin ); wNewTrans.setLayoutData( fdNewTrans ); wNewTrans.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { newTransformation(); } } ); Button wEditTrans = new Button( gTransGroup, SWT.PUSH | SWT.CENTER ); props.setLook( wEditTrans ); wEditTrans.setText( BaseMessages.getString( PKG, "MappingDialog.Edit.Button" ) ); wEditTrans.setToolTipText( BaseMessages.getString( PKG, "System.Tooltip.BrowseForFileOrDirAndAdd" ) ); FormData fdEditTrans = new FormData(); fdEditTrans.left = new FormAttachment( wNewTrans, 2 * margin ); fdEditTrans.top = new FormAttachment( wByReference, 3 * margin ); wEditTrans.setLayoutData( fdEditTrans ); wEditTrans.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent e ) { editTrans(); } } ); FormData fdTransGroup = new FormData(); fdTransGroup.left = new FormAttachment( 0, 0 ); fdTransGroup.top = new FormAttachment( wStepname, 2 * margin ); fdTransGroup.right = new FormAttachment( 100, 0 ); gTransGroup.setLayoutData( fdTransGroup ); Control lastControl = gTransGroup; wMultiInput = new Button( shell, SWT.CHECK ); props.setLook( wMultiInput ); wMultiInput.setText( BaseMessages.getString( PKG, "MappingDialog.AllowMultipleInputs.Label" ) ); FormData fdMultiInput = new FormData(); fdMultiInput.left = new FormAttachment( 0, 0 ); fdMultiInput.right = new FormAttachment( 100, 0 ); fdMultiInput.top = new FormAttachment( lastControl, margin * 2 ); wMultiInput.setLayoutData( fdMultiInput ); wMultiInput.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { setFlags(); } } ); lastControl = wMultiInput; wMultiOutput = new Button( shell, SWT.CHECK ); props.setLook( wMultiOutput ); wMultiOutput.setText( BaseMessages.getString( PKG, "MappingDialog.AllowMultipleOutputs.Label" ) ); FormData fdMultiOutput = new FormData(); fdMultiOutput.left = new FormAttachment( 0, 0 ); fdMultiOutput.right = new FormAttachment( 100, 0 ); fdMultiOutput.top = new FormAttachment( lastControl, margin ); wMultiOutput.setLayoutData( fdMultiOutput ); wMultiOutput.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent event ) { setFlags(); } } ); lastControl = wMultiOutput; // // Add a tab folder for the parameters and various input and output // streams // wTabFolder = new CTabFolder( shell, SWT.BORDER ); props.setLook( wTabFolder, Props.WIDGET_STYLE_TAB ); wTabFolder.setSimple( false ); wTabFolder.setUnselectedCloseVisible( true ); FormData fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment( 0, 0 ); fdTabFolder.right = new FormAttachment( 100, 0 ); fdTabFolder.top = new FormAttachment( lastControl, margin * 2 ); fdTabFolder.bottom = new FormAttachment( 100, -75 ); wTabFolder.setLayoutData( fdTabFolder ); // Now add buttons that will allow us to add or remove input or output // tabs... wAddInput = new Button( shell, SWT.PUSH ); props.setLook( wAddInput ); wAddInput.setText( BaseMessages.getString( PKG, "MappingDialog.button.AddInput" ) ); wAddInput.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { // Simply add a new MappingIODefinition object to the // inputMappings MappingIODefinition definition = new MappingIODefinition(); definition.setRenamingOnOutput( true ); inputMappings.add( definition ); int index = inputMappings.size() - 1; addInputMappingDefinitionTab( definition, index ); setFlags(); } } ); wAddOutput = new Button( shell, SWT.PUSH ); props.setLook( wAddOutput ); wAddOutput.setText( BaseMessages.getString( PKG, "MappingDialog.button.AddOutput" ) ); wAddOutput.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { // Simply add a new MappingIODefinition object to the // inputMappings MappingIODefinition definition = new MappingIODefinition(); outputMappings.add( definition ); int index = outputMappings.size() - 1; addOutputMappingDefinitionTab( definition, index ); setFlags(); } } ); setButtonPositions( new Button[] { wAddInput, wAddOutput }, margin, wTabFolder ); // Some buttons 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" ) ); setButtonPositions( new Button[] { wOK, wCancel }, margin, null ); // 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(); } }; wStepname.addSelectionListener( lsDef ); wFilename.addSelectionListener( lsDef ); wTransname.addSelectionListener( lsDef ); // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed( ShellEvent e ) { cancel(); } } ); // Set the shell size, based upon previous time... setSize(); getData(); mappingMeta.setChanged( changed ); wTabFolder.setSelection( 0 ); shell.open(); while ( !shell.isDisposed() ) { if ( !display.readAndDispatch() ) { display.sleep(); } } return stepname; } protected void selectTransformationByReference() { if ( repository != null ) { SelectObjectDialog sod = new SelectObjectDialog( shell, repository, true, false ); sod.open(); RepositoryElementMetaInterface repositoryObject = sod.getRepositoryObject(); if ( repositoryObject != null ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE ); updateByReferenceField( repositoryObject ); setReferenceObjectId( repositoryObject.getObjectId() ); setRadioButtons(); } } } private void selectRepositoryTrans() { try { SelectObjectDialog sod = new SelectObjectDialog( shell, repository ); String transName = sod.open(); RepositoryDirectoryInterface repdir = sod.getDirectory(); if ( transName != null && repdir != null ) { loadRepositoryTrans( transName, repdir ); wTransname.setText( mappingTransMeta.getName() ); wDirectory.setText( mappingTransMeta.getRepositoryDirectory().getPath() ); wFilename.setText( "" ); radioByName.setSelection( true ); radioFilename.setSelection( false ); setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); setRadioButtons(); } } catch ( KettleException ke ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MappingDialog.ErrorSelectingObject.DialogTitle" ), BaseMessages.getString( PKG, "MappingDialog.ErrorSelectingObject.DialogMessage" ), ke ); } } private void loadRepositoryTrans( String transName, RepositoryDirectoryInterface repdir ) throws KettleException { // Read the transformation... // mappingTransMeta = repository.loadTransformation( transMeta.environmentSubstitute( transName ), repdir, null, true, null ); mappingTransMeta.clearChanged(); } private void selectFileTrans() { String curFile = wFilename.getText(); FileObject root; try { root = KettleVFS.getFileObject( curFile != null ? curFile : Const.getUserHomeDirectory() ); VfsFileChooserDialog vfsFileChooser = Spoon.getInstance().getVfsFileChooserDialog( root.getParent(), root ); FileObject file = vfsFileChooser.open( shell, null, Const.STRING_TRANS_FILTER_EXT, Const.getTransformationFilterNames(), VfsFileChooserDialog.VFS_DIALOG_OPEN_FILE ); if ( file == null ) { return; } String fname; fname = file.getURL().getFile(); if ( fname != null ) { loadFileTrans( fname ); wFilename.setText( mappingTransMeta.getFilename() ); wTransname.setText( Const.NVL( mappingTransMeta.getName(), "" ) ); wDirectory.setText( "" ); setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME ); setRadioButtons(); } } catch ( IOException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MappingDialog.ErrorLoadingTransformation.DialogTitle" ), BaseMessages.getString( PKG, "MappingDialog.ErrorLoadingTransformation.DialogMessage" ), e ); } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MappingDialog.ErrorLoadingTransformation.DialogTitle" ), BaseMessages.getString( PKG, "MappingDialog.ErrorLoadingTransformation.DialogMessage" ), e ); } } private void loadFileTrans( String fname ) throws KettleException { mappingTransMeta = new TransMeta( transMeta.environmentSubstitute( fname ) ); mappingTransMeta.clearChanged(); } private void editTrans() { // Load the transformation again to make sure it's still there and // refreshed // It's an extra check to make sure it's still OK... // try { loadTransformation(); // If we're still here, mappingTransMeta is valid. // SpoonInterface spoon = SpoonFactory.getInstance(); if ( spoon != null ) { spoon.addTransGraph( mappingTransMeta ); } } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MappingDialog.ErrorShowingTransformation.Title" ), BaseMessages.getString( PKG, "MappingDialog.ErrorShowingTransformation.Message" ), e ); } } // Method is defined as package-protected in order to be accessible by unit tests void loadTransformation() throws KettleException { switch( getSpecificationMethod() ) { case FILENAME: loadFileTrans( wFilename.getText() ); break; case REPOSITORY_BY_NAME: String realDirectory = transMeta.environmentSubstitute( wDirectory.getText() ); String realTransname = transMeta.environmentSubstitute( wTransname.getText() ); if ( Const.isEmpty( realDirectory ) || Const.isEmpty( realTransname ) ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.NoValidMappingDetailsFound" ) ); } RepositoryDirectoryInterface repdir = repository.findDirectory( realDirectory ); if ( repdir == null ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.UnableToFindRepositoryDirectory)" ) ); } loadRepositoryTrans( realTransname, repdir ); break; case REPOSITORY_BY_REFERENCE: if ( getReferenceObjectId() == null ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.ReferencedTransformationIdIsNull" ) ); } mappingTransMeta = repository.loadTransformation( getReferenceObjectId(), null ); // load the last version mappingTransMeta.clearChanged(); break; default: break; } } public void setActive() { boolean supportsReferences = repository != null && repository.getRepositoryMeta().getRepositoryCapabilities().supportsReferences(); radioByName.setEnabled( repository != null ); radioByReference.setEnabled( repository != null && supportsReferences ); wFilename.setEnabled( radioFilename.getSelection() ); wbbFilename.setEnabled( radioFilename.getSelection() ); wTransname.setEnabled( repository != null && radioByName.getSelection() ); wDirectory.setEnabled( repository != null && radioByName.getSelection() ); wbTrans.setEnabled( repository != null && radioByName.getSelection() ); wByReference.setEnabled( repository != null && radioByReference.getSelection() && supportsReferences ); wbByReference.setEnabled( repository != null && radioByReference.getSelection() && supportsReferences ); } protected void setRadioButtons() { radioFilename.setSelection( getSpecificationMethod() == ObjectLocationSpecificationMethod.FILENAME ); radioByName.setSelection( getSpecificationMethod() == ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); radioByReference .setSelection( getSpecificationMethod() == ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE ); setActive(); } /** * Ask the user to fill in the details... */ protected void newTransformation() { // Get input fields for this step so we can put this metadata in the mapping // RowMetaInterface inFields = new RowMeta(); try { inFields = transMeta.getPrevStepFields( stepname ); } catch ( Exception e ) { // Just show the error but continue operations. // new ErrorDialog( shell, "Error", "Unable to get input fields from previous step", e ); } TransMeta newTransMeta = new TransMeta(); newTransMeta.getDatabases().addAll( transMeta.getDatabases() ); newTransMeta.setRepository( transMeta.getRepository() ); newTransMeta.setRepositoryDirectory( transMeta.getRepositoryDirectory() ); // Pass some interesting settings from the parent transformations... // newTransMeta.setUsingUniqueConnections( transMeta.isUsingUniqueConnections() ); // Add MappingInput and MappingOutput steps // String INPUT_STEP_NAME = "Mapping Input"; MappingInputMeta inputMeta = new MappingInputMeta(); inputMeta.allocate( inFields.size() ); //CHECKSTYLE:Indentation:OFF for ( int i = 0; i < inFields.size(); i++ ) { ValueMetaInterface valueMeta = inFields.getValueMeta( i ); inputMeta.getFieldName()[ i ] = valueMeta.getName(); inputMeta.getFieldType()[ i ] = valueMeta.getType(); inputMeta.getFieldLength()[ i ] = valueMeta.getLength(); inputMeta.getFieldPrecision()[ i ] = valueMeta.getPrecision(); } StepMeta inputStep = new StepMeta( INPUT_STEP_NAME, inputMeta ); inputStep.setLocation( 50, 50 ); inputStep.setDraw( true ); newTransMeta.addStep( inputStep ); String OUTPUT_STEP_NAME = "Mapping Output"; MappingOutputMeta outputMeta = new MappingOutputMeta(); outputMeta.allocate( 0 ); StepMeta outputStep = new StepMeta( OUTPUT_STEP_NAME, outputMeta ); outputStep.setLocation( 500, 50 ); outputStep.setDraw( true ); newTransMeta.addStep( outputStep ); newTransMeta.addTransHop( new TransHopMeta( inputStep, outputStep ) ); TransDialog transDialog = new TransDialog( shell, SWT.NONE, newTransMeta, repository ); if ( transDialog.open() != null ) { Spoon spoon = Spoon.getInstance(); spoon.addTransGraph( newTransMeta ); boolean saved = false; try { if ( repository != null ) { if ( !Const.isEmpty( newTransMeta.getName() ) ) { wStepname.setText( newTransMeta.getName() ); } saved = spoon.saveToRepository( newTransMeta, false ); if ( repository.getRepositoryMeta().getRepositoryCapabilities().supportsReferences() ) { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_REFERENCE ); } else { setSpecificationMethod( ObjectLocationSpecificationMethod.REPOSITORY_BY_NAME ); } } else { saved = spoon.saveToFile( newTransMeta ); setSpecificationMethod( ObjectLocationSpecificationMethod.FILENAME ); } } catch ( Exception e ) { new ErrorDialog( shell, "Error", "Error saving new transformation", e ); } if ( saved ) { setRadioButtons(); switch( getSpecificationMethod() ) { case FILENAME: wFilename.setText( Const.NVL( newTransMeta.getFilename(), "" ) ); break; case REPOSITORY_BY_NAME: wTransname.setText( Const.NVL( newTransMeta.getName(), "" ) ); wDirectory.setText( newTransMeta.getRepositoryDirectory().getPath() ); break; case REPOSITORY_BY_REFERENCE: getByReferenceData( newTransMeta.getObjectId() ); break; default: break; } } } } private void getByReferenceData( ObjectId transObjectId ) { try { if ( repository == null ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.NotConnectedToRepository.Message" ) ); } RepositoryObject transInf = repository.getObjectInformation( transObjectId, RepositoryObjectType.TRANSFORMATION ); updateByReferenceField( transInf ); } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MappingDialog.Exception.UnableToReferenceObjectId.Title" ), BaseMessages.getString( PKG, "MappingDialog.Exception.UnableToReferenceObjectId.Message" ), e ); } } private void updateByReferenceField( RepositoryElementMetaInterface element ) { String path = getPathOf( element ); if ( path == null ) { path = ""; } wByReference.setText( path ); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData() { setSpecificationMethod( mappingMeta.getSpecificationMethod() ); switch( getSpecificationMethod() ) { case FILENAME: wFilename.setText( Const.NVL( mappingMeta.getFileName(), "" ) ); break; case REPOSITORY_BY_NAME: wDirectory.setText( Const.NVL( mappingMeta.getDirectoryPath(), "" ) ); wTransname.setText( Const.NVL( mappingMeta.getTransName(), "" ) ); break; case REPOSITORY_BY_REFERENCE: wByReference.setText( "" ); if ( mappingMeta.getTransObjectId() != null ) { setReferenceObjectId( mappingMeta.getTransObjectId() ); getByReferenceData( getReferenceObjectId() ); } break; default: break; } setRadioButtons(); // Add the parameters tab addParametersTab( mappingParameters ); wTabFolder.setSelection( 0 ); wMultiInput.setSelection( mappingMeta.isAllowingMultipleInputs() ); wMultiOutput.setSelection( mappingMeta.isAllowingMultipleOutputs() ); // Now add the input stream tabs: where is our data coming from? for ( int i = 0; i < inputMappings.size(); i++ ) { addInputMappingDefinitionTab( inputMappings.get( i ), i ); } // Now add the output stream tabs: where is our data going to? for ( int i = 0; i < outputMappings.size(); i++ ) { addOutputMappingDefinitionTab( outputMappings.get( i ), i ); } try { loadTransformation(); } catch ( Throwable t ) { // Ignore errors } setFlags(); wStepname.selectAll(); wStepname.setFocus(); } private void addOutputMappingDefinitionTab( MappingIODefinition definition, int index ) { addMappingDefinitionTab( outputMappings.get( index ), index + 1 + inputMappings.size(), BaseMessages .getString( PKG, "MappingDialog.OutputTab.Title" ), BaseMessages.getString( PKG, "MappingDialog.OutputTab.Tooltip" ), BaseMessages.getString( PKG, "MappingDialog.OutputTab.label.InputSourceStepName" ), BaseMessages.getString( PKG, "MappingDialog.OutputTab.label.OutputTargetStepName" ), BaseMessages.getString( PKG, "MappingDialog.OutputTab.label.Description" ), BaseMessages.getString( PKG, "MappingDialog.OutputTab.column.SourceField" ), BaseMessages.getString( PKG, "MappingDialog.OutputTab.column.TargetField" ), false ); } private void addInputMappingDefinitionTab( MappingIODefinition definition, int index ) { addMappingDefinitionTab( definition, index + 1, BaseMessages.getString( PKG, "MappingDialog.InputTab.Title" ), BaseMessages .getString( PKG, "MappingDialog.InputTab.Tooltip" ), BaseMessages.getString( PKG, "MappingDialog.InputTab.label.InputSourceStepName" ), BaseMessages.getString( PKG, "MappingDialog.InputTab.label.OutputTargetStepName" ), BaseMessages.getString( PKG, "MappingDialog.InputTab.label.Description" ), BaseMessages.getString( PKG, "MappingDialog.InputTab.column.SourceField" ), BaseMessages.getString( PKG, "MappingDialog.InputTab.column.TargetField" ), true ); } private void addParametersTab( final MappingParameters parameters ) { CTabItem wParametersTab = new CTabItem( wTabFolder, SWT.NONE ); wParametersTab.setText( BaseMessages.getString( PKG, "MappingDialog.Parameters.Title" ) ); wParametersTab.setToolTipText( BaseMessages.getString( PKG, "MappingDialog.Parameters.Tooltip" ) ); Composite wParametersComposite = new Composite( wTabFolder, SWT.NONE ); props.setLook( wParametersComposite ); FormLayout parameterTabLayout = new FormLayout(); parameterTabLayout.marginWidth = Const.FORM_MARGIN; parameterTabLayout.marginHeight = Const.FORM_MARGIN; wParametersComposite.setLayout( parameterTabLayout ); // Add a checkbox: inherit all variables... // Button wInheritAll = new Button( wParametersComposite, SWT.CHECK ); wInheritAll.setText( BaseMessages.getString( PKG, "MappingDialog.Parameters.InheritAll" ) ); props.setLook( wInheritAll ); FormData fdInheritAll = new FormData(); fdInheritAll.bottom = new FormAttachment( 100, 0 ); fdInheritAll.left = new FormAttachment( 0, 0 ); fdInheritAll.right = new FormAttachment( 100, -30 ); wInheritAll.setLayoutData( fdInheritAll ); wInheritAll.setSelection( parameters.isInheritingAllVariables() ); // Now add a tableview with the 2 columns to specify: input and output // fields for the source and target steps. // ColumnInfo[] colinfo = new ColumnInfo[] { new ColumnInfo( BaseMessages.getString( PKG, "MappingDialog.Parameters.column.Variable" ), ColumnInfo.COLUMN_TYPE_TEXT, false, false ), new ColumnInfo( BaseMessages.getString( PKG, "MappingDialog.Parameters.column.ValueOrField" ), ColumnInfo.COLUMN_TYPE_TEXT, false, false ), }; colinfo[ 1 ].setUsingVariables( true ); final TableView wMappingParameters = new TableView( transMeta, wParametersComposite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, parameters .getVariable().length, lsMod, props ); props.setLook( wMappingParameters ); FormData fdMappings = new FormData(); fdMappings.left = new FormAttachment( 0, 0 ); fdMappings.right = new FormAttachment( 100, 0 ); fdMappings.top = new FormAttachment( 0, 0 ); fdMappings.bottom = new FormAttachment( wInheritAll, -margin * 2 ); wMappingParameters.setLayoutData( fdMappings ); for ( int i = 0; i < parameters.getVariable().length; i++ ) { TableItem tableItem = wMappingParameters.table.getItem( i ); tableItem.setText( 1, parameters.getVariable()[ i ] ); tableItem.setText( 2, parameters.getInputField()[ i ] ); } wMappingParameters.setRowNums(); wMappingParameters.optWidth( true ); FormData fdParametersComposite = new FormData(); fdParametersComposite.left = new FormAttachment( 0, 0 ); fdParametersComposite.top = new FormAttachment( 0, 0 ); fdParametersComposite.right = new FormAttachment( 100, 0 ); fdParametersComposite.bottom = new FormAttachment( 100, 0 ); wParametersComposite.setLayoutData( fdParametersComposite ); wParametersComposite.layout(); wParametersTab.setControl( wParametersComposite ); changeList.add( new MappingParametersTab( wMappingParameters, wInheritAll, parameters ) ); } protected String selectTransformationStepname( boolean getTransformationStep, boolean mappingInput ) { String dialogTitle; String dialogMessage; if ( getTransformationStep ) { dialogTitle = BaseMessages.getString( PKG, "MappingDialog.SelectTransStep.Title" ); dialogMessage = BaseMessages.getString( PKG, "MappingDialog.SelectTransStep.Message" ); String[] stepnames; if ( mappingInput ) { stepnames = transMeta.getPrevStepNames( stepMeta ); } else { stepnames = transMeta.getNextStepNames( stepMeta ); } EnterSelectionDialog dialog = new EnterSelectionDialog( shell, stepnames, dialogTitle, dialogMessage ); return dialog.open(); } else { dialogTitle = BaseMessages.getString( PKG, "MappingDialog.SelectMappingStep.Title" ); dialogMessage = BaseMessages.getString( PKG, "MappingDialog.SelectMappingStep.Message" ); String[] stepnames = getMappingSteps( mappingTransMeta, mappingInput ); EnterSelectionDialog dialog = new EnterSelectionDialog( shell, stepnames, dialogTitle, dialogMessage ); return dialog.open(); } } public static String[] getMappingSteps( TransMeta mappingTransMeta, boolean mappingInput ) { List<StepMeta> steps = new ArrayList<StepMeta>(); for ( StepMeta stepMeta : mappingTransMeta.getSteps() ) { if ( mappingInput && stepMeta.getStepID().equals( "MappingInput" ) ) { steps.add( stepMeta ); } if ( !mappingInput && stepMeta.getStepID().equals( "MappingOutput" ) ) { steps.add( stepMeta ); } } String[] stepnames = new String[ steps.size() ]; for ( int i = 0; i < stepnames.length; i++ ) { stepnames[ i ] = steps.get( i ).getName(); } return stepnames; } public RowMetaInterface getFieldsFromStep( String stepname, boolean getTransformationStep, boolean mappingInput ) throws KettleException { if ( !( mappingInput ^ getTransformationStep ) ) { if ( Const.isEmpty( stepname ) ) { // If we don't have a specified stepname we return the input row // metadata // return transMeta.getPrevStepFields( this.stepname ); } else { // OK, a fieldname is specified... // See if we can find it... StepMeta stepMeta = transMeta.findStep( stepname ); if ( stepMeta == null ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.SpecifiedStepWasNotFound", stepname ) ); } return transMeta.getStepFields( stepMeta ); } } else { if ( mappingTransMeta == null ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.NoMappingSpecified" ) ); } if ( Const.isEmpty( stepname ) ) { // If we don't have a specified stepname we select the one and // only "mapping input" step. // String[] stepnames = getMappingSteps( mappingTransMeta, mappingInput ); if ( stepnames.length > 1 ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.OnlyOneMappingInputStepAllowed", "" + stepnames.length ) ); } if ( stepnames.length == 0 ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.OneMappingInputStepRequired", "" + stepnames.length ) ); } return mappingTransMeta.getStepFields( stepnames[ 0 ] ); } else { // OK, a fieldname is specified... // See if we can find it... StepMeta stepMeta = mappingTransMeta.findStep( stepname ); if ( stepMeta == null ) { throw new KettleException( BaseMessages.getString( PKG, "MappingDialog.Exception.SpecifiedStepWasNotFound", stepname ) ); } return mappingTransMeta.getStepFields( stepMeta ); } } } private void addMappingDefinitionTab( final MappingIODefinition definition, int index, final String tabTitle, final String tabTooltip, String inputStepLabel, String outputStepLabel, String descriptionLabel, String sourceColumnLabel, String targetColumnLabel, final boolean input ) { final CTabItem wTab; if ( index >= wTabFolder.getItemCount() ) { wTab = new CTabItem( wTabFolder, SWT.CLOSE ); } else { wTab = new CTabItem( wTabFolder, SWT.CLOSE, index ); } setMappingDefinitionTabNameAndToolTip( wTab, tabTitle, tabTooltip, definition, input ); Composite wInputComposite = new Composite( wTabFolder, SWT.NONE ); props.setLook( wInputComposite ); FormLayout tabLayout = new FormLayout(); tabLayout.marginWidth = Const.FORM_MARGIN; tabLayout.marginHeight = Const.FORM_MARGIN; wInputComposite.setLayout( tabLayout ); // What's the stepname to read from? (empty is OK too) // final Button wbInputStep = new Button( wInputComposite, SWT.PUSH ); props.setLook( wbInputStep ); wbInputStep.setText( BaseMessages.getString( PKG, "MappingDialog.button.SourceStepName" ) ); FormData fdbInputStep = new FormData(); fdbInputStep.top = new FormAttachment( 0, 0 ); fdbInputStep.right = new FormAttachment( 100, 0 ); // First one in the // left top corner wbInputStep.setLayoutData( fdbInputStep ); final Label wlInputStep = new Label( wInputComposite, SWT.RIGHT ); props.setLook( wlInputStep ); wlInputStep.setText( inputStepLabel ); FormData fdlInputStep = new FormData(); fdlInputStep.top = new FormAttachment( wbInputStep, 0, SWT.CENTER ); fdlInputStep.left = new FormAttachment( 0, 0 ); // First one in the left // top corner fdlInputStep.right = new FormAttachment( middle, -margin ); wlInputStep.setLayoutData( fdlInputStep ); final Text wInputStep = new Text( wInputComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wInputStep ); wInputStep.setText( Const.NVL( definition.getInputStepname(), "" ) ); wInputStep.addModifyListener( lsMod ); FormData fdInputStep = new FormData(); fdInputStep.top = new FormAttachment( wbInputStep, 0, SWT.CENTER ); fdInputStep.left = new FormAttachment( middle, 0 ); // To the right of // the label fdInputStep.right = new FormAttachment( wbInputStep, -margin ); wInputStep.setLayoutData( fdInputStep ); wInputStep.addFocusListener( new FocusAdapter() { @Override public void focusLost( FocusEvent event ) { definition.setInputStepname( wInputStep.getText() ); setMappingDefinitionTabNameAndToolTip( wTab, tabTitle, tabTooltip, definition, input ); } } ); wbInputStep.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { String stepName = selectTransformationStepname( input, input ); if ( stepName != null ) { wInputStep.setText( stepName ); definition.setInputStepname( stepName ); setMappingDefinitionTabNameAndToolTip( wTab, tabTitle, tabTooltip, definition, input ); } } } ); // What's the step name to read from? (empty is OK too) // final Button wbOutputStep = new Button( wInputComposite, SWT.PUSH ); props.setLook( wbOutputStep ); wbOutputStep.setText( BaseMessages.getString( PKG, "MappingDialog.button.SourceStepName" ) ); FormData fdbOutputStep = new FormData(); fdbOutputStep.top = new FormAttachment( wbInputStep, margin ); fdbOutputStep.right = new FormAttachment( 100, 0 ); wbOutputStep.setLayoutData( fdbOutputStep ); final Label wlOutputStep = new Label( wInputComposite, SWT.RIGHT ); props.setLook( wlOutputStep ); wlOutputStep.setText( outputStepLabel ); FormData fdlOutputStep = new FormData(); fdlOutputStep.top = new FormAttachment( wbOutputStep, 0, SWT.CENTER ); fdlOutputStep.left = new FormAttachment( 0, 0 ); fdlOutputStep.right = new FormAttachment( middle, -margin ); wlOutputStep.setLayoutData( fdlOutputStep ); final Text wOutputStep = new Text( wInputComposite, SWT.SINGLE | SWT.LEFT | SWT.BORDER ); props.setLook( wOutputStep ); wOutputStep.setText( Const.NVL( definition.getOutputStepname(), "" ) ); wOutputStep.addModifyListener( lsMod ); FormData fdOutputStep = new FormData(); fdOutputStep.top = new FormAttachment( wbOutputStep, 0, SWT.CENTER ); fdOutputStep.left = new FormAttachment( middle, 0 ); // To the right of // the label fdOutputStep.right = new FormAttachment( wbOutputStep, -margin ); wOutputStep.setLayoutData( fdOutputStep ); // Add a checkbox to indicate the main step to read from, the main data // path... // final Label wlMainPath = new Label( wInputComposite, SWT.RIGHT ); props.setLook( wlMainPath ); wlMainPath.setText( BaseMessages.getString( PKG, "MappingDialog.input.MainDataPath" ) ); FormData fdlMainPath = new FormData(); fdlMainPath.top = new FormAttachment( wbOutputStep, margin ); fdlMainPath.left = new FormAttachment( 0, 0 ); fdlMainPath.right = new FormAttachment( middle, -margin ); wlMainPath.setLayoutData( fdlMainPath ); final Button wMainPath = new Button( wInputComposite, SWT.CHECK ); props.setLook( wMainPath ); FormData fdMainPath = new FormData(); fdMainPath.top = new FormAttachment( wbOutputStep, margin ); fdMainPath.left = new FormAttachment( middle, 0 ); // fdMainPath.right = new FormAttachment(100, 0); // who cares, it's a // checkbox wMainPath.setLayoutData( fdMainPath ); wMainPath.setSelection( definition.isMainDataPath() ); wMainPath.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { definition.setMainDataPath( !definition.isMainDataPath() ); // flip // the // switch } } ); Control lastControl = wMainPath; // Allow for a small description // Label wlDescription = new Label( wInputComposite, SWT.RIGHT ); props.setLook( wlDescription ); wlDescription.setText( descriptionLabel ); FormData fdlDescription = new FormData(); fdlDescription.top = new FormAttachment( lastControl, margin ); fdlDescription.left = new FormAttachment( 0, 0 ); // First one in the left // top corner fdlDescription.right = new FormAttachment( middle, -margin ); wlDescription.setLayoutData( fdlDescription ); final Text wDescription = new Text( wInputComposite, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL ); props.setLook( wDescription ); wDescription.setText( Const.NVL( definition.getDescription(), "" ) ); wDescription.addModifyListener( lsMod ); FormData fdDescription = new FormData(); fdDescription.top = new FormAttachment( lastControl, margin ); fdDescription.bottom = new FormAttachment( lastControl, 100 + margin ); fdDescription.left = new FormAttachment( middle, 0 ); // To the right of // the label fdDescription.right = new FormAttachment( wbOutputStep, -margin ); wDescription.setLayoutData( fdDescription ); wDescription.addFocusListener( new FocusAdapter() { @Override public void focusLost( FocusEvent event ) { definition.setDescription( wDescription.getText() ); } } ); lastControl = wDescription; // Now add a table view with the 2 columns to specify: input and output // fields for the source and target steps. // final Button wbEnterMapping = new Button( wInputComposite, SWT.PUSH ); props.setLook( wbEnterMapping ); wbEnterMapping.setText( BaseMessages.getString( PKG, "MappingDialog.button.EnterMapping" ) ); FormData fdbEnterMapping = new FormData(); fdbEnterMapping.top = new FormAttachment( lastControl, margin * 2 ); fdbEnterMapping.right = new FormAttachment( 100, 0 ); // First one in the // left top corner wbEnterMapping.setLayoutData( fdbEnterMapping ); wbEnterMapping.setEnabled( input ); ColumnInfo[] colinfo = new ColumnInfo[] { new ColumnInfo( sourceColumnLabel, ColumnInfo.COLUMN_TYPE_TEXT, false, false ), new ColumnInfo( targetColumnLabel, ColumnInfo.COLUMN_TYPE_TEXT, false, false ), }; final TableView wFieldMappings = new TableView( transMeta, wInputComposite, SWT.FULL_SELECTION | SWT.SINGLE | SWT.BORDER, colinfo, 1, lsMod, props ); props.setLook( wFieldMappings ); FormData fdMappings = new FormData(); fdMappings.left = new FormAttachment( 0, 0 ); fdMappings.right = new FormAttachment( wbEnterMapping, -margin ); fdMappings.top = new FormAttachment( lastControl, margin * 2 ); fdMappings.bottom = new FormAttachment( 100, -50 ); wFieldMappings.setLayoutData( fdMappings ); lastControl = wFieldMappings; for ( MappingValueRename valueRename : definition.getValueRenames() ) { TableItem tableItem = new TableItem( wFieldMappings.table, SWT.NONE ); tableItem.setText( 1, Const.NVL( valueRename.getSourceValueName(), "" ) ); tableItem.setText( 2, Const.NVL( valueRename.getTargetValueName(), "" ) ); } wFieldMappings.removeEmptyRows(); wFieldMappings.setRowNums(); wFieldMappings.optWidth( true ); wbEnterMapping.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent arg0 ) { try { RowMetaInterface sourceRowMeta = getFieldsFromStep( wInputStep.getText(), true, input ); RowMetaInterface targetRowMeta = getFieldsFromStep( wOutputStep.getText(), false, input ); String[] sourceFields = sourceRowMeta.getFieldNames(); String[] targetFields = targetRowMeta.getFieldNames(); EnterMappingDialog dialog = new EnterMappingDialog( shell, sourceFields, targetFields ); List<SourceToTargetMapping> mappings = dialog.open(); if ( mappings != null ) { // first clear the dialog... wFieldMappings.clearAll( false ); // definition.getValueRenames().clear(); // Now add the new values... for ( SourceToTargetMapping mapping : mappings ) { TableItem item = new TableItem( wFieldMappings.table, SWT.NONE ); item.setText( 1, mapping.getSourceString( sourceFields ) ); item.setText( 2, mapping.getTargetString( targetFields ) ); String source = input ? item.getText( 1 ) : item.getText( 2 ); String target = input ? item.getText( 2 ) : item.getText( 1 ); definition.getValueRenames().add( new MappingValueRename( source, target ) ); } wFieldMappings.removeEmptyRows(); wFieldMappings.setRowNums(); wFieldMappings.optWidth( true ); } } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "System.Dialog.Error.Title" ), BaseMessages.getString( PKG, "MappingDialog.Exception.ErrorGettingMappingSourceAndTargetFields", e.toString() ), e ); } } } ); wOutputStep.addFocusListener( new FocusAdapter() { @Override public void focusLost( FocusEvent event ) { definition.setOutputStepname( wOutputStep.getText() ); try { enableMappingButton( wbEnterMapping, input, wInputStep.getText(), wOutputStep.getText() ); } catch ( KettleException e ) { // Show the missing/wrong step name error // new ErrorDialog( shell, "Error", "Unexpected error", e ); } } } ); wbOutputStep.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { String stepName = selectTransformationStepname( !input, input ); if ( stepName != null ) { wOutputStep.setText( stepName ); definition.setOutputStepname( stepName ); try { enableMappingButton( wbEnterMapping, input, wInputStep.getText(), wOutputStep.getText() ); } catch ( KettleException e ) { // Show the missing/wrong stepname error new ErrorDialog( shell, "Error", "Unexpected error", e ); } } } } ); if ( input ) { // Add a checkbox to indicate that all output mappings need to rename // the values back... // Label wlRenameOutput = new Label( wInputComposite, SWT.RIGHT ); props.setLook( wlRenameOutput ); wlRenameOutput.setText( BaseMessages.getString( PKG, "MappingDialog.input.RenamingOnOutput" ) ); FormData fdlRenameOutput = new FormData(); fdlRenameOutput.top = new FormAttachment( lastControl, margin ); fdlRenameOutput.left = new FormAttachment( 0, 0 ); fdlRenameOutput.right = new FormAttachment( middle, -margin ); wlRenameOutput.setLayoutData( fdlRenameOutput ); Button wRenameOutput = new Button( wInputComposite, SWT.CHECK ); props.setLook( wRenameOutput ); FormData fdRenameOutput = new FormData(); fdRenameOutput.top = new FormAttachment( lastControl, margin ); fdRenameOutput.left = new FormAttachment( middle, 0 ); // fdRenameOutput.right = new FormAttachment(100, 0); // who cares, it's // a check box wRenameOutput.setLayoutData( fdRenameOutput ); wRenameOutput.setSelection( definition.isRenamingOnOutput() ); wRenameOutput.addSelectionListener( new SelectionAdapter() { @Override public void widgetSelected( SelectionEvent event ) { definition.setRenamingOnOutput( !definition.isRenamingOnOutput() ); // flip // the // switch } } ); } FormData fdParametersComposite = new FormData(); fdParametersComposite.left = new FormAttachment( 0, 0 ); fdParametersComposite.top = new FormAttachment( 0, 0 ); fdParametersComposite.right = new FormAttachment( 100, 0 ); fdParametersComposite.bottom = new FormAttachment( 100, 0 ); wInputComposite.setLayoutData( fdParametersComposite ); wInputComposite.layout(); wTab.setControl( wInputComposite ); final ApplyChanges applyChanges = new MappingDefinitionTab( definition, wInputStep, wOutputStep, wMainPath, wDescription, wFieldMappings ); changeList.add( applyChanges ); // OK, suppose for some weird reason the user wants to remove an input // or output tab... wTabFolder.addCTabFolder2Listener( new CTabFolder2Adapter() { @Override public void close( CTabFolderEvent event ) { if ( event.item.equals( wTab ) ) { // The user has the audacity to try and close this mapping // definition tab. // We really should warn him that this is a bad idea... MessageBox box = new MessageBox( shell, SWT.YES | SWT.NO ); box.setText( BaseMessages.getString( PKG, "MappingDialog.CloseDefinitionTabAreYouSure.Title" ) ); box.setMessage( BaseMessages.getString( PKG, "MappingDialog.CloseDefinitionTabAreYouSure.Message" ) ); int answer = box.open(); if ( answer != SWT.YES ) { event.doit = false; } else { // Remove it from our list to make sure it's gone... if ( input ) { inputMappings.remove( definition ); } else { outputMappings.remove( definition ); } // remove it from the changeList too... // Otherwise the dialog leaks memory. // changeList.remove( applyChanges ); } setFlags(); } } } ); wMultiInput.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { setTabFlags( input, wlMainPath, wMainPath, wlInputStep, wInputStep, wbInputStep, wlOutputStep, wOutputStep, wbOutputStep ); } } ); wMultiOutput.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { setTabFlags( input, wlMainPath, wMainPath, wlInputStep, wInputStep, wbInputStep, wlOutputStep, wOutputStep, wbOutputStep ); } } ); wMainPath.addSelectionListener( new SelectionAdapter() { public void widgetSelected( SelectionEvent arg0 ) { setTabFlags( input, wlMainPath, wMainPath, wlInputStep, wInputStep, wbInputStep, wlOutputStep, wOutputStep, wbOutputStep ); } } ); setTabFlags( input, wlMainPath, wMainPath, wlInputStep, wInputStep, wbInputStep, wlOutputStep, wOutputStep, wbOutputStep ); wTabFolder.setSelection( wTab ); } private void setTabFlags( boolean input, Label wlMainPath, Button wMainPath, Label wlInputStep, Text wInputStep, Button wbInputStep, Label wlOutputStep, Text wOutputStep, Button wbOutputStep ) { boolean multiInput = wMultiInput.getSelection(); boolean multiOutput = wMultiOutput.getSelection(); if ( multiInput ) { wlMainPath.setEnabled( true ); wMainPath.setEnabled( true ); } else { wMainPath.setSelection( true ); wMainPath.setEnabled( false ); wlMainPath.setEnabled( false ); } boolean mainPath = wMainPath.getSelection(); if ( input ) { wlInputStep.setEnabled( !mainPath ); wInputStep.setEnabled( !mainPath ); wbInputStep.setEnabled( !mainPath ); wlOutputStep.setEnabled( multiInput ); wOutputStep.setEnabled( multiInput ); wbOutputStep.setEnabled( multiInput ); } else { wlInputStep.setEnabled( multiOutput ); wInputStep.setEnabled( multiOutput ); wbInputStep.setEnabled( multiOutput ); wlOutputStep.setEnabled( !mainPath ); wOutputStep.setEnabled( !mainPath ); wbOutputStep.setEnabled( !mainPath ); } } private void setFlags() { // Enable/disable fields... // boolean allowMultiInput = wMultiInput.getSelection(); boolean allowMultiOutput = wMultiOutput.getSelection(); wAddInput.setEnabled( allowMultiInput || inputMappings.size() == 0 ); wAddOutput.setEnabled( allowMultiOutput || outputMappings.size() == 0 ); } /** * Enables or disables the mapping button. We can only enable it if the target steps allows a mapping to be made * against it. * * @param button The button to disable or enable * @param input input or output. If it's true, we keep the button enabled all the time. * @param sourceStepname The mapping output step * @param targetStepname The target step to verify * @throws KettleException */ private void enableMappingButton( final Button button, boolean input, String sourceStepname, String targetStepname ) throws KettleException { if ( input ) { return; // nothing to do } boolean enabled = false; if ( mappingTransMeta != null ) { StepMeta mappingInputStep = mappingTransMeta.findMappingInputStep( sourceStepname ); if ( mappingInputStep != null ) { StepMeta mappingOutputStep = transMeta.findMappingOutputStep( targetStepname ); RowMetaInterface requiredFields = mappingOutputStep.getStepMetaInterface().getRequiredFields( transMeta ); if ( requiredFields != null && requiredFields.size() > 0 ) { enabled = true; } } } button.setEnabled( enabled ); } private void setMappingDefinitionTabNameAndToolTip( CTabItem wTab, String tabTitle, String tabTooltip, MappingIODefinition definition, boolean input ) { String stepname; if ( input ) { stepname = definition.getInputStepname(); } else { stepname = definition.getOutputStepname(); } String description = definition.getDescription(); if ( Const.isEmpty( stepname ) ) { wTab.setText( tabTitle ); } else { wTab.setText( tabTitle + " : " + stepname ); } String tooltip = tabTooltip; if ( !Const.isEmpty( stepname ) ) { tooltip += Const.CR + Const.CR + stepname; } if ( !Const.isEmpty( description ) ) { tooltip += Const.CR + Const.CR + description; } wTab.setToolTipText( tooltip ); } private void cancel() { stepname = null; mappingMeta.setChanged( changed ); dispose(); } private void ok() { if ( Const.isEmpty( wStepname.getText() ) ) { return; } stepname = wStepname.getText(); // return value try { loadTransformation(); } catch ( KettleException e ) { new ErrorDialog( shell, BaseMessages.getString( PKG, "MappingDialog.ErrorLoadingSpecifiedTransformation.Title" ), BaseMessages.getString( PKG, "MappingDialog.ErrorLoadingSpecifiedTransformation.Message" ), e ); return; } mappingMeta.setSpecificationMethod( getSpecificationMethod() ); switch( getSpecificationMethod() ) { case FILENAME: mappingMeta.setFileName( wFilename.getText() ); mappingMeta.setDirectoryPath( null ); mappingMeta.setTransName( null ); mappingMeta.setTransObjectId( null ); break; case REPOSITORY_BY_NAME: mappingMeta.setDirectoryPath( wDirectory.getText() ); mappingMeta.setTransName( wTransname.getText() ); mappingMeta.setFileName( null ); mappingMeta.setTransObjectId( null ); break; case REPOSITORY_BY_REFERENCE: mappingMeta.setFileName( null ); mappingMeta.setDirectoryPath( null ); mappingMeta.setTransName( null ); mappingMeta.setTransObjectId( getReferenceObjectId() ); break; default: break; } // Load the information on the tabs, optionally do some // verifications... // collectInformation(); mappingMeta.setMappingParameters( mappingParameters ); mappingMeta.setInputMappings( inputMappings ); // Set the input steps for input mappings mappingMeta.searchInfoAndTargetSteps( transMeta.getSteps() ); mappingMeta.setOutputMappings( outputMappings ); mappingMeta.setAllowingMultipleInputs( wMultiInput.getSelection() ); mappingMeta.setAllowingMultipleOutputs( wMultiOutput.getSelection() ); mappingMeta.setChanged( true ); dispose(); } private void collectInformation() { for ( ApplyChanges applyChanges : changeList ) { applyChanges.applyChanges(); // collect information from all // tabs... } } // Method is defined as package-protected in order to be accessible by unit tests ObjectId getReferenceObjectId() { return referenceObjectId; } private void setReferenceObjectId( ObjectId referenceObjectId ) { this.referenceObjectId = referenceObjectId; } // Method is defined as package-protected in order to be accessible by unit tests ObjectLocationSpecificationMethod getSpecificationMethod() { return specificationMethod; } private void setSpecificationMethod( ObjectLocationSpecificationMethod specificationMethod ) { this.specificationMethod = specificationMethod; } }
apache-2.0
asedunov/intellij-community
plugins/svn4idea/testSource/org/jetbrains/idea/svn/MockSvnRepository.java
2100
/* * Copyright 2000-2012 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 org.jetbrains.idea.svn; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.internal.io.fs.FSRepository; import org.tmatesoft.svn.core.io.ISVNConnectionListener; import org.tmatesoft.svn.core.io.ISVNSession; public class MockSvnRepository extends FSRepository { private long myCreationTime; private boolean mySessionWasClosed; private boolean myHaveConnectionListener; public MockSvnRepository(SVNURL location, ISVNSession options) { super(location, options); myCreationTime = System.currentTimeMillis(); mySessionWasClosed = false; myHaveConnectionListener = false; } @Override public void addConnectionListener(ISVNConnectionListener listener) { super.addConnectionListener(listener); myHaveConnectionListener = true; } // todo count? @Override public void removeConnectionListener(ISVNConnectionListener listener) { super.removeConnectionListener(listener); myHaveConnectionListener = false; } @Override public void closeSession() { super.closeSession(); mySessionWasClosed = true; } public boolean isSessionWasClosed() { return mySessionWasClosed; } public long getCreationTime() { return myCreationTime; } public boolean isHaveConnectionListener() { return myHaveConnectionListener; } @Override public void fireConnectionClosed() { super.fireConnectionClosed(); } @Override public void fireConnectionOpened() { super.fireConnectionOpened(); } }
apache-2.0
pspaude/uPortal
uportal-war/src/main/java/org/jasig/portal/portlet/container/services/PersonDirectoryUserInfoService.java
9940
/** * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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.jasig.portal.portlet.container.services; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.portlet.PortletRequest; import javax.servlet.http.HttpServletRequest; import org.apache.pluto.container.PortletContainerException; import org.apache.pluto.container.PortletWindow; import org.apache.pluto.container.UserInfoService; import org.apache.pluto.container.om.portlet.PortletApplicationDefinition; import org.apache.pluto.container.om.portlet.UserAttribute; import org.jasig.portal.portlet.om.IPortletDefinition; import org.jasig.portal.portlet.om.IPortletEntity; import org.jasig.portal.portlet.om.IPortletWindow; import org.jasig.portal.portlet.registry.IPortletDefinitionRegistry; import org.jasig.portal.portlet.registry.IPortletEntityRegistry; import org.jasig.portal.portlet.registry.IPortletWindowRegistry; import org.jasig.portal.url.IPortalRequestUtils; import org.jasig.services.persondir.IPersonAttributeDao; import org.jasig.services.persondir.IPersonAttributes; import org.springframework.beans.factory.annotation.Autowired; /** * Ties the IPersonAttributeDao to the Pluto UserInfoService * * @author Eric Dalquist * @version $Revision$ */ public class PersonDirectoryUserInfoService implements UserInfoService { private IPersonAttributeDao personAttributeDao; private IPortletWindowRegistry portletWindowRegistry; private IPortletEntityRegistry portletEntityRegistry; private IPortletDefinitionRegistry portletDefinitionRegistry; private IPortalRequestUtils portalRequestUtils; /** * @return the portalRequestUtils */ public IPortalRequestUtils getPortalRequestUtils() { return portalRequestUtils; } /** * @param portalRequestUtils the portalRequestUtils to set */ @Autowired public void setPortalRequestUtils(IPortalRequestUtils portalRequestUtils) { this.portalRequestUtils = portalRequestUtils; } /** * @return the portletEntityRegistry */ public IPortletEntityRegistry getPortletEntityRegistry() { return this.portletEntityRegistry; } /** * @param portletEntityRegistry the portletEntityRegistry to set */ @Autowired public void setPortletEntityRegistry(IPortletEntityRegistry portletEntityRegistry) { this.portletEntityRegistry = portletEntityRegistry; } /** * @return the personAttributeDao */ public IPersonAttributeDao getPersonAttributeDao() { return this.personAttributeDao; } /** * @param personAttributeDao the personAttributeDao to set */ @Autowired public void setPersonAttributeDao(IPersonAttributeDao personAttributeDao) { this.personAttributeDao = personAttributeDao; } /** * @return the portletWindowRegistry */ public IPortletWindowRegistry getPortletWindowRegistry() { return this.portletWindowRegistry; } /** * @param portletWindowRegistry the portletWindowRegistry to set */ @Autowired public void setPortletWindowRegistry(IPortletWindowRegistry portletWindowRegistry) { this.portletWindowRegistry = portletWindowRegistry; } /** * @return the portletDefinitionRegistry */ public IPortletDefinitionRegistry getPortletDefinitionRegistry() { return this.portletDefinitionRegistry; } /** * @param portletDefinitionRegistry the portletDefinitionRegistry to set */ @Autowired public void setPortletDefinitionRegistry(IPortletDefinitionRegistry portletDefinitionRegistry) { this.portletDefinitionRegistry = portletDefinitionRegistry; } /* (non-Javadoc) * @see org.apache.pluto.spi.optional.UserInfoService#getUserInfo(javax.portlet.PortletRequest, org.apache.pluto.PortletWindow) */ public Map<String, String> getUserInfo(PortletRequest request, PortletWindow plutoPortletWindow) throws PortletContainerException { //Get the remote user final String remoteUser = request.getRemoteUser(); if (remoteUser == null) { return null; } final HttpServletRequest httpServletRequest = this.portalRequestUtils.getPortletHttpRequest(request); final IPortletWindow portletWindow = this.portletWindowRegistry.convertPortletWindow(httpServletRequest, plutoPortletWindow); return this.getUserInfo(remoteUser, httpServletRequest, portletWindow); } /** * Commons logic to get a subset of the user's attributes for the specified portlet window. * * @param remoteUser The user to get attributes for. * @param httpServletRequest The current, underlying httpServletRequest * @param portletWindow The window to filter attributes for * @return A Map of user attributes for the user and windows * @throws PortletContainerException */ protected Map<String, String> getUserInfo(String remoteUser, HttpServletRequest httpServletRequest, IPortletWindow portletWindow) throws PortletContainerException { //Get the list of user attributes the portal knows about the user final IPersonAttributes personAttributes = this.personAttributeDao.getPerson(remoteUser); if (personAttributes == null) { return Collections.emptyMap(); } final List<? extends UserAttribute> expectedUserAttributes = this.getExpectedUserAttributes(httpServletRequest, portletWindow); final Map<String, String> portletUserAttributes = this.generateUserInfo(personAttributes, expectedUserAttributes, httpServletRequest); return portletUserAttributes; } /** * Using the Map of portal user attributes and a List of expected attributes generate the USER_INFO map for the portlet * * @param portalUserAttributes All the attributes the portal knows about the user * @param expectedUserAttributes The attributes the portlet expects to get * @return The Map to use for the USER_INFO attribute */ protected Map<String, String> generateUserInfo(final IPersonAttributes personAttributes, final List<? extends UserAttribute> expectedUserAttributes,HttpServletRequest httpServletRequest) { final Map<String, String> portletUserAttributes = new HashMap<String, String>(expectedUserAttributes.size()); //Copy expected attributes to the USER_INFO Map final Map<String, List<Object>> attributes = personAttributes.getAttributes(); for (final UserAttribute userAttributeDD : expectedUserAttributes) { final String attributeName = userAttributeDD.getName(); //TODO a personAttributes.hasAttribute(String) API is needed here, if hasAttribute and null then put the key with no value in the returned map if (attributes.containsKey(attributeName)) { final Object valueObj = personAttributes.getAttributeValue(attributeName); final String value = valueObj == null ? null : String.valueOf(valueObj); portletUserAttributes.put(attributeName, value); } } return portletUserAttributes; } /** * Converts the full portal user attribute Map to a USER_INFO map for the portlet * * @param portalUserAttributes All the attributes the portal knows about the user * @return The Map to use for the USER_INFO attribute */ protected Map<String, String> generateUserInfo(final Map<String, Object> portalUserAttributes) { final Map<String, String> portletUserAttributes = new HashMap<String, String>(portalUserAttributes.size()); //Copy expected attributes to the USER_INFO Map for (final Map.Entry<String, Object> portalUserAttributeEntry : portalUserAttributes.entrySet()) { final String attributeName = portalUserAttributeEntry.getKey(); final Object valueObj = portalUserAttributeEntry.getValue(); final String value = String.valueOf(valueObj); portletUserAttributes.put(attributeName, value); } return portletUserAttributes; } /** * Get the list of user attributes the portlet expects * * @param request The current request. * @param portletWindow The window to get the expected user attributes for. * @return The List of expected user attributes for the portlet * @throws PortletContainerException If expected attributes cannot be determined */ protected List<? extends UserAttribute> getExpectedUserAttributes(HttpServletRequest request, final IPortletWindow portletWindow) throws PortletContainerException { final IPortletEntity portletEntity = portletWindow.getPortletEntity(); final IPortletDefinition portletDefinition = portletEntity.getPortletDefinition(); final PortletApplicationDefinition portletApplicationDescriptor = this.portletDefinitionRegistry.getParentPortletApplicationDescriptor(portletDefinition.getPortletDefinitionId()); return portletApplicationDescriptor.getUserAttributes(); } }
apache-2.0
siosio/intellij-community
plugins/devkit/devkit-java-tests/testData/inspections/internal/com/intellij/openapi/vfs/VirtualFile.java
902
package com.intellij.openapi.vfs; public abstract class VirtualFile { void test() { assert this == this; assert this != this; VirtualFileImpl first = new VirtualFileImpl(); VirtualFile second = new VirtualFileImpl(); assert first == null; assert first != null; assert this == second; assert second != this; assert <warning descr="'VirtualFile' instances should be compared by 'equals()', not '=='">first == second</warning>; assert <warning descr="'VirtualFile' instances should be compared by 'equals()', not '=='">first != second</warning>; assert <warning descr="'VirtualFile' instances should be compared by 'equals()', not '=='">second == first</warning>; assert <warning descr="'VirtualFile' instances should be compared by 'equals()', not '=='">second != first</warning>; } static final class VirtualFileImpl extends VirtualFile {} }
apache-2.0
robin13/elasticsearch
server/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java
14348
/* * 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.search.suggest; import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.elasticsearch.Version; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.AnalyzerScope; import org.elasticsearch.index.analysis.IndexAnalyzers; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.Mapping; import org.elasticsearch.index.mapper.MappingLookup; import org.elasticsearch.index.mapper.MockFieldMapper; import org.elasticsearch.index.mapper.TextFieldMapper; import org.elasticsearch.index.mapper.TextSearchInfo; import org.elasticsearch.index.query.SearchExecutionContext; import org.elasticsearch.ingest.TestTemplateService; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchModule; import org.elasticsearch.search.suggest.SuggestionSearchContext.SuggestionContext; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.test.IndexSettingsModule; import org.junit.AfterClass; import org.junit.BeforeClass; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static org.elasticsearch.common.lucene.BytesRefs.toBytesRef; import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public abstract class AbstractSuggestionBuilderTestCase<SB extends SuggestionBuilder<SB>> extends ESTestCase { private static final int NUMBER_OF_TESTBUILDERS = 20; protected static NamedWriteableRegistry namedWriteableRegistry; protected static NamedXContentRegistry xContentRegistry; /** * setup for the whole base test class */ @BeforeClass public static void init() { SearchModule searchModule = new SearchModule(Settings.EMPTY, emptyList()); namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables()); xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents()); } @AfterClass public static void afterClass() { namedWriteableRegistry = null; xContentRegistry = null; } /** * Test serialization and deserialization of the suggestion builder */ public void testSerialization() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB original = randomTestBuilder(); SB deserialized = copy(original); assertEquals(deserialized, original); assertEquals(deserialized.hashCode(), original.hashCode()); assertNotSame(deserialized, original); } } /** * returns a random suggestion builder, setting the common options randomly */ protected SB randomTestBuilder() { return randomSuggestionBuilder(); } public static void setCommonPropertiesOnRandomBuilder(SuggestionBuilder<?> randomSuggestion) { randomSuggestion.text(randomAlphaOfLengthBetween(2, 20)); // have to set the text because we don't know if the global text was set maybeSet(randomSuggestion::prefix, randomAlphaOfLengthBetween(2, 20)); maybeSet(randomSuggestion::regex, randomAlphaOfLengthBetween(2, 20)); maybeSet(randomSuggestion::analyzer, randomAlphaOfLengthBetween(2, 20)); maybeSet(randomSuggestion::size, randomIntBetween(1, 20)); maybeSet(randomSuggestion::shardSize, randomIntBetween(1, 20)); } /** * create a randomized {@link SuggestBuilder} that is used in further tests */ protected abstract SB randomSuggestionBuilder(); /** * Test equality and hashCode properties */ public void testEqualsAndHashcode() { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { checkEqualsAndHashCode(randomTestBuilder(), this::copy, this::mutate); } } /** * creates random suggestion builder, renders it to xContent and back to new * instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB suggestionBuilder = randomTestBuilder(); XContentBuilder xContentBuilder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { xContentBuilder.prettyPrint(); } xContentBuilder.startObject(); suggestionBuilder.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS); xContentBuilder.endObject(); XContentBuilder shuffled = shuffleXContent(xContentBuilder, shuffleProtectedFields()); try (XContentParser parser = createParser(shuffled)) { // we need to skip the start object and the name, those will be parsed by outer SuggestBuilder parser.nextToken(); SuggestionBuilder<?> secondSuggestionBuilder = SuggestionBuilder.fromXContent(parser); assertNotSame(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder, secondSuggestionBuilder); assertEquals(suggestionBuilder.hashCode(), secondSuggestionBuilder.hashCode()); } } } public void testBuild() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { SB suggestionBuilder = randomTestBuilder(); Settings indexSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(new Index(randomAlphaOfLengthBetween(1, 10), "_na_"), indexSettings); ScriptService scriptService = mock(ScriptService.class); MappedFieldType fieldType = mockFieldType(suggestionBuilder.field()); IndexAnalyzers indexAnalyzers = new IndexAnalyzers( new HashMap<>() { @Override public NamedAnalyzer get(Object key) { return new NamedAnalyzer(key.toString(), AnalyzerScope.INDEX, new SimpleAnalyzer()); } }, Collections.emptyMap(), Collections.emptyMap()); MapperService mapperService = mock(MapperService.class); when(mapperService.getIndexAnalyzers()).thenReturn(indexAnalyzers); when(scriptService.compile(any(Script.class), any())).then(invocation -> new TestTemplateService.MockTemplateScript.Factory( ((Script) invocation.getArguments()[0]).getIdOrCode())); List<FieldMapper> mappers = Collections.singletonList(new MockFieldMapper(fieldType)); MappingLookup lookup = MappingLookup.fromMappers(Mapping.EMPTY, mappers, emptyList(), emptyList()); SearchExecutionContext mockContext = new SearchExecutionContext(0, 0, idxSettings, null, null, mapperService, lookup, null, scriptService, xContentRegistry(), namedWriteableRegistry, null, null, System::currentTimeMillis, null, null, () -> true, null, emptyMap()); SuggestionContext suggestionContext = suggestionBuilder.build(mockContext); assertEquals(toBytesRef(suggestionBuilder.text()), suggestionContext.getText()); if (suggestionBuilder.text() != null && suggestionBuilder.prefix() == null) { assertEquals(toBytesRef(suggestionBuilder.text()), suggestionContext.getPrefix()); } else { assertEquals(toBytesRef(suggestionBuilder.prefix()), suggestionContext.getPrefix()); } assertEquals(toBytesRef(suggestionBuilder.regex()), suggestionContext.getRegex()); assertEquals(suggestionBuilder.field(), suggestionContext.getField()); int expectedSize = suggestionBuilder.size() != null ? suggestionBuilder.size : 5; assertEquals(expectedSize, suggestionContext.getSize()); Integer expectedShardSize = suggestionBuilder.shardSize != null ? suggestionBuilder.shardSize : Math.max(expectedSize, 5); assertEquals(expectedShardSize, suggestionContext.getShardSize()); assertSame(mockContext, suggestionContext.getSearchExecutionContext()); if (suggestionBuilder.analyzer() != null) { assertEquals(suggestionBuilder.analyzer(), ((NamedAnalyzer) suggestionContext.getAnalyzer()).name()); } else { assertEquals("fieldSearchAnalyzer", ((NamedAnalyzer) suggestionContext.getAnalyzer()).name()); } assertSuggestionContext(suggestionBuilder, suggestionContext); } } public void testBuildWithUnmappedField() { Settings.Builder builder = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT); if (randomBoolean()) { builder.put(IndexSettings.ALLOW_UNMAPPED.getKey(), randomBoolean()); } Settings indexSettings = builder.build(); IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(new Index(randomAlphaOfLengthBetween(1, 10), "_na_"), indexSettings); SearchExecutionContext mockContext = new SearchExecutionContext(0, 0, idxSettings, null, null, mock(MapperService.class), MappingLookup.EMPTY, null, null, xContentRegistry(), namedWriteableRegistry, null, null, System::currentTimeMillis, null, null, () -> true, null, emptyMap()); if (randomBoolean()) { mockContext.setAllowUnmappedFields(randomBoolean()); } SB suggestionBuilder = randomTestBuilder(); IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> suggestionBuilder.build(mockContext)); assertEquals("no mapping found for field [" + suggestionBuilder.field + "]", iae.getMessage()); } /** * put implementation dependent assertions in the sub-type test */ protected abstract void assertSuggestionContext(SB builder, SuggestionContext context) throws IOException; protected MappedFieldType mockFieldType(String fieldName) { MappedFieldType fieldType = mock(MappedFieldType.class); when(fieldType.name()).thenReturn(fieldName); NamedAnalyzer searchAnalyzer = new NamedAnalyzer("fieldSearchAnalyzer", AnalyzerScope.INDEX, new SimpleAnalyzer()); TextSearchInfo tsi = new TextSearchInfo(TextFieldMapper.Defaults.FIELD_TYPE, null, searchAnalyzer, searchAnalyzer); when(fieldType.getTextSearchInfo()).thenReturn(tsi); return fieldType; } /** * Subclasses can override this method and return a set of fields which should be protected from * recursive random shuffling in the {@link #testFromXContent()} test case */ protected String[] shuffleProtectedFields() { return new String[0]; } private SB mutate(SB firstBuilder) throws IOException { SB mutation = copy(firstBuilder); assertNotSame(mutation, firstBuilder); // change ither one of the shared SuggestionBuilder parameters, or delegate to the specific tests mutate method if (randomBoolean()) { switch (randomIntBetween(0, 5)) { case 0: mutation.text(randomValueOtherThan(mutation.text(), () -> randomAlphaOfLengthBetween(2, 20))); break; case 1: mutation.prefix(randomValueOtherThan(mutation.prefix(), () -> randomAlphaOfLengthBetween(2, 20))); break; case 2: mutation.regex(randomValueOtherThan(mutation.regex(), () -> randomAlphaOfLengthBetween(2, 20))); break; case 3: mutation.analyzer(randomValueOtherThan(mutation.analyzer(), () -> randomAlphaOfLengthBetween(2, 20))); break; case 4: mutation.size(randomValueOtherThan(mutation.size(), () -> randomIntBetween(1, 20))); break; case 5: mutation.shardSize(randomValueOtherThan(mutation.shardSize(), () -> randomIntBetween(1, 20))); break; } } else { mutateSpecificParameters(firstBuilder); } return mutation; } /** * take and input {@link SuggestBuilder} and return another one that is * different in one aspect (to test non-equality) */ protected abstract void mutateSpecificParameters(SB firstBuilder) throws IOException; @SuppressWarnings("unchecked") protected SB copy(SB original) throws IOException { return copyWriteable(original, namedWriteableRegistry, (Writeable.Reader<SB>) namedWriteableRegistry.getReader(SuggestionBuilder.class, original.getWriteableName())); } @Override protected NamedXContentRegistry xContentRegistry() { return xContentRegistry; } }
apache-2.0
mdecourci/assertj-core
src/test/java/org/assertj/core/api/fail/Fail_fest_elements_stack_trace_filtering_Test.java
1721
/** * 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. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.api.fail; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.util.StackTraceUtils.hasStackTraceElementRelatedToAssertJ; import org.assertj.core.api.Fail; import org.junit.Test; /** * Tests for <code>{@link Fail#setRemoveAssertJRelatedElementsFromStackTrace(boolean)}</code>. * * @author Joel Costigliola */ public class Fail_fest_elements_stack_trace_filtering_Test { @Test public void fest_elements_should_be_removed_from_assertion_error_stack_trace() { Fail.setRemoveAssertJRelatedElementsFromStackTrace(true); try { assertThat(5).isLessThan(0); } catch (AssertionError assertionError) { assertThat(hasStackTraceElementRelatedToAssertJ(assertionError)).isFalse(); } } @Test public void fest_elements_should_be_kept_in_assertion_error_stack_trace() { Fail.setRemoveAssertJRelatedElementsFromStackTrace(false); try { assertThat(5).isLessThan(0); } catch (AssertionError assertionError) { assertThat(hasStackTraceElementRelatedToAssertJ(assertionError)).isTrue(); } } }
apache-2.0
ravipesala/incubator-carbondata
core/src/main/java/org/apache/carbondata/core/readcommitter/ReadCommittedIndexFileSnapShot.java
2076
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.carbondata.core.readcommitter; import java.io.Serializable; import java.util.List; import java.util.Map; import org.apache.carbondata.common.annotations.InterfaceAudience; import org.apache.carbondata.common.annotations.InterfaceStability; import org.apache.carbondata.core.statusmanager.SegmentRefreshInfo; /** * This class is going to save the the Index files which are taken snapshot * from the readCommitter Interface. */ @InterfaceAudience.Internal @InterfaceStability.Evolving public class ReadCommittedIndexFileSnapShot implements Serializable { /** * Segment Numbers are mapped with list of Index Files. */ private Map<String, List<String>> segmentIndexFileMap; private Map<String, SegmentRefreshInfo> segmentTimestampUpdaterMap; public ReadCommittedIndexFileSnapShot(Map<String, List<String>> segmentIndexFileMap, Map<String, SegmentRefreshInfo> segmentTimestampUpdaterMap) { this.segmentIndexFileMap = segmentIndexFileMap; this.segmentTimestampUpdaterMap = segmentTimestampUpdaterMap; } public Map<String, List<String>> getSegmentIndexFileMap() { return segmentIndexFileMap; } public Map<String, SegmentRefreshInfo> getSegmentTimestampUpdaterMap() { return segmentTimestampUpdaterMap; } }
apache-2.0
mdecourci/assertj-core
src/test/java/org/assertj/core/internal/objects/Objects_assertHasSameClassAs_Test.java
2471
/** * 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. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.internal.objects; import static org.assertj.core.error.ShouldHaveSameClass.shouldHaveSameClass; import static org.assertj.core.test.TestData.someInfo; import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown; import static org.assertj.core.util.FailureMessages.actualIsNull; import static org.mockito.Mockito.verify; import org.assertj.core.api.AssertionInfo; import org.assertj.core.internal.Objects; import org.assertj.core.internal.ObjectsBaseTest; import org.assertj.core.test.Person; import org.junit.BeforeClass; import org.junit.Test; /** * Tests for <code>{@link Objects#assertHasSameClassAs(AssertionInfo, Object, Object)}</code>. * * @author Nicolas François * @author Joel Costigliola */ public class Objects_assertHasSameClassAs_Test extends ObjectsBaseTest { private static Person actual; @BeforeClass public static void setUpOnce() { actual = new Person("Yoda"); } @Test public void should_pass_if_actual_has_same_type_as_other() { objects.assertHasSameClassAs(someInfo(), actual, new Person("Luke")); } @Test public void should_throw_error_if_type_is_null() { thrown.expectNullPointerException("The given object should not be null"); objects.assertHasSameClassAs(someInfo(), actual, null); } @Test public void should_fail_if_actual_is_null() { thrown.expectAssertionError(actualIsNull()); objects.assertHasSameClassAs(someInfo(), null, new Person("Luke")); } @Test public void should_pass_if_actual_not_has_same_type_as_other() { AssertionInfo info = someInfo(); try { objects.assertHasSameClassAs(info, actual, "Yoda"); failBecauseExpectedAssertionErrorWasNotThrown(); } catch (AssertionError err) { verify(failures).failure(info, shouldHaveSameClass(actual, "Yoda")); } } }
apache-2.0
smmribeiro/intellij-community
python/python-psi-impl/src/com/jetbrains/python/validation/AssignTargetAnnotator.java
11767
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jetbrains.python.validation; import com.intellij.codeInspection.util.InspectionMessage; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyPsiBundle; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.sdk.PythonSdkUtil; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.jetbrains.python.PyPsiBundle.message; public class AssignTargetAnnotator extends PyAnnotator { private enum Operation { Assign, AugAssign, Delete, Except, For, With } @Override public void visitPyAssignmentStatement(final @NotNull PyAssignmentStatement node) { for (PyExpression expression : node.getRawTargets()) { expression.accept(new ExprVisitor(Operation.Assign)); } PyExpression expression = node.getAssignedValue(); if (expression instanceof PyAssignmentExpression) { getHolder() .newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.unparenthesized.assignment.expression.value")) .range(expression) .create(); } } @Override public void visitPyAugAssignmentStatement(final @NotNull PyAugAssignmentStatement node) { node.getTarget().accept(new ExprVisitor(Operation.AugAssign)); } @Override public void visitPyDelStatement(final @NotNull PyDelStatement node) { ExprVisitor visitor = new ExprVisitor(Operation.Delete); for (PyExpression expr : node.getTargets()) { expr.accept(visitor); } } @Override public void visitPyExceptBlock(final @NotNull PyExceptPart node) { PyExpression target = node.getTarget(); if (target != null) { target.accept(new ExprVisitor(Operation.Except)); } } @Override public void visitPyForStatement(final @NotNull PyForStatement node) { PyExpression target = node.getForPart().getTarget(); if (target != null) { target.accept(new ExprVisitor(Operation.For)); checkNotAssignmentExpression(target, PyPsiBundle.message("ANN.assignment.expression.as.a.target")); } } @Override public void visitPyWithItem(@NotNull PyWithItem node) { PyExpression target = node.getTarget(); if (target != null) { target.accept(new ExprVisitor(Operation.With)); } } @Override public void visitPyExpressionStatement(@NotNull PyExpressionStatement node) { PyExpression expression = node.getExpression(); if (expression instanceof PyAssignmentExpression) { getHolder() .newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.unparenthesized.assignment.expression.statement")) .range(expression) .create(); } } @Override public void visitPyAssignmentExpression(@NotNull PyAssignmentExpression node) { final PyComprehensionElement comprehensionElement = PsiTreeUtil.getParentOfType(node, PyComprehensionElement.class, true, ScopeOwner.class); if (ScopeUtil.getScopeOwner(comprehensionElement) instanceof PyClass) { getHolder().newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.assignment.expressions.within.a.comprehension.cannot.be.used.in.a.class.body")).create(); } } @Override public void visitPyComprehensionElement(@NotNull PyComprehensionElement node) { final String targetMessage = PyPsiBundle.message("ANN.assignment.expression.as.a.target"); final String iterableMessage = PyPsiBundle.message("ANN.assignment.expression.in.an.iterable"); node.getForComponents().forEach( it -> { checkNotAssignmentExpression(it.getIteratorVariable(), targetMessage); checkNoAssignmentExpressionAsChild(it.getIteratedList(), iterableMessage); } ); } private void checkNoAssignmentExpressionAsChild(@Nullable PyExpression expression, @NotNull @InspectionMessage String message) { PsiTreeUtil .findChildrenOfType(expression, PyAssignmentExpression.class) .forEach(it -> checkNotAssignmentExpression(it, message)); } private void checkNotAssignmentExpression(@Nullable PyExpression expression, @NotNull @InspectionMessage String message) { if (PyPsiUtils.flattenParens(expression) instanceof PyAssignmentExpression) { getHolder() .newAnnotation(HighlightSeverity.ERROR, message) .range(expression) .create(); } } private class ExprVisitor extends PyElementVisitor { private final Operation myOp; private final @Nls String DELETING_NONE = message("ANN.deleting.none"); private final @Nls String ASSIGNMENT_TO_NONE = message("ANN.assign.to.none"); private final @Nls String CANT_ASSIGN_TO_FUNCTION_CALL = message("ANN.cant.assign.to.call"); private final @Nls String CANT_DELETE_FUNCTION_CALL = message("ANN.cant.delete.call"); ExprVisitor(Operation op) { myOp = op; } @Override public void visitPyReferenceExpression(final @NotNull PyReferenceExpression node) { String referencedName = node.getReferencedName(); if (PyNames.NONE.equals(referencedName)) { //noinspection DialogTitleCapitalization getHolder().newAnnotation(HighlightSeverity.ERROR, (myOp == Operation.Delete) ? DELETING_NONE : ASSIGNMENT_TO_NONE).range(node).create(); } } @Override public void visitPyTargetExpression(final @NotNull PyTargetExpression node) { String targetName = node.getName(); if (PyNames.NONE.equals(targetName)) { final VirtualFile vfile = node.getContainingFile().getVirtualFile(); if (vfile != null && !vfile.getUrl().contains("/" + PythonSdkUtil.SKELETON_DIR_NAME + "/")){ //noinspection DialogTitleCapitalization getHolder().newAnnotation(HighlightSeverity.ERROR, (myOp == Operation.Delete) ? DELETING_NONE : ASSIGNMENT_TO_NONE).range(node).create(); } } if (PyNames.DEBUG.equals(targetName)) { if (LanguageLevel.forElement(node).isPy3K()) { getHolder().newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.assignment.to.keyword")).range(node).create(); } else { getHolder().newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.cannot.assign.to.debug")).range(node).create(); } } } @Override public void visitPyCallExpression(final @NotNull PyCallExpression node) { getHolder().newAnnotation(HighlightSeverity.ERROR, (myOp == Operation.Delete) ? CANT_DELETE_FUNCTION_CALL : CANT_ASSIGN_TO_FUNCTION_CALL).range(node).create(); } @Override public void visitPyGeneratorExpression(final @NotNull PyGeneratorExpression node) { getHolder().newAnnotation(HighlightSeverity.ERROR, message( myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.generator" : "ANN.cant.assign.to.generator")).range(node).create(); } @Override public void visitPyBinaryExpression(final @NotNull PyBinaryExpression node) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.cant.assign.to.operator")).range(node).create(); } @Override public void visitPyTupleExpression(final @NotNull PyTupleExpression node) { if (node.isEmpty() && LanguageLevel.forElement(node).isPython2()) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.cant.assign.to.parens")).range(node).create(); } else if (myOp == Operation.AugAssign) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.cant.aug.assign.to.tuple.or.generator")).range(node).create(); } else { node.acceptChildren(this); } } @Override public void visitPyParenthesizedExpression(final @NotNull PyParenthesizedExpression node) { if (myOp == Operation.AugAssign) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.cant.aug.assign.to.tuple.or.generator")).range(node).create(); } else { node.acceptChildren(this); } } @Override public void visitPyListLiteralExpression(final @NotNull PyListLiteralExpression node) { if (myOp == Operation.AugAssign) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.cant.aug.assign.to.list.or.comprh")).range(node).create(); } else { node.acceptChildren(this); } } @Override public void visitPyListCompExpression(final @NotNull PyListCompExpression node) { markError(node, message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.comprh" : "ANN.cant.assign.to.comprh")); } @Override public void visitPyDictCompExpression(@NotNull PyDictCompExpression node) { markError(node, message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.dict.comprh" : "ANN.cant.assign.to.dict.comprh")); } @Override public void visitPySetCompExpression(@NotNull PySetCompExpression node) { markError(node, message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.set.comprh" : "ANN.cant.assign.to.set.comprh")); } @Override public void visitPyStarExpression(@NotNull PyStarExpression node) { super.visitPyStarExpression(node); if (!(node.getParent() instanceof PySequenceExpression)) { markError(node, message("ANN.cant.aug.assign.starred.assignment.target.must.be.in.list.or.tuple")); } } @Override public void visitPyDictLiteralExpression(@NotNull PyDictLiteralExpression node) { checkLiteral(node); } @Override public void visitPySetLiteralExpression(@NotNull PySetLiteralExpression node) { checkLiteral(node); } @Override public void visitPyNumericLiteralExpression(final @NotNull PyNumericLiteralExpression node) { checkLiteral(node); } @Override public void visitPyStringLiteralExpression(final @NotNull PyStringLiteralExpression node) { checkLiteral(node); } private void checkLiteral(@NotNull PsiElement node) { getHolder().newAnnotation(HighlightSeverity.ERROR, message(myOp == Operation.Delete ? "ANN.cant.delete.literal" : "ANN.cant.assign.to.literal")).range(node).create(); } @Override public void visitPyLambdaExpression(final @NotNull PyLambdaExpression node) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.cant.assign.to.lambda")).range(node).create(); } @Override public void visitPyNoneLiteralExpression(@NotNull PyNoneLiteralExpression node) { getHolder().newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.assignment.to.keyword")).range(node).create(); } @Override public void visitPyBoolLiteralExpression(@NotNull PyBoolLiteralExpression node) { getHolder().newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.assignment.to.keyword")).range(node).create(); } } }
apache-2.0
skinzer/camel
camel-core/src/main/java/org/apache/camel/model/ConvertBodyDefinition.java
3784
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.model; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.Processor; import org.apache.camel.processor.ConvertBodyProcessor; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.Required; import org.apache.camel.spi.RouteContext; /** * Converts the message body to another type */ @Metadata(label = "eip,transformation") @XmlRootElement(name = "convertBodyTo") @XmlAccessorType(XmlAccessType.FIELD) public class ConvertBodyDefinition extends NoOutputDefinition<ConvertBodyDefinition> { @XmlAttribute(required = true) private String type; @XmlAttribute private String charset; @XmlTransient private Class<?> typeClass; public ConvertBodyDefinition() { } public ConvertBodyDefinition(String type) { setType(type); } public ConvertBodyDefinition(Class<?> typeClass) { setTypeClass(typeClass); setType(typeClass.getName()); } public ConvertBodyDefinition(Class<?> typeClass, String charset) { setTypeClass(typeClass); setType(typeClass.getName()); setCharset(charset); } @Override public String toString() { return "ConvertBodyTo[" + getType() + "]"; } @Override public String getLabel() { return "convertBodyTo[" + getType() + "]"; } public static void validateCharset(String charset) throws UnsupportedCharsetException { if (charset != null) { if (Charset.isSupported(charset)) { Charset.forName(charset); return; } } throw new UnsupportedCharsetException(charset); } @Override public Processor createProcessor(RouteContext routeContext) throws Exception { if (typeClass == null && type != null) { typeClass = routeContext.getCamelContext().getClassResolver().resolveMandatoryClass(type); } // validate charset if (charset != null) { validateCharset(charset); } return new ConvertBodyProcessor(getTypeClass(), getCharset()); } public String getType() { return type; } /** * The java type to convert to */ @Required public void setType(String type) { this.type = type; } public Class<?> getTypeClass() { return typeClass; } public void setTypeClass(Class<?> typeClass) { this.typeClass = typeClass; } public String getCharset() { return charset; } /** * To use a specific charset when converting */ public void setCharset(String charset) { this.charset = charset; } }
apache-2.0
ric2b/Vivaldi-browser
chromium/chrome/android/junit/src/org/chromium/chrome/browser/explore_sites/ExploreSitesBackgroundTaskUnitTest.java
11676
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.explore_sites; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import android.content.Context; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.mockito.invocation.InvocationOnMock; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implements; import org.robolectric.shadows.multidex.ShadowMultiDex; import org.chromium.base.Callback; import org.chromium.base.metrics.test.ShadowRecordHistogram; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.device.DeviceConditions; import org.chromium.chrome.browser.device.ShadowDeviceConditions; import org.chromium.chrome.browser.init.BrowserParts; import org.chromium.chrome.browser.init.ChromeBrowserInitializer; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.components.background_task_scheduler.BackgroundTaskScheduler; import org.chromium.components.background_task_scheduler.BackgroundTaskSchedulerFactory; import org.chromium.components.background_task_scheduler.NativeBackgroundTask; import org.chromium.components.background_task_scheduler.TaskIds; import org.chromium.components.background_task_scheduler.TaskInfo; import org.chromium.components.background_task_scheduler.TaskParameters; import org.chromium.net.ConnectionType; import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; /** Unit tests for {@link ExploreSitesBackgroundTask}. */ @RunWith(BaseRobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowMultiDex.class, ShadowDeviceConditions.class, ShadowRecordHistogram.class, ExploreSitesBackgroundTaskUnitTest.ShadowExploreSitesBridge.class}) public class ExploreSitesBackgroundTaskUnitTest { /** Implementation of ExploreSitesBridge which does not rely on native. */ @Implements(ExploreSitesBridge.class) public static class ShadowExploreSitesBridge { public static Callback<Void> mUpdateCatalogFinishedCallback; public static int mVariation = ExploreSitesVariation.ENABLED; @Implementation public static void getEspCatalog( Profile profile, Callback<List<ExploreSitesCategory>> callback) {} @Implementation public static void updateCatalogFromNetwork( Profile profile, boolean isImmediateFetch, Callback<Void> finishedCallback) { mUpdateCatalogFinishedCallback = finishedCallback; } @Implementation @ExploreSitesVariation public static int getVariation() { return mVariation; } } /** * Fake of BackgroundTaskScheduler system service. */ public static class FakeBackgroundTaskScheduler implements BackgroundTaskScheduler { private HashMap<Integer, TaskInfo> mTaskInfos = new HashMap<>(); @Override public boolean schedule(Context context, TaskInfo taskInfo) { mTaskInfos.put(taskInfo.getTaskId(), taskInfo); return true; } @Override public void cancel(Context context, int taskId) { mTaskInfos.remove(taskId); } @Override public boolean isScheduled(Context context, int taskId) { return (mTaskInfos.get(taskId) != null); } @Override public void checkForOSUpgrade(Context context) {} @Override public void reschedule(Context context) {} public TaskInfo getTaskInfo(int taskId) { return mTaskInfos.get(taskId); } } void initDeviceConditions(@ConnectionType int connectionType) { boolean powerConnected = true; boolean powerSaveModeOn = true; int highBatteryLevel = 75; boolean metered = true; boolean screenOnAndUnlocked = true; DeviceConditions deviceConditions = new DeviceConditions(!powerConnected, highBatteryLevel, connectionType, !powerSaveModeOn, !metered, screenOnAndUnlocked); ShadowDeviceConditions.setCurrentConditions(deviceConditions); } @Spy private ExploreSitesBackgroundTask mExploreSitesBackgroundTask = new ExploreSitesBackgroundTask(); @Mock private ChromeBrowserInitializer mChromeBrowserInitializer; @Captor ArgumentCaptor<BrowserParts> mBrowserParts; private FakeBackgroundTaskScheduler mFakeTaskScheduler; public void disableExploreSites() { ShadowExploreSitesBridge.mVariation = ExploreSitesVariation.DISABLED; } @Before public void setUp() { ShadowRecordHistogram.reset(); MockitoAnnotations.initMocks(this); doNothing() .when(mChromeBrowserInitializer) .handlePreNativeStartupAndLoadLibraries(any(BrowserParts.class)); doAnswer((InvocationOnMock invocation) -> { mBrowserParts.getValue().finishNativeInitialization(); return null; }) .when(mChromeBrowserInitializer) .handlePostNativeStartup(eq(true), mBrowserParts.capture()); ChromeBrowserInitializer.setForTesting(mChromeBrowserInitializer); mFakeTaskScheduler = new FakeBackgroundTaskScheduler(); BackgroundTaskSchedulerFactory.setSchedulerForTesting(mFakeTaskScheduler); doReturn(null).when(mExploreSitesBackgroundTask).getProfile(); ShadowExploreSitesBridge.mVariation = ExploreSitesVariation.ENABLED; } @Test public void scheduleTask() { ExploreSitesBackgroundTask.schedule(false /* updateCurrent */); TaskInfo scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(scheduledTask); assertEquals(TimeUnit.HOURS.toMillis(ExploreSitesBackgroundTask.DEFAULT_DELAY_HOURS), scheduledTask.getPeriodicInfo().getIntervalMs()); assertEquals(true, scheduledTask.isPersisted()); assertEquals(TaskInfo.NetworkType.ANY, scheduledTask.getRequiredNetworkType()); } @Test public void cancelTask() { TaskInfo scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNull(scheduledTask); ExploreSitesBackgroundTask.schedule(false /* updateCurrent */); scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(scheduledTask); assertEquals(TimeUnit.HOURS.toMillis(ExploreSitesBackgroundTask.DEFAULT_DELAY_HOURS), scheduledTask.getPeriodicInfo().getIntervalMs()); ExploreSitesBackgroundTask.cancelTask(); scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNull(scheduledTask); } @Test public void testNoNetwork() { initDeviceConditions(ConnectionType.CONNECTION_NONE); TaskParameters params = TaskParameters.create(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID).build(); int result = mExploreSitesBackgroundTask.onStartTaskBeforeNativeLoaded( RuntimeEnvironment.application, params, (boolean needsReschedule) -> { fail("Finished callback should not be run, network conditions not met."); }); assertEquals(NativeBackgroundTask.StartBeforeNativeResult.RESCHEDULE, result); } @Test public void testRemovesDeprecatedJobId() { TaskInfo.Builder deprecatedTaskInfoBuilder = TaskInfo.createPeriodicTask(TaskIds.DEPRECATED_EXPLORE_SITES_REFRESH_JOB_ID, TimeUnit.HOURS.toMillis(4), TimeUnit.HOURS.toMillis(1)) .setRequiredNetworkType(TaskInfo.NetworkType.ANY) .setIsPersisted(true) .setUpdateCurrent(false); mFakeTaskScheduler.schedule( RuntimeEnvironment.application, deprecatedTaskInfoBuilder.build()); TaskInfo deprecatedTask = mFakeTaskScheduler.getTaskInfo(TaskIds.DEPRECATED_EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(deprecatedTask); ExploreSitesBackgroundTask.schedule(false /* updateCurrent */); TaskInfo scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(scheduledTask); deprecatedTask = mFakeTaskScheduler.getTaskInfo(TaskIds.DEPRECATED_EXPLORE_SITES_REFRESH_JOB_ID); assertNull(deprecatedTask); } @Test public void testRemovesTaskIfFeatureIsDisabled() { disableExploreSites(); TaskInfo.Builder taskInfoBuilder = TaskInfo.createPeriodicTask(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID, TimeUnit.HOURS.toMillis(4), TimeUnit.HOURS.toMillis(1)) .setRequiredNetworkType(TaskInfo.NetworkType.ANY) .setIsPersisted(true) .setUpdateCurrent(false); mFakeTaskScheduler.schedule(RuntimeEnvironment.application, taskInfoBuilder.build()); TaskInfo task = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(task); TaskParameters params = TaskParameters.create(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID).build(); mExploreSitesBackgroundTask.onStartTaskWithNative( RuntimeEnvironment.application, params, (boolean needsReschedule) -> { fail("Finished callback should not be run, the task should be cancelled."); }); TaskInfo scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNull(scheduledTask); } @Test public void testDoesNotRemoveTaskIfFeatureIsEnabled() { TaskInfo.Builder taskInfoBuilder = TaskInfo.createPeriodicTask(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID, TimeUnit.HOURS.toMillis(4), TimeUnit.HOURS.toMillis(1)) .setRequiredNetworkType(TaskInfo.NetworkType.ANY) .setIsPersisted(true) .setUpdateCurrent(false); mFakeTaskScheduler.schedule(RuntimeEnvironment.application, taskInfoBuilder.build()); TaskInfo task = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(task); TaskParameters params = TaskParameters.create(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID).build(); mExploreSitesBackgroundTask.onStartTaskWithNative(RuntimeEnvironment.application, params, (boolean needsReschedule) -> { fail("Finished callback should not be run"); }); TaskInfo scheduledTask = mFakeTaskScheduler.getTaskInfo(TaskIds.EXPLORE_SITES_REFRESH_JOB_ID); assertNotNull(scheduledTask); } }
bsd-3-clause
ric2b/Vivaldi-browser
chromium/chrome/android/java/src/org/chromium/chrome/browser/ntp/IncognitoDescriptionView.java
1529
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.ntp; import android.view.View; import android.widget.CompoundButton; /** * This interface includes methods that are shared in LegacyIncognitoDescriptionView and * RevampedIncognitoDescriptionView. */ public interface IncognitoDescriptionView { /** * Set learn more on click listener. * @param listener The given listener. */ void setLearnMoreOnclickListener(View.OnClickListener listener); /** * Set cookie controls toggle's checked value. * @param enabled The value to set the toggle to. */ void setCookieControlsToggle(boolean enabled); /** * Set cookie controls toggle on checked change listerner. * @param listener The given listener. */ void setCookieControlsToggleOnCheckedChangeListener( CompoundButton.OnCheckedChangeListener listener); /** * Sets the cookie controls enforced state. * @param enforcement A CookieControlsEnforcement enum type indicating the type of * enforcement policy being applied to Cookie Controls. */ void setCookieControlsEnforcement(int enforcement); /** * Add click listener that redirects user to the Cookie Control Settings. * @param listener The given listener. */ void setCookieControlsIconOnclickListener(View.OnClickListener listener); }
bsd-3-clause
Mr-DLib/jabref
src/main/java/net/sf/jabref/logic/importer/WebFetcher.java
626
package net.sf.jabref.logic.importer; import net.sf.jabref.logic.help.HelpFile; /** * Searches web resources for bibliographic information. */ public interface WebFetcher { /** * Returns the localized name of this fetcher. * The title can be used to display the fetcher in the menu and in the side pane. * * @return the localized name */ String getName(); /** * Returns the help page for this fetcher. * * @return the {@link HelpFile} enum constant for the help page */ default HelpFile getHelpPage() { return null; // no help page by default } }
mit
yoolk/fakie
lib/fakie/js/java/libphonenumber/src/com/google/i18n/phonenumbers/ShortNumberInfo.java
18190
/* * Copyright (C) 2013 The Libphonenumber Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.i18n.phonenumbers; import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata; import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; /** * Methods for getting information about short phone numbers, such as short codes and emergency * numbers. Note that most commercial short numbers are not handled here, but by the * {@link PhoneNumberUtil}. * * @author Shaopeng Jia * @author David Yonge-Mallo */ public class ShortNumberInfo { private static final Logger logger = Logger.getLogger(ShortNumberInfo.class.getName()); private static final ShortNumberInfo INSTANCE = new ShortNumberInfo(PhoneNumberUtil.getInstance()); // In these countries, if extra digits are added to an emergency number, it no longer connects // to the emergency service. private static final Set<String> REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT = new HashSet<String>(); static { REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT.add("BR"); REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT.add("CL"); REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT.add("NI"); } /** Cost categories of short numbers. */ public enum ShortNumberCost { TOLL_FREE, STANDARD_RATE, PREMIUM_RATE, UNKNOWN_COST } /** Returns the singleton instance of the ShortNumberInfo. */ public static ShortNumberInfo getInstance() { return INSTANCE; } private final PhoneNumberUtil phoneUtil; // @VisibleForTesting ShortNumberInfo(PhoneNumberUtil util) { phoneUtil = util; } /** * Check whether a short number is a possible number when dialled from a region, given the number * in the form of a string, and the region where the number is dialed from. This provides a more * lenient check than {@link #isValidShortNumberForRegion}. * * @param shortNumber the short number to check as a string * @param regionDialingFrom the region from which the number is dialed * @return whether the number is a possible short number */ public boolean isPossibleShortNumberForRegion(String shortNumber, String regionDialingFrom) { PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionDialingFrom); if (phoneMetadata == null) { return false; } PhoneNumberDesc generalDesc = phoneMetadata.getGeneralDesc(); return phoneUtil.isNumberPossibleForDesc(shortNumber, generalDesc); } /** * Check whether a short number is a possible number. If a country calling code is shared by * multiple regions, this returns true if it's possible in any of them. This provides a more * lenient check than {@link #isValidShortNumber}. See {@link * #isPossibleShortNumberForRegion(String, String)} for details. * * @param number the short number to check * @return whether the number is a possible short number */ public boolean isPossibleShortNumber(PhoneNumber number) { List<String> regionCodes = phoneUtil.getRegionCodesForCountryCode(number.getCountryCode()); String shortNumber = phoneUtil.getNationalSignificantNumber(number); for (String region : regionCodes) { PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(region); if (phoneUtil.isNumberPossibleForDesc(shortNumber, phoneMetadata.getGeneralDesc())) { return true; } } return false; } /** * Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify * the number is actually in use, which is impossible to tell by just looking at the number * itself. * * @param shortNumber the short number to check as a string * @param regionDialingFrom the region from which the number is dialed * @return whether the short number matches a valid pattern */ public boolean isValidShortNumberForRegion(String shortNumber, String regionDialingFrom) { PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionDialingFrom); if (phoneMetadata == null) { return false; } PhoneNumberDesc generalDesc = phoneMetadata.getGeneralDesc(); if (!generalDesc.hasNationalNumberPattern() || !phoneUtil.isNumberMatchingDesc(shortNumber, generalDesc)) { return false; } PhoneNumberDesc shortNumberDesc = phoneMetadata.getShortCode(); if (!shortNumberDesc.hasNationalNumberPattern()) { logger.log(Level.WARNING, "No short code national number pattern found for region: " + regionDialingFrom); return false; } return phoneUtil.isNumberMatchingDesc(shortNumber, shortNumberDesc); } /** * Tests whether a short number matches a valid pattern. If a country calling code is shared by * multiple regions, this returns true if it's valid in any of them. Note that this doesn't verify * the number is actually in use, which is impossible to tell by just looking at the number * itself. See {@link #isValidShortNumberForRegion(String, String)} for details. * * @param number the short number for which we want to test the validity * @return whether the short number matches a valid pattern */ public boolean isValidShortNumber(PhoneNumber number) { List<String> regionCodes = phoneUtil.getRegionCodesForCountryCode(number.getCountryCode()); String shortNumber = phoneUtil.getNationalSignificantNumber(number); String regionCode = getRegionCodeForShortNumberFromRegionList(number, regionCodes); if (regionCodes.size() > 1 && regionCode != null) { // If a matching region had been found for the phone number from among two or more regions, // then we have already implicitly verified its validity for that region. return true; } return isValidShortNumberForRegion(shortNumber, regionCode); } /** * Gets the expected cost category of a short number when dialled from a region (however, nothing * is implied about its validity). If it is important that the number is valid, then its validity * must first be checked using {@link isValidShortNumberForRegion}. Note that emergency numbers * are always considered toll-free. Example usage: * <pre>{@code * ShortNumberInfo shortInfo = ShortNumberInfo.getInstance(); * String shortNumber = "110"; * String regionCode = "FR"; * if (shortInfo.isValidShortNumberForRegion(shortNumber, regionCode)) { * ShortNumberInfo.ShortNumberCost cost = shortInfo.getExpectedCostForRegion(shortNumber, * regionCode); * // Do something with the cost information here. * }}</pre> * * @param shortNumber the short number for which we want to know the expected cost category, * as a string * @param regionDialingFrom the region from which the number is dialed * @return the expected cost category for that region of the short number. Returns UNKNOWN_COST if * the number does not match a cost category. Note that an invalid number may match any cost * category. */ public ShortNumberCost getExpectedCostForRegion(String shortNumber, String regionDialingFrom) { // Note that regionDialingFrom may be null, in which case phoneMetadata will also be null. PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion( regionDialingFrom); if (phoneMetadata == null) { return ShortNumberCost.UNKNOWN_COST; } // The cost categories are tested in order of decreasing expense, since if for some reason the // patterns overlap the most expensive matching cost category should be returned. if (phoneUtil.isNumberMatchingDesc(shortNumber, phoneMetadata.getPremiumRate())) { return ShortNumberCost.PREMIUM_RATE; } if (phoneUtil.isNumberMatchingDesc(shortNumber, phoneMetadata.getStandardRate())) { return ShortNumberCost.STANDARD_RATE; } if (phoneUtil.isNumberMatchingDesc(shortNumber, phoneMetadata.getTollFree())) { return ShortNumberCost.TOLL_FREE; } if (isEmergencyNumber(shortNumber, regionDialingFrom)) { // Emergency numbers are implicitly toll-free. return ShortNumberCost.TOLL_FREE; } return ShortNumberCost.UNKNOWN_COST; } /** * Gets the expected cost category of a short number (however, nothing is implied about its * validity). If the country calling code is unique to a region, this method behaves exactly the * same as {@link #getExpectedCostForRegion(String, String)}. However, if the country calling * code is shared by multiple regions, then it returns the highest cost in the sequence * PREMIUM_RATE, UNKNOWN_COST, STANDARD_RATE, TOLL_FREE. The reason for the position of * UNKNOWN_COST in this order is that if a number is UNKNOWN_COST in one region but STANDARD_RATE * or TOLL_FREE in another, its expected cost cannot be estimated as one of the latter since it * might be a PREMIUM_RATE number. * * For example, if a number is STANDARD_RATE in the US, but TOLL_FREE in Canada, the expected cost * returned by this method will be STANDARD_RATE, since the NANPA countries share the same country * calling code. * * Note: If the region from which the number is dialed is known, it is highly preferable to call * {@link #getExpectedCostForRegion(String, String)} instead. * * @param number the short number for which we want to know the expected cost category * @return the highest expected cost category of the short number in the region(s) with the given * country calling code */ public ShortNumberCost getExpectedCost(PhoneNumber number) { List<String> regionCodes = phoneUtil.getRegionCodesForCountryCode(number.getCountryCode()); if (regionCodes.size() == 0) { return ShortNumberCost.UNKNOWN_COST; } String shortNumber = phoneUtil.getNationalSignificantNumber(number); if (regionCodes.size() == 1) { return getExpectedCostForRegion(shortNumber, regionCodes.get(0)); } ShortNumberCost cost = ShortNumberCost.TOLL_FREE; for (String regionCode : regionCodes) { ShortNumberCost costForRegion = getExpectedCostForRegion(shortNumber, regionCode); switch (costForRegion) { case PREMIUM_RATE: return ShortNumberCost.PREMIUM_RATE; case UNKNOWN_COST: cost = ShortNumberCost.UNKNOWN_COST; break; case STANDARD_RATE: if (cost != ShortNumberCost.UNKNOWN_COST) { cost = ShortNumberCost.STANDARD_RATE; } break; case TOLL_FREE: // Do nothing. break; default: logger.log(Level.SEVERE, "Unrecognised cost for region: " + costForRegion); } } return cost; } // Helper method to get the region code for a given phone number, from a list of possible region // codes. If the list contains more than one region, the first region for which the number is // valid is returned. private String getRegionCodeForShortNumberFromRegionList(PhoneNumber number, List<String> regionCodes) { if (regionCodes.size() == 0) { return null; } else if (regionCodes.size() == 1) { return regionCodes.get(0); } String nationalNumber = phoneUtil.getNationalSignificantNumber(number); for (String regionCode : regionCodes) { PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionCode); if (phoneMetadata != null && phoneUtil.isNumberMatchingDesc(nationalNumber, phoneMetadata.getShortCode())) { // The number is valid for this region. return regionCode; } } return null; } /** * Convenience method to get a list of what regions the library has metadata for. */ Set<String> getSupportedRegions() { return Collections.unmodifiableSet(MetadataManager.getShortNumberMetadataSupportedRegions()); } /** * Gets a valid short number for the specified region. * * @param regionCode the region for which an example short number is needed * @return a valid short number for the specified region. Returns an empty string when the * metadata does not contain such information. */ // @VisibleForTesting String getExampleShortNumber(String regionCode) { PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionCode); if (phoneMetadata == null) { return ""; } PhoneNumberDesc desc = phoneMetadata.getShortCode(); if (desc.hasExampleNumber()) { return desc.getExampleNumber(); } return ""; } /** * Gets a valid short number for the specified cost category. * * @param regionCode the region for which an example short number is needed * @param cost the cost category of number that is needed * @return a valid short number for the specified region and cost category. Returns an empty * string when the metadata does not contain such information, or the cost is UNKNOWN_COST. */ // @VisibleForTesting String getExampleShortNumberForCost(String regionCode, ShortNumberCost cost) { PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionCode); if (phoneMetadata == null) { return ""; } PhoneNumberDesc desc = null; switch (cost) { case TOLL_FREE: desc = phoneMetadata.getTollFree(); break; case STANDARD_RATE: desc = phoneMetadata.getStandardRate(); break; case PREMIUM_RATE: desc = phoneMetadata.getPremiumRate(); break; default: // UNKNOWN_COST numbers are computed by the process of elimination from the other cost // categories. } if (desc != null && desc.hasExampleNumber()) { return desc.getExampleNumber(); } return ""; } /** * Returns true if the number might be used to connect to an emergency service in the given * region. * * This method takes into account cases where the number might contain formatting, or might have * additional digits appended (when it is okay to do that in the region specified). * * @param number the phone number to test * @param regionCode the region where the phone number is being dialed * @return whether the number might be used to connect to an emergency service in the given region */ public boolean connectsToEmergencyNumber(String number, String regionCode) { return matchesEmergencyNumberHelper(number, regionCode, true /* allows prefix match */); } /** * Returns true if the number exactly matches an emergency service number in the given region. * * This method takes into account cases where the number might contain formatting, but doesn't * allow additional digits to be appended. * * @param number the phone number to test * @param regionCode the region where the phone number is being dialed * @return whether the number exactly matches an emergency services number in the given region */ public boolean isEmergencyNumber(String number, String regionCode) { return matchesEmergencyNumberHelper(number, regionCode, false /* doesn't allow prefix match */); } private boolean matchesEmergencyNumberHelper(String number, String regionCode, boolean allowPrefixMatch) { number = PhoneNumberUtil.extractPossibleNumber(number); if (PhoneNumberUtil.PLUS_CHARS_PATTERN.matcher(number).lookingAt()) { // Returns false if the number starts with a plus sign. We don't believe dialing the country // code before emergency numbers (e.g. +1911) works, but later, if that proves to work, we can // add additional logic here to handle it. return false; } PhoneMetadata metadata = MetadataManager.getShortNumberMetadataForRegion(regionCode); if (metadata == null || !metadata.hasEmergency()) { return false; } Pattern emergencyNumberPattern = Pattern.compile(metadata.getEmergency().getNationalNumberPattern()); String normalizedNumber = PhoneNumberUtil.normalizeDigitsOnly(number); return (!allowPrefixMatch || REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT.contains(regionCode)) ? emergencyNumberPattern.matcher(normalizedNumber).matches() : emergencyNumberPattern.matcher(normalizedNumber).lookingAt(); } /** * Given a valid short number, determines whether it is carrier-specific (however, nothing is * implied about its validity). If it is important that the number is valid, then its validity * must first be checked using {@link #isValidShortNumber} or * {@link #isValidShortNumberForRegion}. * * @param number the valid short number to check * @return whether the short number is carrier-specific (assuming the input was a valid short * number). */ public boolean isCarrierSpecific(PhoneNumber number) { List<String> regionCodes = phoneUtil.getRegionCodesForCountryCode(number.getCountryCode()); String regionCode = getRegionCodeForShortNumberFromRegionList(number, regionCodes); String nationalNumber = phoneUtil.getNationalSignificantNumber(number); PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionCode); return (phoneMetadata != null) && (phoneUtil.isNumberMatchingDesc(nationalNumber, phoneMetadata.getCarrierSpecific())); } }
mit
antonini/takes
src/test/java/org/takes/facets/slf4j/TkLoggedTest.java
2079
/** * The MIT License (MIT) * * Copyright (c) 2015 Yegor Bugayenko * * 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 NON-INFRINGEMENT. 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.takes.facets.slf4j; import java.io.IOException; import org.junit.Test; import org.mockito.Mockito; import org.takes.Response; import org.takes.Take; import org.takes.rq.RqFake; import org.takes.tk.TkText; /** * Test case for {@link TkLogged}. * @author Dmitry Zaytsev (dmitry.zaytsev@gmail.com) * @version $Id$ * @since 0.11.2 */ public final class TkLoggedTest { /** * TkLogged can log message. * @throws IOException If some problem inside */ @Test public void logsMessage() throws IOException { final Target target = Mockito.mock(Target.class); new TkLogged(new TkText("test"), target).act(new RqFake()); Mockito.verify(target, Mockito.times(1)).log( Mockito.eq("[{}] #act() return [{}] in [{}] ms"), Mockito.isA(Take.class), Mockito.isA(Response.class), Mockito.anyLong() ); } }
mit
YouDiSN/OpenJDK-Research
jdk9/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/ErrorHandlerAdaptor.java
2810
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * 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.sun.org.apache.xerces.internal.jaxp.validation; import com.sun.org.apache.xerces.internal.xni.parser.XMLErrorHandler; import com.sun.org.apache.xerces.internal.xni.parser.XMLParseException; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; /** * Receives errors through Xerces {@link XMLErrorHandler} * and pass them down to SAX {@link ErrorHandler}. * * @author * Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com) */ public abstract class ErrorHandlerAdaptor implements XMLErrorHandler { /** set to true if there was any error. */ private boolean hadError = false; /** * returns if there was an error since the last invocation of * the resetError method. */ public boolean hadError() { return hadError; } /** resets the error flag. */ public void reset() { hadError = false; } /** * Implemented by the derived class to return the actual * {@link ErrorHandler} to which errors are sent. * * @return always return non-null valid object. */ protected abstract ErrorHandler getErrorHandler(); public void fatalError( String domain, String key, XMLParseException e ) { try { hadError = true; getErrorHandler().fatalError( Util.toSAXParseException(e) ); } catch( SAXException se ) { throw new WrappedSAXException(se); } } public void error( String domain, String key, XMLParseException e ) { try { hadError = true; getErrorHandler().error( Util.toSAXParseException(e) ); } catch( SAXException se ) { throw new WrappedSAXException(se); } } public void warning( String domain, String key, XMLParseException e ) { try { getErrorHandler().warning( Util.toSAXParseException(e) ); } catch( SAXException se ) { throw new WrappedSAXException(se); } } }
gpl-2.0
jvanz/core
qadevOOo/tests/java/mod/_sch/AccDataSeries.java
3490
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ package mod._sch; import java.io.PrintWriter; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.AccessibilityTools; import util.SOfficeFactory; import util.utils; import com.sun.star.accessibility.AccessibleRole; import com.sun.star.accessibility.XAccessible; import com.sun.star.accessibility.XAccessibleComponent; import com.sun.star.accessibility.XAccessibleContext; import com.sun.star.awt.XWindow; import com.sun.star.chart.XChartDocument; import com.sun.star.frame.XModel; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; public class AccDataSeries extends TestCase { XChartDocument xChartDoc = null; @Override protected TestEnvironment createTestEnvironment( TestParameters Param, PrintWriter log) throws Exception { if (xChartDoc != null) cleanup(Param, log); log.println( "creating a chart document" ); SOfficeFactory SOF = SOfficeFactory.getFactory( Param.getMSF()); log.println( "creating a chartdocument" ); xChartDoc = SOF.createChartDoc(); XInterface oObj = null; XModel aModel = UnoRuntime.queryInterface(XModel.class, xChartDoc); XWindow xWindow = AccessibilityTools.getCurrentWindow(aModel); XAccessible xRoot = AccessibilityTools.getAccessibleObject(xWindow); AccessibilityTools.printAccessibleTree(log, xRoot, Param.getBool(util.PropertyName.DEBUG_IS_ACTIVE)); XAccessibleContext cont = AccessibilityTools.getAccessibleObjectForRole( xRoot, AccessibleRole.SHAPE, "", "AccDataSeries"); oObj = cont; log.println("ImplementationName " + utils.getImplName(oObj)); log.println("AccessibleName " + cont.getAccessibleName()); TestEnvironment tEnv = new TestEnvironment(oObj); final XAccessibleComponent acc = UnoRuntime.queryInterface( XAccessibleComponent.class,oObj); tEnv.addObjRelation("EventProducer", new ifc.accessibility._XAccessibleEventBroadcaster.EventProducer() { public void fireEvent() { acc.grabFocus(); } }); return tEnv; } /** * Called while disposing a <code>TestEnvironment</code>. * Disposes text document. * @param Param test parameters * @param log writer to log information while testing */ @Override protected void cleanup( TestParameters Param, PrintWriter log) { if( xChartDoc!=null ) { log.println( " closing xChartDoc" ); util.DesktopTools.closeDoc(xChartDoc); xChartDoc = null; } } }
gpl-3.0
gxyang/hstore
tests/frontend/edu/brown/protorpc/ProtoConnectionTest.java
4153
package edu.brown.protorpc; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.Before; import org.junit.Test; import ca.evanjones.protorpc.Counter; import com.google.protobuf.CodedInputStream; import com.google.protobuf.CodedOutputStream; import edu.brown.net.MockByteChannel; import edu.brown.net.NonBlockingConnection; public class ProtoConnectionTest { MockByteChannel channel; NonBlockingConnection nonblock; ProtoConnection connection; @Before public void setUp() throws IOException { channel = new MockByteChannel(); connection = new ProtoConnection(new NonBlockingConnection(null, channel)); } @Test public void testTryWrite() throws IOException { Counter.Value v = Counter.Value.newBuilder().setValue(42).build(); assertFalse(connection.tryWrite(v)); CodedInputStream in = CodedInputStream.newInstance(channel.lastWrites.get(0)); int length = in.readRawLittleEndian32(); assertEquals(length, channel.lastWrites.get(0).length - 4); Counter.Value w = Counter.Value.parseFrom(in); assertEquals(v, w); assertTrue(in.isAtEnd()); channel.clear(); channel.numBytesToAccept = 3; assertTrue(connection.tryWrite(v)); channel.numBytesToAccept = -1; assertFalse(connection.writeAvailable()); assertEquals(2, channel.lastWrites.size()); } @Test public void testReadBufferedMessage() throws IOException { Counter.Value.Builder builder = Counter.Value.newBuilder(); assertTrue(connection.readAllAvailable()); assertFalse(connection.readBufferedMessage(builder)); Counter.Value v = Counter.Value.newBuilder().setValue(42).build(); byte[] all = makeConnectionMessage(v); byte[] fragment1 = new byte[3]; System.arraycopy(all, 0, fragment1, 0, fragment1.length); byte[] fragment2 = new byte[all.length - fragment1.length]; System.arraycopy(all, fragment1.length, fragment2, 0, fragment2.length); channel.setNextRead(fragment1); assertTrue(connection.readAllAvailable()); assertTrue(connection.readAllAvailable()); assertFalse(connection.readBufferedMessage(builder)); channel.setNextRead(fragment2); assertTrue(connection.readAllAvailable()); assertTrue(connection.readBufferedMessage(builder)); assertEquals(v, builder.build()); channel.end = true; assertFalse(connection.readBufferedMessage(builder)); connection.close(); assertTrue(channel.closed); } private static byte[] makeConnectionMessage(Counter.Value value) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); CodedOutputStream codedOutput = CodedOutputStream.newInstance(out); codedOutput.writeRawLittleEndian32(value.getSerializedSize()); value.writeTo(codedOutput); codedOutput.flush(); byte[] all = out.toByteArray(); return all; } @Test public void testInputStreamLimitReset() throws IOException { // Build a ~40 MB string final int MEGABYTE = 1 << 20; final int CODED_INPUT_LIMIT = 64; char[] megabyte = new char[MEGABYTE]; for (int i = 0; i < megabyte.length; ++i) { megabyte[i] = 'a'; } String megaString = new String(megabyte); Counter.Value megaValue = Counter.Value.newBuilder() .setName(megaString.toString()) .setValue(42) .build(); byte[] all = makeConnectionMessage(megaValue); Counter.Value.Builder builder = Counter.Value.newBuilder(); for (int i = 0; i < CODED_INPUT_LIMIT * 2; ++i) { channel.setNextRead(all); assertTrue(connection.readAllAvailable()); assertTrue(connection.readBufferedMessage(builder)); builder.clear(); } } }
gpl-3.0
Kandru/KandruIM
src/main/java/eu/siacs/conversations/utils/AndroidUsingExecLowPriority.java
2702
/* * Copyright 2015-2016 the original author or authors * * This software is licensed under the Apache License, Version 2.0, * the GNU Lesser General Public License version 2 or later ("LGPL") * and the WTFPL. * You may choose either license to govern your use of this software only * upon the condition that you accept all of the terms of either * the Apache License 2.0, the LGPL 2.1+ or the WTFPL. */ package eu.siacs.conversations.utils; import de.measite.minidns.dnsserverlookup.AbstractDNSServerLookupMechanism; import de.measite.minidns.dnsserverlookup.AndroidUsingReflection; import de.measite.minidns.dnsserverlookup.DNSServerLookupMechanism; import de.measite.minidns.util.PlatformDetection; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.net.InetAddress; import java.util.HashSet; import java.util.logging.Level; /** * Try to retrieve the list of DNS server by executing getprop. */ public class AndroidUsingExecLowPriority extends AbstractDNSServerLookupMechanism { public static final DNSServerLookupMechanism INSTANCE = new AndroidUsingExecLowPriority(); public static final int PRIORITY = AndroidUsingReflection.PRIORITY + 1; private AndroidUsingExecLowPriority() { super(AndroidUsingExecLowPriority.class.getSimpleName(), PRIORITY); } @Override public String[] getDnsServerAddresses() { try { Process process = Runtime.getRuntime().exec("getprop"); InputStream inputStream = process.getInputStream(); LineNumberReader lnr = new LineNumberReader( new InputStreamReader(inputStream)); String line; HashSet<String> server = new HashSet<>(6); while ((line = lnr.readLine()) != null) { int split = line.indexOf("]: ["); if (split == -1) { continue; } String property = line.substring(1, split); String value = line.substring(split + 4, line.length() - 1); if (value.isEmpty()) { continue; } if (property.endsWith(".dns") || property.endsWith(".dns1") || property.endsWith(".dns2") || property.endsWith(".dns3") || property.endsWith(".dns4")) { // normalize the address InetAddress ip = InetAddress.getByName(value); if (ip == null) continue; value = ip.getHostAddress(); if (value == null) continue; if (value.length() == 0) continue; server.add(value); } } if (server.size() > 0) { return server.toArray(new String[server.size()]); } } catch (IOException e) { LOGGER.log(Level.WARNING, "Exception in findDNSByExec", e); } return null; } @Override public boolean isAvailable() { return PlatformDetection.isAndroid(); } }
gpl-3.0
imam-san/jPOS-1
jpos/src/main/java/org/jpos/iso/ISOFieldValidator.java
6106
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2015 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.iso; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.core.Configurable; import org.jpos.iso.validator.ISOVException; /** * Validator for ISOField components. * <p>Title: jPOS</p> * <p>Description: Java Framework for Financial Systems</p> * <p>Copyright: Copyright (c) 2000 jPOS.org. All rights reserved.</p> * <p>Company: www.jPOS.org</p> * @author Jose Eduardo Leon * @version 1.0 */ public class ISOFieldValidator implements Configurable, ISOValidator { public ISOFieldValidator( ) { description = ""; } public ISOFieldValidator( String Description ) { description = Description; } public ISOFieldValidator( int maxLen, String Description ) { description = Description; this.minLen = 0; this.maxLen = maxLen; } public ISOFieldValidator( int minLen, int maxLen, String Description ) { description = Description; this.minLen = minLen; this.maxLen = maxLen; } public ISOFieldValidator( boolean breakOnError, int minLen, int maxLen, String Description ) { this( minLen, maxLen, Description ); this.breakOnError = breakOnError; } public ISOFieldValidator( boolean breakOnError, int maxLen, String Description ) { this( maxLen, Description ); this.breakOnError = breakOnError; } public ISOFieldValidator( boolean breakOnError, String Description ) { this( Description ); this.breakOnError = breakOnError; } /** * Create a validator instance specifying breaking if any error * during validation process id found. * @param breakOnError break condition */ public ISOFieldValidator( boolean breakOnError ) { this(); this.breakOnError = breakOnError; } /** * Default config params are: min-len Minimun length, * max-len Max length, break-on-error break condition. * @param cfg configuration instance * @throws ConfigurationException */ public void setConfiguration(Configuration cfg) throws ConfigurationException { this.cfg = cfg; this.minLen = cfg.getInt( "min-len", 0 ); this.maxLen = cfg.getInt( "max-len", 999999 ); this.breakOnError = cfg.getBoolean( "break-on-error", false ); } public void setMaxLength( int maxLen ){ this.maxLen = maxLen; } public void setMinLength( int minLen ){ this.minLen = minLen; } public void setBreakOnError( boolean breakOnErr ){ this.breakOnError = breakOnErr; } public boolean breakOnError(){ return breakOnError; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setFieldId ( int f ){ fieldId = f; } public int getFieldId(){ return fieldId; } /** * Get the reject code for an error type. At this level is empty. * It must be redefined by childs if it is necessary return an * error code for specific errors. ISOVError.ERR_INVALID_LENGTH * and ISOVErro.ERR_INVALID_VALUE are the defaults. * @param ErrType Key for error type. * @return the related error code. At this level return null. */ public String getRejCode( int ErrType ){ /** empty at this level **/ return null; } /** * Validate a field component. Default for fields only consider * field length validations. * @param c ISOField component * @return an ISOComponent result of validation process. If there area any * validation error, then an ISOV component replace original c and it's * returned in case of break-on-error condition is false. If break-on-error * is false, then an ISOVException containing the ISOV component is raised. * @throws ISOException if there are some errors during validation. * It contains an ISOV component inside referencing the errors. */ public ISOComponent validate( ISOComponent c ) throws ISOException { ISOField f = (ISOField)c; Object v = f.getValue(); int l=0; if ( v instanceof byte[] ) l = ((byte[])v).length; else if ( v instanceof String ) l = ((String)v).length(); if ( l < minLen || l > maxLen ){ ISOVError e = new ISOVError( "Invalid Length Error. Length must be in [" + minLen + ", " + maxLen + "]. (Current len: " + l + ") ", getRejCode( ISOVError.ERR_INVALID_LENGTH ) ); if ( f instanceof ISOVField ) ((ISOVField)f).addISOVError( e ); else f = new ISOVField( f, e ); if ( breakOnError ) throw new ISOVException ( "Error on field " + f.getKey(), f ); } return f; } /** brief field description **/ protected String description; /** field id **/ protected int fieldId; /** field length bounds **/ protected int minLen = 0, maxLen = 999999; /** Flag used to indicate if validat process break on first error or keep an error vector **/ protected boolean breakOnError = false; protected Configuration cfg; }
agpl-3.0
mkrajcov/testsuite
src/main/java/org/jboss/hal/testsuite/page/config/DomainConfigEntryPoint.java
533
package org.jboss.hal.testsuite.page.config; import org.jboss.arquillian.graphene.page.Location; import org.jboss.hal.testsuite.page.BasePage; /** * @author jcechace * * This class represents a meta page entry point to the Config part of the consle in domain. * As such it is meant for navigation purposes only and thus can't be instantiated. Also note * that the actual landing page is determined by console and may change in the future. * */ @Location("#profiles") public class DomainConfigEntryPoint extends BasePage { }
lgpl-2.1
minudika/carbon-analytics
components/org.wso2.carbon.business.rules.core/src/main/java/org/wso2/carbon/business/rules/core/datasource/util/BusinessRuleDatasourceUtils.java
1886
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.business.rules.core.datasource.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Cleaning connections, statements and result sets */ public class BusinessRuleDatasourceUtils { private static Logger log = LoggerFactory.getLogger(BusinessRuleDatasourceUtils.class); public static void cleanupConnection(ResultSet rs, Statement stmt, Connection conn) { if (rs != null) { try { rs.close(); } catch (SQLException e) { if (log.isDebugEnabled()) { log.error("Failed to close the result set. ", e); } } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { log.error("Failed to close the prepared statement. ", e); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { log.error("Failed to close the connection. ", e); } } } }
apache-2.0
nishantmonu51/druid
extensions-core/druid-basic-security/src/main/java/org/apache/druid/security/basic/authentication/validator/MetadataStoreCredentialsValidator.java
3346
/* * 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.security.basic.authentication.validator; import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.inject.Provider; import org.apache.druid.java.util.common.IAE; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.security.basic.BasicAuthUtils; import org.apache.druid.security.basic.BasicSecurityAuthenticationException; import org.apache.druid.security.basic.authentication.db.cache.BasicAuthenticatorCacheManager; import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorCredentials; import org.apache.druid.security.basic.authentication.entity.BasicAuthenticatorUser; import org.apache.druid.server.security.AuthenticationResult; import javax.annotation.Nullable; import java.util.Arrays; import java.util.Map; @JsonTypeName("metadata") public class MetadataStoreCredentialsValidator implements CredentialsValidator { private static final Logger LOG = new Logger(MetadataStoreCredentialsValidator.class); private final Provider<BasicAuthenticatorCacheManager> cacheManager; @JsonCreator public MetadataStoreCredentialsValidator( @JacksonInject Provider<BasicAuthenticatorCacheManager> cacheManager ) { this.cacheManager = cacheManager; } @Override @Nullable public AuthenticationResult validateCredentials( String authenticatorName, String authorizerName, String username, char[] password ) { Map<String, BasicAuthenticatorUser> userMap = cacheManager.get().getUserMap(authenticatorName); if (userMap == null) { throw new IAE("No userMap is available for authenticator with prefix: [%s]", authenticatorName); } BasicAuthenticatorUser user = userMap.get(username); if (user == null) { return null; } BasicAuthenticatorCredentials credentials = user.getCredentials(); if (credentials == null) { return null; } byte[] recalculatedHash = BasicAuthUtils.hashPassword( password, credentials.getSalt(), credentials.getIterations() ); if (Arrays.equals(recalculatedHash, credentials.getHash())) { return new AuthenticationResult(username, authorizerName, authenticatorName, null); } else { LOG.debug("Password incorrect for metadata store user %s", username); throw new BasicSecurityAuthenticationException("User metadata store authentication failed."); } } }
apache-2.0
asedunov/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/dataFlow/reachingDefs/ReachingDefinitionsCollector.java
17084
/* * 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 org.jetbrains.plugins.groovy.lang.psi.dataFlow.reachingDefs; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import gnu.trove.TIntHashSet; import gnu.trove.TIntObjectHashMap; import gnu.trove.TIntObjectProcedure; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction; import org.jetbrains.plugins.groovy.lang.psi.controlFlow.ReadWriteVariableInstruction; import org.jetbrains.plugins.groovy.lang.psi.dataFlow.DFAEngine; import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.ClosureSyntheticParameter; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import java.util.*; import static org.jetbrains.plugins.groovy.lang.psi.controlFlow.OrderUtil.reversedPostOrder; /** * @author ven */ public class ReachingDefinitionsCollector { private ReachingDefinitionsCollector() { } @NotNull public static FragmentVariableInfos obtainVariableFlowInformation(@NotNull final GrStatement first, @NotNull final GrStatement last, @NotNull final GrControlFlowOwner flowOwner, @NotNull final Instruction[] flow) { final DefinitionMap dfaResult = inferDfaResult(flow); final LinkedHashSet<Integer> fragmentInstructions = getFragmentInstructions(first, last, flow); final int[] postorder = reversedPostOrder(flow); LinkedHashSet<Integer> reachableFromFragmentReads = getReachable(fragmentInstructions, flow, dfaResult, postorder); LinkedHashSet<Integer> fragmentReads = filterReads(fragmentInstructions, flow); final Map<String, VariableInfo> imap = new LinkedHashMap<>(); final Map<String, VariableInfo> omap = new LinkedHashMap<>(); final PsiManager manager = first.getManager(); for (final Integer ref : fragmentReads) { ReadWriteVariableInstruction rwInstruction = (ReadWriteVariableInstruction)flow[ref]; String name = rwInstruction.getVariableName(); final int[] defs = dfaResult.getDefinitions(ref); if (!allDefsInFragment(defs, fragmentInstructions)) { addVariable(name, imap, manager, getType(rwInstruction.getElement())); } } for (final Integer ref : reachableFromFragmentReads) { ReadWriteVariableInstruction rwInstruction = (ReadWriteVariableInstruction)flow[ref]; String name = rwInstruction.getVariableName(); final int[] defs = dfaResult.getDefinitions(ref); if (anyDefInFragment(defs, fragmentInstructions)) { for (int def : defs) { if (fragmentInstructions.contains(def)) { PsiType outputType = getType(flow[def].getElement()); addVariable(name, omap, manager, outputType); } } if (!allProperDefsInFragment(defs, ref, fragmentInstructions, postorder)) { PsiType inputType = getType(rwInstruction.getElement()); addVariable(name, imap, manager, inputType); } } } addClosureUsages(imap, omap, first, last, flowOwner); final VariableInfo[] iarr = filterNonlocals(imap, last); final VariableInfo[] oarr = filterNonlocals(omap, last); return new FragmentVariableInfos() { @Override public VariableInfo[] getInputVariableNames() { return iarr; } @Override public VariableInfo[] getOutputVariableNames() { return oarr; } }; } private static DefinitionMap inferDfaResult(Instruction[] flow) { final ReachingDefinitionsDfaInstance dfaInstance = new ReachingDefinitionsDfaInstance(flow); final ReachingDefinitionsSemilattice lattice = new ReachingDefinitionsSemilattice(); final DFAEngine<DefinitionMap> engine = new DFAEngine<>(flow, dfaInstance, lattice); return postprocess(engine.performForceDFA(), flow, dfaInstance); } private static void addClosureUsages(final Map<String, VariableInfo> imap, final Map<String, VariableInfo> omap, final GrStatement first, final GrStatement last, GrControlFlowOwner flowOwner) { flowOwner.accept(new GroovyRecursiveElementVisitor() { @Override public void visitClosure(@NotNull GrClosableBlock closure) { addUsagesInClosure(imap, omap, closure, first, last); super.visitClosure(closure); } private void addUsagesInClosure(final Map<String, VariableInfo> imap, final Map<String, VariableInfo> omap, final GrClosableBlock closure, final GrStatement first, final GrStatement last) { closure.accept(new GroovyRecursiveElementVisitor() { @Override public void visitReferenceExpression(@NotNull GrReferenceExpression refExpr) { if (refExpr.isQualified()) { return; } PsiElement resolved = refExpr.resolve(); if (!(resolved instanceof GrVariable)) { return; } GrVariable variable = (GrVariable)resolved; if (PsiTreeUtil.isAncestor(closure, variable, true)) { return; } if (variable instanceof ClosureSyntheticParameter && PsiTreeUtil.isAncestor(closure, ((ClosureSyntheticParameter)variable).getClosure(), false)) { return; } String name = variable.getName(); if (!(variable instanceof GrField)) { if (!isInFragment(first, last, resolved)) { if (isInFragment(first, last, closure)) { addVariable(name, imap, variable.getManager(), variable.getType()); } } else { if (!isInFragment(first, last, closure)) { addVariable(name, omap, variable.getManager(), variable.getType()); } } } } }); } }); } private static void addVariable(String name, Map<String, VariableInfo> map, PsiManager manager, PsiType type) { VariableInfoImpl info = (VariableInfoImpl)map.get(name); if (info == null) { info = new VariableInfoImpl(name, manager); map.put(name, info); } info.addSubtype(type); } private static LinkedHashSet<Integer> filterReads(final LinkedHashSet<Integer> instructions, final Instruction[] flow) { final LinkedHashSet<Integer> result = new LinkedHashSet<>(); for (final Integer i : instructions) { final Instruction instruction = flow[i]; if (isReadInsn(instruction)) { result.add(i); } } return result; } private static boolean allDefsInFragment(int[] defs, LinkedHashSet<Integer> fragmentInstructions) { for (int def : defs) { if (!fragmentInstructions.contains(def)) return false; } return true; } private static boolean allProperDefsInFragment(int[] defs, int ref, LinkedHashSet<Integer> fragmentInstructions, int[] postorder) { for (int def : defs) { if (!fragmentInstructions.contains(def) && postorder[def] < postorder[ref]) return false; } return true; } private static boolean anyDefInFragment(int[] defs, LinkedHashSet<Integer> fragmentInstructions) { for (int def : defs) { if (fragmentInstructions.contains(def)) return true; } return false; } @Nullable private static PsiType getType(PsiElement element) { if (element instanceof GrVariable) { return ((GrVariable)element).getTypeGroovy(); } else if (element instanceof GrReferenceExpression) return ((GrReferenceExpression)element).getType(); return null; } private static VariableInfo[] filterNonlocals(Map<String, VariableInfo> infos, GrStatement place) { List<VariableInfo> result = new ArrayList<>(); for (Iterator<VariableInfo> iterator = infos.values().iterator(); iterator.hasNext(); ) { VariableInfo info = iterator.next(); String name = info.getName(); GroovyPsiElement property = ResolveUtil.resolveProperty(place, name); if (property instanceof GrVariable) { iterator.remove(); } else if (property instanceof GrReferenceExpression) { GrMember member = PsiTreeUtil.getParentOfType(property, GrMember.class); if (member == null) { continue; } else if (!member.hasModifierProperty(PsiModifier.STATIC)) { if (member.getContainingClass() instanceof GroovyScriptClass) { //binding variable continue; } } } if (ResolveUtil.resolveClass(place, name) == null) { result.add(info); } } return result.toArray(new VariableInfo[result.size()]); } private static LinkedHashSet<Integer> getFragmentInstructions(GrStatement first, GrStatement last, Instruction[] flow) { LinkedHashSet<Integer> result = new LinkedHashSet<>(); for (Instruction instruction : flow) { if (isInFragment(instruction, first, last)) { result.add(instruction.num()); } } return result; } private static boolean isInFragment(Instruction instruction, GrStatement first, GrStatement last) { final PsiElement element = instruction.getElement(); if (element == null) return false; return isInFragment(first, last, element); } private static boolean isInFragment(GrStatement first, GrStatement last, PsiElement element) { final PsiElement parent = first.getParent(); if (!PsiTreeUtil.isAncestor(parent, element, true)) return false; PsiElement run = element; while (run.getParent() != parent) run = run.getParent(); return isBetween(first, last, run); } private static boolean isBetween(PsiElement first, PsiElement last, PsiElement run) { while (first != null && first != run) first = first.getNextSibling(); if (first == null) return false; while (last != null && last != run) last = last.getPrevSibling(); if (last == null) return false; return true; } private static LinkedHashSet<Integer> getReachable(final LinkedHashSet<Integer> fragmentInsns, final Instruction[] flow, final DefinitionMap dfaResult, final int[] postorder) { final LinkedHashSet<Integer> result = new LinkedHashSet<>(); for (final Instruction insn : flow) { if (isReadInsn(insn)) { final int ref = insn.num(); int[] definitions = dfaResult.getDefinitions(ref); if (definitions != null) { for (final int def : definitions) { if (fragmentInsns.contains(def) && (!fragmentInsns.contains(ref) || postorder[ref] < postorder[def] && checkPathIsOutsideOfFragment(def, ref, flow, fragmentInsns))) { result.add(ref); break; } } } } } return result; } private static boolean checkPathIsOutsideOfFragment(int def, int ref, Instruction[] flow, LinkedHashSet<Integer> fragmentInsns) { Boolean path = findPath(flow[def], ref, fragmentInsns, false, new HashMap<>()); assert path != null : "def=" + def + ", ref=" + ref; return path.booleanValue(); } /** * return true if path is outside of fragment, null if there is no pathand false if path is inside fragment */ @Nullable private static Boolean findPath(Instruction cur, int destination, LinkedHashSet<Integer> fragmentInsns, boolean wasOutside, HashMap<Instruction, Boolean> visited) { wasOutside = wasOutside || !fragmentInsns.contains(cur.num()); visited.put(cur, null); Iterable<? extends Instruction> instructions = cur.allSuccessors(); boolean pathExists = false; for (Instruction i : instructions) { if (i.num() == destination) return wasOutside; Boolean result; if (visited.containsKey(i)) { result = visited.get(i); } else { result = findPath(i, destination, fragmentInsns, wasOutside, visited); visited.put(i, result); } if (result != null) { if (result.booleanValue()) { visited.put(cur, true); return true; } pathExists = true; } } if (pathExists) { visited.put(cur, false); return false; } else { visited.put(cur, null); return null; } } private static boolean isReadInsn(Instruction insn) { return insn instanceof ReadWriteVariableInstruction && !((ReadWriteVariableInstruction)insn).isWrite(); } @SuppressWarnings({"UnusedDeclaration"}) private static String dumpDfaResult(ArrayList<TIntObjectHashMap<TIntHashSet>> dfaResult, ReachingDefinitionsDfaInstance dfa) { final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < dfaResult.size(); i++) { TIntObjectHashMap<TIntHashSet> map = dfaResult.get(i); buffer.append("At ").append(i).append(":\n"); map.forEachEntry(new TIntObjectProcedure<TIntHashSet>() { @Override public boolean execute(int i, TIntHashSet defs) { buffer.append(i).append(" -> "); defs.forEach(i1 -> { buffer.append(i1).append(" "); return true; }); return true; } }); buffer.append("\n"); } return buffer.toString(); } private static class VariableInfoImpl implements VariableInfo { @NotNull private final String myName; private final PsiManager myManager; @Nullable private PsiType myType; VariableInfoImpl(@NotNull String name, PsiManager manager) { myName = name; myManager = manager; } @Override @NotNull public String getName() { return myName; } @Override @Nullable public PsiType getType() { if (myType instanceof PsiIntersectionType) return ((PsiIntersectionType)myType).getConjuncts()[0]; return myType; } void addSubtype(PsiType t) { if (t != null) { if (myType == null) { myType = t; } else { if (!myType.isAssignableFrom(t)) { if (t.isAssignableFrom(myType)) { myType = t; } else { myType = TypesUtil.getLeastUpperBound(myType, t, myManager); } } } } } } @NotNull private static DefinitionMap postprocess(@NotNull final List<DefinitionMap> dfaResult, @NotNull Instruction[] flow, @NotNull ReachingDefinitionsDfaInstance dfaInstance) { DefinitionMap result = new DefinitionMap(); for (int i = 0; i < flow.length; i++) { Instruction insn = flow[i]; if (insn instanceof ReadWriteVariableInstruction) { ReadWriteVariableInstruction rwInsn = (ReadWriteVariableInstruction)insn; if (!rwInsn.isWrite()) { int idx = dfaInstance.getVarIndex(rwInsn.getVariableName()); result.copyFrom(dfaResult.get(i), idx, i); } } } return result; } }
apache-2.0
masaki-yamakawa/geode
geode-core/src/integrationTest/java/org/apache/geode/internal/offheap/TxReleasesOffHeapOnCloseJUnitTest.java
2545
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.offheap; import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.junit.Assert.assertEquals; import java.util.Properties; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.CacheTransactionManager; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionFactory; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.test.junit.categories.OffHeapTest; @Category({OffHeapTest.class}) public class TxReleasesOffHeapOnCloseJUnitTest { protected Cache cache; protected void createCache() { Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOCATORS, ""); props.setProperty(ConfigurationProperties.OFF_HEAP_MEMORY_SIZE, "1m"); cache = new CacheFactory(props).create(); } // Start a tx and have it modify an entry on an offheap region. // Close the cache and verify that the offheap memory was released // even though the tx was not commited or rolled back. @Test public void testTxReleasesOffHeapOnClose() { createCache(); MemoryAllocatorImpl sma = MemoryAllocatorImpl.getAllocator(); RegionFactory rf = cache.createRegionFactory(); rf.setOffHeap(true); Region r = rf.create("testTxReleasesOffHeapOnClose"); r.put("key", "value"); CacheTransactionManager txmgr = cache.getCacheTransactionManager(); txmgr.begin(); r.put("key", "value2"); cache.close(); assertEquals(0, sma.getUsedMemory()); } }
apache-2.0
trekawek/jackrabbit-oak
oak-lucene/src/test/java/org/apache/jackrabbit/oak/plugins/index/lucene/OakCodecTest.java
1500
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.plugins.index.lucene; import org.junit.Test; import static org.junit.Assert.assertNotNull; /** * Tests for {@link OakCodec} */ public class OakCodecTest { @Test public void tesFormats() { OakCodec oakCodec = new OakCodec(); assertNotNull(oakCodec.docValuesFormat()); assertNotNull(oakCodec.fieldInfosFormat()); assertNotNull(oakCodec.liveDocsFormat()); assertNotNull(oakCodec.normsFormat()); assertNotNull(oakCodec.postingsFormat()); assertNotNull(oakCodec.segmentInfoFormat()); assertNotNull(oakCodec.storedFieldsFormat()); assertNotNull(oakCodec.termVectorsFormat()); } }
apache-2.0
nikhilvibhav/camel
components/camel-pgevent/src/generated/java/org/apache/camel/component/pgevent/PgEventEndpointConfigurer.java
3632
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.pgevent; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.ExtendedPropertyConfigurerGetter; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.spi.ConfigurerStrategy; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class PgEventEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { PgEventEndpoint target = (PgEventEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "datasource": target.setDatasource(property(camelContext, javax.sql.DataSource.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "pass": target.setPass(property(camelContext, java.lang.String.class, value)); return true; case "user": target.setUser(property(camelContext, java.lang.String.class, value)); return true; default: return false; } } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeerrorhandler": case "bridgeErrorHandler": return boolean.class; case "datasource": return javax.sql.DataSource.class; case "exceptionhandler": case "exceptionHandler": return org.apache.camel.spi.ExceptionHandler.class; case "exchangepattern": case "exchangePattern": return org.apache.camel.ExchangePattern.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "pass": return java.lang.String.class; case "user": return java.lang.String.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { PgEventEndpoint target = (PgEventEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "datasource": return target.getDatasource(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "pass": return target.getPass(); case "user": return target.getUser(); default: return null; } } }
apache-2.0
twalpole/selenium
java/server/test/org/openqa/testing/FakeHttpServletResponse.java
5143
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.openqa.testing; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Collection; import java.util.Locale; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; public class FakeHttpServletResponse extends HeaderContainer implements HttpServletResponse { private final StringWriter stringWriter = new StringWriter(); private final ServletOutputStream servletOutputStream = new StringServletOutputStream(stringWriter); private final PrintWriter printWriter = new PrintWriter(servletOutputStream); private int status = HttpServletResponse.SC_OK; @Override public int getStatus() { return status; } public String getBody() { return stringWriter.toString(); } @Override public Collection<String> getHeaders(String name) { return getHeaders().get(name); } @Override public Collection<String> getHeaderNames() { return getHeaders().keySet(); } ///////////////////////////////////////////////////////////////////////////// // // HttpServletResponse methods. // ///////////////////////////////////////////////////////////////////////////// @Override public void addCookie(Cookie cookie) { throw new UnsupportedOperationException(); } @Override public String encodeURL(String s) { throw new UnsupportedOperationException(); } @Override public String encodeRedirectURL(String s) { throw new UnsupportedOperationException(); } @Override public String encodeUrl(String s) { throw new UnsupportedOperationException(); } @Override public String encodeRedirectUrl(String s) { throw new UnsupportedOperationException(); } @Override public void sendError(int i, String s) { throw new UnsupportedOperationException(); } @Override public void sendError(int i) { setStatus(i); } @Override public void sendRedirect(String s) { setStatus(SC_SEE_OTHER); setHeader("Location", s); } @Override public void setStatus(int i) { this.status = i; } @Override public void setStatus(int i, String s) { throw new UnsupportedOperationException(); } @Override public String getCharacterEncoding() { throw new UnsupportedOperationException(); } @Override public String getContentType() { return getHeader("Content-Type"); } @Override public ServletOutputStream getOutputStream() { return servletOutputStream; } @Override public PrintWriter getWriter() { return printWriter; } @Override public void setCharacterEncoding(String s) { String type = getHeader("content-type"); setHeader("content-type", type + "; charset=" + s); } @Override public void setContentLength(int i) { setIntHeader("content-length", i); } @Override public void setContentLengthLong(long len) { setIntHeader("content-length", (int) len); } @Override public void setContentType(String type) { setHeader("content-type", type); } @Override public void setBufferSize(int i) { throw new UnsupportedOperationException(); } @Override public int getBufferSize() { throw new UnsupportedOperationException(); } @Override public void flushBuffer() { // no-op } @Override public void resetBuffer() { throw new UnsupportedOperationException(); } @Override public boolean isCommitted() { throw new UnsupportedOperationException(); } @Override public void reset() { getHeaders().clear(); } @Override public void setLocale(Locale locale) { throw new UnsupportedOperationException(); } @Override public Locale getLocale() { throw new UnsupportedOperationException(); } private static class StringServletOutputStream extends ServletOutputStream { private final PrintWriter printWriter; private StringServletOutputStream(StringWriter stringWriter) { this.printWriter = new PrintWriter(stringWriter); } @Override public void write(int i) { printWriter.write(i); } @Override public boolean isReady() { return true; } @Override public void setWriteListener(WriteListener writeListener) { throw new UnsupportedOperationException(); } } }
apache-2.0
doom369/netty
handler/src/main/java/io/netty/handler/ssl/DefaultOpenSslKeyMaterial.java
3553
/* * Copyright 2018 The Netty Project * * The Netty Project 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: * * 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. */ package io.netty.handler.ssl; import io.netty.internal.tcnative.SSL; import io.netty.util.AbstractReferenceCounted; import io.netty.util.IllegalReferenceCountException; import io.netty.util.ResourceLeakDetector; import io.netty.util.ResourceLeakDetectorFactory; import io.netty.util.ResourceLeakTracker; import java.security.cert.X509Certificate; final class DefaultOpenSslKeyMaterial extends AbstractReferenceCounted implements OpenSslKeyMaterial { private static final ResourceLeakDetector<DefaultOpenSslKeyMaterial> leakDetector = ResourceLeakDetectorFactory.instance().newResourceLeakDetector(DefaultOpenSslKeyMaterial.class); private final ResourceLeakTracker<DefaultOpenSslKeyMaterial> leak; private final X509Certificate[] x509CertificateChain; private long chain; private long privateKey; DefaultOpenSslKeyMaterial(long chain, long privateKey, X509Certificate[] x509CertificateChain) { this.chain = chain; this.privateKey = privateKey; this.x509CertificateChain = x509CertificateChain; leak = leakDetector.track(this); } @Override public X509Certificate[] certificateChain() { return x509CertificateChain.clone(); } @Override public long certificateChainAddress() { if (refCnt() <= 0) { throw new IllegalReferenceCountException(); } return chain; } @Override public long privateKeyAddress() { if (refCnt() <= 0) { throw new IllegalReferenceCountException(); } return privateKey; } @Override protected void deallocate() { SSL.freeX509Chain(chain); chain = 0; SSL.freePrivateKey(privateKey); privateKey = 0; if (leak != null) { boolean closed = leak.close(this); assert closed; } } @Override public DefaultOpenSslKeyMaterial retain() { if (leak != null) { leak.record(); } super.retain(); return this; } @Override public DefaultOpenSslKeyMaterial retain(int increment) { if (leak != null) { leak.record(); } super.retain(increment); return this; } @Override public DefaultOpenSslKeyMaterial touch() { if (leak != null) { leak.record(); } super.touch(); return this; } @Override public DefaultOpenSslKeyMaterial touch(Object hint) { if (leak != null) { leak.record(hint); } return this; } @Override public boolean release() { if (leak != null) { leak.record(); } return super.release(); } @Override public boolean release(int decrement) { if (leak != null) { leak.record(); } return super.release(decrement); } }
apache-2.0
congdepeng/java-guava-lib-demo
guava-libraries/guava-gwt/test/com/google/common/primitives/LongsTest_gwt.java
6447
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; public class LongsTest_gwt extends com.google.gwt.junit.client.GWTTestCase { @Override public String getModuleName() { return "com.google.common.primitives.testModule"; } public void testAsListEmpty() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testAsListEmpty(); } public void testAsList_isAView() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testAsList_isAView(); } public void testAsList_subList_toArray_roundTrip() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testAsList_subList_toArray_roundTrip(); } public void testAsList_toArray_roundTrip() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testAsList_toArray_roundTrip(); } public void testByteArrayRoundTrips() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testByteArrayRoundTrips(); } public void testCompare() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testCompare(); } public void testConcat() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testConcat(); } public void testContains() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testContains(); } public void testEnsureCapacity() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testEnsureCapacity(); } public void testEnsureCapacity_fail() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testEnsureCapacity_fail(); } public void testFromByteArray() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testFromByteArray(); } public void testFromBytes() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testFromBytes(); } public void testIndexOf() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testIndexOf(); } public void testIndexOf_arrayTarget() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testIndexOf_arrayTarget(); } public void testJoin() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testJoin(); } public void testLastIndexOf() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testLastIndexOf(); } public void testLexicographicalComparator() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testLexicographicalComparator(); } public void testMax() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testMax(); } public void testMax_noArgs() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testMax_noArgs(); } public void testMin() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testMin(); } public void testMin_noArgs() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testMin_noArgs(); } public void testStringConverter_convert() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testStringConverter_convert(); } public void testStringConverter_convertError() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testStringConverter_convertError(); } public void testStringConverter_nullConversions() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testStringConverter_nullConversions(); } public void testStringConverter_reverse() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testStringConverter_reverse(); } public void testToArray() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testToArray(); } public void testToArray_threadSafe() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testToArray_threadSafe(); } public void testToArray_withConversion() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testToArray_withConversion(); } public void testToArray_withNull() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testToArray_withNull(); } public void testToByteArray() throws Exception { com.google.common.primitives.LongsTest testCase = new com.google.common.primitives.LongsTest(); testCase.testToByteArray(); } }
apache-2.0
MariusVolkhart/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/models/BoxCollection.java
1723
package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.util.Map; /** * Class that represents a collection on Box. */ public class BoxCollection extends BoxEntity { /** * Constructs an empty BoxCollection object. */ public BoxCollection() { super(); } /** * Constructs a BoxCollection with the provided map values * * @param map - map of keys and values of the object */ public BoxCollection(Map<String, Object> map) { super(map); } public static final String TYPE = "collection"; public static final String FIELD_NAME = "name"; public static final String FIELD_COLLECTION_TYPE = "collection_type"; /** * Gets the name of the collection. * * @return the name of the collection. */ public String getName() { return (String) mProperties.get(FIELD_NAME); } /** * Gets the type of the collection. Currently only "favorites" is supported. * * @return type of collection. */ public String getCollectionType() { return (String) mProperties.get(FIELD_COLLECTION_TYPE); } @Override protected void parseJSONMember(JsonObject.Member member) { String memberName = member.getName(); JsonValue value = member.getValue(); if (memberName.equals(FIELD_NAME)) { mProperties.put(FIELD_NAME, value.asString()); return; } else if (memberName.equals(FIELD_COLLECTION_TYPE)) { mProperties.put(FIELD_COLLECTION_TYPE, value.asString()); return; } super.parseJSONMember(member); } }
apache-2.0
zhuyuanyan/PCCredit_TY
src/java/com/cardpay/pccredit/product/constant/DictTypeConstant.java
746
package com.cardpay.pccredit.product.constant; import java.util.HashMap; import java.util.Map; import com.cardpay.pccredit.common.Dictionary; public class DictTypeConstant { public static Map<String, Object> TypeMap=new HashMap<String, Object>(); static{ TypeMap.put(ProductFilterColumn.TITLE,Dictionary.titleList); TypeMap.put(ProductFilterColumn.POSITIO,Dictionary.positioList); TypeMap.put(ProductFilterColumn.DEGREE_EDUCATION,Dictionary.degreeeducationList); TypeMap.put(ProductFilterColumn.RESIDENTIAL_PROPERTIE,Dictionary.residentialPropertieList); TypeMap.put(ProductFilterColumn.UNIT_NATURE,Dictionary.unitPropertisList); TypeMap.put(ProductFilterColumn.INDUSTRY_TYPE,Dictionary.industryTypeList); } }
apache-2.0
fnkhan/New
src/main/java/org/openflow/protocol/action/OFActionStripVirtualLan.java
2493
/******************************************************************************* * Copyright 2014 Open Networking Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /** * Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior * University * * 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. **/ /** * @author David Erickson (daviderickson@cs.stanford.edu) - Mar 11, 2010 */ package org.openflow.protocol.action; import org.jboss.netty.buffer.ChannelBuffer; /** * Represents an ofp_action_strip_vlan * * @author David Erickson (daviderickson@cs.stanford.edu) - Mar 11, 2010 */ public class OFActionStripVirtualLan extends OFAction { public static int MINIMUM_LENGTH = 8; public OFActionStripVirtualLan() { super(); super.setType(OFActionType.STRIP_VLAN); super.setLength((short) OFActionStripVirtualLan.MINIMUM_LENGTH); } @Override public void readFrom(final ChannelBuffer data) { super.readFrom(data); // PAD data.readInt(); } @Override public void writeTo(final ChannelBuffer data) { super.writeTo(data); // PAD data.writeInt(0); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(this.type); return builder.toString(); } }
apache-2.0
flydream2046/azure-sdk-for-java
service-management/azure-svc-mgmt-websites/src/main/java/com/microsoft/windowsazure/management/websites/models/WebSiteCreateResponse.java
1447
/** * * Copyright (c) Microsoft and contributors. 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. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.windowsazure.management.websites.models; import com.microsoft.windowsazure.core.OperationResponse; /** * The Create Web Site operation response. */ public class WebSiteCreateResponse extends OperationResponse { private WebSite webSite; /** * Optional. Details of the created web site. * @return The WebSite value. */ public WebSite getWebSite() { return this.webSite; } /** * Optional. Details of the created web site. * @param webSiteValue The WebSite value. */ public void setWebSite(final WebSite webSiteValue) { this.webSite = webSiteValue; } }
apache-2.0
vineetgarg02/hive
hcatalog/webhcat/svr/src/main/java/org/apache/hive/hcatalog/templeton/ExecBean.java
1535
/* * 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.hive.hcatalog.templeton; /** * ExecBean - The results of an exec call. */ public class ExecBean { public String stdout; public String stderr; public int exitcode; public ExecBean() {} /** * Create a new ExecBean. * * @param stdout standard output of the the program. * @param stderr error output of the the program. * @param exitcode exit code of the program. */ public ExecBean(String stdout, String stderr, int exitcode) { this.stdout = stdout; this.stderr = stderr; this.exitcode = exitcode; } public String toString() { return String.format("ExecBean(stdout=%s, stderr=%s, exitcode=%s)", stdout, stderr, exitcode); } }
apache-2.0
rainerh/camunda-bpm-platform
engine-rest/src/test/java/org/camunda/bpm/engine/rest/wink/JobDefinitionRestServiceQueryTest.java
923
package org.camunda.bpm.engine.rest.wink; import org.camunda.bpm.engine.rest.AbstractJobDefinitionRestServiceQueryTest; import org.camunda.bpm.engine.rest.util.WinkTomcatServerBootstrap; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.rules.TemporaryFolder; public class JobDefinitionRestServiceQueryTest extends AbstractJobDefinitionRestServiceQueryTest { protected static WinkTomcatServerBootstrap serverBootstrap; @ClassRule public static TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass public static void setUpEmbeddedRuntime() { serverBootstrap = new WinkTomcatServerBootstrap(); serverBootstrap.setWorkingDir(temporaryFolder.getRoot().getAbsolutePath()); serverBootstrap.start(); } @AfterClass public static void tearDownEmbeddedRuntime() { serverBootstrap.stop(); } }
apache-2.0
adufilie/flex-sdk
modules/thirdparty/batik/sources/org/apache/flex/forks/batik/ext/awt/image/URLImageCache.java
3727
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.apache.flex.forks.batik.ext.awt.image; import org.apache.flex.forks.batik.ext.awt.image.renderable.Filter; import org.apache.flex.forks.batik.util.ParsedURL; import org.apache.flex.forks.batik.util.SoftReferenceCache; /** * This class manages a cache of soft references to Images that * we have already loaded. * * <p> * Adding an image is two fold. First you add the ParsedURL, this lets * the cache know that someone is working on this ParsedURL. Then when * the completed RenderedImage is ready you put it into the cache. * </p> * <p> * If someone requests a ParsedURL after it has been added but before it has * been put they will be blocked until the put. * </p> * * @author <a href="mailto:thomas.deweese@kodak.com">Thomas DeWeese</a> * @version $Id: URLImageCache.java 475477 2006-11-15 22:44:28Z cam $ */ public class URLImageCache extends SoftReferenceCache { static URLImageCache theCache = new URLImageCache(); public static URLImageCache getDefaultCache() { return theCache; } /** * Let people create there own caches. */ public URLImageCache() { } /** * Check if <tt>request(url)</tt> will return with a Filter * (not putting you on the hook for it). Note that it is possible * that this will return true but between this call and the call * to request the soft-reference will be cleared. So it * is still possible for request to return NULL, just much less * likely (you can always call 'clear' in that case). */ public synchronized boolean isPresent(ParsedURL purl) { return super.isPresentImpl(purl); } /** * Check if <tt>request(url)</tt> will return immediately with the * Filter. Note that it is possible that this will return * true but between this call and the call to request the * soft-reference will be cleared. */ public synchronized boolean isDone(ParsedURL purl) { return super.isDoneImpl(purl); } /** * If this returns null then you are now 'on the hook'. * to put the Filter associated with ParsedURL into the * cache. */ public synchronized Filter request(ParsedURL purl) { return (Filter)super.requestImpl(purl); } /** * Clear the entry for ParsedURL. * This is the easiest way to 'get off the hook'. * if you didn't indend to get on it. */ public synchronized void clear(ParsedURL purl) { super.clearImpl(purl); } /** * Associate bi with purl. bi is only referenced through * a soft reference so don't rely on the cache to keep it * around. If the map no longer contains our purl it was * probably cleared or flushed since we were put on the hook * for it, so in that case we will do nothing. */ public synchronized void put(ParsedURL purl, Filter filt) { super.putImpl(purl, filt); } }
apache-2.0
k-r-g/FrameworkBenchmarks
frameworks/Java/undertow/src/main/java/hello/UpdatesMongoAsyncHandler.java
3233
package hello; import static hello.Helper.getQueries; import static hello.Helper.randomWorld; import static hello.Helper.sendException; import static hello.Helper.sendJson; import com.mongodb.async.client.MongoCollection; import com.mongodb.async.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.Updates; import com.mongodb.client.model.WriteModel; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import org.bson.Document; import org.bson.conversions.Bson; /** * Handles the updates test using MongoDB with an asynchronous API. */ final class UpdatesMongoAsyncHandler implements HttpHandler { private final MongoCollection<Document> worldCollection; UpdatesMongoAsyncHandler(MongoDatabase db) { worldCollection = db.getCollection("world"); } @Override public void handleRequest(HttpServerExchange exchange) { int queries = getQueries(exchange); nUpdatedWorlds(queries).whenComplete( (worlds, exception) -> { if (exception != null) { sendException(exchange, exception); } else { sendJson(exchange, worlds); } }); } private CompletableFuture<World[]> nUpdatedWorlds(int n) { return nWorlds(n).thenCompose( worlds -> { List<WriteModel<Document>> writes = new ArrayList<>(worlds.length); for (World world : worlds) { world.randomNumber = randomWorld(); Bson filter = Filters.eq(world.id); Bson update = Updates.set("randomNumber", world.randomNumber); writes.add(new UpdateOneModel<>(filter, update)); } CompletableFuture<World[]> next = new CompletableFuture<>(); worldCollection.bulkWrite( writes, (result, exception) -> { if (exception != null) { next.completeExceptionally(exception); } else { next.complete(worlds); } }); return next; }); } private CompletableFuture<World[]> nWorlds(int n) { @SuppressWarnings("unchecked") CompletableFuture<World>[] futures = new CompletableFuture[n]; for (int i = 0; i < futures.length; i++) { futures[i] = oneWorld(); } return CompletableFuture.allOf(futures).thenApply( nil -> { World[] worlds = new World[futures.length]; for (int i = 0; i < futures.length; i++) { worlds[i] = futures[i].join(); } return worlds; }); } private CompletableFuture<World> oneWorld() { CompletableFuture<World> future = new CompletableFuture<>(); worldCollection .find(Filters.eq(randomWorld())) .map(Helper::mongoDocumentToWorld) .first( (world, exception) -> { if (exception != null) { future.completeExceptionally(exception); } else { future.complete(world); } }); return future; } }
bsd-3-clause
rokn/Count_Words_2015
testing/spring-boot-master/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/repackage/RepackageTask.java
7655
/* * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.gradle.repackage; import java.io.File; import java.io.IOException; import java.util.HashSet; import java.util.Set; import java.util.concurrent.TimeUnit; import org.gradle.api.Action; import org.gradle.api.DefaultTask; import org.gradle.api.Project; import org.gradle.api.Task; import org.gradle.api.plugins.ExtraPropertiesExtension; import org.gradle.api.tasks.TaskAction; import org.gradle.api.tasks.bundling.Jar; import org.springframework.boot.gradle.SpringBootPluginExtension; import org.springframework.boot.loader.tools.DefaultLaunchScript; import org.springframework.boot.loader.tools.LaunchScript; import org.springframework.boot.loader.tools.Repackager; import org.springframework.util.FileCopyUtils; /** * Repackage task. * * @author Phillip Webb * @author Janne Valkealahti * @author Andy Wilkinson */ public class RepackageTask extends DefaultTask { private static final long FIND_WARNING_TIMEOUT = TimeUnit.SECONDS.toMillis(10); private String customConfiguration; private Object withJarTask; private String mainClass; private String classifier; private File outputFile; public void setCustomConfiguration(String customConfiguration) { this.customConfiguration = customConfiguration; } public Object getWithJarTask() { return this.withJarTask; } public void setWithJarTask(Object withJarTask) { this.withJarTask = withJarTask; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public String getMainClass() { return this.mainClass; } public String getClassifier() { return this.classifier; } public void setClassifier(String classifier) { this.classifier = classifier; } void setOutputFile(File file) { this.outputFile = file; } @TaskAction public void repackage() { Project project = getProject(); SpringBootPluginExtension extension = project.getExtensions() .getByType(SpringBootPluginExtension.class); ProjectLibraries libraries = getLibraries(); project.getTasks().withType(Jar.class, new RepackageAction(extension, libraries)); } public ProjectLibraries getLibraries() { Project project = getProject(); SpringBootPluginExtension extension = project.getExtensions() .getByType(SpringBootPluginExtension.class); ProjectLibraries libraries = new ProjectLibraries(project, extension); if (extension.getProvidedConfiguration() != null) { libraries.setProvidedConfigurationName(extension.getProvidedConfiguration()); } if (this.customConfiguration != null) { libraries.setCustomConfigurationName(this.customConfiguration); } else if (extension.getCustomConfiguration() != null) { libraries.setCustomConfigurationName(extension.getCustomConfiguration()); } return libraries; } /** * Action to repackage JARs. */ private class RepackageAction implements Action<Jar> { private final SpringBootPluginExtension extension; private final ProjectLibraries libraries; RepackageAction(SpringBootPluginExtension extension, ProjectLibraries libraries) { this.extension = extension; this.libraries = libraries; } @Override public void execute(Jar jarTask) { if (!RepackageTask.this.isEnabled()) { getLogger().info("Repackage disabled"); return; } Object withJarTask = RepackageTask.this.withJarTask; if (!isTaskMatch(jarTask, withJarTask)) { getLogger().info( "Jar task not repackaged (didn't match withJarTask): " + jarTask); return; } File file = jarTask.getArchivePath(); if (file.exists()) { repackage(file); } } private boolean isTaskMatch(Jar task, Object withJarTask) { if (withJarTask == null) { if ("".equals(task.getClassifier())) { Set<Object> tasksWithCustomRepackaging = new HashSet<Object>(); for (RepackageTask repackageTask : RepackageTask.this.getProject() .getTasks().withType(RepackageTask.class)) { if (repackageTask.getWithJarTask() != null) { tasksWithCustomRepackaging .add(repackageTask.getWithJarTask()); } } return !tasksWithCustomRepackaging.contains(task); } return false; } return task.equals(withJarTask) || task.getName().equals(withJarTask); } private void repackage(File file) { File outputFile = RepackageTask.this.outputFile; if (outputFile != null && !file.equals(outputFile)) { copy(file, outputFile); file = outputFile; } Repackager repackager = new LoggingRepackager(file); setMainClass(repackager); if (this.extension.convertLayout() != null) { repackager.setLayout(this.extension.convertLayout()); } repackager.setBackupSource(this.extension.isBackupSource()); try { LaunchScript launchScript = getLaunchScript(); repackager.repackage(file, this.libraries, launchScript); } catch (IOException ex) { throw new IllegalStateException(ex.getMessage(), ex); } } private void copy(File source, File dest) { try { FileCopyUtils.copy(source, dest); } catch (IOException ex) { throw new IllegalStateException(ex.getMessage(), ex); } } private void setMainClass(Repackager repackager) { String mainClass; if (getProject().hasProperty("mainClassName")) { mainClass = (String) getProject().property("mainClassName"); } else { ExtraPropertiesExtension extraProperties = (ExtraPropertiesExtension) getProject() .getExtensions().getByName("ext"); mainClass = (String) extraProperties.get("mainClassName"); } if (RepackageTask.this.mainClass != null) { mainClass = RepackageTask.this.mainClass; } else if (this.extension.getMainClass() != null) { mainClass = this.extension.getMainClass(); } else { Task runTask = getProject().getTasks().findByName("run"); if (runTask != null && runTask.hasProperty("main")) { mainClass = (String) getProject().getTasks().getByName("run") .property("main"); } } getLogger().info("Setting mainClass: " + mainClass); repackager.setMainClass(mainClass); } private LaunchScript getLaunchScript() throws IOException { if (this.extension.isExecutable() || this.extension.getEmbeddedLaunchScript() != null) { return new DefaultLaunchScript(this.extension.getEmbeddedLaunchScript(), this.extension.getEmbeddedLaunchScriptProperties()); } return null; } } /** * {@link Repackager} that also logs when searching takes too long. */ private class LoggingRepackager extends Repackager { LoggingRepackager(File source) { super(source); } @Override protected String findMainMethod(java.util.jar.JarFile source) throws IOException { long startTime = System.currentTimeMillis(); try { return super.findMainMethod(source); } finally { long duration = System.currentTimeMillis() - startTime; if (duration > FIND_WARNING_TIMEOUT) { getLogger().warn("Searching for the main-class is taking " + "some time, consider using setting " + "'springBoot.mainClass'"); } } } } }
mit
oleg-nenashev/jenkins
test/src/test/java/hudson/cli/ListJobsCommandTest.java
6254
/* * The MIT License * * Copyright 2018 Victor Martinez. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.cli; import hudson.matrix.Axis; import hudson.matrix.AxisList; import hudson.matrix.MatrixProject; import hudson.maven.MavenModuleSet; import hudson.model.DirectlyModifiableView; import hudson.model.FreeStyleProject; import hudson.model.Label; import hudson.model.ListView; import hudson.model.labels.LabelExpression; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockFolder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; public class ListJobsCommandTest { @Rule public JenkinsRule j = new JenkinsRule(); private CLICommand listJobsCommand; private CLICommandInvoker command; @Before public void setUp() { listJobsCommand = new ListJobsCommand(); command = new CLICommandInvoker(j, listJobsCommand); } @Test public void getAllJobsFromView() throws Exception { MockFolder folder = j.createFolder("Folder"); MockFolder nestedFolder = folder.createProject(MockFolder.class, "NestedFolder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); FreeStyleProject nestedJob = nestedFolder.createProject(FreeStyleProject.class, "nestedJob"); ListView view = new ListView("OuterFolder"); view.setRecurse(true); j.jenkins.addView(view); ((DirectlyModifiableView) j.jenkins.getView("OuterFolder")).add(folder); ((DirectlyModifiableView) j.jenkins.getView("OuterFolder")).add(job); CLICommandInvoker.Result result = command.invokeWithArgs("OuterFolder"); assertThat(result, CLICommandInvoker.Matcher.succeeded()); assertThat(result.stdout(), containsString("Folder")); assertThat(result.stdout(), containsString("job")); assertThat(result.stdout(), not(containsString("nestedJob"))); } @Issue("JENKINS-48220") @Test public void getAllJobsFromFolder() throws Exception { MockFolder folder = j.createFolder("Folder"); MockFolder nestedFolder = folder.createProject(MockFolder.class, "NestedFolder"); FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"); FreeStyleProject nestedJob = nestedFolder.createProject(FreeStyleProject.class, "nestedJob"); CLICommandInvoker.Result result = command.invokeWithArgs("Folder"); assertThat(result, CLICommandInvoker.Matcher.succeeded()); assertThat(result.stdout(), containsString("job")); assertThat(result.stdout(), containsString("NestedFolder")); assertThat(result.stdout(), not(containsString("nestedJob"))); } @Issue("JENKINS-18393") @Test public void getAllJobsFromFolderWithMatrixProject() throws Exception { MockFolder folder = j.createFolder("Folder"); FreeStyleProject job1 = folder.createProject(FreeStyleProject.class, "job1"); FreeStyleProject job2 = folder.createProject(FreeStyleProject.class, "job2"); MatrixProject matrixProject = folder.createProject(MatrixProject.class, "mp"); matrixProject.setDisplayName("downstream"); matrixProject.setAxes(new AxisList( new Axis("axis", "a", "b") )); Label label = LabelExpression.get("aws-linux-dummy"); matrixProject.setAssignedLabel(label); CLICommandInvoker.Result result = command.invokeWithArgs("Folder"); assertThat(result, CLICommandInvoker.Matcher.succeeded()); assertThat(result.stdout(), containsString("job1")); assertThat(result.stdout(), containsString("job2")); assertThat(result.stdout(), containsString("mp")); } @Issue("JENKINS-18393") @Test public void getAllJobsFromFolderWithMavenModuleSet() throws Exception { MockFolder folder = j.createFolder("Folder"); FreeStyleProject job1 = folder.createProject(FreeStyleProject.class, "job1"); FreeStyleProject job2 = folder.createProject(FreeStyleProject.class, "job2"); MavenModuleSet mavenProject = folder.createProject(MavenModuleSet.class, "mvn"); CLICommandInvoker.Result result = command.invokeWithArgs("Folder"); assertThat(result, CLICommandInvoker.Matcher.succeeded()); assertThat(result.stdout(), containsString("job1")); assertThat(result.stdout(), containsString("job2")); assertThat(result.stdout(), containsString("mvn")); } @Issue("JENKINS-18393") @Test public void failForMatrixProject() throws Exception { MatrixProject matrixProject = j.createProject(MatrixProject.class, "mp"); CLICommandInvoker.Result result = command.invokeWithArgs("MatrixJob"); assertThat(result, CLICommandInvoker.Matcher.failedWith(3)); assertThat(result.stdout(), isEmptyString()); assertThat(result.stderr(), containsString("No view or item group with the given name 'MatrixJob' found.")); } }
mit
FauxFaux/jdk9-jdk
src/java.base/share/classes/jdk/internal/org/objectweb/asm/commons/Remapper.java
9445
/* * 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. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * 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 holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package jdk.internal.org.objectweb.asm.commons; import jdk.internal.org.objectweb.asm.Handle; import jdk.internal.org.objectweb.asm.Type; import jdk.internal.org.objectweb.asm.signature.SignatureReader; import jdk.internal.org.objectweb.asm.signature.SignatureVisitor; import jdk.internal.org.objectweb.asm.signature.SignatureWriter; /** * A class responsible for remapping types and names. Subclasses can override * the following methods: * * <ul> * <li>{@link #map(String)} - map type</li> * <li>{@link #mapFieldName(String, String, String)} - map field name</li> * <li>{@link #mapMethodName(String, String, String)} - map method name</li> * </ul> * * @author Eugene Kuleshov */ public abstract class Remapper { public String mapDesc(String desc) { Type t = Type.getType(desc); switch (t.getSort()) { case Type.ARRAY: String s = mapDesc(t.getElementType().getDescriptor()); for (int i = 0; i < t.getDimensions(); ++i) { s = '[' + s; } return s; case Type.OBJECT: String newType = map(t.getInternalName()); if (newType != null) { return 'L' + newType + ';'; } } return desc; } private Type mapType(Type t) { switch (t.getSort()) { case Type.ARRAY: String s = mapDesc(t.getElementType().getDescriptor()); for (int i = 0; i < t.getDimensions(); ++i) { s = '[' + s; } return Type.getType(s); case Type.OBJECT: s = map(t.getInternalName()); return s != null ? Type.getObjectType(s) : t; case Type.METHOD: return Type.getMethodType(mapMethodDesc(t.getDescriptor())); } return t; } public String mapType(String type) { if (type == null) { return null; } return mapType(Type.getObjectType(type)).getInternalName(); } public String[] mapTypes(String[] types) { String[] newTypes = null; boolean needMapping = false; for (int i = 0; i < types.length; i++) { String type = types[i]; String newType = map(type); if (newType != null && newTypes == null) { newTypes = new String[types.length]; if (i > 0) { System.arraycopy(types, 0, newTypes, 0, i); } needMapping = true; } if (needMapping) { newTypes[i] = newType == null ? type : newType; } } return needMapping ? newTypes : types; } public String mapMethodDesc(String desc) { if ("()V".equals(desc)) { return desc; } Type[] args = Type.getArgumentTypes(desc); StringBuilder sb = new StringBuilder("("); for (int i = 0; i < args.length; i++) { sb.append(mapDesc(args[i].getDescriptor())); } Type returnType = Type.getReturnType(desc); if (returnType == Type.VOID_TYPE) { sb.append(")V"); return sb.toString(); } sb.append(')').append(mapDesc(returnType.getDescriptor())); return sb.toString(); } public Object mapValue(Object value) { if (value instanceof Type) { return mapType((Type) value); } if (value instanceof Handle) { Handle h = (Handle) value; return new Handle(h.getTag(), mapType(h.getOwner()), mapMethodName( h.getOwner(), h.getName(), h.getDesc()), mapMethodDesc(h.getDesc()), h.isInterface()); } return value; } /** * @param signature * signature for mapper * @param typeSignature * true if signature is a FieldTypeSignature, such as the * signature parameter of the ClassVisitor.visitField or * MethodVisitor.visitLocalVariable methods * @return signature rewritten as a string */ public String mapSignature(String signature, boolean typeSignature) { if (signature == null) { return null; } SignatureReader r = new SignatureReader(signature); SignatureWriter w = new SignatureWriter(); SignatureVisitor a = createSignatureRemapper(w); if (typeSignature) { r.acceptType(a); } else { r.accept(a); } return w.toString(); } /** * @deprecated use {@link #createSignatureRemapper} instead. */ @Deprecated protected SignatureVisitor createRemappingSignatureAdapter( SignatureVisitor v) { return new SignatureRemapper(v, this); } protected SignatureVisitor createSignatureRemapper( SignatureVisitor v) { return createRemappingSignatureAdapter(v); } /** * Map method name to the new name. Subclasses can override. * * @param owner * owner of the method. * @param name * name of the method. * @param desc * descriptor of the method. * @return new name of the method */ public String mapMethodName(String owner, String name, String desc) { return name; } /** * Map invokedynamic method name to the new name. Subclasses can override. * * @param name * name of the invokedynamic. * @param desc * descriptor of the invokedynamic. * @return new invokdynamic name. */ public String mapInvokeDynamicMethodName(String name, String desc) { return name; } /** * Map field name to the new name. Subclasses can override. * * @param owner * owner of the field. * @param name * name of the field * @param desc * descriptor of the field * @return new name of the field. */ public String mapFieldName(String owner, String name, String desc) { return name; } /** * Map type name to the new name. Subclasses can override. * * @param typeName * the type name * @return new name, default implementation is the identity. */ public String map(String typeName) { return typeName; } }
gpl-2.0
FauxFaux/jdk9-jdk
test/sun/management/jdp/JdpTestCase.java
7749
/* * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * A JVM with JDP on should send multicast JDP packets regularly. * Look at JdpOnTestCase.java and JdpOffTestCase.java */ import sun.management.jdp.JdpJmxPacket; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.MulticastSocket; import java.net.SocketTimeoutException; import java.util.Arrays; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public abstract class JdpTestCase { final Logger log = Logger.getLogger("sun.management.jdp"); final int MAGIC = 0xC0FFEE42; // Jdp magic number. private static final int BUFFER_LENGTH = 64 * 1024; // max UDP size, except for IPv6 jumbograms. private final int TIME_OUT_FACTOR = 10; // Socket times out after 10 times the jdp pause. protected int timeOut; private long startTime; protected ClientConnection connection; public JdpTestCase(ClientConnection connection) { this.connection = connection; JdpTestUtil.enableConsoleLogging(log, Level.ALL); } public void run() throws Exception { log.fine("Test started."); log.fine("Listening for multicast packets at " + connection.address.getHostAddress() + ":" + String.valueOf(connection.port)); log.fine(initialLogMessage()); log.fine("Pause in between packets is: " + connection.pauseInSeconds + " seconds."); startTime = System.currentTimeMillis(); timeOut = connection.pauseInSeconds * TIME_OUT_FACTOR; log.fine("Timeout set to " + String.valueOf(timeOut) + " seconds."); MulticastSocket socket = connection.connectWithTimeout(timeOut * 1000); byte[] buffer = new byte[BUFFER_LENGTH]; DatagramPacket datagram = new DatagramPacket(buffer, buffer.length); do { try { socket.receive(datagram); onReceived(extractUDPpayload(datagram)); } catch (SocketTimeoutException e) { onSocketTimeOut(e); } if (hasTestLivedLongEnough()) { shutdown(); } } while (shouldContinue()); log.fine("Test ended successfully."); } /** * Subclasses: JdpOnTestCase and JdpOffTestCase have different messages. */ protected abstract String initialLogMessage(); /** * Executed when the socket receives a UDP packet. */ private void onReceived(byte[] packet) throws Exception { if (isJDP(packet)) { Map<String, String> payload = checkStructure(packet); jdpPacketReceived(payload); } else { log.fine("Non JDP packet received, ignoring it."); } } /** * Determine whether the test should end. * * @return */ abstract protected boolean shouldContinue(); /** * This method is executed when the socket has not received any packet for timeOut seconds. */ abstract protected void onSocketTimeOut(SocketTimeoutException e) throws Exception; /** * This method is executed after a correct Jdp packet has been received. * * @param payload A dictionary containing the data if the received Jdp packet. */ private void jdpPacketReceived(Map<String, String> payload) throws Exception { final String instanceName = payload.get("INSTANCE_NAME"); if (instanceName != null && instanceName.equals(connection.instanceName)) { packetFromThisVMReceived(payload); } else { packetFromOtherVMReceived(payload); } } /** * This method is executed after a correct Jdp packet, coming from this VM has been received. * * @param payload A dictionary containing the data if the received Jdp packet. */ protected abstract void packetFromThisVMReceived(Map<String, String> payload) throws Exception; /** * This method is executed after a correct Jdp packet, coming from another VM has been received. * * @param payload A dictionary containing the data if the received Jdp packet. */ protected void packetFromOtherVMReceived(Map<String, String> payload) { final String jdpName = payload.get("INSTANCE_NAME"); log.fine("Ignoring JDP packet sent by other VM, jdp.name=" + jdpName); } /** * The test should stop if it has been 12 times the jdp.pause. * jdp.pause is how many seconds in between packets. * <p/> * This timeout (12 times)is slightly longer than the socket timeout (10 times) on purpose. * In the off test case, the socket should time out first. * * @return */ protected boolean hasTestLivedLongEnough() { long now = System.currentTimeMillis(); boolean haslivedLongEnough = (now - startTime) > (timeOut * 1.2 * 1000); return haslivedLongEnough; } /** * This exit condition arises when we receive UDP packets but they are not valid Jdp. */ protected void shutdown() throws Exception { log.severe("Shutting down the test."); throw new Exception("Not enough JDP packets received before timeout!"); } /** * Assert that this Jdp packet contains the required two keys. * <p/> * We expect zero packet corruption and thus fail on the first corrupted packet. * This might need revision. */ protected Map<String, String> checkStructure(byte[] packet) throws UnsupportedEncodingException { Map<String, String> payload = JdpTestUtil.readPayload(packet); assertTrue(payload.size() >= 2, "JDP should have minimun 2 entries."); assertTrue(payload.get(JdpJmxPacket.UUID_KEY).length() > 0); assertTrue(payload.get(JdpJmxPacket.JMX_SERVICE_URL_KEY).length() > 0); return payload; } /** * Check if packet has correct JDP magic number. * * @param packet * @return * @throws IOException */ private boolean isJDP(byte[] packet) throws IOException { int magic = JdpTestUtil.decode4ByteInt(packet, 0); return (magic == MAGIC); } private byte[] extractUDPpayload(DatagramPacket datagram) { byte[] data = Arrays.copyOf(datagram.getData(), datagram.getLength()); return data; } /** * Hack until I find a way to use TestNG's assertions. */ private void assertTrue(boolean assertion, String message) { if (assertion == false) { log.severe(message); assert (false); } } private void assertTrue(boolean assertion) { assertTrue(assertion, ""); } }
gpl-2.0
armenrz/adempiere
base/src/org/compiere/model/I_C_Phase.java
6102
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. * * This program is free software, you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY, without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program, if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.model; import java.math.BigDecimal; import java.sql.Timestamp; import org.compiere.util.KeyNamePair; /** Generated Interface for C_Phase * @author Adempiere (generated) * @version Release 3.8.0 */ public interface I_C_Phase { /** TableName=C_Phase */ public static final String Table_Name = "C_Phase"; /** AD_Table_ID=577 */ public static final int Table_ID = MTable.getTable_ID(Table_Name); KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name); /** AccessLevel = 3 - Client - Org */ BigDecimal accessLevel = BigDecimal.valueOf(3); /** Load Meta Data */ /** Column name AD_Client_ID */ public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID"; /** Get Client. * Client/Tenant for this installation. */ public int getAD_Client_ID(); /** Column name AD_Org_ID */ public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID"; /** Set Organization. * Organizational entity within client */ public void setAD_Org_ID (int AD_Org_ID); /** Get Organization. * Organizational entity within client */ public int getAD_Org_ID(); /** Column name C_Phase_ID */ public static final String COLUMNNAME_C_Phase_ID = "C_Phase_ID"; /** Set Standard Phase. * Standard Phase of the Project Type */ public void setC_Phase_ID (int C_Phase_ID); /** Get Standard Phase. * Standard Phase of the Project Type */ public int getC_Phase_ID(); /** Column name C_ProjectType_ID */ public static final String COLUMNNAME_C_ProjectType_ID = "C_ProjectType_ID"; /** Set Project Type. * Type of the project */ public void setC_ProjectType_ID (int C_ProjectType_ID); /** Get Project Type. * Type of the project */ public int getC_ProjectType_ID(); public org.compiere.model.I_C_ProjectType getC_ProjectType() throws RuntimeException; /** Column name Created */ public static final String COLUMNNAME_Created = "Created"; /** Get Created. * Date this record was created */ public Timestamp getCreated(); /** Column name CreatedBy */ public static final String COLUMNNAME_CreatedBy = "CreatedBy"; /** Get Created By. * User who created this records */ public int getCreatedBy(); /** Column name Description */ public static final String COLUMNNAME_Description = "Description"; /** Set Description. * Optional short description of the record */ public void setDescription (String Description); /** Get Description. * Optional short description of the record */ public String getDescription(); /** Column name Help */ public static final String COLUMNNAME_Help = "Help"; /** Set Comment/Help. * Comment or Hint */ public void setHelp (String Help); /** Get Comment/Help. * Comment or Hint */ public String getHelp(); /** Column name IsActive */ public static final String COLUMNNAME_IsActive = "IsActive"; /** Set Active. * The record is active in the system */ public void setIsActive (boolean IsActive); /** Get Active. * The record is active in the system */ public boolean isActive(); /** Column name M_Product_ID */ public static final String COLUMNNAME_M_Product_ID = "M_Product_ID"; /** Set Product. * Product, Service, Item */ public void setM_Product_ID (int M_Product_ID); /** Get Product. * Product, Service, Item */ public int getM_Product_ID(); public org.compiere.model.I_M_Product getM_Product() throws RuntimeException; /** Column name Name */ public static final String COLUMNNAME_Name = "Name"; /** Set Name. * Alphanumeric identifier of the entity */ public void setName (String Name); /** Get Name. * Alphanumeric identifier of the entity */ public String getName(); /** Column name SeqNo */ public static final String COLUMNNAME_SeqNo = "SeqNo"; /** Set Sequence. * Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo); /** Get Sequence. * Method of ordering records; lowest number comes first */ public int getSeqNo(); /** Column name StandardQty */ public static final String COLUMNNAME_StandardQty = "StandardQty"; /** Set Standard Quantity. * Standard Quantity */ public void setStandardQty (BigDecimal StandardQty); /** Get Standard Quantity. * Standard Quantity */ public BigDecimal getStandardQty(); /** Column name Updated */ public static final String COLUMNNAME_Updated = "Updated"; /** Get Updated. * Date this record was updated */ public Timestamp getUpdated(); /** Column name UpdatedBy */ public static final String COLUMNNAME_UpdatedBy = "UpdatedBy"; /** Get Updated By. * User who updated this records */ public int getUpdatedBy(); }
gpl-2.0
danielyc/test-1.9.4
build/tmp/recompileMc/sources/net/minecraft/util/WeightedSpawnerEntity.java
973
package net.minecraft.util; import net.minecraft.nbt.NBTTagCompound; public class WeightedSpawnerEntity extends WeightedRandom.Item { private final NBTTagCompound nbt; public WeightedSpawnerEntity() { super(1); this.nbt = new NBTTagCompound(); this.nbt.setString("id", "Pig"); } public WeightedSpawnerEntity(NBTTagCompound nbtIn) { this(nbtIn.hasKey("Weight", 99) ? nbtIn.getInteger("Weight") : 1, nbtIn.getCompoundTag("Entity")); } public WeightedSpawnerEntity(int itemWeightIn, NBTTagCompound nbtIn) { super(itemWeightIn); this.nbt = nbtIn; } public NBTTagCompound toCompoundTag() { NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setTag("Entity", this.nbt); nbttagcompound.setInteger("Weight", this.itemWeight); return nbttagcompound; } public NBTTagCompound getNbt() { return this.nbt; } }
gpl-3.0
xasx/wildfly
testsuite/integration/basic/src/test/java/org/jboss/as/test/integration/jaxrs/decorator/ResourceInterface.java
289
package org.jboss.as.test.integration.jaxrs.decorator; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * @author Stuart Douglas */ @Path("decorator") @Produces({"text/plain"}) public interface ResourceInterface { @GET String getMessage(); }
lgpl-2.1
paulk-asert/groovy
src/test/gls/ch06/s05/testClasses/Tt1go.java
1197
/* * 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 gls.ch06.s05.testClasses; import groovy.lang.GroovyObjectSupport; public class Tt1go extends GroovyObjectSupport { public String x = "field"; public String getX() { return this.p1; } public void setX(final String x) { this.p1 = x; } public String x() { return "method"; } public String p1 = "property"; }
apache-2.0
rickyHong/RSparkMR4C
java/src/java/com/google/mr4c/message/DefaultMessageHandler.java
1149
/** * 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.mr4c.message; import com.google.mr4c.util.MR4CLogging; import java.io.IOException; import java.net.URI; import org.slf4j.Logger; public class DefaultMessageHandler implements MessageHandler { protected static final Logger s_log = MR4CLogging.getLogger(DefaultMessageHandler.class); public void setURI(URI uri) {} public void handleMessage(Message msg) throws IOException { s_log.info("Message sent to default handler for topic [{}] : [{}]", msg.getTopic(), msg.getContent()); } }
apache-2.0
first087/Android-RoundCornerProgressBar
library/src/main/java/com/akexorcist/roundcornerprogressbar/TextRoundCornerProgressBar.java
8335
/* Copyright 2015 Akexorcist 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.akexorcist.roundcornerprogressbar; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; import android.widget.LinearLayout; import android.widget.TextView; import com.akexorcist.roundcornerprogressbar.common.BaseRoundCornerProgressBar; import java.text.NumberFormat; public class TextRoundCornerProgressBar extends BaseRoundCornerProgressBar { protected final static int DEFAULT_PROGRESS_BAR_HEIGHT = 30; protected final static int DEFAULT_TEXT_PADDING = 10; protected final static int DEFAULT_TEXT_SIZE = 18; protected final static int DEFAULT_TEXT_WIDTH = 100; protected final static int DEFAULT_TEXT_COLOR = Color.parseColor("#ff333333"); protected TextView textViewValue; protected String text; protected String textUnit; protected boolean autoTextChange; protected int textSize; protected int textPadding; protected int textWidth; protected int textColor; @SuppressLint("NewApi") public TextRoundCornerProgressBar(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected int initProgressBarLayout() { return R.layout.round_corner_with_text_layout; } @Override protected void setup(TypedArray typedArray, DisplayMetrics metrics) { autoTextChange = typedArray.getBoolean(R.styleable.RoundCornerProgress_rcAutoTextChange, false); textSize = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcTextProgressSize, DEFAULT_TEXT_SIZE); textPadding = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcTextProgressPadding, DEFAULT_TEXT_PADDING); text = typedArray.getString(R.styleable.RoundCornerProgress_rcTextProgress); text = (text == null) ? "" : text; textUnit = typedArray.getString(R.styleable.RoundCornerProgress_rcTextProgressUnit); textUnit = (textUnit == null) ? "" : textUnit; textWidth = (int) typedArray.getDimension(R.styleable.RoundCornerProgress_rcTextProgressWidth, DEFAULT_TEXT_WIDTH); textViewValue = (TextView) findViewById(R.id.round_corner_progress_text); textViewValue.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); textViewValue.setTextColor(typedArray.getColor(R.styleable.RoundCornerProgress_rcTextProgressColor, DEFAULT_TEXT_COLOR)); textViewValue.setText(text); textViewValue.setPadding(textPadding, 0, textPadding, 0); } @Override public void setBackgroundLayoutSize(LinearLayout layoutBackground) { int height, width; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { width = getMeasuredWidth() - textWidth; height = getMeasuredHeight(); } else { width = getWidth() - textWidth; height = getHeight(); } if(height == 0) { height = (int) dp2px(DEFAULT_PROGRESS_BAR_HEIGHT); } setBackgroundWidth(width); setBackgroundHeight(height); } @Override protected void setGradientRadius(GradientDrawable gradient) { int radius = getRadius() - (getPadding() / 2); gradient.setCornerRadii(new float[]{radius, radius, radius, radius, radius, radius, radius, radius}); } @Override protected void onLayoutMeasured() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { setBackgroundWidth(getMeasuredWidth() - textWidth); } else { setBackgroundWidth(getWidth() - textWidth); } } @Override protected float setLayoutProgressWidth(float ratio) { if (isAutoTextChange()) { String strProgress = NumberFormat.getInstance().format((progress % 1 == 0) ? (int) progress : progress); textViewValue.setText(strProgress + " " + textUnit); } return (ratio > 0) ? (getBackgroundWidth() - (getPadding() * 2)) / ratio : 0; } @Override protected float setSecondaryLayoutProgressWidth(float ratio) { return (ratio > 0) ? (getBackgroundWidth() - (getPadding() * 2)) / ratio : 0; } public void setTextUnit(String unit) { textUnit = unit; setProgress(); } public String getTextUnit() { return textUnit; } public void setTextProgress(CharSequence text) { textViewValue.setText(text); } public CharSequence getTextProgress() { return textViewValue.getText(); } public void setTextColor(int color) { textColor = color; textViewValue.setTextColor(color); } public int getTextColor() { return textColor; } public void setAutoTextChange(boolean isAuto) { autoTextChange = isAuto; } public boolean isAutoTextChange() { return autoTextChange; } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.autoTextChange = this.autoTextChange; ss.textSize = this.textSize; ss.textPadding = this.textPadding; ss.textWidth = this.textWidth; ss.textColor = this.textColor; ss.text = this.text; ss.textUnit = this.textUnit; return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { if(!(state instanceof SavedState)) { super.onRestoreInstanceState(state); return; } SavedState ss = (SavedState)state; super.onRestoreInstanceState(ss.getSuperState()); this.autoTextChange = ss.autoTextChange; this.textSize = ss.textSize; this.textPadding = ss.textPadding; this.textWidth = ss.textWidth; this.textColor = ss.textColor; this.text = ss.text; this.textUnit = ss.textUnit; setTextProgress(text + textUnit); setTextColor(textColor); } private static class SavedState extends BaseSavedState { String text; String textUnit; int textSize; int textPadding; int textWidth; int textColor; boolean autoTextChange; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); this.textSize = in.readInt(); this.textPadding = in.readInt(); this.textWidth = in.readInt(); this.textColor = in.readInt(); this.autoTextChange = in.readByte() != 0; this.text = in.readString(); this.textUnit = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(this.textSize); out.writeInt(this.textPadding); out.writeInt(this.textWidth); out.writeInt(this.textColor); out.writeByte((byte) (this.autoTextChange ? 1 : 0)); out.writeString(this.text); out.writeString(this.textUnit); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
apache-2.0
kidaa/incubator-ignite
examples/src/main/java8/org/apache/ignite/examples/java8/streaming/package-info.java
937
/* * 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 description. --> * Demonstrates usage of data streamer. */ package org.apache.ignite.examples.java8.streaming;
apache-2.0
SoftwareKing/zstack
header/src/main/java/org/zstack/header/host/AttachNicToVmOnHypervisorMsg.java
806
package org.zstack.header.host; import org.zstack.header.message.NeedReplyMessage; import org.zstack.header.vm.VmNicInventory; import java.util.List; public class AttachNicToVmOnHypervisorMsg extends NeedReplyMessage implements HostMessage { private String vmInstanceUuid; private String hostUuid; private List<VmNicInventory> nics; public String getVmUuid() { return vmInstanceUuid; } public void setVmUuid(String vmInstanceUuid) { this.vmInstanceUuid = vmInstanceUuid; } public List<VmNicInventory> getNics() { return nics; } public void setNics(List<VmNicInventory> nics) { this.nics = nics; } public void setHostUuid(String hostUuid) { this.hostUuid = hostUuid; } @Override public String getHostUuid() { return hostUuid; } }
apache-2.0
WangTaoTheTonic/flink
flink-runtime/src/main/java/org/apache/flink/runtime/concurrent/CompletableFuture.java
1816
/* * 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.concurrent; /** * Flink's completable future abstraction. A completable future can be completed with a regular * value or an exception. * * @param <T> type of the future's value */ public interface CompletableFuture<T> extends Future<T> { /** * Completes the future with the given value. The complete operation only succeeds if the future * has not been completed before. Whether it is successful or not is returned by the method. * * @param value to complete the future with * @return true if the completion was successful; otherwise false */ boolean complete(T value); /** * Completes the future with the given exception. The complete operation only succeeds if the * future has not been completed before. Whether it is successful or not is returned by the * method. * * @param t the exception to complete the future with * @return true if the completion was successful; otherwise false */ boolean completeExceptionally(Throwable t); }
apache-2.0
objmagic/heron
tools/java/src/com/twitter/bazel/checkstyle/JavaCheckstyle.java
5067
// Copyright 2016 Twitter. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.twitter.bazel.checkstyle; import java.io.IOException; import java.util.Collection; import java.util.logging.Logger; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2; import com.google.devtools.build.lib.actions.extra.ExtraActionInfo; import com.google.devtools.build.lib.actions.extra.JavaCompileInfo; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.ArrayUtils; /** * Verifies that the java classes styles conform to the styles in the config. * Usage: java com.twitter.bazel.checkstyle.JavaCheckstyle -f &lt;extra_action_file&gt; -c &lt;checkstyle_config&gt; * <p> * To test: * $ bazel build --config=darwin heron/spi/src/java:heron-spi --experimental_action_listener=tools/java:compile_java */ public final class JavaCheckstyle { public static final Logger LOG = Logger.getLogger(JavaCheckstyle.class.getName()); private static final String CLASSNAME = JavaCheckstyle.class.getCanonicalName(); private JavaCheckstyle() { } public static void main(String[] args) throws IOException { CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption(Option.builder("f") .required(true).hasArg() .longOpt("extra_action_file") .desc("bazel extra action protobuf file") .build()); options.addOption(Option.builder("hc") .required(true).hasArg() .longOpt("heron_checkstyle_config_file") .desc("checkstyle config file") .build()); options.addOption(Option.builder("ac") .required(true).hasArg() .longOpt("apache_checkstyle_config_file") .desc("checkstyle config file for imported source files") .build()); try { // parse the command line arguments CommandLine line = parser.parse(options, args); String extraActionFile = line.getOptionValue("f"); String configFile = line.getOptionValue("hc"); String apacheConfigFile = line.getOptionValue("ac"); // check heron source file style String[] heronSourceFiles = getHeronSourceFiles(extraActionFile); checkStyle(heronSourceFiles, configFile); // check other apache source file style String[] apacheSourceFiles = getApacheSourceFiles(extraActionFile); checkStyle(apacheSourceFiles, apacheConfigFile); } catch (ParseException exp) { LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage())); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java " + CLASSNAME, options); } } private static void checkStyle(String[] files, String config) throws IOException { if (files.length == 0) { LOG.fine("No java files found by checkstyle"); return; } LOG.fine(files.length + " java files found by checkstyle"); String[] checkstyleArgs = (String[]) ArrayUtils.addAll( new String[]{"-c", config}, files); LOG.fine("checkstyle args: " + Joiner.on(" ").join(checkstyleArgs)); com.puppycrawl.tools.checkstyle.Main.main(checkstyleArgs); } private static String[] getHeronSourceFiles(String extraActionFile) { return getSourceFiles(extraActionFile, Predicates.not(Predicates.or( Predicates.containsPattern("heron/storm.src.java"), Predicates.containsPattern("contrib") ))); } private static String[] getApacheSourceFiles(String extraActionFile) { return getSourceFiles(extraActionFile, Predicates.or( Predicates.containsPattern("heron/storm.src.java"), Predicates.containsPattern("contrib") )); } private static String[] getSourceFiles(String extraActionFile, Predicate<CharSequence> predicate) { ExtraActionInfo info = ExtraActionUtils.getExtraActionInfo(extraActionFile); JavaCompileInfo jInfo = info.getExtension(JavaCompileInfo.javaCompileInfo); Collection<String> sourceFiles = Collections2.filter(jInfo.getSourceFileList(), predicate); return sourceFiles.toArray(new String[sourceFiles.size()]); } }
apache-2.0
weitzj/closure-compiler
src/com/google/javascript/jscomp/JoinOp.java
2431
/* * Copyright 2010 The Closure Compiler Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.javascript.jscomp.graph.LatticeElement; import java.util.List; /** * Defines a way join a list of LatticeElements. */ interface JoinOp<L extends LatticeElement> extends Function<List<L>, L> { /** * An implementation of {@code JoinOp} that makes it easy to join to * lattice elements at a time. */ static abstract class BinaryJoinOp<L extends LatticeElement> implements JoinOp<L> { @Override public final L apply(List<L> values) { Preconditions.checkArgument(!values.isEmpty()); int size = values.size(); if (size == 1) { return values.get(0); } else if (size == 2) { return apply(values.get(0), values.get(1)); } else { int mid = computeMidPoint(size); return apply( apply(values.subList(0, mid)), apply(values.subList(mid, size))); } } /** * Creates a new lattice that will be the join of two input lattices. * * @return The join of {@code latticeA} and {@code latticeB}. */ abstract L apply(L latticeA, L latticeB); /** * Finds the midpoint of a list. The function will favor two lists of * even length instead of two lists of the same odd length. The list * must be at least length two. * * @param size Size of the list. */ static int computeMidPoint(int size) { int midpoint = size >>> 1; if (size > 4) { /* Any list longer than 4 should prefer an even split point * over the true midpoint, so that [0,6] splits at 2, not 3. */ midpoint &= -2; // (0xfffffffe) clears low bit so midpoint is even } return midpoint; } } }
apache-2.0
GlenRSmith/elasticsearch
libs/x-content/src/main/java/org/elasticsearch/xcontent/ObjectParser.java
35948
/* * 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.xcontent; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.RestApiVersion; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import static java.util.Objects.requireNonNull; import static org.elasticsearch.xcontent.XContentParser.Token.START_ARRAY; import static org.elasticsearch.xcontent.XContentParser.Token.START_OBJECT; import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_BOOLEAN; import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_EMBEDDED_OBJECT; import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_NULL; import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_NUMBER; import static org.elasticsearch.xcontent.XContentParser.Token.VALUE_STRING; /** * A declarative, stateless parser that turns XContent into setter calls. A single parser should be defined for each object being parsed, * nested elements can be added via {@link #declareObject(BiConsumer, ContextParser, ParseField)} which should be satisfied where possible * by passing another instance of {@link ObjectParser}, this one customized for that Object. * <p> * This class works well for object that do have a constructor argument or that can be built using information available from earlier in the * XContent. For objects that have constructors with required arguments that are specified on the same level as other fields see * {@link ConstructingObjectParser}. * </p> * <p> * Instances of {@link ObjectParser} should be setup by declaring a constant field for the parsers and declaring all fields in a static * block just below the creation of the parser. Like this: * </p> * <pre>{@code * private static final ObjectParser<Thing, SomeContext> PARSER = new ObjectParser<>("thing", Thing::new)); * static { * PARSER.declareInt(Thing::setMineral, new ParseField("mineral")); * PARSER.declareInt(Thing::setFruit, new ParseField("fruit")); * } * }</pre> * It's highly recommended to use the high level declare methods like {@link #declareString(BiConsumer, ParseField)} instead of * {@link #declareField} which can be used to implement exceptional parsing operations not covered by the high level methods. */ public final class ObjectParser<Value, Context> extends AbstractObjectParser<Value, Context> implements BiFunction<XContentParser, Context, Value>, ContextParser<Context, Value> { private final List<String[]> requiredFieldSets = new ArrayList<>(); private final List<String[]> exclusiveFieldSets = new ArrayList<>(); /** * Adapts an array (or varags) setter into a list setter. */ public static <Value, ElementValue> BiConsumer<Value, List<ElementValue>> fromList( Class<ElementValue> c, BiConsumer<Value, ElementValue[]> consumer ) { return (Value v, List<ElementValue> l) -> { @SuppressWarnings("unchecked") ElementValue[] array = (ElementValue[]) Array.newInstance(c, l.size()); consumer.accept(v, l.toArray(array)); }; } private interface UnknownFieldParser<Value, Context> { void acceptUnknownField( ObjectParser<Value, Context> objectParser, String field, XContentLocation location, XContentParser parser, Value value, Context context ) throws IOException; } private static <Value, Context> UnknownFieldParser<Value, Context> ignoreUnknown() { return (op, f, l, p, v, c) -> p.skipChildren(); } private static <Value, Context> UnknownFieldParser<Value, Context> errorOnUnknown() { return (op, f, l, p, v, c) -> { throw new XContentParseException( l, ErrorOnUnknown.IMPLEMENTATION.errorMessage( op.name, f, op.fieldParserMap.getOrDefault(p.getRestApiVersion(), Collections.emptyMap()).keySet() ) ); }; } /** * Defines how to consume a parsed undefined field */ public interface UnknownFieldConsumer<Value> { void accept(Value target, String field, Object value); } private static <Value, Context> UnknownFieldParser<Value, Context> consumeUnknownField(UnknownFieldConsumer<Value> consumer) { return (objectParser, field, location, parser, value, context) -> { XContentParser.Token t = parser.currentToken(); switch (t) { case VALUE_STRING: consumer.accept(value, field, parser.text()); break; case VALUE_NUMBER: consumer.accept(value, field, parser.numberValue()); break; case VALUE_BOOLEAN: consumer.accept(value, field, parser.booleanValue()); break; case VALUE_NULL: consumer.accept(value, field, null); break; case START_OBJECT: consumer.accept(value, field, parser.map()); break; case START_ARRAY: consumer.accept(value, field, parser.list()); break; default: throw new XContentParseException( parser.getTokenLocation(), "[" + objectParser.name + "] cannot parse field [" + field + "] with value type [" + t + "]" ); } }; } private static <Value, Category, Context> UnknownFieldParser<Value, Context> unknownIsNamedXContent( Class<Category> categoryClass, BiConsumer<Value, ? super Category> consumer ) { return (objectParser, field, location, parser, value, context) -> { Category o; try { o = parser.namedObject(categoryClass, field, context); } catch (NamedObjectNotFoundException e) { Set<String> candidates = new HashSet<>( objectParser.fieldParserMap.getOrDefault(parser.getRestApiVersion(), Collections.emptyMap()).keySet() ); e.getCandidates().forEach(candidates::add); String message = ErrorOnUnknown.IMPLEMENTATION.errorMessage(objectParser.name, field, candidates); throw new XContentParseException(location, message, e); } consumer.accept(value, o); }; } private final Map<RestApiVersion, Map<String, FieldParser>> fieldParserMap = new HashMap<>(); private final String name; private final Function<Context, Value> valueBuilder; private final UnknownFieldParser<Value, Context> unknownFieldParser; /** * Creates a new ObjectParser. * @param name the parsers name, used to reference the parser in exceptions and messages. */ public ObjectParser(String name) { this(name, errorOnUnknown(), null); } /** * Creates a new ObjectParser. * @param name the parsers name, used to reference the parser in exceptions and messages. * @param valueSupplier A supplier that creates a new Value instance. Used when the parser is used as an inner object parser. */ public ObjectParser(String name, @Nullable Supplier<Value> valueSupplier) { this(name, errorOnUnknown(), wrapValueSupplier(valueSupplier)); } /** * Creates a new ObjectParser. * @param name the parsers name, used to reference the parser in exceptions and messages. * @param valueBuilder A function that creates a new Value from the parse Context. Used * when the parser is used as an inner object parser. */ public static <Value, Context> ObjectParser<Value, Context> fromBuilder(String name, Function<Context, Value> valueBuilder) { requireNonNull(valueBuilder, "Use the single argument ctor instead"); return new ObjectParser<Value, Context>(name, errorOnUnknown(), valueBuilder); } /** * Creates a new ObjectParser. * @param name the parsers name, used to reference the parser in exceptions and messages. * @param ignoreUnknownFields Should this parser ignore unknown fields? This should generally be set to true only when parsing * responses from external systems, never when parsing requests from users. * @param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser. */ public ObjectParser(String name, boolean ignoreUnknownFields, @Nullable Supplier<Value> valueSupplier) { this(name, ignoreUnknownFields ? ignoreUnknown() : errorOnUnknown(), wrapValueSupplier(valueSupplier)); } private static <C, V> Function<C, V> wrapValueSupplier(@Nullable Supplier<V> valueSupplier) { return valueSupplier == null ? c -> { throw new NullPointerException(); } : c -> valueSupplier.get(); } /** * Creates a new ObjectParser that consumes unknown fields as generic Objects. * @param name the parsers name, used to reference the parser in exceptions and messages. * @param unknownFieldConsumer how to consume parsed unknown fields * @param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser. */ public ObjectParser(String name, UnknownFieldConsumer<Value> unknownFieldConsumer, @Nullable Supplier<Value> valueSupplier) { this(name, consumeUnknownField(unknownFieldConsumer), wrapValueSupplier(valueSupplier)); } /** * Creates a new ObjectParser that attempts to resolve unknown fields as {@link XContentParser#namedObject namedObjects}. * @param <C> the type of named object that unknown fields are expected to be * @param name the parsers name, used to reference the parser in exceptions and messages. * @param categoryClass the type of named object that unknown fields are expected to be * @param unknownFieldConsumer how to consume parsed unknown fields * @param valueSupplier a supplier that creates a new Value instance used when the parser is used as an inner object parser. */ public <C> ObjectParser( String name, Class<C> categoryClass, BiConsumer<Value, C> unknownFieldConsumer, @Nullable Supplier<Value> valueSupplier ) { this(name, unknownIsNamedXContent(categoryClass, unknownFieldConsumer), wrapValueSupplier(valueSupplier)); } /** * Creates a new ObjectParser instance with a name. * @param name the parsers name, used to reference the parser in exceptions and messages. * @param unknownFieldParser how to parse unknown fields * @param valueBuilder builds the value from the context. Used when the ObjectParser is not passed a value. */ private ObjectParser( String name, UnknownFieldParser<Value, Context> unknownFieldParser, @Nullable Function<Context, Value> valueBuilder ) { this.name = name; this.unknownFieldParser = unknownFieldParser; this.valueBuilder = valueBuilder == null ? c -> { throw new NullPointerException("valueBuilder is not set"); } : valueBuilder; } /** * Parses a Value from the given {@link XContentParser} * @param parser the parser to build a value from * @param context context needed for parsing * @return a new value instance drawn from the provided value supplier on {@link #ObjectParser(String, Supplier)} * @throws IOException if an IOException occurs. */ @Override public Value parse(XContentParser parser, Context context) throws IOException { return parse(parser, valueBuilder.apply(context), context); } /** * Parses a Value from the given {@link XContentParser} * @param parser the parser to build a value from * @param value the value to fill from the parser * @param context a context that is passed along to all declared field parsers * @return the parsed value * @throws IOException if an IOException occurs. */ public Value parse(XContentParser parser, Value value, Context context) throws IOException { XContentParser.Token token; if (parser.currentToken() != XContentParser.Token.START_OBJECT) { token = parser.nextToken(); if (token != XContentParser.Token.START_OBJECT) { throwExpectedStartObject(parser, token); } } FieldParser fieldParser = null; String currentFieldName = null; XContentLocation currentPosition = null; final List<String[]> requiredFields = this.requiredFieldSets.isEmpty() ? null : new ArrayList<>(this.requiredFieldSets); final List<List<String>> exclusiveFields; if (exclusiveFieldSets.isEmpty()) { exclusiveFields = null; } else { exclusiveFields = new ArrayList<>(); for (int i = 0; i < this.exclusiveFieldSets.size(); i++) { exclusiveFields.add(new ArrayList<>()); } } final Map<String, FieldParser> parsers = fieldParserMap.getOrDefault(parser.getRestApiVersion(), Collections.emptyMap()); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); currentPosition = parser.getTokenLocation(); fieldParser = parsers.get(currentFieldName); } else { if (currentFieldName == null) { throwNoFieldFound(parser); } if (fieldParser == null) { unknownFieldParser.acceptUnknownField(this, currentFieldName, currentPosition, parser, value, context); } else { fieldParser.assertSupports(name, parser, currentFieldName); if (requiredFields != null) { // Check to see if this field is a required field, if it is we can // remove the entry as the requirement is satisfied maybeMarkRequiredField(currentFieldName, requiredFields); } if (exclusiveFields != null) { // Check if this field is in an exclusive set, if it is then mark // it as seen. maybeMarkExclusiveField(currentFieldName, exclusiveFields); } parseSub(parser, fieldParser, currentFieldName, value, context); } fieldParser = null; } } // Check for a) multiple entries appearing in exclusive field sets and b) empty required field entries if (exclusiveFields != null) { ensureExclusiveFields(exclusiveFields); } if (requiredFields != null && requiredFields.isEmpty() == false) { throwMissingRequiredFields(requiredFields); } return value; } private void throwExpectedStartObject(XContentParser parser, XContentParser.Token token) { throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] Expected START_OBJECT but was: " + token); } private void throwNoFieldFound(XContentParser parser) { throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] no field found"); } private void throwMissingRequiredFields(List<String[]> requiredFields) { final StringBuilder message = new StringBuilder(); for (String[] fields : requiredFields) { message.append("Required one of fields ").append(Arrays.toString(fields)).append(", but none were specified. "); } throw new IllegalArgumentException(message.toString()); } private void ensureExclusiveFields(List<List<String>> exclusiveFields) { StringBuilder message = null; for (List<String> fieldset : exclusiveFields) { if (fieldset.size() > 1) { if (message == null) { message = new StringBuilder(); } message.append("The following fields are not allowed together: ").append(fieldset).append(" "); } } if (message != null && message.length() > 0) { throw new IllegalArgumentException(message.toString()); } } private void maybeMarkExclusiveField(String currentFieldName, List<List<String>> exclusiveFields) { for (int i = 0; i < this.exclusiveFieldSets.size(); i++) { for (String field : this.exclusiveFieldSets.get(i)) { if (field.equals(currentFieldName)) { exclusiveFields.get(i).add(currentFieldName); } } } } private void maybeMarkRequiredField(String currentFieldName, List<String[]> requiredFields) { Iterator<String[]> iter = requiredFields.iterator(); while (iter.hasNext()) { String[] requiredFieldNames = iter.next(); for (String field : requiredFieldNames) { if (field.equals(currentFieldName)) { iter.remove(); break; } } } } @Override public Value apply(XContentParser parser, Context context) { try { return parse(parser, context); } catch (IOException e) { throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] failed to parse object", e); } } public interface Parser<Value, Context> { void parse(XContentParser parser, Value value, Context context) throws IOException; } public void declareField(Parser<Value, Context> p, ParseField parseField, ValueType type) { if (parseField == null) { throw new IllegalArgumentException("[parseField] is required"); } if (type == null) { throw new IllegalArgumentException("[type] is required"); } FieldParser fieldParser = new FieldParser(p, type.supportedTokens(), parseField, type); for (String fieldValue : parseField.getAllNamesIncludedDeprecated()) { if (RestApiVersion.minimumSupported().matches(parseField.getForRestApiVersion())) { Map<String, FieldParser> nameToParserMap = fieldParserMap.computeIfAbsent( RestApiVersion.minimumSupported(), (v) -> new HashMap<>() ); FieldParser previousValue = nameToParserMap.putIfAbsent(fieldValue, fieldParser); if (previousValue != null) { throw new IllegalArgumentException("Parser already registered for name=[" + fieldValue + "]. " + previousValue); } } if (RestApiVersion.current().matches(parseField.getForRestApiVersion())) { Map<String, FieldParser> nameToParserMap = fieldParserMap.computeIfAbsent(RestApiVersion.current(), (v) -> new HashMap<>()); FieldParser previousValue = nameToParserMap.putIfAbsent(fieldValue, fieldParser); if (previousValue != null) { throw new IllegalArgumentException("Parser already registered for name=[" + fieldValue + "]. " + previousValue); } } } } @Override public <T> void declareField(BiConsumer<Value, T> consumer, ContextParser<Context, T> parser, ParseField parseField, ValueType type) { if (consumer == null) { throw new IllegalArgumentException("[consumer] is required"); } if (parser == null) { throw new IllegalArgumentException("[parser] is required"); } declareField((p, v, c) -> consumer.accept(v, parser.parse(p, c)), parseField, type); } public <T> void declareObjectOrDefault( BiConsumer<Value, T> consumer, BiFunction<XContentParser, Context, T> objectParser, Supplier<T> defaultValue, ParseField field ) { declareField((p, v, c) -> { if (p.currentToken() == XContentParser.Token.VALUE_BOOLEAN) { if (p.booleanValue()) { consumer.accept(v, defaultValue.get()); } } else { consumer.accept(v, objectParser.apply(p, c)); } }, field, ValueType.OBJECT_OR_BOOLEAN); } @Override public <T> void declareNamedObject(BiConsumer<Value, T> consumer, NamedObjectParser<T, Context> namedObjectParser, ParseField field) { BiFunction<XContentParser, Context, T> objectParser = (XContentParser p, Context c) -> { try { XContentParser.Token token = p.nextToken(); assert token == XContentParser.Token.FIELD_NAME; String currentName = p.currentName(); try { T namedObject = namedObjectParser.parse(p, c, currentName); // consume the end object token token = p.nextToken(); assert token == XContentParser.Token.END_OBJECT; return namedObject; } catch (Exception e) { throw rethrowFieldParseFailure(field, p, currentName, e); } } catch (IOException e) { throw wrapParseError(field, p, e, "error while parsing named object"); } }; declareField((XContentParser p, Value v, Context c) -> consumer.accept(v, objectParser.apply(p, c)), field, ValueType.OBJECT); } @Override public <T> void declareNamedObjects( BiConsumer<Value, List<T>> consumer, NamedObjectParser<T, Context> namedObjectParser, Consumer<Value> orderedModeCallback, ParseField field ) { // This creates and parses the named object BiFunction<XContentParser, Context, T> objectParser = (XContentParser p, Context c) -> { if (p.currentToken() != XContentParser.Token.FIELD_NAME) { throw wrapCanBeObjectOrArrayOfObjects(field, p); } // This messy exception nesting has the nice side effect of telling the user which field failed to parse try { String currentName = p.currentName(); try { return namedObjectParser.parse(p, c, currentName); } catch (Exception e) { throw rethrowFieldParseFailure(field, p, currentName, e); } } catch (IOException e) { throw wrapParseError(field, p, e, "error while parsing"); } }; declareField((XContentParser p, Value v, Context c) -> { List<T> fields = new ArrayList<>(); if (p.currentToken() == XContentParser.Token.START_OBJECT) { // Fields are just named entries in a single object while (p.nextToken() != XContentParser.Token.END_OBJECT) { fields.add(objectParser.apply(p, c)); } } else if (p.currentToken() == XContentParser.Token.START_ARRAY) { // Fields are objects in an array. Each object contains a named field. parseObjectsInArray(orderedModeCallback, field, objectParser, p, v, c, fields); } consumer.accept(v, fields); }, field, ValueType.OBJECT_ARRAY); } private <T> void parseObjectsInArray( Consumer<Value> orderedModeCallback, ParseField field, BiFunction<XContentParser, Context, T> objectParser, XContentParser p, Value v, Context c, List<T> fields ) throws IOException { orderedModeCallback.accept(v); XContentParser.Token token; while ((token = p.nextToken()) != XContentParser.Token.END_ARRAY) { if (token != XContentParser.Token.START_OBJECT) { throw wrapCanBeObjectOrArrayOfObjects(field, p); } p.nextToken(); // Move to the first field in the object fields.add(objectParser.apply(p, c)); p.nextToken(); // Move past the object, should be back to into the array if (p.currentToken() != XContentParser.Token.END_OBJECT) { throw wrapCanBeObjectOrArrayOfObjects(field, p); } } } private XContentParseException wrapCanBeObjectOrArrayOfObjects(ParseField field, XContentParser p) { return new XContentParseException( p.getTokenLocation(), "[" + field + "] can be a single object with any number of " + "fields or an array where each entry is an object with a single field" ); } private XContentParseException wrapParseError(ParseField field, XContentParser p, IOException e, String s) { return new XContentParseException(p.getTokenLocation(), "[" + field + "] " + s, e); } private XContentParseException rethrowFieldParseFailure(ParseField field, XContentParser p, String currentName, Exception e) { return new XContentParseException(p.getTokenLocation(), "[" + field + "] failed to parse field [" + currentName + "]", e); } @Override public <T> void declareNamedObjects( BiConsumer<Value, List<T>> consumer, NamedObjectParser<T, Context> namedObjectParser, ParseField field ) { Consumer<Value> orderedModeCallback = (v) -> { throw new IllegalArgumentException("[" + field + "] doesn't support arrays. Use a single object with multiple fields."); }; declareNamedObjects(consumer, namedObjectParser, orderedModeCallback, field); } /** * Functional interface for instantiating and parsing named objects. See ObjectParserTests#NamedObject for the canonical way to * implement this for objects that themselves have a parser. */ @FunctionalInterface public interface NamedObjectParser<T, Context> { T parse(XContentParser p, Context c, String name) throws IOException; } /** * Get the name of the parser. */ @Override public String getName() { return name; } @Override public void declareRequiredFieldSet(String... requiredSet) { if (requiredSet.length == 0) { return; } this.requiredFieldSets.add(requiredSet); } @Override public void declareExclusiveFieldSet(String... exclusiveSet) { if (exclusiveSet.length == 0) { return; } this.exclusiveFieldSets.add(exclusiveSet); } private void parseArray(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) { assert parser.currentToken() == XContentParser.Token.START_ARRAY : "Token was: " + parser.currentToken(); parseValue(parser, fieldParser, currentFieldName, value, context); } private void parseValue(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) { try { fieldParser.parser.parse(parser, value, context); } catch (Exception ex) { throwFailedToParse(parser, currentFieldName, ex); } } private void throwFailedToParse(XContentParser parser, String currentFieldName, Exception ex) { throw new XContentParseException(parser.getTokenLocation(), "[" + name + "] failed to parse field [" + currentFieldName + "]", ex); } private void parseSub(XContentParser parser, FieldParser fieldParser, String currentFieldName, Value value, Context context) { final XContentParser.Token token = parser.currentToken(); switch (token) { case START_OBJECT: parseValue(parser, fieldParser, currentFieldName, value, context); /* * Well behaving parsers should consume the entire object but * asserting that they do that is not something we can do * efficiently here. Instead we can check that they end on an * END_OBJECT. They could end on the *wrong* end object and * this test won't catch them, but that is the price that we pay * for having a cheap test. */ if (parser.currentToken() != XContentParser.Token.END_OBJECT) { throwMustEndOn(currentFieldName, XContentParser.Token.END_OBJECT); } break; case START_ARRAY: parseArray(parser, fieldParser, currentFieldName, value, context); /* * Well behaving parsers should consume the entire array but * asserting that they do that is not something we can do * efficiently here. Instead we can check that they end on an * END_ARRAY. They could end on the *wrong* end array and * this test won't catch them, but that is the price that we pay * for having a cheap test. */ if (parser.currentToken() != XContentParser.Token.END_ARRAY) { throwMustEndOn(currentFieldName, XContentParser.Token.END_ARRAY); } break; case END_OBJECT: case END_ARRAY: case FIELD_NAME: throw throwUnexpectedToken(parser, token); case VALUE_STRING: case VALUE_NUMBER: case VALUE_BOOLEAN: case VALUE_EMBEDDED_OBJECT: case VALUE_NULL: parseValue(parser, fieldParser, currentFieldName, value, context); } } private void throwMustEndOn(String currentFieldName, XContentParser.Token token) { throw new IllegalStateException("parser for [" + currentFieldName + "] did not end on " + token); } private XContentParseException throwUnexpectedToken(XContentParser parser, XContentParser.Token token) { return new XContentParseException(parser.getTokenLocation(), "[" + name + "]" + token + " is unexpected"); } private class FieldParser { private final Parser<Value, Context> parser; private final EnumSet<XContentParser.Token> supportedTokens; private final ParseField parseField; private final ValueType type; FieldParser(Parser<Value, Context> parser, EnumSet<XContentParser.Token> supportedTokens, ParseField parseField, ValueType type) { this.parser = parser; this.supportedTokens = supportedTokens; this.parseField = parseField; this.type = type; } void assertSupports(String parserName, XContentParser xContentParser, String currentFieldName) { boolean match = parseField.match( parserName, xContentParser::getTokenLocation, currentFieldName, xContentParser.getDeprecationHandler() ); if (match == false) { throw new XContentParseException( xContentParser.getTokenLocation(), "[" + parserName + "] parsefield doesn't accept: " + currentFieldName ); } if (supportedTokens.contains(xContentParser.currentToken()) == false) { throw new XContentParseException( xContentParser.getTokenLocation(), "[" + parserName + "] " + currentFieldName + " doesn't support values of type: " + xContentParser.currentToken() ); } } @Override public String toString() { String[] deprecatedNames = parseField.getDeprecatedNames(); String allReplacedWith = parseField.getAllReplacedWith(); String deprecated = ""; if (deprecatedNames != null && deprecatedNames.length > 0) { deprecated = ", deprecated_names=" + Arrays.toString(deprecatedNames); } return "FieldParser{" + "preferred_name=" + parseField.getPreferredName() + ", supportedTokens=" + supportedTokens + deprecated + (allReplacedWith == null ? "" : ", replaced_with=" + allReplacedWith) + ", type=" + type.name() + '}'; } } public enum ValueType { STRING(VALUE_STRING), STRING_OR_NULL(VALUE_STRING, VALUE_NULL), FLOAT(VALUE_NUMBER, VALUE_STRING), FLOAT_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL), DOUBLE(VALUE_NUMBER, VALUE_STRING), DOUBLE_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL), LONG(VALUE_NUMBER, VALUE_STRING), LONG_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL), INT(VALUE_NUMBER, VALUE_STRING), INT_OR_NULL(VALUE_NUMBER, VALUE_STRING, VALUE_NULL), BOOLEAN(VALUE_BOOLEAN, VALUE_STRING), BOOLEAN_OR_NULL(VALUE_BOOLEAN, VALUE_STRING, VALUE_NULL), STRING_ARRAY(START_ARRAY, VALUE_STRING), FLOAT_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING), DOUBLE_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING), LONG_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING), INT_ARRAY(START_ARRAY, VALUE_NUMBER, VALUE_STRING), BOOLEAN_ARRAY(START_ARRAY, VALUE_BOOLEAN), OBJECT(START_OBJECT), OBJECT_OR_NULL(START_OBJECT, VALUE_NULL), OBJECT_ARRAY(START_OBJECT, START_ARRAY), OBJECT_ARRAY_OR_NULL(START_OBJECT, START_ARRAY, VALUE_NULL), OBJECT_OR_BOOLEAN(START_OBJECT, VALUE_BOOLEAN), OBJECT_OR_STRING(START_OBJECT, VALUE_STRING), OBJECT_OR_LONG(START_OBJECT, VALUE_NUMBER), OBJECT_ARRAY_BOOLEAN_OR_STRING(START_OBJECT, START_ARRAY, VALUE_BOOLEAN, VALUE_STRING), OBJECT_ARRAY_OR_STRING(START_OBJECT, START_ARRAY, VALUE_STRING), OBJECT_ARRAY_STRING_OR_NUMBER(START_OBJECT, START_ARRAY, VALUE_STRING, VALUE_NUMBER), VALUE(VALUE_BOOLEAN, VALUE_NULL, VALUE_EMBEDDED_OBJECT, VALUE_NUMBER, VALUE_STRING), VALUE_OBJECT_ARRAY(VALUE_BOOLEAN, VALUE_NULL, VALUE_EMBEDDED_OBJECT, VALUE_NUMBER, VALUE_STRING, START_OBJECT, START_ARRAY), VALUE_ARRAY(VALUE_BOOLEAN, VALUE_NULL, VALUE_NUMBER, VALUE_STRING, START_ARRAY); private final EnumSet<XContentParser.Token> tokens; ValueType(XContentParser.Token first, XContentParser.Token... rest) { this.tokens = EnumSet.of(first, rest); } public EnumSet<XContentParser.Token> supportedTokens() { return this.tokens; } } @Override public String toString() { return "ObjectParser{" + "name='" + name + '\'' + ", fields=" + fieldParserMap + '}'; } }
apache-2.0
apratkin/pentaho-kettle
engine/test-src/org/pentaho/di/trans/steps/loadsave/setter/MethodSetter.java
468
package org.pentaho.di.trans.steps.loadsave.setter; import java.lang.reflect.Method; public class MethodSetter<T> implements Setter<T> { private final Method method; public MethodSetter( Method method ) { this.method = method; } @Override public void set( Object obj, T value ) { try { method.invoke( obj, value ); } catch ( Exception e ) { throw new RuntimeException( "Error invoking " + method + " on " + obj, e ); } } }
apache-2.0
brettwooldridge/btm
btm/src/main/java/bitronix/tm/resource/jdbc/proxy/JdbcCglibProxyFactory.java
11137
/* * Copyright (C) 2006-2013 Bitronix Software (http://www.bitronix.be) * * 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 bitronix.tm.resource.jdbc.proxy; import bitronix.tm.resource.jdbc.JdbcPooledConnection; import bitronix.tm.resource.jdbc.LruStatementCache.CacheKey; import bitronix.tm.resource.jdbc.PooledConnectionProxy; import bitronix.tm.resource.jdbc.lrc.LrcXAResource; import bitronix.tm.utils.ClassLoaderUtils; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.CallbackFilter; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.Factory; import net.sf.cglib.proxy.LazyLoader; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import javax.sql.XAConnection; import java.lang.reflect.Method; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Map; import java.util.Set; /** * This class generates JDBC proxy classes using CGLIB bytecode generated * implementations. This factory's proxies are more efficient than JdbcJavaProxyFactory * but less efficient than JdbcJavassistProxyFactory. * * @author Brett Wooldridge */ public class JdbcCglibProxyFactory implements JdbcProxyFactory { private final Class<Connection> proxyConnectionClass; private final Class<Statement> proxyStatementClass; private final Class<CallableStatement> proxyCallableStatementClass; private final Class<PreparedStatement> proxyPreparedStatementClass; private final Class<ResultSet> proxyResultSetClass; // For LRC we just use the standard Java Proxies private final JdbcJavaProxyFactory lrcProxyFactory; JdbcCglibProxyFactory() { proxyConnectionClass = createProxyConnectionClass(); proxyStatementClass = createProxyStatementClass(); proxyCallableStatementClass = createProxyCallableStatementClass(); proxyPreparedStatementClass = createProxyPreparedStatementClass(); proxyResultSetClass = createProxyResultSetClass(); lrcProxyFactory = new JdbcJavaProxyFactory(); } /** {@inheritDoc} */ @Override public Connection getProxyConnection(JdbcPooledConnection jdbcPooledConnection, Connection connection) { ConnectionJavaProxy methodInterceptor = new ConnectionJavaProxy(jdbcPooledConnection, connection); Interceptor interceptor = new Interceptor(methodInterceptor); FastDispatcher fastDispatcher = new FastDispatcher(connection); try { Connection connectionCglibProxy = proxyConnectionClass.newInstance(); ((Factory) connectionCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor }); return connectionCglibProxy; } catch (Exception e) { throw new RuntimeException(e); } } /** {@inheritDoc} */ @Override public Statement getProxyStatement(JdbcPooledConnection jdbcPooledConnection, Statement statement) { StatementJavaProxy methodInterceptor = new StatementJavaProxy(jdbcPooledConnection, statement); Interceptor interceptor = new Interceptor(methodInterceptor); FastDispatcher fastDispatcher = new FastDispatcher(statement); try { Statement statementCglibProxy = proxyStatementClass.newInstance(); ((Factory) statementCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor }); return statementCglibProxy; } catch (Exception e) { throw new RuntimeException(e); } } /** {@inheritDoc} */ @Override public CallableStatement getProxyCallableStatement(JdbcPooledConnection jdbcPooledConnection, CallableStatement statement) { CallableStatementJavaProxy methodInterceptor = new CallableStatementJavaProxy(jdbcPooledConnection, statement); Interceptor interceptor = new Interceptor(methodInterceptor); FastDispatcher fastDispatcher = new FastDispatcher(statement); try { CallableStatement statementCglibProxy = proxyCallableStatementClass.newInstance(); ((Factory) statementCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor }); return statementCglibProxy; } catch (Exception e) { throw new RuntimeException(e); } } /** {@inheritDoc} */ @Override public PreparedStatement getProxyPreparedStatement(JdbcPooledConnection jdbcPooledConnection, PreparedStatement statement, CacheKey cacheKey) { PreparedStatementJavaProxy methodInterceptor = new PreparedStatementJavaProxy(jdbcPooledConnection, statement, cacheKey); Interceptor interceptor = new Interceptor(methodInterceptor); FastDispatcher fastDispatcher = new FastDispatcher(statement); try { PreparedStatement statementCglibProxy = proxyPreparedStatementClass.newInstance(); ((Factory) statementCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor }); return statementCglibProxy; } catch (Exception e) { throw new RuntimeException(e); } } /** {@inheritDoc} */ @Override public ResultSet getProxyResultSet(Statement statement, ResultSet resultSet) { ResultSetJavaProxy methodInterceptor = new ResultSetJavaProxy(statement, resultSet); Interceptor interceptor = new Interceptor(methodInterceptor); FastDispatcher fastDispatcher = new FastDispatcher(resultSet); try { ResultSet resultSetCglibProxy = proxyResultSetClass.newInstance(); ((Factory) resultSetCglibProxy).setCallbacks(new Callback[] { fastDispatcher, interceptor }); return resultSetCglibProxy; } catch (Exception e) { throw new RuntimeException(e); } } /** {@inheritDoc} */ @Override public XAConnection getProxyXaConnection(Connection connection) { return lrcProxyFactory.getProxyXaConnection(connection); } /** {@inheritDoc} */ @Override public Connection getProxyConnection(LrcXAResource xaResource, Connection connection) { return lrcProxyFactory.getProxyConnection(xaResource, connection); } // --------------------------------------------------------------- // Generate CGLIB Proxy Classes // --------------------------------------------------------------- @SuppressWarnings("unchecked") private Class<Connection> createProxyConnectionClass() { Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(Connection.class); interfaces.add(PooledConnectionProxy.class); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(interfaces.toArray(new Class<?>[0])); enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} ); enhancer.setCallbackFilter(new InterceptorFilter(new ConnectionJavaProxy())); return enhancer.createClass(); } @SuppressWarnings("unchecked") private Class<PreparedStatement> createProxyPreparedStatementClass() { Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(PreparedStatement.class); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(interfaces.toArray(new Class<?>[0])); enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} ); enhancer.setCallbackFilter(new InterceptorFilter(new PreparedStatementJavaProxy())); return enhancer.createClass(); } @SuppressWarnings("unchecked") private Class<Statement> createProxyStatementClass() { Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(Statement.class); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(interfaces.toArray(new Class<?>[0])); enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} ); enhancer.setCallbackFilter(new InterceptorFilter(new StatementJavaProxy())); return enhancer.createClass(); } @SuppressWarnings("unchecked") private Class<CallableStatement> createProxyCallableStatementClass() { Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(CallableStatement.class); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(interfaces.toArray(new Class<?>[0])); enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} ); enhancer.setCallbackFilter(new InterceptorFilter(new CallableStatementJavaProxy())); return enhancer.createClass(); } @SuppressWarnings("unchecked") private Class<ResultSet> createProxyResultSetClass() { Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(ResultSet.class); Enhancer enhancer = new Enhancer(); enhancer.setInterfaces(interfaces.toArray(new Class<?>[0])); enhancer.setCallbackTypes(new Class[] {FastDispatcher.class, Interceptor.class} ); enhancer.setCallbackFilter(new InterceptorFilter(new ResultSetJavaProxy())); return enhancer.createClass(); } // --------------------------------------------------------------- // CGLIB Classes // --------------------------------------------------------------- static class FastDispatcher implements LazyLoader { private final Object delegate; public FastDispatcher(Object delegate) { this.delegate = delegate; } @Override public Object loadObject() throws Exception { return delegate; } } static class Interceptor implements MethodInterceptor { private final JavaProxyBase<?> interceptor; public Interceptor(JavaProxyBase<?> interceptor) { this.interceptor = interceptor; } @Override public Object intercept(Object enhanced, Method method, Object[] args, MethodProxy fastProxy) throws Throwable { interceptor.proxy = enhanced; return interceptor.invoke(interceptor, method, args); } } static class InterceptorFilter implements CallbackFilter { private final Map<String, Method> methodMap; public InterceptorFilter(JavaProxyBase<?> proxyClass) { methodMap = proxyClass.getMethodMap(); } @Override public int accept(Method method) { if (methodMap.containsKey(JavaProxyBase.getMethodKey(method))) { // Use the Interceptor return 1; } // Use the FastDispatcher return 0; } } }
apache-2.0
kevin3061/cas-4.0.1
cas-server-core/src/main/java/org/jasig/cas/util/AopUtils.java
1525
/* * Licensed to Jasig under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Jasig 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 the following location: * * 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.jasig.cas.util; import org.aspectj.lang.JoinPoint; /** * Utility class to assist with AOP operations. * * @author Marvin S. Addison * @since 3.4 * */ public final class AopUtils { private AopUtils() {} /** * Unwraps a join point that may be nested due to layered proxies. * * @param point Join point to unwrap. * @return Innermost join point; if not nested, simply returns the argument. */ public static JoinPoint unWrapJoinPoint(final JoinPoint point) { JoinPoint naked = point; while (naked.getArgs().length > 0 && naked.getArgs()[0] instanceof JoinPoint) { naked = (JoinPoint) naked.getArgs()[0]; } return naked; } }
apache-2.0
sn00py2/SimpleXMLLegacy
src/org/simpleframework/xml/stream/OutputBuffer.java
5031
/* * OutputBuffer.java June 2007 * * Copyright (C) 2007, Niall Gallagher <niallg@users.sf.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 org.simpleframework.xml.stream; import java.io.IOException; import java.io.Writer; /** * This is primarily used to replace the <code>StringBuffer</code> * class, as a way for the <code>Formatter</code> to store the start * tag for an XML element. This enables the start tag of the current * element to be removed without disrupting any of the other nodes * within the document. Once the contents of the output buffer have * been filled its contents can be emitted to the writer object. * * @author Niall Gallagher */ class OutputBuffer { /** * The characters that this buffer has accumulated. */ private StringBuilder text; /** * Constructor for <code>OutputBuffer</code>. The default * <code>OutputBuffer</code> stores 16 characters before a * resize is needed to append extra characters. */ public OutputBuffer() { this.text = new StringBuilder(); } /** * This will add a <code>char</code> to the end of the buffer. * The buffer will not overflow with repeated uses of the * <code>append</code>, it uses an <code>ensureCapacity</code> * method which will allow the buffer to dynamically grow in * size to accommodate more characters. * * @param ch the character to be appended to the buffer */ public void append(char ch){ text.append(ch); } /** * This will add a <code>String</code> to the end of the buffer. * The buffer will not overflow with repeated uses of the * <code>append</code>, it uses an <code>ensureCapacity</code> * method which will allow the buffer to dynamically grow in * size to accommodate large string objects. * * @param value the string to be appended to this output buffer */ public void append(String value){ text.append(value); } /** * This will add a <code>char</code> array to the buffer. * The buffer will not overflow with repeated uses of the * <code>append</code>, it uses an <code>ensureCapacity</code> * method which will allow the buffer to dynamically grow in * size to accommodate large character arrays. * * @param value the character array to be appended to this */ public void append(char[] value){ text.append(value, 0, value.length); } /** * This will add a <code>char</code> array to the buffer. * The buffer will not overflow with repeated uses of the * <code>append</code>, it uses an <code>ensureCapacity</code> * method which will allow the buffer to dynamically grow in * size to accommodate large character arrays. * * @param value the character array to be appended to this * @param off the read offset for the array to begin reading * @param len the number of characters to append to this */ public void append(char[] value, int off, int len){ text.append(value, off, len); } /** * This will add a <code>String</code> to the end of the buffer. * The buffer will not overflow with repeated uses of the * <code>append</code>, it uses an <code>ensureCapacity</code> * method which will allow the buffer to dynamically grow in * size to accommodate large string objects. * * @param value the string to be appended to the output buffer * @param off the offset to begin reading from the string * @param len the number of characters to append to this */ public void append(String value, int off, int len){ text.append(value, off, len); } /** * This method is used to write the contents of the buffer to the * specified <code>Writer</code> object. This is used when the * XML element is to be committed to the resulting XML document. * * @param out this is the writer to write the buffered text to * * @throws IOException thrown if there is an I/O problem */ public void write(Writer out) throws IOException { out.append(text); } /** * This will empty the <code>OutputBuffer</code> so that it does * not contain any content. This is used to that when the buffer * is written to a specified <code>Writer</code> object nothing * is written out. This allows XML elements to be removed. */ public void clear(){ text.setLength(0); } }
apache-2.0
rokn/Count_Words_2015
testing/openjdk2/nashorn/src/jdk/nashorn/internal/parser/Token.java
4603
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. 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 jdk.nashorn.internal.parser; import static jdk.nashorn.internal.parser.TokenKind.LITERAL; import jdk.nashorn.internal.runtime.Source; /** * Basic parse/lex unit. * */ public class Token { private Token() { } /** * Create a compact form of token information. * @param type Type of token. * @param position Start position of the token in the source. * @param length Length of the token. * @return Token descriptor. */ public static long toDesc(final TokenType type, final int position, final int length) { return (long)position << 32 | (long)length << 8 | type.ordinal(); } /** * Extract token position from a token descriptor. * @param token Token descriptor. * @return Start position of the token in the source. */ public static int descPosition(final long token) { return (int)(token >>> 32); } /** * Extract token length from a token descriptor. * @param token Token descriptor. * @return Length of the token. */ public static int descLength(final long token) { return (int)token >>> 8; } /** * Extract token type from a token descriptor. * @param token Token descriptor. * @return Type of token. */ public static TokenType descType(final long token) { return TokenType.getValues()[(int)token & 0xff]; } /** * Change the token to use a new type. * * @param token The original token. * @param newType The new token type. * @return The recast token. */ public static long recast(final long token, final TokenType newType) { return token & ~0xFFL | newType.ordinal(); } /** * Return a string representation of a token. * @param source Token source. * @param token Token descriptor. * @param verbose True to include details. * @return String representation. */ public static String toString(final Source source, final long token, final boolean verbose) { final TokenType type = Token.descType(token); String result; if (source != null && type.getKind() == LITERAL) { result = source.getString(token); } else { result = type.getNameOrType(); } if (verbose) { final int position = Token.descPosition(token); final int length = Token.descLength(token); result += " (" + position + ", " + length + ")"; } return result; } /** * String conversion of token * * @param source the source * @param token the token * * @return token as string */ public static String toString(final Source source, final long token) { return Token.toString(source, token, false); } /** * String conversion of token - version without source given * * @param token the token * * @return token as string */ public static String toString(final long token) { return Token.toString(null, token, false); } /** * Static hash code computation function token * * @param token a token * * @return hash code for token */ public static int hashCode(final long token) { return (int)(token ^ token >>> 32); } }
mit
AvinashPD/mondrian
src/main/mondrian/olap/Util.java
147689
/* // This software is subject to the terms of the Eclipse Public License v1.0 // Agreement, available at the following URL: // http://www.eclipse.org/legal/epl-v10.html. // You must accept the terms of that agreement to use this software. // // Copyright (C) 2001-2005 Julian Hyde // Copyright (C) 2005-2015 Pentaho and others // All Rights Reserved. */ package mondrian.olap; import mondrian.mdx.*; import mondrian.olap.fun.FunUtil; import mondrian.olap.fun.Resolver; import mondrian.olap.type.Type; import mondrian.resource.MondrianResource; import mondrian.rolap.*; import mondrian.spi.UserDefinedFunction; import mondrian.util.*; import org.apache.commons.collections.keyvalue.AbstractMapEntry; import org.apache.commons.io.IOUtils; import org.apache.commons.vfs2.FileContent; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemManager; import org.apache.commons.vfs2.VFS; import org.apache.commons.vfs2.provider.http.HttpFileObject; import org.apache.log4j.Logger; import org.eigenbase.xom.XOMUtil; import org.olap4j.impl.Olap4jUtil; import org.olap4j.mdx.*; import java.io.*; import java.lang.ref.Reference; import java.lang.reflect.*; import java.lang.reflect.Array; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.sql.Connection; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility functions used throughout mondrian. All methods are static. * * @author jhyde * @since 6 August, 2001 */ public class Util extends XOMUtil { public static final String nl = System.getProperty("line.separator"); private static final Logger LOGGER = Logger.getLogger(Util.class); /** * Placeholder which indicates a value NULL. */ public static final Object nullValue = new Double(FunUtil.DoubleNull); /** * Placeholder which indicates an EMPTY value. */ public static final Object EmptyValue = new Double(FunUtil.DoubleEmpty); /** * Cumulative time spent accessing the database. */ private static long databaseMillis = 0; /** * Random number generator to provide seed for other random number * generators. */ private static final Random metaRandom = createRandom(MondrianProperties.instance().TestSeed.get()); /** Unique id for this JVM instance. Part of a key that ensures that if * two JVMs in the same cluster have a data-source with the same * identity-hash-code, they will be treated as different data-sources, * and therefore caches will not be incorrectly shared. */ public static final UUID JVM_INSTANCE_UUID = UUID.randomUUID(); /** * Whether this is an IBM JVM. */ public static final boolean IBM_JVM = System.getProperties().getProperty("java.vendor").equals( "IBM Corporation"); /** * What version of JDBC? * Returns:<ul> * <li>0x0401 in JDK 1.7 and higher</li> * <li>0x0400 in JDK 1.6</li> * <li>0x0300 otherwise</li> * </ul> */ public static final int JdbcVersion = System.getProperty("java.version").compareTo("1.7") >= 0 ? 0x0401 : System.getProperty("java.version").compareTo("1.6") >= 0 ? 0x0400 : 0x0300; /** * Whether the code base has re-engineered using retroweaver. * If this is the case, some functionality is not available, but a lot of * things are available via {@link mondrian.util.UtilCompatible}. * Retroweaver has some problems involving {@link java.util.EnumSet}. */ public static final boolean Retrowoven = Access.class.getSuperclass().getName().equals( "net.sourceforge.retroweaver.runtime.java.lang.Enum"); private static final UtilCompatible compatible; /** * Flag to control expensive debugging. (More expensive than merely * enabling assertions: as we know, a lot of people run with assertions * enabled.) */ public static final boolean DEBUG = false; static { compatible = new UtilCompatibleJdk16(); } public static boolean isNull(Object o) { return o == null || o == nullValue; } /** * Returns whether a list is strictly sorted. * * @param list List * @return whether list is sorted */ public static <T> boolean isSorted(List<T> list) { T prev = null; for (T t : list) { if (prev != null && ((Comparable<T>) prev).compareTo(t) >= 0) { return false; } prev = t; } return true; } /** * Parses a string and returns a SHA-256 checksum of it. * * @param value The source string to parse. * @return A checksum of the source string. */ public static byte[] digestSha256(String value) { final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return algorithm.digest(value.getBytes()); } /** * Creates an MD5 hash of a String. * * @param value String to create one way hash upon. * @return MD5 hash. */ public static byte[] digestMd5(final String value) { final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return algorithm.digest(value.getBytes()); } /** * Creates an {@link ExecutorService} object backed by a thread pool. * @param maximumPoolSize Maximum number of concurrent * threads. * @param corePoolSize Minimum number of concurrent * threads to maintain in the pool, even if they are * idle. * @param keepAliveTime Time, in seconds, for which to * keep alive unused threads. * @param name The name of the threads. * @param rejectionPolicy The rejection policy to enforce. * @return An executor service preconfigured. */ public static ExecutorService getExecutorService( int maximumPoolSize, int corePoolSize, long keepAliveTime, final String name, RejectedExecutionHandler rejectionPolicy) { // We must create a factory where the threads // have the right name and are marked as daemon threads. final ThreadFactory factory = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(0); public Thread newThread(Runnable r) { final Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); t.setName(name + '_' + counter.incrementAndGet()); return t; } }; // Ok, create the executor final ThreadPoolExecutor executor = new ThreadPoolExecutor( corePoolSize, maximumPoolSize > 0 ? maximumPoolSize : Integer.MAX_VALUE, keepAliveTime, TimeUnit.SECONDS, // we use a sync queue. any other type of queue // will prevent the tasks from running concurrently // because the executors API requires blocking queues. // Important to pass true here. This makes the // order of tasks deterministic. // TODO Write a non-blocking queue which implements // the blocking queue API so we can pass that to the // executor. new LinkedBlockingQueue<Runnable>(), factory); // Set the rejection policy if required. if (rejectionPolicy != null) { executor.setRejectedExecutionHandler( rejectionPolicy); } // Done return executor; } /** * Creates an {@link ScheduledExecutorService} object backed by a * thread pool with a fixed number of threads.. * @param maxNbThreads Maximum number of concurrent * threads. * @param name The name of the threads. * @return An scheduled executor service preconfigured. */ public static ScheduledExecutorService getScheduledExecutorService( final int maxNbThreads, final String name) { return Executors.newScheduledThreadPool( maxNbThreads, new ThreadFactory() { final AtomicInteger counter = new AtomicInteger(0); public Thread newThread(Runnable r) { final Thread thread = Executors.defaultThreadFactory().newThread(r); thread.setDaemon(true); thread.setName(name + '_' + counter.incrementAndGet()); return thread; } } ); } /** * Encodes string for MDX (escapes ] as ]] inside a name). * * @deprecated Will be removed in 4.0 */ public static String mdxEncodeString(String st) { StringBuilder retString = new StringBuilder(st.length() + 20); for (int i = 0; i < st.length(); i++) { char c = st.charAt(i); if ((c == ']') && ((i + 1) < st.length()) && (st.charAt(i + 1) != '.')) { retString.append(']'); // escaping character } retString.append(c); } return retString.toString(); } /** * Converts a string into a double-quoted string. */ public static String quoteForMdx(String val) { StringBuilder buf = new StringBuilder(val.length() + 20); quoteForMdx(buf, val); return buf.toString(); } /** * Appends a double-quoted string to a string builder. */ public static StringBuilder quoteForMdx(StringBuilder buf, String val) { buf.append("\""); String s0 = replace(val, "\"", "\"\""); buf.append(s0); buf.append("\""); return buf; } /** * Return string quoted in [...]. For example, "San Francisco" becomes * "[San Francisco]"; "a [bracketed] string" becomes * "[a [bracketed]] string]". */ public static String quoteMdxIdentifier(String id) { StringBuilder buf = new StringBuilder(id.length() + 20); quoteMdxIdentifier(id, buf); return buf.toString(); } public static void quoteMdxIdentifier(String id, StringBuilder buf) { buf.append('['); int start = buf.length(); buf.append(id); replace(buf, start, "]", "]]"); buf.append(']'); } /** * Return identifiers quoted in [...].[...]. For example, {"Store", "USA", * "California"} becomes "[Store].[USA].[California]". */ public static String quoteMdxIdentifier(List<Id.Segment> ids) { StringBuilder sb = new StringBuilder(64); quoteMdxIdentifier(ids, sb); return sb.toString(); } public static void quoteMdxIdentifier( List<Id.Segment> ids, StringBuilder sb) { for (int i = 0; i < ids.size(); i++) { if (i > 0) { sb.append('.'); } ids.get(i).toString(sb); } } /** * Quotes a string literal for Java or JavaScript. * * @param s Unquoted literal * @return Quoted string literal */ public static String quoteJavaString(String s) { return s == null ? "null" : "\"" + s.replaceAll("\\\\", "\\\\\\\\") .replaceAll("\\\"", "\\\\\"") + "\""; } /** * Returns true if two objects are equal, or are both null. * * @param s First object * @param t Second object * @return Whether objects are equal or both null */ public static boolean equals(Object s, Object t) { if (s == t) { return true; } if (s == null || t == null) { return false; } return s.equals(t); } /** * Returns true if two strings are equal, or are both null. * * <p>The result is not affected by * {@link MondrianProperties#CaseSensitive the case sensitive option}; if * you wish to compare names, use {@link #equalName(String, String)}. */ public static boolean equals(String s, String t) { return equals((Object) s, (Object) t); } /** * Returns whether two names are equal. * Takes into account the * {@link MondrianProperties#CaseSensitive case sensitive option}. * Names may be null. */ public static boolean equalName(String s, String t) { if (s == null) { return t == null; } boolean caseSensitive = MondrianProperties.instance().CaseSensitive.get(); return caseSensitive ? s.equals(t) : s.equalsIgnoreCase(t); } /** * Tests two strings for equality, optionally ignoring case. * * @param s First string * @param t Second string * @param matchCase Whether to perform case-sensitive match * @return Whether strings are equal */ public static boolean equal(String s, String t, boolean matchCase) { return matchCase ? s.equals(t) : s.equalsIgnoreCase(t); } /** * Compares two names. if case sensitive flag is false, * apply finer grain difference with case sensitive * Takes into account the {@link MondrianProperties#CaseSensitive case * sensitive option}. * Names must not be null. */ public static int caseSensitiveCompareName(String s, String t) { boolean caseSensitive = MondrianProperties.instance().CaseSensitive.get(); if (caseSensitive) { return s.compareTo(t); } else { int v = s.compareToIgnoreCase(t); // if ignore case returns 0 compare in a case sensitive manner // this was introduced to solve an issue with Member.equals() // and Member.compareTo() not agreeing with each other return v == 0 ? s.compareTo(t) : v; } } /** * Compares two names. * Takes into account the {@link MondrianProperties#CaseSensitive case * sensitive option}. * Names must not be null. */ public static int compareName(String s, String t) { boolean caseSensitive = MondrianProperties.instance().CaseSensitive.get(); return caseSensitive ? s.compareTo(t) : s.compareToIgnoreCase(t); } /** * Generates a normalized form of a name, for use as a key into a map. * Returns the upper case name if * {@link MondrianProperties#CaseSensitive} is true, the name unchanged * otherwise. */ public static String normalizeName(String s) { return MondrianProperties.instance().CaseSensitive.get() ? s : s.toUpperCase(); } /** * Returns the result of ((Comparable) k1).compareTo(k2), with * special-casing for the fact that Boolean only became * comparable in JDK 1.5. * * @see Comparable#compareTo */ public static int compareKey(Object k1, Object k2) { if (k1 instanceof Boolean) { // Luckily, "F" comes before "T" in the alphabet. k1 = k1.toString(); k2 = k2.toString(); } return ((Comparable) k1).compareTo(k2); } /** * Compares integer values. * * @param i0 First integer * @param i1 Second integer * @return Comparison of integers */ public static int compare(int i0, int i1) { return i0 < i1 ? -1 : (i0 == i1 ? 0 : 1); } /** * Returns a string with every occurrence of a seek string replaced with * another. */ public static String replace(String s, String find, String replace) { // let's be optimistic int found = s.indexOf(find); if (found == -1) { return s; } StringBuilder sb = new StringBuilder(s.length() + 20); int start = 0; char[] chars = s.toCharArray(); final int step = find.length(); if (step == 0) { // Special case where find is "". sb.append(s); replace(sb, 0, find, replace); } else { for (;;) { sb.append(chars, start, found - start); if (found == s.length()) { break; } sb.append(replace); start = found + step; found = s.indexOf(find, start); if (found == -1) { found = s.length(); } } } return sb.toString(); } /** * Replaces all occurrences of a string in a buffer with another. * * @param buf String buffer to act on * @param start Ordinal within <code>find</code> to start searching * @param find String to find * @param replace String to replace it with * @return The string buffer */ public static StringBuilder replace( StringBuilder buf, int start, String find, String replace) { // Search and replace from the end towards the start, to avoid O(n ^ 2) // copying if the string occurs very commonly. int findLength = find.length(); if (findLength == 0) { // Special case where the seek string is empty. for (int j = buf.length(); j >= 0; --j) { buf.insert(j, replace); } return buf; } int k = buf.length(); while (k > 0) { int i = buf.lastIndexOf(find, k); if (i < start) { break; } buf.replace(i, i + find.length(), replace); // Step back far enough to ensure that the beginning of the section // we just replaced does not cause a match. k = i - findLength; } return buf; } /** * Parses an MDX identifier such as <code>[Foo].[Bar].Baz.&Key&Key2</code> * and returns the result as a list of segments. * * @param s MDX identifier * @return List of segments */ public static List<Id.Segment> parseIdentifier(String s) { return convert( org.olap4j.impl.IdentifierParser.parseIdentifier(s)); } /** * Converts an array of name parts {"part1", "part2"} into a single string * "[part1].[part2]". If the names contain "]" they are escaped as "]]". */ public static String implode(List<Id.Segment> names) { StringBuilder sb = new StringBuilder(64); for (int i = 0; i < names.size(); i++) { if (i > 0) { sb.append("."); } // FIXME: should be: // names.get(i).toString(sb); // but that causes some tests to fail Id.Segment segment = names.get(i); switch (segment.getQuoting()) { case UNQUOTED: segment = new Id.NameSegment(((Id.NameSegment) segment).name); } segment.toString(sb); } return sb.toString(); } public static String makeFqName(String name) { return quoteMdxIdentifier(name); } public static String makeFqName(OlapElement parent, String name) { if (parent == null) { return Util.quoteMdxIdentifier(name); } else { StringBuilder buf = new StringBuilder(64); buf.append(parent.getUniqueName()); buf.append('.'); Util.quoteMdxIdentifier(name, buf); return buf.toString(); } } public static String makeFqName(String parentUniqueName, String name) { if (parentUniqueName == null) { return quoteMdxIdentifier(name); } else { StringBuilder buf = new StringBuilder(64); buf.append(parentUniqueName); buf.append('.'); Util.quoteMdxIdentifier(name, buf); return buf.toString(); } } public static OlapElement lookupCompound( SchemaReader schemaReader, OlapElement parent, List<Id.Segment> names, boolean failIfNotFound, int category) { return lookupCompound( schemaReader, parent, names, failIfNotFound, category, MatchType.EXACT); } /** * Resolves a name such as * '[Products]&#46;[Product Department]&#46;[Produce]' by resolving the * components ('Products', and so forth) one at a time. * * @param schemaReader Schema reader, supplies access-control context * @param parent Parent element to search in * @param names Exploded compound name, such as {"Products", * "Product Department", "Produce"} * @param failIfNotFound If the element is not found, determines whether * to return null or throw an error * @param category Type of returned element, a {@link Category} value; * {@link Category#Unknown} if it doesn't matter. * * @pre parent != null * @post !(failIfNotFound && return == null) * * @see #parseIdentifier(String) */ public static OlapElement lookupCompound( SchemaReader schemaReader, OlapElement parent, List<Id.Segment> names, boolean failIfNotFound, int category, MatchType matchType) { Util.assertPrecondition(parent != null, "parent != null"); if (LOGGER.isDebugEnabled()) { StringBuilder buf = new StringBuilder(64); buf.append("Util.lookupCompound: "); buf.append("parent.name="); buf.append(parent.getName()); buf.append(", category="); buf.append(Category.instance.getName(category)); buf.append(", names="); quoteMdxIdentifier(names, buf); LOGGER.debug(buf.toString()); } // First look up a member from the cache of calculated members // (cubes and queries both have them). switch (category) { case Category.Member: case Category.Unknown: Member member = schemaReader.getCalculatedMember(names); if (member != null) { return member; } } // Likewise named set. switch (category) { case Category.Set: case Category.Unknown: NamedSet namedSet = schemaReader.getNamedSet(names); if (namedSet != null) { return namedSet; } } // Now resolve the name one part at a time. for (int i = 0; i < names.size(); i++) { OlapElement child; Id.NameSegment name; if (names.get(i) instanceof Id.NameSegment) { name = (Id.NameSegment) names.get(i); child = schemaReader.getElementChild(parent, name, matchType); } else if (parent instanceof RolapLevel && names.get(i) instanceof Id.KeySegment && names.get(i).getKeyParts().size() == 1) { // The following code is for SsasCompatibleNaming=false. // Continues the very limited support for key segments in // mondrian-3.x. To be removed in mondrian-4, when // SsasCompatibleNaming=true is the only option. final Id.KeySegment keySegment = (Id.KeySegment) names.get(i); name = keySegment.getKeyParts().get(0); final List<Member> levelMembers = schemaReader.getLevelMembers( (Level) parent, false); child = null; for (Member member : levelMembers) { if (((RolapMember) member).getKey().toString().equals( name.getName())) { child = member; break; } } } else { name = null; child = schemaReader.getElementChild(parent, name, matchType); } // if we're doing a non-exact match, and we find a non-exact // match, then for an after match, return the first child // of each subsequent level; for a before match, return the // last child if (child instanceof Member && !matchType.isExact() && !Util.equalName(child.getName(), name.getName())) { Member bestChild = (Member) child; for (int j = i + 1; j < names.size(); j++) { List<Member> childrenList = schemaReader.getMemberChildren(bestChild); FunUtil.hierarchizeMemberList(childrenList, false); if (matchType == MatchType.AFTER) { bestChild = childrenList.get(0); } else { bestChild = childrenList.get(childrenList.size() - 1); } if (bestChild == null) { child = null; break; } } parent = bestChild; break; } if (child == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Util.lookupCompound: " + "parent.name=" + parent.getName() + " has no child with name=" + name); } if (!failIfNotFound) { return null; } else if (category == Category.Member) { throw MondrianResource.instance().MemberNotFound.ex( quoteMdxIdentifier(names)); } else { throw MondrianResource.instance().MdxChildObjectNotFound .ex(name.toString(), parent.getQualifiedName()); } } parent = child; if (matchType == MatchType.EXACT_SCHEMA) { matchType = MatchType.EXACT; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Util.lookupCompound: " + "found child.name=" + parent.getName() + ", child.class=" + parent.getClass().getName()); } switch (category) { case Category.Dimension: if (parent instanceof Dimension) { return parent; } else if (parent instanceof Hierarchy) { return parent.getDimension(); } else if (failIfNotFound) { throw Util.newError( "Can not find dimension '" + implode(names) + "'"); } else { return null; } case Category.Hierarchy: if (parent instanceof Hierarchy) { return parent; } else if (parent instanceof Dimension) { return parent.getHierarchy(); } else if (failIfNotFound) { throw Util.newError( "Can not find hierarchy '" + implode(names) + "'"); } else { return null; } case Category.Level: if (parent instanceof Level) { return parent; } else if (failIfNotFound) { throw Util.newError( "Can not find level '" + implode(names) + "'"); } else { return null; } case Category.Member: if (parent instanceof Member) { return parent; } else if (failIfNotFound) { throw MondrianResource.instance().MdxCantFindMember.ex( implode(names)); } else { return null; } case Category.Unknown: assertPostcondition(parent != null, "return != null"); return parent; default: throw newInternal("Bad switch " + category); } } public static OlapElement lookup(Query q, List<Id.Segment> nameParts) { final Exp exp = lookup(q, nameParts, false); if (exp instanceof MemberExpr) { MemberExpr memberExpr = (MemberExpr) exp; return memberExpr.getMember(); } else if (exp instanceof LevelExpr) { LevelExpr levelExpr = (LevelExpr) exp; return levelExpr.getLevel(); } else if (exp instanceof HierarchyExpr) { HierarchyExpr hierarchyExpr = (HierarchyExpr) exp; return hierarchyExpr.getHierarchy(); } else if (exp instanceof DimensionExpr) { DimensionExpr dimensionExpr = (DimensionExpr) exp; return dimensionExpr.getDimension(); } else { throw Util.newInternal("Not an olap element: " + exp); } } /** * Converts an identifier into an expression by resolving its parts into * an OLAP object (dimension, hierarchy, level or member) within the * context of a query. * * <p>If <code>allowProp</code> is true, also allows property references * from valid members, for example * <code>[Measures].[Unit Sales].FORMATTED_VALUE</code>. * In this case, the result will be a {@link mondrian.mdx.ResolvedFunCall}. * * @param q Query expression belongs to * @param nameParts Parts of the identifier * @param allowProp Whether to allow property references * @return OLAP object or property reference */ public static Exp lookup( Query q, List<Id.Segment> nameParts, boolean allowProp) { return lookup(q, q.getSchemaReader(true), nameParts, allowProp); } /** * Converts an identifier into an expression by resolving its parts into * an OLAP object (dimension, hierarchy, level or member) within the * context of a query. * * <p>If <code>allowProp</code> is true, also allows property references * from valid members, for example * <code>[Measures].[Unit Sales].FORMATTED_VALUE</code>. * In this case, the result will be a {@link ResolvedFunCall}. * * @param q Query expression belongs to * @param schemaReader Schema reader * @param segments Parts of the identifier * @param allowProp Whether to allow property references * @return OLAP object or property reference */ public static Exp lookup( Query q, SchemaReader schemaReader, List<Id.Segment> segments, boolean allowProp) { // First, look for a calculated member defined in the query. final String fullName = quoteMdxIdentifier(segments); // Look for any kind of object (member, level, hierarchy, // dimension) in the cube. Use a schema reader without restrictions. final SchemaReader schemaReaderSansAc = schemaReader.withoutAccessControl().withLocus(); final Cube cube = q.getCube(); OlapElement olapElement = schemaReaderSansAc.lookupCompound( cube, segments, false, Category.Unknown); if (olapElement != null) { Role role = schemaReader.getRole(); if (!role.canAccess(olapElement)) { olapElement = null; } if (olapElement instanceof Member) { olapElement = schemaReader.substitute((Member) olapElement); } } if (olapElement == null) { if (allowProp && segments.size() > 1) { List<Id.Segment> segmentsButOne = segments.subList(0, segments.size() - 1); final Id.Segment lastSegment = last(segments); final String propertyName = lastSegment instanceof Id.NameSegment ? ((Id.NameSegment) lastSegment).getName() : null; final Member member = (Member) schemaReaderSansAc.lookupCompound( cube, segmentsButOne, false, Category.Member); if (member != null && propertyName != null && isValidProperty(propertyName, member.getLevel())) { return new UnresolvedFunCall( propertyName, Syntax.Property, new Exp[] { createExpr(member)}); } final Level level = (Level) schemaReaderSansAc.lookupCompound( cube, segmentsButOne, false, Category.Level); if (level != null && propertyName != null && isValidProperty(propertyName, level)) { return new UnresolvedFunCall( propertyName, Syntax.Property, new Exp[] { createExpr(level)}); } } // if we're in the middle of loading the schema, the property has // been set to ignore invalid members, and the member is // non-existent, return the null member corresponding to the // hierarchy of the element we're looking for; locate the // hierarchy by incrementally truncating the name of the element if (q.ignoreInvalidMembers()) { int nameLen = segments.size() - 1; olapElement = null; while (nameLen > 0 && olapElement == null) { List<Id.Segment> partialName = segments.subList(0, nameLen); olapElement = schemaReaderSansAc.lookupCompound( cube, partialName, false, Category.Unknown); nameLen--; } if (olapElement != null) { olapElement = olapElement.getHierarchy().getNullMember(); } else { throw MondrianResource.instance().MdxChildObjectNotFound.ex( fullName, cube.getQualifiedName()); } } else { throw MondrianResource.instance().MdxChildObjectNotFound.ex( fullName, cube.getQualifiedName()); } } // keep track of any measure members referenced; these will be used // later to determine if cross joins on virtual cubes can be // processed natively q.addMeasuresMembers(olapElement); return createExpr(olapElement); } /** * Looks up a cube in a schema reader. * * @param cubeName Cube name * @param fail Whether to fail if not found. * @return Cube, or null if not found */ static Cube lookupCube( SchemaReader schemaReader, String cubeName, boolean fail) { for (Cube cube : schemaReader.getCubes()) { if (Util.compareName(cube.getName(), cubeName) == 0) { return cube; } } if (fail) { throw MondrianResource.instance().MdxCubeNotFound.ex(cubeName); } return null; } /** * Converts an olap element (dimension, hierarchy, level or member) into * an expression representing a usage of that element in an MDX statement. */ public static Exp createExpr(OlapElement element) { if (element instanceof Member) { Member member = (Member) element; return new MemberExpr(member); } else if (element instanceof Level) { Level level = (Level) element; return new LevelExpr(level); } else if (element instanceof Hierarchy) { Hierarchy hierarchy = (Hierarchy) element; return new HierarchyExpr(hierarchy); } else if (element instanceof Dimension) { Dimension dimension = (Dimension) element; return new DimensionExpr(dimension); } else if (element instanceof NamedSet) { NamedSet namedSet = (NamedSet) element; return new NamedSetExpr(namedSet); } else { throw Util.newInternal("Unexpected element type: " + element); } } public static Member lookupHierarchyRootMember( SchemaReader reader, Hierarchy hierarchy, Id.NameSegment memberName) { return lookupHierarchyRootMember( reader, hierarchy, memberName, MatchType.EXACT); } /** * Finds a root member of a hierarchy with a given name. * * @param hierarchy Hierarchy * @param memberName Name of root member * @return Member, or null if not found */ public static Member lookupHierarchyRootMember( SchemaReader reader, Hierarchy hierarchy, Id.NameSegment memberName, MatchType matchType) { // Lookup member at first level. // // Don't use access control. Suppose we cannot see the 'nation' level, // we still want to be able to resolve '[Customer].[USA].[CA]'. List<Member> rootMembers = reader.getHierarchyRootMembers(hierarchy); // if doing an inexact search on a non-all hierarchy, create // a member corresponding to the name we're searching for so // we can use it in a hierarchical search Member searchMember = null; if (!matchType.isExact() && !hierarchy.hasAll() && !rootMembers.isEmpty()) { searchMember = hierarchy.createMember( null, rootMembers.get(0).getLevel(), memberName.name, null); } int bestMatch = -1; int k = -1; for (Member rootMember : rootMembers) { ++k; int rc; // when searching on the ALL hierarchy, match must be exact if (matchType.isExact() || hierarchy.hasAll()) { rc = rootMember.getName().compareToIgnoreCase(memberName.name); } else { rc = FunUtil.compareSiblingMembers( rootMember, searchMember); } if (rc == 0) { return rootMember; } if (!hierarchy.hasAll()) { if (matchType == MatchType.BEFORE) { if (rc < 0 && (bestMatch == -1 || FunUtil.compareSiblingMembers( rootMember, rootMembers.get(bestMatch)) > 0)) { bestMatch = k; } } else if (matchType == MatchType.AFTER) { if (rc > 0 && (bestMatch == -1 || FunUtil.compareSiblingMembers( rootMember, rootMembers.get(bestMatch)) < 0)) { bestMatch = k; } } } } if (matchType == MatchType.EXACT_SCHEMA) { return null; } if (matchType != MatchType.EXACT && bestMatch != -1) { return rootMembers.get(bestMatch); } // If the first level is 'all', lookup member at second level. For // example, they could say '[USA]' instead of '[(All // Customers)].[USA]'. return (rootMembers.size() > 0 && rootMembers.get(0).isAll()) ? reader.lookupMemberChildByName( rootMembers.get(0), memberName, matchType) : null; } /** * Finds a named level in this hierarchy. Returns null if there is no * such level. */ public static Level lookupHierarchyLevel(Hierarchy hierarchy, String s) { final Level[] levels = hierarchy.getLevels(); for (Level level : levels) { if (level.getName().equalsIgnoreCase(s)) { return level; } } return null; } /** * Finds the zero based ordinal of a Member among its siblings. */ public static int getMemberOrdinalInParent( SchemaReader reader, Member member) { Member parent = member.getParentMember(); List<Member> siblings = (parent == null) ? reader.getHierarchyRootMembers(member.getHierarchy()) : reader.getMemberChildren(parent); for (int i = 0; i < siblings.size(); i++) { if (siblings.get(i).equals(member)) { return i; } } throw Util.newInternal( "could not find member " + member + " amongst its siblings"); } /** * returns the first descendant on the level underneath parent. * If parent = [Time].[1997] and level = [Time].[Month], then * the member [Time].[1997].[Q1].[1] will be returned */ public static Member getFirstDescendantOnLevel( SchemaReader reader, Member parent, Level level) { Member m = parent; while (m.getLevel() != level) { List<Member> children = reader.getMemberChildren(m); m = children.get(0); } return m; } /** * Returns whether a string is null or empty. */ public static boolean isEmpty(String s) { return (s == null) || (s.length() == 0); } /** * Encloses a value in single-quotes, to make a SQL string value. Examples: * <code>singleQuoteForSql(null)</code> yields <code>NULL</code>; * <code>singleQuoteForSql("don't")</code> yields <code>'don''t'</code>. */ public static String singleQuoteString(String val) { StringBuilder buf = new StringBuilder(64); singleQuoteString(val, buf); return buf.toString(); } /** * Encloses a value in single-quotes, to make a SQL string value. Examples: * <code>singleQuoteForSql(null)</code> yields <code>NULL</code>; * <code>singleQuoteForSql("don't")</code> yields <code>'don''t'</code>. */ public static void singleQuoteString(String val, StringBuilder buf) { buf.append('\''); String s0 = replace(val, "'", "''"); buf.append(s0); buf.append('\''); } /** * Creates a random number generator. * * @param seed Seed for random number generator. * If 0, generate a seed from the system clock and print the value * chosen. (This is effectively non-deterministic.) * If -1, generate a seed from an internal random number generator. * (This is deterministic, but ensures that different tests have * different seeds.) * * @return A random number generator. */ public static Random createRandom(long seed) { if (seed == 0) { seed = new Random().nextLong(); System.out.println("random: seed=" + seed); } else if (seed == -1 && metaRandom != null) { seed = metaRandom.nextLong(); } return new Random(seed); } /** * Returns whether a property is valid for a member of a given level. * It is valid if the property is defined at the level or at * an ancestor level, or if the property is a standard property such as * "FORMATTED_VALUE". * * @param propertyName Property name * @param level Level * @return Whether property is valid */ public static boolean isValidProperty( String propertyName, Level level) { return lookupProperty(level, propertyName) != null; } /** * Finds a member property called <code>propertyName</code> at, or above, * <code>level</code>. */ public static Property lookupProperty( Level level, String propertyName) { do { Property[] properties = level.getProperties(); for (Property property : properties) { if (property.getName().equals(propertyName)) { return property; } } level = level.getParentLevel(); } while (level != null); // Now try a standard property. boolean caseSensitive = MondrianProperties.instance().CaseSensitive.get(); final Property property = Property.lookup(propertyName, caseSensitive); if (property != null && property.isMemberProperty() && property.isStandard()) { return property; } return null; } /** * Insert a call to this method if you want to flag a piece of * undesirable code. * * @deprecated */ public static <T> T deprecated(T reason) { throw new UnsupportedOperationException(reason.toString()); } /** * Insert a call to this method if you want to flag a piece of * undesirable code. * * @deprecated */ public static <T> T deprecated(T reason, boolean fail) { if (fail) { throw new UnsupportedOperationException(reason.toString()); } else { return reason; } } public static List<Member> addLevelCalculatedMembers( SchemaReader reader, Level level, List<Member> members) { List<Member> calcMembers = reader.getCalculatedMembers(level.getHierarchy()); List<Member> calcMembersInThisLevel = new ArrayList<Member>(); for (Member calcMember : calcMembers) { if (calcMember.getLevel().equals(level)) { calcMembersInThisLevel.add(calcMember); } } if (!calcMembersInThisLevel.isEmpty()) { List<Member> newMemberList = new ConcatenableList<Member>(); newMemberList.addAll(members); newMemberList.addAll(calcMembersInThisLevel); return newMemberList; } return members; } /** * Returns an exception which indicates that a particular piece of * functionality should work, but a developer has not implemented it yet. */ public static RuntimeException needToImplement(Object o) { throw new UnsupportedOperationException("need to implement " + o); } /** * Returns an exception indicating that we didn't expect to find this value * here. */ public static <T extends Enum<T>> RuntimeException badValue( Enum<T> anEnum) { return Util.newInternal( "Was not expecting value '" + anEnum + "' for enumeration '" + anEnum.getDeclaringClass().getName() + "' in this context"); } /** * Converts a list of SQL-style patterns into a Java regular expression. * * <p>For example, {"Foo_", "Bar%BAZ"} becomes "Foo.|Bar.*BAZ". * * @param wildcards List of SQL-style wildcard expressions * @return Regular expression */ public static String wildcardToRegexp(List<String> wildcards) { StringBuilder buf = new StringBuilder(); for (String value : wildcards) { if (buf.length() > 0) { buf.append('|'); } int i = 0; while (true) { int percent = value.indexOf('%', i); int underscore = value.indexOf('_', i); if (percent == -1 && underscore == -1) { if (i < value.length()) { buf.append(quotePattern(value.substring(i))); } break; } if (underscore >= 0 && (underscore < percent || percent < 0)) { if (i < underscore) { buf.append( quotePattern(value.substring(i, underscore))); } buf.append('.'); i = underscore + 1; } else if (percent >= 0 && (percent < underscore || underscore < 0)) { if (i < percent) { buf.append( quotePattern(value.substring(i, percent))); } buf.append(".*"); i = percent + 1; } else { throw new IllegalArgumentException(); } } } return buf.toString(); } /** * Converts a camel-case name to an upper-case name with underscores. * * <p>For example, <code>camelToUpper("FooBar")</code> returns "FOO_BAR". * * @param s Camel-case string * @return Upper-case string */ public static String camelToUpper(String s) { StringBuilder buf = new StringBuilder(s.length() + 10); int prevUpper = -1; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (Character.isUpperCase(c)) { if (i > prevUpper + 1) { buf.append('_'); } prevUpper = i; } else { c = Character.toUpperCase(c); } buf.append(c); } return buf.toString(); } /** * Parses a comma-separated list. * * <p>If a value contains a comma, escape it with a second comma. For * example, <code>parseCommaList("x,y,,z")</code> returns * <code>{"x", "y,z"}</code>. * * @param nameCommaList List of names separated by commas * @return List of names */ public static List<String> parseCommaList(String nameCommaList) { if (nameCommaList.equals("")) { return Collections.emptyList(); } if (nameCommaList.endsWith(",")) { // Special treatment for list ending in ",", because split ignores // entries after separator. final String zzz = "zzz"; final List<String> list = parseCommaList(nameCommaList + zzz); String last = list.get(list.size() - 1); if (last.equals(zzz)) { list.remove(list.size() - 1); } else { list.set( list.size() - 1, last.substring(0, last.length() - zzz.length())); } return list; } List<String> names = new ArrayList<String>(); final String[] strings = nameCommaList.split(","); for (String string : strings) { final int count = names.size(); if (count > 0 && names.get(count - 1).equals("")) { if (count == 1) { if (string.equals("")) { names.add(""); } else { names.set( 0, "," + string); } } else { names.set( count - 2, names.get(count - 2) + "," + string); names.remove(count - 1); } } else { names.add(string); } } return names; } /** * Returns an annotation of a particular class on a method. Returns the * default value if the annotation is not present, or in JDK 1.4. * * @param method Method containing annotation * @param annotationClassName Name of annotation class to find * @param defaultValue Value to return if annotation is not present * @return value of annotation */ public static <T> T getAnnotation( Method method, String annotationClassName, T defaultValue) { return compatible.getAnnotation( method, annotationClassName, defaultValue); } /** * Closes and cancels a {@link Statement} using the correct methods * available on the current Java runtime. * <p>If errors are encountered while canceling a statement, * the message is logged in {@link Util}. * @param stmt The statement to cancel. */ public static void cancelStatement(Statement stmt) { compatible.cancelStatement(stmt); } public static MemoryInfo getMemoryInfo() { return compatible.getMemoryInfo(); } /** * Converts a list of a string. * * For example, * <code>commaList("foo", Arrays.asList({"a", "b"}))</code> * returns "foo(a, b)". * * @param s Prefix * @param list List * @return String representation of string */ public static <T> String commaList( String s, List<T> list) { final StringBuilder buf = new StringBuilder(s); buf.append("("); int k = -1; for (T t : list) { if (++k > 0) { buf.append(", "); } buf.append(t); } buf.append(")"); return buf.toString(); } /** * Makes a name distinct from other names which have already been used * and shorter than a length limit, adds it to the list, and returns it. * * @param name Suggested name, may not be unique * @param maxLength Maximum length of generated name * @param nameList Collection of names already used * * @return Unique name */ public static String uniquify( String name, int maxLength, Collection<String> nameList) { assert name != null; if (name.length() > maxLength) { name = name.substring(0, maxLength); } if (nameList.contains(name)) { String aliasBase = name; int j = 0; while (true) { name = aliasBase + j; if (name.length() > maxLength) { aliasBase = aliasBase.substring(0, aliasBase.length() - 1); continue; } if (!nameList.contains(name)) { break; } j++; } } nameList.add(name); return name; } /** * Returns whether a collection contains precisely one distinct element. * Returns false if the collection is empty, or if it contains elements * that are not the same as each other. * * @param collection Collection * @return boolean true if all values are same */ public static <T> boolean areOccurencesEqual( Collection<T> collection) { Iterator<T> it = collection.iterator(); if (!it.hasNext()) { // Collection is empty return false; } T first = it.next(); while (it.hasNext()) { T t = it.next(); if (!t.equals(first)) { return false; } } return true; } /** * Creates a memory-, CPU- and cache-efficient immutable list. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T> List<T> flatList(T... t) { return _flatList(t, false); } /** * Creates a memory-, CPU- and cache-efficient immutable list, * always copying the contents. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T> List<T> flatListCopy(T... t) { return _flatList(t, true); } /** * Creates a memory-, CPU- and cache-efficient immutable list, optionally * copying the list. * * @param copy Whether to always copy the list * @param t Array of members of list * @return List containing the given members */ private static <T> List<T> _flatList(T[] t, boolean copy) { switch (t.length) { case 0: return Collections.emptyList(); case 1: return Collections.singletonList(t[0]); case 2: return new Flat2List<T>(t[0], t[1]); case 3: return new Flat3List<T>(t[0], t[1], t[2]); default: // REVIEW: AbstractList contains a modCount field; we could // write our own implementation and reduce creation overhead a // bit. if (copy) { return Arrays.asList(t.clone()); } else { return Arrays.asList(t); } } } /** * Creates a memory-, CPU- and cache-efficient immutable list from an * existing list. The list is always copied. * * @param t Array of members of list * @param <T> Element type * @return List containing the given members */ public static <T> List<T> flatList(List<T> t) { switch (t.size()) { case 0: return Collections.emptyList(); case 1: return Collections.singletonList(t.get(0)); case 2: return new Flat2List<T>(t.get(0), t.get(1)); case 3: return new Flat3List<T>(t.get(0), t.get(1), t.get(2)); default: // REVIEW: AbstractList contains a modCount field; we could // write our own implementation and reduce creation overhead a // bit. //noinspection unchecked return (List<T>) Arrays.asList(t.toArray()); } } /** * Parses a locale string. * * <p>The inverse operation of {@link java.util.Locale#toString()}. * * @param localeString Locale string, e.g. "en" or "en_US" * @return Java locale object */ public static Locale parseLocale(String localeString) { String[] strings = localeString.split("_"); switch (strings.length) { case 1: return new Locale(strings[0]); case 2: return new Locale(strings[0], strings[1]); case 3: return new Locale(strings[0], strings[1], strings[2]); default: throw newInternal( "bad locale string '" + localeString + "'"); } } private static final Map<String, String> TIME_UNITS = Olap4jUtil.mapOf( "ns", "NANOSECONDS", "us", "MICROSECONDS", "ms", "MILLISECONDS", "s", "SECONDS", "m", "MINUTES", "h", "HOURS", "d", "DAYS"); /** * Parses an interval. * * <p>For example, "30s" becomes (30, {@link TimeUnit#SECONDS}); * "2us" becomes (2, {@link TimeUnit#MICROSECONDS}).</p> * * <p>Units m (minutes), h (hours) and d (days) are only available * in JDK 1.6 or later, because the corresponding constants are missing * from {@link TimeUnit} in JDK 1.5.</p> * * @param s String to parse * @param unit Default time unit; may be null * * @return Pair of value and time unit. Neither pair or its components are * null * * @throws NumberFormatException if unit is not present and there is no * default, or if number is not valid */ public static Pair<Long, TimeUnit> parseInterval( String s, TimeUnit unit) throws NumberFormatException { final String original = s; for (Map.Entry<String, String> entry : TIME_UNITS.entrySet()) { final String abbrev = entry.getKey(); if (s.endsWith(abbrev)) { final String full = entry.getValue(); try { unit = TimeUnit.valueOf(full); s = s.substring(0, s.length() - abbrev.length()); break; } catch (IllegalArgumentException e) { // ignore - MINUTES, HOURS, DAYS are not defined in JDK1.5 } } } if (unit == null) { throw new NumberFormatException( "Invalid time interval '" + original + "'. Does not contain a " + "time unit. (Suffix may be ns (nanoseconds), " + "us (microseconds), ms (milliseconds), s (seconds), " + "h (hours), d (days). For example, '20s' means 20 seconds.)"); } try { return Pair.of(new BigDecimal(s).longValue(), unit); } catch (NumberFormatException e) { throw new NumberFormatException( "Invalid time interval '" + original + "'"); } } /** * Converts a list of olap4j-style segments to a list of mondrian-style * segments. * * @param olap4jSegmentList List of olap4j segments * @return List of mondrian segments */ public static List<Id.Segment> convert( List<IdentifierSegment> olap4jSegmentList) { final List<Id.Segment> list = new ArrayList<Id.Segment>(); for (IdentifierSegment olap4jSegment : olap4jSegmentList) { list.add(convert(olap4jSegment)); } return list; } /** * Converts an olap4j-style segment to a mondrian-style segment. * * @param olap4jSegment olap4j segment * @return mondrian segment */ public static Id.Segment convert(IdentifierSegment olap4jSegment) { if (olap4jSegment instanceof NameSegment) { return convert((NameSegment) olap4jSegment); } else { return convert((KeySegment) olap4jSegment); } } private static Id.KeySegment convert(final KeySegment keySegment) { return new Id.KeySegment( new AbstractList<Id.NameSegment>() { public Id.NameSegment get(int index) { return convert(keySegment.getKeyParts().get(index)); } public int size() { return keySegment.getKeyParts().size(); } }); } private static Id.NameSegment convert(NameSegment nameSegment) { return new Id.NameSegment( nameSegment.getName(), convert(nameSegment.getQuoting())); } private static Id.Quoting convert(Quoting quoting) { switch (quoting) { case QUOTED: return Id.Quoting.QUOTED; case UNQUOTED: return Id.Quoting.UNQUOTED; case KEY: return Id.Quoting.KEY; default: throw Util.unexpected(quoting); } } /** * Applies a collection of filters to an iterable. * * @param iterable Iterable * @param conds Zero or more conditions * @param <T> * @return Iterable that returns only members of underlying iterable for * for which all conditions evaluate to true */ public static <T> Iterable<T> filter( final Iterable<T> iterable, final Functor1<Boolean, T>... conds) { final Functor1<Boolean, T>[] conds2 = optimizeConditions(conds); if (conds2.length == 0) { return iterable; } return new Iterable<T>() { public Iterator<T> iterator() { return new Iterator<T>() { final Iterator<T> iterator = iterable.iterator(); T next; boolean hasNext = moveToNext(); private boolean moveToNext() { outer: while (iterator.hasNext()) { next = iterator.next(); for (Functor1<Boolean, T> cond : conds2) { if (!cond.apply(next)) { continue outer; } } return true; } return false; } public boolean hasNext() { return hasNext; } public T next() { T t = next; hasNext = moveToNext(); return t; } public void remove() { throw new UnsupportedOperationException(); } }; } }; } private static <T> Functor1<Boolean, T>[] optimizeConditions( Functor1<Boolean, T>[] conds) { final List<Functor1<Boolean, T>> functor1List = new ArrayList<Functor1<Boolean, T>>(Arrays.asList(conds)); for (Iterator<Functor1<Boolean, T>> funcIter = functor1List.iterator(); funcIter.hasNext();) { Functor1<Boolean, T> booleanTFunctor1 = funcIter.next(); if (booleanTFunctor1 == trueFunctor()) { funcIter.remove(); } } if (functor1List.size() < conds.length) { //noinspection unchecked return functor1List.toArray(new Functor1[functor1List.size()]); } else { return conds; } } /** * Sorts a collection of {@link Comparable} objects and returns a list. * * @param collection Collection * @param <T> Element type * @return Sorted list */ public static <T extends Comparable> List<T> sort( Collection<T> collection) { Object[] a = collection.toArray(new Object[collection.size()]); Arrays.sort(a); return cast(Arrays.asList(a)); } /** * Sorts a collection of objects using a {@link java.util.Comparator} and returns a * list. * * @param collection Collection * @param comparator Comparator * @param <T> Element type * @return Sorted list */ public static <T> List<T> sort( Collection<T> collection, Comparator<T> comparator) { Object[] a = collection.toArray(new Object[collection.size()]); //noinspection unchecked Arrays.sort(a, (Comparator<? super Object>) comparator); return cast(Arrays.asList(a)); } public static List<IdentifierSegment> toOlap4j( final List<Id.Segment> segments) { return new AbstractList<IdentifierSegment>() { public IdentifierSegment get(int index) { return toOlap4j(segments.get(index)); } public int size() { return segments.size(); } }; } public static IdentifierSegment toOlap4j(Id.Segment segment) { switch (segment.quoting) { case KEY: return toOlap4j((Id.KeySegment) segment); default: return toOlap4j((Id.NameSegment) segment); } } private static KeySegment toOlap4j(final Id.KeySegment keySegment) { return new KeySegment( new AbstractList<NameSegment>() { public NameSegment get(int index) { return toOlap4j(keySegment.subSegmentList.get(index)); } public int size() { return keySegment.subSegmentList.size(); } }); } private static NameSegment toOlap4j(Id.NameSegment nameSegment) { return new NameSegment( null, nameSegment.name, toOlap4j(nameSegment.quoting)); } public static Quoting toOlap4j(Id.Quoting quoting) { return Quoting.valueOf(quoting.name()); } // TODO: move to IdentifierSegment public static boolean matches(IdentifierSegment segment, String name) { switch (segment.getQuoting()) { case KEY: return false; // FIXME case QUOTED: return equalName(segment.getName(), name); case UNQUOTED: return segment.getName().equalsIgnoreCase(name); default: throw unexpected(segment.getQuoting()); } } public static boolean matches( Member member, List<Id.Segment> nameParts) { if (Util.equalName(Util.implode(nameParts), member.getUniqueName())) { // exact match return true; } Id.Segment segment = nameParts.get(nameParts.size() - 1); while (member.getParentMember() != null) { if (!segment.matches(member.getName())) { return false; } member = member.getParentMember(); nameParts = nameParts.subList(0, nameParts.size() - 1); segment = nameParts.get(nameParts.size() - 1); } if (segment.matches(member.getName())) { return Util.equalName( member.getHierarchy().getUniqueName(), Util.implode(nameParts.subList(0, nameParts.size() - 1))); } else if (member.isAll()) { return Util.equalName( member.getHierarchy().getUniqueName(), Util.implode(nameParts)); } else { return false; } } public static RuntimeException newElementNotFoundException( int category, IdentifierNode identifierNode) { String type; switch (category) { case Category.Member: return MondrianResource.instance().MemberNotFound.ex( identifierNode.toString()); case Category.Unknown: type = "Element"; break; default: type = Category.instance().getDescription(category); } return newError(type + " '" + identifierNode + "' not found"); } /** * Calls {@link java.util.concurrent.Future#get()} and converts any * throwable into a non-checked exception. * * @param future Future * @param message Message to qualify wrapped exception * @param <T> Result type * @return Result */ public static <T> T safeGet(Future<T> future, String message) { try { return future.get(); } catch (InterruptedException e) { throw newError(e, message); } catch (ExecutionException e) { final Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } else if (cause instanceof Error) { throw (Error) cause; } else { throw newError(cause, message); } } } public static <T> Set<T> newIdentityHashSetFake() { final HashMap<T, Boolean> map = new HashMap<T, Boolean>(); return new Set<T>() { public int size() { return map.size(); } public boolean isEmpty() { return map.isEmpty(); } public boolean contains(Object o) { return map.containsKey(o); } public Iterator<T> iterator() { return map.keySet().iterator(); } public Object[] toArray() { return map.keySet().toArray(); } public <T> T[] toArray(T[] a) { return map.keySet().toArray(a); } public boolean add(T t) { return map.put(t, Boolean.TRUE) == null; } public boolean remove(Object o) { return map.remove(o) == Boolean.TRUE; } public boolean containsAll(Collection<?> c) { return map.keySet().containsAll(c); } public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } public void clear() { map.clear(); } }; } /** * Equivalent to {@link Timer#Timer(String, boolean)}. * (Introduced in JDK 1.5.) * * @param name the name of the associated thread * @param isDaemon true if the associated thread should run as a daemon * @return timer */ public static Timer newTimer(String name, boolean isDaemon) { return compatible.newTimer(name, isDaemon); } /** * As Arrays#binarySearch(Object[], int, int, Object), but * available pre-JDK 1.6. */ public static <T extends Comparable<T>> int binarySearch( T[] ts, int start, int end, T t) { return compatible.binarySearch(ts, start, end, t); } /** * Returns the intersection of two sorted sets. Does not modify either set. * * <p>Optimized for the case that both sets are {@link ArraySortedSet}.</p> * * @param set1 First set * @param set2 Second set * @return Intersection of the sets */ public static <E extends Comparable> SortedSet<E> intersect( SortedSet<E> set1, SortedSet<E> set2) { if (set1.isEmpty()) { return set1; } if (set2.isEmpty()) { return set2; } if (!(set1 instanceof ArraySortedSet) || !(set2 instanceof ArraySortedSet)) { final TreeSet<E> set = new TreeSet<E>(set1); set.retainAll(set2); return set; } final Comparable<?>[] result = new Comparable[Math.min(set1.size(), set2.size())]; final Iterator<E> it1 = set1.iterator(); final Iterator<E> it2 = set2.iterator(); int i = 0; E e1 = it1.next(); E e2 = it2.next(); for (;;) { final int compare = e1.compareTo(e2); if (compare == 0) { result[i++] = e1; if (!it1.hasNext() || !it2.hasNext()) { break; } e1 = it1.next(); e2 = it2.next(); } else if (compare == 1) { if (!it2.hasNext()) { break; } e2 = it2.next(); } else { if (!it1.hasNext()) { break; } e1 = it1.next(); } } return new ArraySortedSet(result, 0, i); } /** * Compares two integers using the same algorithm as * {@link Integer#compareTo(Integer)}. * * @param i0 First integer * @param i1 Second integer * @return Comparison */ public static int compareIntegers(int i0, int i1) { return (i0 < i1 ? -1 : (i0 == i1 ? 0 : 1)); } /** * Returns the last item in a list. * * @param list List * @param <T> Element type * @return Last item in the list * @throws IndexOutOfBoundsException if list is empty */ public static <T> T last(List<T> list) { return list.get(list.size() - 1); } /** * Returns the sole item in a list. * * <p>If the list has 0 or more than one element, throws.</p> * * @param list List * @param <T> Element type * @return Sole item in the list * @throws IndexOutOfBoundsException if list is empty or has more than 1 elt */ public static <T> T only(List<T> list) { if (list.size() != 1) { throw new IndexOutOfBoundsException( "list " + list + " has " + list.size() + " elements, expected 1"); } return list.get(0); } /** * Closes a JDBC result set, statement, and connection, ignoring any errors. * If any of them are null, that's fine. * * <p>If any of them throws a {@link SQLException}, returns the first * such exception, but always executes all closes.</p> * * @param resultSet Result set * @param statement Statement * @param connection Connection */ public static SQLException close( ResultSet resultSet, Statement statement, Connection connection) { SQLException firstException = null; if (resultSet != null) { try { if (statement == null) { statement = resultSet.getStatement(); } resultSet.close(); } catch (Throwable t) { firstException = new SQLException(); firstException.initCause(t); } } if (statement != null) { try { statement.close(); } catch (Throwable t) { if (firstException == null) { firstException = new SQLException(); firstException.initCause(t); } } } if (connection != null) { try { connection.close(); } catch (Throwable t) { if (firstException == null) { firstException = new SQLException(); firstException.initCause(t); } } } return firstException; } /** * Creates a bitset with bits from {@code fromIndex} (inclusive) to * specified {@code toIndex} (exclusive) set to {@code true}. * * <p>For example, {@code bitSetBetween(0, 3)} returns a bit set with bits * {0, 1, 2} set. * * @param fromIndex Index of the first bit to be set. * @param toIndex Index after the last bit to be set. * @return Bit set */ public static BitSet bitSetBetween(int fromIndex, int toIndex) { final BitSet bitSet = new BitSet(); if (toIndex > fromIndex) { // Avoid http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6222207 // "BitSet internal invariants may be violated" bitSet.set(fromIndex, toIndex); } return bitSet; } public static class ErrorCellValue { public String toString() { return "#ERR"; } } @SuppressWarnings({"unchecked"}) public static <T> T[] genericArray(Class<T> clazz, int size) { return (T[]) Array.newInstance(clazz, size); } /** * Throws an internal error if condition is not true. It would be called * <code>assert</code>, but that is a keyword as of JDK 1.4. */ public static void assertTrue(boolean b) { if (!b) { throw newInternal("assert failed"); } } /** * Throws an internal error with the given messagee if condition is not * true. It would be called <code>assert</code>, but that is a keyword as * of JDK 1.4. */ public static void assertTrue(boolean b, String message) { if (!b) { throw newInternal("assert failed: " + message); } } /** * Creates an internal error with a given message. */ public static RuntimeException newInternal(String message) { return MondrianResource.instance().Internal.ex(message); } /** * Creates an internal error with a given message and cause. */ public static RuntimeException newInternal(Throwable e, String message) { return MondrianResource.instance().Internal.ex(message, e); } /** * Creates a non-internal error. Currently implemented in terms of * internal errors, but later we will create resourced messages. */ public static RuntimeException newError(String message) { return newInternal(message); } /** * Creates a non-internal error. Currently implemented in terms of * internal errors, but later we will create resourced messages. */ public static RuntimeException newError(Throwable e, String message) { return newInternal(e, message); } /** * Returns an exception indicating that we didn't expect to find this value * here. * * @param value Value */ public static RuntimeException unexpected(Enum value) { return Util.newInternal( "Was not expecting value '" + value + "' for enumeration '" + value.getClass().getName() + "' in this context"); } /** * Checks that a precondition (declared using the javadoc <code>@pre</code> * tag) is satisfied. * * @param b The value of executing the condition */ public static void assertPrecondition(boolean b) { assertTrue(b); } /** * Checks that a precondition (declared using the javadoc <code>@pre</code> * tag) is satisfied. For example, * * <blockquote><pre>void f(String s) { * Util.assertPrecondition(s != null, "s != null"); * ... * }</pre></blockquote> * * @param b The value of executing the condition * @param condition The text of the condition */ public static void assertPrecondition(boolean b, String condition) { assertTrue(b, condition); } /** * Checks that a postcondition (declared using the javadoc * <code>@post</code> tag) is satisfied. * * @param b The value of executing the condition */ public static void assertPostcondition(boolean b) { assertTrue(b); } /** * Checks that a postcondition (declared using the javadoc * <code>@post</code> tag) is satisfied. * * @param b The value of executing the condition */ public static void assertPostcondition(boolean b, String condition) { assertTrue(b, condition); } /** * Converts an error into an array of strings, the most recent error first. * * @param e the error; may be null. Errors are chained according to their * {@link Throwable#getCause cause}. */ public static String[] convertStackToString(Throwable e) { List<String> list = new ArrayList<String>(); while (e != null) { String sMsg = getErrorMessage(e); list.add(sMsg); e = e.getCause(); } return list.toArray(new String[list.size()]); } /** * Constructs the message associated with an arbitrary Java error, making * up one based on the stack trace if there is none. As * {@link #getErrorMessage(Throwable,boolean)}, but does not print the * class name if the exception is derived from {@link java.sql.SQLException} * or is exactly a {@link java.lang.Exception}. */ public static String getErrorMessage(Throwable err) { boolean prependClassName = !(err instanceof java.sql.SQLException || err.getClass() == java.lang.Exception.class); return getErrorMessage(err, prependClassName); } /** * Constructs the message associated with an arbitrary Java error, making * up one based on the stack trace if there is none. * * @param err the error * @param prependClassName should the error be preceded by the * class name of the Java exception? defaults to false, unless the error * is derived from {@link java.sql.SQLException} or is exactly a {@link * java.lang.Exception} */ public static String getErrorMessage( Throwable err, boolean prependClassName) { String errMsg = err.getMessage(); if ((errMsg == null) || (err instanceof RuntimeException)) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); err.printStackTrace(pw); return sw.toString(); } else { return (prependClassName) ? err.getClass().getName() + ": " + errMsg : errMsg; } } /** * If one of the causes of an exception is of a particular class, returns * that cause. Otherwise returns null. * * @param e Exception * @param clazz Desired class * @param <T> Class * @return Cause of given class, or null */ public static <T extends Throwable> T getMatchingCause(Throwable e, Class<T> clazz) { for (;;) { if (clazz.isInstance(e)) { return clazz.cast(e); } final Throwable cause = e.getCause(); if (cause == null || cause == e) { return null; } e = cause; } } /** * Converts an expression to a string. */ public static String unparse(Exp exp) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); exp.unparse(pw); return sw.toString(); } /** * Converts an query to a string. */ public static String unparse(Query query) { StringWriter sw = new StringWriter(); PrintWriter pw = new QueryPrintWriter(sw); query.unparse(pw); return sw.toString(); } /** * Creates a file-protocol URL for the given file. */ public static URL toURL(File file) throws MalformedURLException { String path = file.getAbsolutePath(); // This is a bunch of weird code that is required to // make a valid URL on the Windows platform, due // to inconsistencies in what getAbsolutePath returns. String fs = System.getProperty("file.separator"); if (fs.length() == 1) { char sep = fs.charAt(0); if (sep != '/') { path = path.replace(sep, '/'); } if (path.charAt(0) != '/') { path = '/' + path; } } path = "file://" + path; return new URL(path); } /** * <code>PropertyList</code> is an order-preserving list of key-value * pairs. Lookup is case-insensitive, but the case of keys is preserved. */ public static class PropertyList implements Iterable<Pair<String, String>>, Serializable { List<Pair<String, String>> list = new ArrayList<Pair<String, String>>(); public PropertyList() { this.list = new ArrayList<Pair<String, String>>(); } private PropertyList(List<Pair<String, String>> list) { this.list = list; } @SuppressWarnings({"CloneDoesntCallSuperClone"}) @Override public PropertyList clone() { return new PropertyList(new ArrayList<Pair<String, String>>(list)); } public String get(String key) { return get(key, null); } public String get(String key, String defaultValue) { for (int i = 0, n = list.size(); i < n; i++) { Pair<String, String> pair = list.get(i); if (pair.left.equalsIgnoreCase(key)) { return pair.right; } } return defaultValue; } public String put(String key, String value) { for (int i = 0, n = list.size(); i < n; i++) { Pair<String, String> pair = list.get(i); if (pair.left.equalsIgnoreCase(key)) { String old = pair.right; if (key.equalsIgnoreCase("Provider")) { // Unlike all other properties, later values of // "Provider" do not supersede } else { pair.right = value; } return old; } } list.add(new Pair<String, String>(key, value)); return null; } public boolean remove(String key) { boolean found = false; for (int i = 0; i < list.size(); i++) { Pair<String, String> pair = list.get(i); if (pair.getKey().equalsIgnoreCase(key)) { list.remove(i); found = true; --i; } } return found; } public String toString() { StringBuilder sb = new StringBuilder(64); for (int i = 0, n = list.size(); i < n; i++) { Pair<String, String> pair = list.get(i); if (i > 0) { sb.append("; "); } sb.append(pair.left); sb.append('='); final String right = pair.right; if (right == null) { sb.append("'null'"); } else { // Quote a property value if is has a semi colon in it // 'xxx;yyy'. Escape any single-quotes by doubling them. final int needsQuote = right.indexOf(';'); if (needsQuote >= 0) { // REVIEW: This logic leaves off the leading/trailing // quote if the property value already has a // leading/trailing quote. Doesn't seem right to me. if (right.charAt(0) != '\'') { sb.append("'"); } sb.append(replace(right, "'", "''")); if (right.charAt(right.length() - 1) != '\'') { sb.append("'"); } } else { sb.append(right); } } } return sb.toString(); } public Iterator<Pair<String, String>> iterator() { return list.iterator(); } } /** * Converts an OLE DB connect string into a {@link PropertyList}. * * <p> For example, <code>"Provider=MSOLAP; DataSource=LOCALHOST;"</code> * becomes the set of (key, value) pairs <code>{("Provider","MSOLAP"), * ("DataSource", "LOCALHOST")}</code>. Another example is * <code>Provider='sqloledb';Data Source='MySqlServer';Initial * Catalog='Pubs';Integrated Security='SSPI';</code>. * * <p> This method implements as much as possible of the <a * href="http://msdn.microsoft.com/library/en-us/oledb/htm/oledbconnectionstringsyntax.asp" * target="_blank">OLE DB connect string syntax * specification</a>. To find what it <em>actually</em> does, take * a look at the <code>mondrian.olap.UtilTestCase</code> test case. */ public static PropertyList parseConnectString(String s) { return new ConnectStringParser(s).parse(); } private static class ConnectStringParser { private final String s; private final int n; private int i; private final StringBuilder nameBuf; private final StringBuilder valueBuf; private ConnectStringParser(String s) { this.s = s; this.i = 0; this.n = s.length(); this.nameBuf = new StringBuilder(64); this.valueBuf = new StringBuilder(64); } PropertyList parse() { PropertyList list = new PropertyList(); while (i < n) { parsePair(list); } return list; } /** * Reads "name=value;" or "name=value<EOF>". */ void parsePair(PropertyList list) { String name = parseName(); if (name == null) { return; } String value; if (i >= n) { value = ""; } else if (s.charAt(i) == ';') { i++; value = ""; } else { value = parseValue(); } list.put(name, value); } /** * Reads "name=". Name can contain equals sign if equals sign is * doubled. Returns null if there is no name to read. */ String parseName() { nameBuf.setLength(0); while (true) { char c = s.charAt(i); switch (c) { case '=': i++; if (i < n && (c = s.charAt(i)) == '=') { // doubled equals sign; take one of them, and carry on i++; nameBuf.append(c); break; } String name = nameBuf.toString(); name = name.trim(); return name; case ' ': if (nameBuf.length() == 0) { // ignore preceding spaces i++; if (i >= n) { // there is no name, e.g. trailing spaces after // semicolon, 'x=1; y=2; ' return null; } break; } else { // fall through } default: nameBuf.append(c); i++; if (i >= n) { return nameBuf.toString().trim(); } } } } /** * Reads "value;" or "value<EOF>" */ String parseValue() { char c; // skip over leading white space while ((c = s.charAt(i)) == ' ') { i++; if (i >= n) { return ""; } } if (c == '"' || c == '\'') { String value = parseQuoted(c); // skip over trailing white space while (i < n && (c = s.charAt(i)) == ' ') { i++; } if (i >= n) { return value; } else if (s.charAt(i) == ';') { i++; return value; } else { throw new RuntimeException( "quoted value ended too soon, at position " + i + " in '" + s + "'"); } } else { String value; int semi = s.indexOf(';', i); if (semi >= 0) { value = s.substring(i, semi); i = semi + 1; } else { value = s.substring(i); i = n; } return value.trim(); } } /** * Reads a string quoted by a given character. Occurrences of the * quoting character must be doubled. For example, * <code>parseQuoted('"')</code> reads <code>"a ""new"" string"</code> * and returns <code>a "new" string</code>. */ String parseQuoted(char q) { char c = s.charAt(i++); Util.assertTrue(c == q); valueBuf.setLength(0); while (i < n) { c = s.charAt(i); if (c == q) { i++; if (i < n) { c = s.charAt(i); if (c == q) { valueBuf.append(c); i++; continue; } } return valueBuf.toString(); } else { valueBuf.append(c); i++; } } throw new RuntimeException( "Connect string '" + s + "' contains unterminated quoted value '" + valueBuf.toString() + "'"); } } /** * Combines two integers into a hash code. */ public static int hash(int i, int j) { return (i << 4) ^ j; } /** * Computes a hash code from an existing hash code and an object (which * may be null). */ public static int hash(int h, Object o) { int k = (o == null) ? 0 : o.hashCode(); return ((h << 4) | h) ^ k; } /** * Computes a hash code from an existing hash code and an array of objects * (which may be null). */ public static int hashArray(int h, Object [] a) { // The hashcode for a null array and an empty array should be different // than h, so use magic numbers. if (a == null) { return hash(h, 19690429); } if (a.length == 0) { return hash(h, 19690721); } for (Object anA : a) { h = hash(h, anA); } return h; } /** * Concatenates one or more arrays. * * <p>Resulting array has same element type as first array. Each arrays may * be empty, but must not be null. * * @param a0 First array * @param as Zero or more subsequent arrays * @return Array containing all elements */ public static <T> T[] appendArrays( T[] a0, T[]... as) { int n = a0.length; for (T[] a : as) { n += a.length; } T[] copy = Util.copyOf(a0, n); n = a0.length; for (T[] a : as) { System.arraycopy(a, 0, copy, n, a.length); n += a.length; } return copy; } /** * Adds an object to the end of an array. The resulting array is of the * same type (e.g. <code>String[]</code>) as the input array. * * @param a Array * @param o Element * @return New array containing original array plus element * * @see #appendArrays */ public static <T> T[] append(T[] a, T o) { T[] a2 = Util.copyOf(a, a.length + 1); a2[a.length] = o; return a2; } /** * Like <code>{@link java.util.Arrays}.copyOf(double[], int)</code>, but * exists prior to JDK 1.6. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length */ public static double[] copyOf(double[] original, int newLength) { double[] copy = new double[newLength]; System.arraycopy( original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** * Like <code>{@link java.util.Arrays}.copyOf(int[], int)</code>, but * exists prior to JDK 1.6. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length */ public static int[] copyOf(int[] original, int newLength) { int[] copy = new int[newLength]; System.arraycopy( original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** * Like <code>{@link java.util.Arrays}.copyOf(long[], int)</code>, but * exists prior to JDK 1.6. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length */ public static long[] copyOf(long[] original, int newLength) { long[] copy = new long[newLength]; System.arraycopy( original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** * Like <code>{@link java.util.Arrays}.copyOf(Object[], int)</code>, but * exists prior to JDK 1.6. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with zeros * to obtain the specified length */ public static <T> T[] copyOf(T[] original, int newLength) { //noinspection unchecked return (T[]) copyOf(original, newLength, original.getClass()); } /** * Copies the specified array. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned * @return a copy of the original array, truncated or padded with nulls * to obtain the specified length */ public static <T, U> T[] copyOf( U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings({"unchecked", "RedundantCast"}) T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); //noinspection SuspiciousSystemArraycopy System.arraycopy( original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } /** * Returns the cumulative amount of time spent accessing the database. * * @deprecated Use {@link mondrian.server.monitor.Monitor#getServer()} and * {@link mondrian.server.monitor.ServerInfo#sqlStatementExecuteNanos}; * will be removed in 4.0. */ public static long dbTimeMillis() { return databaseMillis; } /** * Adds to the cumulative amount of time spent accessing the database. * * @deprecated Will be removed in 4.0. */ public static void addDatabaseTime(long millis) { databaseMillis += millis; } /** * Returns the system time less the time spent accessing the database. * Use this method to figure out how long an operation took: call this * method before an operation and after an operation, and the difference * is the amount of non-database time spent. * * @deprecated Will be removed in 4.0. */ public static long nonDbTimeMillis() { final long systemMillis = System.currentTimeMillis(); return systemMillis - databaseMillis; } /** * Creates a very simple implementation of {@link Validator}. (Only * useful for resolving trivial expressions.) */ public static Validator createSimpleValidator(final FunTable funTable) { return new Validator() { public Query getQuery() { return null; } public SchemaReader getSchemaReader() { throw new UnsupportedOperationException(); } public Exp validate(Exp exp, boolean scalar) { return exp; } public void validate(ParameterExpr parameterExpr) { } public void validate(MemberProperty memberProperty) { } public void validate(QueryAxis axis) { } public void validate(Formula formula) { } public FunDef getDef(Exp[] args, String name, Syntax syntax) { // Very simple resolution. Assumes that there is precisely // one resolver (i.e. no overloading) and no argument // conversions are necessary. List<Resolver> resolvers = funTable.getResolvers(name, syntax); final Resolver resolver = resolvers.get(0); final List<Resolver.Conversion> conversionList = new ArrayList<Resolver.Conversion>(); final FunDef def = resolver.resolve(args, this, conversionList); assert conversionList.isEmpty(); return def; } public boolean alwaysResolveFunDef() { return false; } public boolean canConvert( int ordinal, Exp fromExp, int to, List<Resolver.Conversion> conversions) { return true; } public boolean requiresExpression() { return false; } public FunTable getFunTable() { return funTable; } public Parameter createOrLookupParam( boolean definition, String name, Type type, Exp defaultExp, String description) { return null; } }; } /** * Reads a Reader until it returns EOF and returns the contents as a String. * * @param rdr Reader to Read. * @param bufferSize size of buffer to allocate for reading. * @return content of Reader as String * @throws IOException on I/O error */ public static String readFully(final Reader rdr, final int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException( "Buffer size must be greater than 0"); } final char[] buffer = new char[bufferSize]; final StringBuilder buf = new StringBuilder(bufferSize); int len; while ((len = rdr.read(buffer)) != -1) { buf.append(buffer, 0, len); } return buf.toString(); } /** * Reads an input stream until it returns EOF and returns the contents as an * array of bytes. * * @param in Input stream * @param bufferSize size of buffer to allocate for reading. * @return content of stream as an array of bytes * @throws IOException on I/O error */ public static byte[] readFully(final InputStream in, final int bufferSize) throws IOException { if (bufferSize <= 0) { throw new IllegalArgumentException( "Buffer size must be greater than 0"); } final byte[] buffer = new byte[bufferSize]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize); int len; while ((len = in.read(buffer)) != -1) { baos.write(buffer, 0, len); } return baos.toByteArray(); } /** * Returns the contents of a URL, substituting tokens. * * <p>Replaces the tokens "${key}" if the map is not null and "key" occurs * in the key-value map. * * <p>If the URL string starts with "inline:" the contents are the * rest of the URL. * * @param urlStr URL string * @param map Key/value map * @return Contents of URL with tokens substituted * @throws IOException on I/O error */ public static String readURL(final String urlStr, Map<String, String> map) throws IOException { if (urlStr.startsWith("inline:")) { String content = urlStr.substring("inline:".length()); if (map != null) { content = Util.replaceProperties(content, map); } return content; } else { final URL url = new URL(urlStr); return readURL(url, map); } } /** * Returns the contents of a URL. * * @param url URL * @return Contents of URL * @throws IOException on I/O error */ public static String readURL(final URL url) throws IOException { return readURL(url, null); } /** * Returns the contents of a URL, substituting tokens. * * <p>Replaces the tokens "${key}" if the map is not null and "key" occurs * in the key-value map. * * @param url URL * @param map Key/value map * @return Contents of URL with tokens substituted * @throws IOException on I/O error */ public static String readURL( final URL url, Map<String, String> map) throws IOException { final Reader r = new BufferedReader(new InputStreamReader(url.openStream())); final int BUF_SIZE = 8096; try { String xmlCatalog = readFully(r, BUF_SIZE); xmlCatalog = Util.replaceProperties(xmlCatalog, map); return xmlCatalog; } finally { r.close(); } } /** * Gets content via Apache VFS. File must exist and have content * * @param url String * @return Apache VFS FileContent for further processing * @throws FileSystemException on error */ public static InputStream readVirtualFile(String url) throws FileSystemException { // Treat catalogUrl as an Apache VFS (Virtual File System) URL. // VFS handles all of the usual protocols (http:, file:) // and then some. FileSystemManager fsManager = VFS.getManager(); if (fsManager == null) { throw newError("Cannot get virtual file system manager"); } // Workaround VFS bug. if (url.startsWith("file://localhost")) { url = url.substring("file://localhost".length()); } if (url.startsWith("file:")) { url = url.substring("file:".length()); } // work around for VFS bug not closing http sockets // (Mondrian-585) if (url.startsWith("http")) { try { return new URL(url).openStream(); } catch (IOException e) { throw newError( "Could not read URL: " + url); } } File userDir = new File("").getAbsoluteFile(); FileObject file = fsManager.resolveFile(userDir, url); FileContent fileContent = null; try { // Because of VFS caching, make sure we refresh to get the latest // file content. This refresh may possibly solve the following // workaround for defect MONDRIAN-508, but cannot be tested, so we // will leave the work around for now. file.refresh(); // Workaround to defect MONDRIAN-508. For HttpFileObjects, verifies // the URL of the file retrieved matches the URL passed in. A VFS // cache bug can cause it to treat URLs with different parameters // as the same file (e.g. http://blah.com?param=A, // http://blah.com?param=B) if (file instanceof HttpFileObject && !file.getName().getURI().equals(url)) { fsManager.getFilesCache().removeFile( file.getFileSystem(), file.getName()); file = fsManager.resolveFile(userDir, url); } if (!file.isReadable()) { throw newError( "Virtual file is not readable: " + url); } fileContent = file.getContent(); } finally { file.close(); } if (fileContent == null) { throw newError( "Cannot get virtual file content: " + url); } return fileContent.getInputStream(); } public static String readVirtualFileAsString( String catalogUrl) throws IOException { InputStream in = readVirtualFile(catalogUrl); try { return IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); } } /** * Converts a {@link Properties} object to a string-to-string {@link Map}. * * @param properties Properties * @return String-to-string map */ public static Map<String, String> toMap(final Properties properties) { return new AbstractMap<String, String>() { @SuppressWarnings({"unchecked"}) public Set<Entry<String, String>> entrySet() { return (Set) properties.entrySet(); } }; } /** * Replaces tokens in a string. * * <p>Replaces the tokens "${key}" if "key" occurs in the key-value map. * Otherwise "${key}" is left in the string unchanged. * * @param text Source string * @param env Map of key-value pairs * @return String with tokens substituted */ public static String replaceProperties( String text, Map<String, String> env) { // As of JDK 1.5, cannot use StringBuilder - appendReplacement requires // the antediluvian StringBuffer. StringBuffer buf = new StringBuffer(text.length() + 200); Pattern pattern = Pattern.compile("\\$\\{([^${}]+)\\}"); Matcher matcher = pattern.matcher(text); while (matcher.find()) { String varName = matcher.group(1); String varValue = env.get(varName); if (varValue != null) { matcher.appendReplacement(buf, varValue); } else { matcher.appendReplacement(buf, "\\${$1}"); } } matcher.appendTail(buf); return buf.toString(); } public static String printMemory() { return printMemory(null); } public static String printMemory(String msg) { final Runtime rt = Runtime.getRuntime(); final long freeMemory = rt.freeMemory(); final long totalMemory = rt.totalMemory(); final StringBuilder buf = new StringBuilder(64); buf.append("FREE_MEMORY:"); if (msg != null) { buf.append(msg); buf.append(':'); } buf.append(' '); buf.append(freeMemory / 1024); buf.append("kb "); long hundredths = (freeMemory * 10000) / totalMemory; buf.append(hundredths / 100); hundredths %= 100; if (hundredths >= 10) { buf.append('.'); } else { buf.append(".0"); } buf.append(hundredths); buf.append('%'); return buf.toString(); } /** * Casts a Set to a Set with a different element type. * * @param set Set * @return Set of desired type */ @SuppressWarnings({"unchecked"}) public static <T> Set<T> cast(Set<?> set) { return (Set<T>) set; } /** * Casts a List to a List with a different element type. * * @param list List * @return List of desired type */ @SuppressWarnings({"unchecked"}) public static <T> List<T> cast(List<?> list) { return (List<T>) list; } /** * Returns whether it is safe to cast a collection to a collection with a * given element type. * * @param collection Collection * @param clazz Target element type * @param <T> Element type * @return Whether all not-null elements of the collection are instances of * element type */ public static <T> boolean canCast( Collection<?> collection, Class<T> clazz) { for (Object o : collection) { if (o != null && !clazz.isInstance(o)) { return false; } } return true; } /** * Casts a collection to iterable. * * Under JDK 1.4, {@link Collection} objects do not implement * {@link Iterable}, so this method inserts a casting wrapper. (Since * Iterable does not exist under JDK 1.4, they will have been compiled * under JDK 1.5 or later, then retrowoven to 1.4 class format. References * to Iterable will have been replaced with references to * <code>com.rc.retroweaver.runtime.Retroweaver_</code>. * * <p>Under later JDKs this method is trivial. This method can be deleted * when we discontinue support for JDK 1.4. * * @param iterable Object which ought to be iterable * @param <T> Element type * @return Object cast to Iterable */ public static <T> Iterable<T> castToIterable( final Object iterable) { if (Util.Retrowoven && !(iterable instanceof Iterable)) { return new Iterable<T>() { public Iterator<T> iterator() { return ((Collection<T>) iterable).iterator(); } }; } return (Iterable<T>) iterable; } /** * Looks up an enumeration by name, returning null if null or not valid. * * @param clazz Enumerated type * @param name Name of constant */ public static <E extends Enum<E>> E lookup(Class<E> clazz, String name) { return lookup(clazz, name, null); } /** * Looks up an enumeration by name, returning a given default value if null * or not valid. * * @param clazz Enumerated type * @param name Name of constant * @param defaultValue Default value if constant is not found * @return Value, or null if name is null or value does not exist */ public static <E extends Enum<E>> E lookup( Class<E> clazz, String name, E defaultValue) { if (name == null) { return defaultValue; } try { return Enum.valueOf(clazz, name); } catch (IllegalArgumentException e) { return defaultValue; } } /** * Make a BigDecimal from a double. On JDK 1.5 or later, the BigDecimal * precision reflects the precision of the double while with JDK 1.4 * this is not the case. * * @param d the input double * @return the BigDecimal */ public static BigDecimal makeBigDecimalFromDouble(double d) { return compatible.makeBigDecimalFromDouble(d); } /** * Returns a literal pattern String for the specified String. * * <p>Specification as for {@link Pattern#quote(String)}, which was * introduced in JDK 1.5. * * @param s The string to be literalized * @return A literal string replacement */ public static String quotePattern(String s) { return compatible.quotePattern(s); } /** * Generates a unique id. * * <p>From JDK 1.5 onwards, uses a {@code UUID}. * * @return A unique id */ public static String generateUuidString() { return compatible.generateUuidString(); } /** * Compiles a script to yield a Java interface. * * <p>Only valid JDK 1.6 and higher; fails on JDK 1.5 and earlier.</p> * * @param iface Interface script should implement * @param script Script code * @param engineName Name of engine (e.g. "JavaScript") * @param <T> Interface * @return Object that implements given interface */ public static <T> T compileScript( Class<T> iface, String script, String engineName) { return compatible.compileScript(iface, script, engineName); } /** * Removes a thread local from the current thread. * * <p>From JDK 1.5 onwards, calls {@link ThreadLocal#remove()}; before * that, no-ops.</p> * * @param threadLocal Thread local * @param <T> Type */ public static <T> void threadLocalRemove(ThreadLocal<T> threadLocal) { compatible.threadLocalRemove(threadLocal); } /** * Creates a hash set that, like {@link java.util.IdentityHashMap}, * compares keys using identity. * * @param <T> Element type * @return Set */ public static <T> Set<T> newIdentityHashSet() { return compatible.newIdentityHashSet(); } /** * Creates a new udf instance from the given udf class. * * @param udfClass the class to create new instance for * @param functionName Function name, or null * @return an instance of UserDefinedFunction */ public static UserDefinedFunction createUdf( Class<? extends UserDefinedFunction> udfClass, String functionName) { // Instantiate class with default constructor. UserDefinedFunction udf; String className = udfClass.getName(); String functionNameOrEmpty = functionName == null ? "" : functionName; // Find a constructor. Constructor<?> constructor; Object[] args = {}; // 0. Check that class is public and top-level or static. if (!Modifier.isPublic(udfClass.getModifiers()) || (udfClass.getEnclosingClass() != null && !Modifier.isStatic(udfClass.getModifiers()))) { throw MondrianResource.instance().UdfClassMustBePublicAndStatic.ex( functionName, className); } // 1. Look for a constructor "public Udf(String name)". try { constructor = udfClass.getConstructor(String.class); if (Modifier.isPublic(constructor.getModifiers())) { args = new Object[] {functionName}; } else { constructor = null; } } catch (NoSuchMethodException e) { constructor = null; } // 2. Otherwise, look for a constructor "public Udf()". if (constructor == null) { try { constructor = udfClass.getConstructor(); if (Modifier.isPublic(constructor.getModifiers())) { args = new Object[] {}; } else { constructor = null; } } catch (NoSuchMethodException e) { constructor = null; } } // 3. Else, no constructor suitable. if (constructor == null) { throw MondrianResource.instance().UdfClassWrongIface.ex( functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } // Instantiate class. try { udf = (UserDefinedFunction) constructor.newInstance(args); } catch (InstantiationException e) { throw MondrianResource.instance().UdfClassWrongIface.ex( functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } catch (IllegalAccessException e) { throw MondrianResource.instance().UdfClassWrongIface.ex( functionName, className, UserDefinedFunction.class.getName()); } catch (ClassCastException e) { throw MondrianResource.instance().UdfClassWrongIface.ex( functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } catch (InvocationTargetException e) { throw MondrianResource.instance().UdfClassWrongIface.ex( functionName, className, UserDefinedFunction.class.getName()); } return udf; } /** * Check the resultSize against the result limit setting. Throws * LimitExceededDuringCrossjoin exception if limit exceeded. * * When it is called from RolapNativeSet.checkCrossJoin(), it is only * possible to check the known input size, because the final CJ result * will come from the DB(and will be checked against the limit when * fetching from the JDBC result set, in SqlTupleReader.prepareTuples()) * * @param resultSize Result limit * @throws ResourceLimitExceededException */ public static void checkCJResultLimit(long resultSize) { int resultLimit = MondrianProperties.instance().ResultLimit.get(); // Throw an exeption, if the size of the crossjoin exceeds the result // limit. if (resultLimit > 0 && resultLimit < resultSize) { throw MondrianResource.instance().LimitExceededDuringCrossjoin.ex( resultSize, resultLimit); } // Throw an exception if the crossjoin exceeds a reasonable limit. // (Yes, 4 billion is a reasonable limit.) if (resultSize > Integer.MAX_VALUE) { throw MondrianResource.instance().LimitExceededDuringCrossjoin.ex( resultSize, Integer.MAX_VALUE); } } /** * Converts an olap4j connect string into a legacy mondrian connect string. * * <p>For example, * "jdbc:mondrian:Datasource=jdbc/SampleData;Catalog=foodmart/FoodMart.xml;" * becomes * "Provider=Mondrian; * Datasource=jdbc/SampleData;Catalog=foodmart/FoodMart.xml;" * * <p>This method is intended to allow legacy applications (such as JPivot * and Mondrian's XMLA server) to continue to create connections using * Mondrian's legacy connection API even when they are handed an olap4j * connect string. * * @param url olap4j connect string * @return mondrian connect string, or null if cannot be converted */ public static String convertOlap4jConnectStringToNativeMondrian( String url) { if (url.startsWith("jdbc:mondrian:")) { return "Provider=Mondrian; " + url.substring("jdbc:mondrian:".length()); } return null; } /** * Checks if a String is whitespace, empty ("") or null.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * <p>(Copied from commons-lang.) * * @param str the String to check, may be null * @return <code>true</code> if the String is null, empty or whitespace */ public static boolean isBlank(String str) { final int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(str.charAt(i))) { return false; } } return true; } /** * Returns a role which has access to everything. * @param schema A schema to bind this role to. * @return A role with root access to the schema. */ public static Role createRootRole(Schema schema) { RoleImpl role = new RoleImpl(); role.grant(schema, Access.ALL); role.makeImmutable(); return role; } /** * Tries to find the cube from which a dimension is taken. * It considers private dimensions, shared dimensions and virtual * dimensions. If it can't determine with certitude the origin * of the dimension, it returns null. */ public static Cube getDimensionCube(Dimension dimension) { final Cube[] cubes = dimension.getSchema().getCubes(); for (Cube cube : cubes) { for (Dimension dimension1 : cube.getDimensions()) { // If the dimensions have the same identity, // we found an access rule. if (dimension == dimension1) { return cube; } // If the passed dimension argument is of class // RolapCubeDimension, we must validate the cube // assignment and make sure the cubes are the same. // If not, skip to the next grant. if (dimension instanceof RolapCubeDimension && dimension.equals(dimension1) && !((RolapCubeDimension)dimension1) .getCube() .equals(cube)) { continue; } // Last thing is to allow for equality correspondences // to work with virtual cubes. if (cube instanceof RolapCube && ((RolapCube)cube).isVirtual() && dimension.equals(dimension1)) { return cube; } } } return null; } /** * Similar to {@link ClassLoader#getResource(String)}, except the lookup * is in reverse order.<br> * i.e. returns the resource from the supplied classLoader or the * one closest to it in the hierarchy, instead of the closest to the root * class loader * @param classLoader The class loader to fetch from * @param name The resource name * @return A URL object for reading the resource, or null if the resource * could not be found or the invoker doesn't have adequate privileges to get * the resource. * @see ClassLoader#getResource(String) * @see ClassLoader#getResources(String) */ public static URL getClosestResource(ClassLoader classLoader, String name) { URL resource = null; try { // The last resource will be from the nearest ClassLoader. Enumeration<URL> resourceCandidates = classLoader.getResources(name); while (resourceCandidates.hasMoreElements()) { resource = resourceCandidates.nextElement(); } } catch (IOException ioe) { // ignore exception - it's OK if file is not found // just keep getResource contract and return null Util.discard(ioe); } return resource; } public static abstract class AbstractFlatList<T> implements List<T>, RandomAccess { protected final List<T> asArrayList() { //noinspection unchecked return Arrays.asList((T[]) toArray()); } public Iterator<T> iterator() { return asArrayList().iterator(); } public ListIterator<T> listIterator() { return asArrayList().listIterator(); } public boolean isEmpty() { return false; } public boolean add(Object t) { throw new UnsupportedOperationException(); } public boolean addAll(Collection<? extends T> c) { throw new UnsupportedOperationException(); } public boolean addAll(int index, Collection<? extends T> c) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public T set(int index, Object element) { throw new UnsupportedOperationException(); } public void add(int index, Object element) { throw new UnsupportedOperationException(); } public T remove(int index) { throw new UnsupportedOperationException(); } public ListIterator<T> listIterator(int index) { return asArrayList().listIterator(index); } public List<T> subList(int fromIndex, int toIndex) { return asArrayList().subList(fromIndex, toIndex); } public boolean contains(Object o) { return indexOf(o) >= 0; } public boolean containsAll(Collection<?> c) { Iterator<?> e = c.iterator(); while (e.hasNext()) { if (!contains(e.next())) { return false; } } return true; } public boolean remove(Object o) { throw new UnsupportedOperationException(); } } /** * List that stores its two elements in the two members of the class. * Unlike {@link java.util.ArrayList} or * {@link java.util.Arrays#asList(Object[])} there is * no array, only one piece of memory allocated, therefore is very compact * and cache and CPU efficient. * * <p>The list is read-only, cannot be modified or resized, and neither * of the elements can be null. * * <p>The list is created via {@link Util#flatList(Object[])}. * * @see mondrian.olap.Util.Flat3List * @param <T> */ protected static class Flat2List<T> extends AbstractFlatList<T> { private final T t0; private final T t1; Flat2List(T t0, T t1) { this.t0 = t0; this.t1 = t1; assert t0 != null; assert t1 != null; } public String toString() { return "[" + t0 + ", " + t1 + "]"; } public T get(int index) { switch (index) { case 0: return t0; case 1: return t1; default: throw new IndexOutOfBoundsException("index " + index); } } public int size() { return 2; } public boolean equals(Object o) { if (o instanceof Flat2List) { Flat2List that = (Flat2List) o; return Util.equals(this.t0, that.t0) && Util.equals(this.t1, that.t1); } return Arrays.asList(t0, t1).equals(o); } public int hashCode() { int h = 1; h = h * 31 + t0.hashCode(); h = h * 31 + t1.hashCode(); return h; } public int indexOf(Object o) { if (t0.equals(o)) { return 0; } if (t1.equals(o)) { return 1; } return -1; } public int lastIndexOf(Object o) { if (t1.equals(o)) { return 1; } if (t0.equals(o)) { return 0; } return -1; } @SuppressWarnings({"unchecked"}) public <T2> T2[] toArray(T2[] a) { a[0] = (T2) t0; a[1] = (T2) t1; return a; } public Object[] toArray() { return new Object[] {t0, t1}; } } /** * List that stores its three elements in the three members of the class. * Unlike {@link java.util.ArrayList} or * {@link java.util.Arrays#asList(Object[])} there is * no array, only one piece of memory allocated, therefore is very compact * and cache and CPU efficient. * * <p>The list is read-only, cannot be modified or resized, and none * of the elements can be null. * * <p>The list is created via {@link Util#flatList(Object[])}. * * @see mondrian.olap.Util.Flat2List * @param <T> */ protected static class Flat3List<T> extends AbstractFlatList<T> { private final T t0; private final T t1; private final T t2; Flat3List(T t0, T t1, T t2) { this.t0 = t0; this.t1 = t1; this.t2 = t2; assert t0 != null; assert t1 != null; assert t2 != null; } public String toString() { return "[" + t0 + ", " + t1 + ", " + t2 + "]"; } public T get(int index) { switch (index) { case 0: return t0; case 1: return t1; case 2: return t2; default: throw new IndexOutOfBoundsException("index " + index); } } public int size() { return 3; } public boolean equals(Object o) { if (o instanceof Flat3List) { Flat3List that = (Flat3List) o; return Util.equals(this.t0, that.t0) && Util.equals(this.t1, that.t1) && Util.equals(this.t2, that.t2); } return o.equals(this); } public int hashCode() { int h = 1; h = h * 31 + t0.hashCode(); h = h * 31 + t1.hashCode(); h = h * 31 + t2.hashCode(); return h; } public int indexOf(Object o) { if (t0.equals(o)) { return 0; } if (t1.equals(o)) { return 1; } if (t2.equals(o)) { return 2; } return -1; } public int lastIndexOf(Object o) { if (t2.equals(o)) { return 2; } if (t1.equals(o)) { return 1; } if (t0.equals(o)) { return 0; } return -1; } @SuppressWarnings({"unchecked"}) public <T2> T2[] toArray(T2[] a) { a[0] = (T2) t0; a[1] = (T2) t1; a[2] = (T2) t2; return a; } public Object[] toArray() { return new Object[] {t0, t1, t2}; } } /** * Garbage-collecting iterator. Iterates over a collection of references, * and if any of the references has been garbage-collected, removes it from * the collection. * * @param <T> Element type */ public static class GcIterator<T> implements Iterator<T> { private final Iterator<? extends Reference<T>> iterator; private boolean hasNext; private T next; public GcIterator(Iterator<? extends Reference<T>> iterator) { this.iterator = iterator; this.hasNext = true; moveToNext(); } /** * Creates an iterator over a collection of references. * * @param referenceIterable Collection of references * @param <T2> element type * @return iterable over collection */ public static <T2> Iterable<T2> over( final Iterable<? extends Reference<T2>> referenceIterable) { return new Iterable<T2>() { public Iterator<T2> iterator() { return new GcIterator<T2>(referenceIterable.iterator()); } }; } private void moveToNext() { while (iterator.hasNext()) { final Reference<T> ref = iterator.next(); next = ref.get(); if (next != null) { return; } iterator.remove(); } hasNext = false; } public boolean hasNext() { return hasNext; } public T next() { final T next1 = next; moveToNext(); return next1; } public void remove() { throw new UnsupportedOperationException(); } } public static interface Functor1<RT, PT> { RT apply(PT param); } public static <T> Functor1<T, T> identityFunctor() { //noinspection unchecked return IDENTITY_FUNCTOR; } private static final Functor1 IDENTITY_FUNCTOR = new Functor1<Object, Object>() { public Object apply(Object param) { return param; } }; public static <PT> Functor1<Boolean, PT> trueFunctor() { //noinspection unchecked return TRUE_FUNCTOR; } public static <PT> Functor1<Boolean, PT> falseFunctor() { //noinspection unchecked return FALSE_FUNCTOR; } private static final Functor1 TRUE_FUNCTOR = new Functor1<Boolean, Object>() { public Boolean apply(Object param) { return true; } }; private static final Functor1 FALSE_FUNCTOR = new Functor1<Boolean, Object>() { public Boolean apply(Object param) { return false; } }; /** * Information about memory usage. * * @see mondrian.olap.Util#getMemoryInfo() */ public interface MemoryInfo { Usage get(); public interface Usage { long getUsed(); long getCommitted(); long getMax(); } } /** * A {@link Comparator} implementation which can deal * correctly with {@link RolapUtil#sqlNullValue}. */ public static class SqlNullSafeComparator implements Comparator<Comparable> { public static final SqlNullSafeComparator instance = new SqlNullSafeComparator(); private SqlNullSafeComparator() { } public int compare(Comparable o1, Comparable o2) { if (o1 == RolapUtil.sqlNullValue) { return -1; } if (o2 == RolapUtil.sqlNullValue) { return 1; } return o1.compareTo(o2); } } /** * This class implements the Knuth-Morris-Pratt algorithm * to search within a byte array for a token byte array. */ public static class ByteMatcher { private final int[] matcher; public final byte[] key; public ByteMatcher(byte[] key) { this.key = key; this.matcher = compile(key); } /** * Matches the pre-compiled byte array token against a * byte array variable and returns the index of the key * within the array. * @param a An array of bytes to search for. * @return -1 if not found, or the index (0 based) of the match. */ public int match(byte[] a) { int j = 0; for (int i = 0; i < a.length; i++) { while (j > 0 && key[j] != a[i]) { j = matcher[j - 1]; } if (a[i] == key[j]) { j++; } if (key.length == j) { return i - key.length + 1; } } return -1; } private int[] compile(byte[] key) { int[] matcher = new int[key.length]; int j = 0; for (int i = 1; i < key.length; i++) { while (j > 0 && key[j] != key[i]) { j = matcher[j - 1]; } if (key[i] == key[j]) { j++; } matcher[i] = j; } return matcher; } } /** * Transforms a list into a map for which all the keys return * a null value associated to it. * * <p>The list passed as an argument will be used to back * the map returned and as many methods are overridden as * possible to make sure that we don't iterate over the backing * list when creating it and when performing operations like * .size(), entrySet() and contains(). * * <p>The returned map is to be considered immutable. It will * throw an {@link UnsupportedOperationException} if attempts to * modify it are made. */ public static <K, V> Map<K, V> toNullValuesMap(List<K> list) { return new NullValuesMap<K, V>(list); } private static class NullValuesMap<K, V> extends AbstractMap<K, V> { private final List<K> list; private NullValuesMap(List<K> list) { super(); this.list = Collections.unmodifiableList(list); } public Set<Entry<K, V>> entrySet() { return new AbstractSet<Entry<K, V>>() { public Iterator<Entry<K, V>> iterator() { return new Iterator<Entry<K, V>>() { private int pt = -1; public void remove() { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public Entry<K, V> next() { return new AbstractMapEntry( list.get(++pt), null) {}; } public boolean hasNext() { return pt < list.size(); } }; } public int size() { return list.size(); } public boolean contains(Object o) { if (o instanceof Entry) { if (list.contains(((Entry) o).getKey())) { return true; } } return false; } }; } public Set<K> keySet() { return new AbstractSet<K>() { public Iterator<K> iterator() { return new Iterator<K>() { private int pt = -1; public void remove() { throw new UnsupportedOperationException(); } public K next() { return list.get(++pt); } public boolean hasNext() { return pt < list.size(); } }; } public int size() { return list.size(); } public boolean contains(Object o) { return list.contains(o); } }; } public Collection<V> values() { return new AbstractList<V>() { public V get(int index) { return null; } public int size() { return list.size(); } public boolean contains(Object o) { if (o == null && size() > 0) { return true; } else { return false; } } }; } public V get(Object key) { return null; } public boolean containsKey(Object key) { return list.contains(key); } public boolean containsValue(Object o) { if (o == null && size() > 0) { return true; } else { return false; } } } } // End Util.java
epl-1.0
TwitchPlaysPokemon/dolphinWatch
Source/Android/app/src/main/java/org/dolphinemu/dolphinemu/viewholders/TvGameViewHolder.java
765
package org.dolphinemu.dolphinemu.viewholders; import android.view.View; import android.widget.ImageView; import androidx.leanback.widget.ImageCardView; import androidx.leanback.widget.Presenter; import org.dolphinemu.dolphinemu.model.GameFile; /** * A simple class that stores references to views so that the GameAdapter doesn't need to * keep calling findViewById(), which is expensive. */ public final class TvGameViewHolder extends Presenter.ViewHolder { public ImageCardView cardParent; public ImageView imageScreenshot; public GameFile gameFile; public TvGameViewHolder(View itemView) { super(itemView); itemView.setTag(this); cardParent = (ImageCardView) itemView; imageScreenshot = cardParent.getMainImageView(); } }
gpl-2.0
helloiloveit/VkxPhoneProject
submodules/externals/antlr3/tool/src/test/java/org/antlr/test/TestCompositeGrammars.java
33185
/* * [The "BSD license"] * Copyright (c) 2010 Terence Parr * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.antlr.test; import org.antlr.Tool; import org.antlr.tool.*; import org.junit.Test; import java.io.File; public class TestCompositeGrammars extends BaseTest { protected boolean debug = false; @Test public void testWildcardStillWorks() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String grammar = "parser grammar S;\n" + "a : B . C ;\n"; // not qualified ID Grammar g = new Grammar(grammar); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } @Test public void testDelegatorInvokesDelegateRule() throws Exception { String slave = "parser grammar S;\n" + "a : B {System.out.println(\"S.a\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : a ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "s", "b", debug); assertEquals("S.a\n", found); } @Test public void testDelegatorInvokesDelegateRuleWithArgs() throws Exception { // must generate something like: // public int a(int x) throws RecognitionException { return gS.a(x); } // in M. String slave = "parser grammar S;\n" + "a[int x] returns [int y] : B {System.out.print(\"S.a\"); $y=1000;} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : label=a[3] {System.out.println($label.y);} ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "s", "b", debug); assertEquals("S.a1000\n", found); } @Test public void testDelegatorInvokesDelegateRuleWithReturnStruct() throws Exception { // must generate something like: // public int a(int x) throws RecognitionException { return gS.a(x); } // in M. String slave = "parser grammar S;\n" + "a : B {System.out.print(\"S.a\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : a {System.out.println($a.text);} ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "s", "b", debug); assertEquals("S.ab\n", found); } @Test public void testDelegatorAccessesDelegateMembers() throws Exception { String slave = "parser grammar S;\n" + "@members {\n" + " public void foo() {System.out.println(\"foo\");}\n" + "}\n" + "a : B ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + // uses no rules from the import "import S;\n" + "s : 'b' {gS.foo();} ;\n" + // gS is import pointer "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "s", "b", debug); assertEquals("foo\n", found); } @Test public void testDelegatorInvokesFirstVersionOfDelegateRule() throws Exception { String slave = "parser grammar S;\n" + "a : b {System.out.println(\"S.a\");} ;\n" + "b : B ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String slave2 = "parser grammar T;\n" + "a : B {System.out.println(\"T.a\");} ;\n"; // hidden by S.a writeFile(tmpdir, "T.g", slave2); String master = "grammar M;\n" + "import S,T;\n" + "s : a ;\n" + "B : 'b' ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "s", "b", debug); assertEquals("S.a\n", found); } @Test public void testDelegatesSeeSameTokenType() throws Exception { String slave = "parser grammar S;\n" + // A, B, C token type order "tokens { A; B; C; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String slave2 = "parser grammar T;\n" + "tokens { C; B; A; }\n" + // reverse order "y : A {System.out.println(\"T.y\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "T.g", slave2); // The lexer will create rules to match letters a, b, c. // The associated token types A, B, C must have the same value // and all import'd parsers. Since ANTLR regenerates all imports // for use with the delegator M, it can generate the same token type // mapping in each parser: // public static final int C=6; // public static final int EOF=-1; // public static final int B=5; // public static final int WS=7; // public static final int A=4; String master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + // matches AA, which should be "aa" "B : 'b' ;\n" + // another order: B, A, C "A : 'a' ;\n" + "C : 'c' ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "s", "aa", debug); assertEquals("S.x\n" + "T.y\n", found); } @Test public void testDelegatesSeeSameTokenType2() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + // A, B, C token type order "tokens { A; B; C; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String slave2 = "parser grammar T;\n" + "tokens { C; B; A; }\n" + // reverse order "y : A {System.out.println(\"T.y\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "T.g", slave2); String master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + // matches AA, which should be "aa" "B : 'b' ;\n" + // another order: B, A, C "A : 'a' ;\n" + "C : 'c' ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); String expectedTokenIDToTypeMap = "[A=4, B=5, C=6, WS=7]"; String expectedStringLiteralToTypeMap = "{}"; String expectedTypeToTokenList = "[A, B, C, WS]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } @Test public void testCombinedImportsCombined() throws Exception { // for now, we don't allow combined to import combined ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "grammar S;\n" + // A, B, C token type order "tokens { A; B; C; }\n" + "x : 'x' INT {System.out.println(\"S.x\");} ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : x INT ;\n"; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); assertEquals("unexpected errors: "+equeue, 1, equeue.errors.size()); String expectedError = "error(161): "+tmpdir.toString().replaceFirst("\\-[0-9]+","")+"/M.g:2:8: combined grammar M cannot import combined grammar S"; assertEquals("unexpected errors: "+equeue, expectedError, equeue.errors.get(0).toString().replaceFirst("\\-[0-9]+","")); } @Test public void testSameStringTwoNames() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String slave2 = "parser grammar T;\n" + "tokens { X='a'; }\n" + "y : X {System.out.println(\"T.y\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "T.g", slave2); String master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); String expectedTokenIDToTypeMap = "[A=4, WS=5, X=6]"; String expectedStringLiteralToTypeMap = "{'a'=4}"; String expectedTypeToTokenList = "[A, WS, X]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); Object expectedArg = "X='a'"; Object expectedArg2 = "A"; int expectedMsgID = ErrorManager.MSG_TOKEN_ALIAS_CONFLICT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkGrammarSemanticsError(equeue, expectedMessage); assertEquals("unexpected errors: "+equeue, 1, equeue.errors.size()); String expectedError = "error(158): T.g:2:10: cannot alias X='a'; string already assigned to A"; assertEquals(expectedError, equeue.errors.get(0).toString()); } @Test public void testSameNameTwoStrings() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String slave2 = "parser grammar T;\n" + "tokens { A='x'; }\n" + "y : A {System.out.println(\"T.y\");} ;\n"; writeFile(tmpdir, "T.g", slave2); String master = "grammar M;\n" + "import S,T;\n" + "s : x y ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); String expectedTokenIDToTypeMap = "[A=4, T__6=6, WS=5]"; String expectedStringLiteralToTypeMap = "{'a'=4, 'x'=6}"; String expectedTypeToTokenList = "[A, WS, T__6]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, sortMapToString(g.composite.stringLiteralToTypeMap)); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); Object expectedArg = "A='x'"; Object expectedArg2 = "'a'"; int expectedMsgID = ErrorManager.MSG_TOKEN_ALIAS_REASSIGNMENT; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg, expectedArg2); checkGrammarSemanticsError(equeue, expectedMessage); assertEquals("unexpected errors: "+equeue, 1, equeue.errors.size()); String expectedError = "error(159): T.g:2:10: cannot alias A='x'; token name already assigned to 'a'"; assertEquals(expectedError, equeue.errors.get(0).toString()); } @Test public void testImportedTokenVocabIgnoredWithWarning() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + "options {tokenVocab=whatever;}\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); Object expectedArg = "S"; int expectedMsgID = ErrorManager.MSG_TOKEN_VOCAB_IN_DELEGATE; GrammarSemanticsMessage expectedMessage = new GrammarSemanticsMessage(expectedMsgID, g, null, expectedArg); checkGrammarSemanticsWarning(equeue, expectedMessage); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals("unexpected errors: "+equeue, 1, equeue.warnings.size()); String expectedError = "warning(160): S.g:2:10: tokenVocab option ignored in imported grammar S"; assertEquals(expectedError, equeue.warnings.get(0).toString()); } @Test public void testImportedTokenVocabWorksInRoot() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + "tokens { A='a'; }\n" + "x : A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String tokens = "A=99\n"; writeFile(tmpdir, "Test.tokens", tokens); String master = "grammar M;\n" + "options {tokenVocab=Test;}\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); String expectedTokenIDToTypeMap = "[A=99, WS=101]"; String expectedStringLiteralToTypeMap = "{'a'=100}"; String expectedTypeToTokenList = "[A, 'a', WS]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } @Test public void testSyntaxErrorsInImportsNotThrownOut() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + "options {toke\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); // whole bunch of errors from bad S.g file assertEquals("unexpected errors: "+equeue, 5, equeue.errors.size()); } @Test public void testSyntaxErrorsInImportsNotThrownOut2() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar S;\n" + ": A {System.out.println(\"S.x\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "s : x ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); // whole bunch of errors from bad S.g file assertEquals("unexpected errors: "+equeue, 3, equeue.errors.size()); } @Test public void testDelegatorRuleOverridesDelegate() throws Exception { String slave = "parser grammar S;\n" + "a : b {System.out.println(\"S.a\");} ;\n" + "b : B ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "b : 'b'|'c' ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "a", "c", debug); assertEquals("S.a\n", found); } @Test public void testDelegatorRuleOverridesLookaheadInDelegate() throws Exception { String slave = "parser grammar JavaDecl;\n" + "type : 'int' ;\n" + "decl : type ID ';'\n" + " | type ID init ';' {System.out.println(\"JavaDecl: \"+$decl.text);}\n" + " ;\n" + "init : '=' INT ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "JavaDecl.g", slave); String master = "grammar Java;\n" + "import JavaDecl;\n" + "prog : decl ;\n" + "type : 'int' | 'float' ;\n" + "\n" + "ID : 'a'..'z'+ ;\n" + "INT : '0'..'9'+ ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; // for float to work in decl, type must be overridden String found = execParser("Java.g", master, "JavaParser", "JavaLexer", "prog", "float x = 3;", debug); assertEquals("JavaDecl: floatx=3;\n", found); } @Test public void testDelegatorRuleOverridesDelegates() throws Exception { String slave = "parser grammar S;\n" + "a : b {System.out.println(\"S.a\");} ;\n" + "b : B ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String slave2 = "parser grammar T;\n" + "tokens { A='x'; }\n" + "b : B {System.out.println(\"T.b\");} ;\n"; writeFile(tmpdir, "T.g", slave2); String master = "grammar M;\n" + "import S, T;\n" + "b : 'b'|'c' {System.out.println(\"M.b\");}|B|A ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "a", "c", debug); assertEquals("M.b\n" + "S.a\n", found); } // LEXER INHERITANCE @Test public void testLexerDelegatorInvokesDelegateRule() throws Exception { String slave = "lexer grammar S;\n" + "A : 'a' {System.out.println(\"S.A\");} ;\n" + "C : 'c' ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "lexer grammar M;\n" + "import S;\n" + "B : 'b' ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execLexer("M.g", master, "M", "abc", debug); assertEquals("S.A\nabc\n", found); } @Test public void testLexerDelegatorRuleOverridesDelegate() throws Exception { String slave = "lexer grammar S;\n" + "A : 'a' {System.out.println(\"S.A\");} ;\n" + "B : 'b' {System.out.println(\"S.B\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "lexer grammar M;\n" + "import S;\n" + "A : 'a' B {System.out.println(\"M.A\");} ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execLexer("M.g", master, "M", "ab", debug); assertEquals("S.B\n" + "M.A\n" + "ab\n", found); } @Test public void testLexerDelegatorRuleOverridesDelegateLeavingNoRules() throws Exception { // M.Tokens has nothing to predict tokens from S. Should // not include S.Tokens alt in this case? String slave = "lexer grammar S;\n" + "A : 'a' {System.out.println(\"S.A\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "lexer grammar M;\n" + "import S;\n" + "A : 'a' {System.out.println(\"M.A\");} ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; writeFile(tmpdir, "/M.g", master); ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); composite.assignTokenTypes(); composite.defineGrammarSymbols(); composite.createNFAs(); g.createLookaheadDFAs(false); // predict only alts from M not S String expectingDFA = ".s0-'a'->.s1\n" + ".s0-{'\\n', ' '}->:s3=>2\n" + ".s1-<EOT>->:s2=>1\n"; org.antlr.analysis.DFA dfa = g.getLookaheadDFA(1); FASerializer serializer = new FASerializer(g); String result = serializer.serialize(dfa.startState); assertEquals(expectingDFA, result); // must not be a "unreachable alt: Tokens" error assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } @Test public void testInvalidImportMechanism() throws Exception { // M.Tokens has nothing to predict tokens from S. Should // not include S.Tokens alt in this case? String slave = "lexer grammar S;\n" + "A : 'a' {System.out.println(\"S.A\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "tree grammar M;\n" + "import S;\n" + "a : A ;"; writeFile(tmpdir, "/M.g", master); ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); assertEquals("unexpected errors: "+equeue, 1, equeue.errors.size()); assertEquals("unexpected errors: "+equeue, 0, equeue.warnings.size()); String expectedError = "error(161): "+tmpdir.toString().replaceFirst("\\-[0-9]+","")+"/M.g:2:8: tree grammar M cannot import lexer grammar S"; assertEquals(expectedError, equeue.errors.get(0).toString().replaceFirst("\\-[0-9]+","")); } @Test public void testSyntacticPredicateRulesAreNotInherited() throws Exception { // if this compiles, it means that synpred1_S is defined in S.java // but not MParser.java. MParser has its own synpred1_M which must // be separate to compile. String slave = "parser grammar S;\n" + "a : 'a' {System.out.println(\"S.a1\");}\n" + " | 'a' {System.out.println(\"S.a2\");}\n" + " ;\n" + "b : 'x' | 'y' {;} ;\n"; // preds generated but not need in DFA here mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "options {backtrack=true;}\n" + "import S;\n" + "start : a b ;\n" + "nonsense : 'q' | 'q' {;} ;" + // forces def of preds here in M "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "start", "ax", debug); assertEquals("S.a1\n", found); } @Test public void testKeywordVSIDGivesNoWarning() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "lexer grammar S;\n" + "A : 'abc' {System.out.println(\"S.A\");} ;\n" + "ID : 'a'..'z'+ ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "a : A {System.out.println(\"M.a\");} ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; String found = execParser("M.g", master, "MParser", "MLexer", "a", "abc", debug); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals("unexpected warnings: "+equeue, 0, equeue.warnings.size()); assertEquals("S.A\nM.a\n", found); } @Test public void testWarningForUndefinedToken() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "lexer grammar S;\n" + "A : 'abc' {System.out.println(\"S.A\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "a : ABC A {System.out.println(\"M.a\");} ;\n" + "WS : (' '|'\\n') {skip();} ;\n" ; // A is defined in S but M should still see it and not give warning. // only problem is ABC. rawGenerateAndBuildRecognizer("M.g", master, "MParser", "MLexer", debug); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); assertEquals("unexpected warnings: "+equeue, 1, equeue.warnings.size()); String expectedError = "warning(105): "+tmpdir.toString().replaceFirst("\\-[0-9]+","")+File.separator+"M.g:3:5: no lexer rule corresponding to token: ABC"; assertEquals(expectedError, equeue.warnings.get(0).toString().replaceFirst("\\-[0-9]+","")); } /** Make sure that M can import S that imports T. */ @Test public void test3LevelImport() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar T;\n" + "a : T ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "T.g", slave); String slave2 = "parser grammar S;\n" + // A, B, C token type order "import T;\n" + "a : S ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave2); String master = "grammar M;\n" + "import S;\n" + "a : M ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); g.composite.defineGrammarSymbols(); String expectedTokenIDToTypeMap = "[M=4, S=5, T=6]"; String expectedStringLiteralToTypeMap = "{}"; String expectedTypeToTokenList = "[M, S, T]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); boolean ok = rawGenerateAndBuildRecognizer("M.g", master, "MParser", null, false); boolean expecting = true; // should be ok assertEquals(expecting, ok); } @Test public void testBigTreeOfImports() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar T;\n" + "x : T ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "T.g", slave); slave = "parser grammar S;\n" + "import T;\n" + "y : S ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); slave = "parser grammar C;\n" + "i : C ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "C.g", slave); slave = "parser grammar B;\n" + "j : B ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "B.g", slave); slave = "parser grammar A;\n" + "import B,C;\n" + "k : A ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "A.g", slave); String master = "grammar M;\n" + "import S,A;\n" + "a : M ;\n" ; writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); g.composite.defineGrammarSymbols(); String expectedTokenIDToTypeMap = "[A=4, B=5, C=6, M=7, S=8, T=9]"; String expectedStringLiteralToTypeMap = "{}"; String expectedTypeToTokenList = "[A, B, C, M, S, T]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); boolean ok = rawGenerateAndBuildRecognizer("M.g", master, "MParser", null, false); boolean expecting = true; // should be ok assertEquals(expecting, ok); } @Test public void testRulesVisibleThroughMultilevelImport() throws Exception { ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String slave = "parser grammar T;\n" + "x : T ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "T.g", slave); String slave2 = "parser grammar S;\n" + // A, B, C token type order "import T;\n" + "a : S ;\n" ; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave2); String master = "grammar M;\n" + "import S;\n" + "a : M x ;\n" ; // x MUST BE VISIBLE TO M writeFile(tmpdir, "M.g", master); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/M.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); g.composite.defineGrammarSymbols(); String expectedTokenIDToTypeMap = "[M=4, S=5, T=6]"; String expectedStringLiteralToTypeMap = "{}"; String expectedTypeToTokenList = "[M, S, T]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); } @Test public void testNestedComposite() throws Exception { // Wasn't compiling. http://www.antlr.org/jira/browse/ANTLR-438 ErrorQueue equeue = new ErrorQueue(); ErrorManager.setErrorListener(equeue); String gstr = "lexer grammar L;\n" + "T1: '1';\n" + "T2: '2';\n" + "T3: '3';\n" + "T4: '4';\n" ; mkdir(tmpdir); writeFile(tmpdir, "L.g", gstr); gstr = "parser grammar G1;\n" + "s: a | b;\n" + "a: T1;\n" + "b: T2;\n" ; mkdir(tmpdir); writeFile(tmpdir, "G1.g", gstr); gstr = "parser grammar G2;\n" + "import G1;\n" + "a: T3;\n" ; mkdir(tmpdir); writeFile(tmpdir, "G2.g", gstr); String G3str = "grammar G3;\n" + "import G2;\n" + "b: T4;\n" ; mkdir(tmpdir); writeFile(tmpdir, "G3.g", G3str); Tool antlr = newTool(new String[] {"-lib", tmpdir}); CompositeGrammar composite = new CompositeGrammar(); Grammar g = new Grammar(antlr,tmpdir+"/G3.g",composite); composite.setDelegationRoot(g); g.parseAndBuildAST(); g.composite.assignTokenTypes(); g.composite.defineGrammarSymbols(); String expectedTokenIDToTypeMap = "[T1=4, T2=5, T3=6, T4=7]"; String expectedStringLiteralToTypeMap = "{}"; String expectedTypeToTokenList = "[T1, T2, T3, T4]"; assertEquals(expectedTokenIDToTypeMap, realElements(g.composite.tokenIDToTypeMap).toString()); assertEquals(expectedStringLiteralToTypeMap, g.composite.stringLiteralToTypeMap.toString()); assertEquals(expectedTypeToTokenList, realElements(g.composite.typeToTokenList).toString()); assertEquals("unexpected errors: "+equeue, 0, equeue.errors.size()); boolean ok = rawGenerateAndBuildRecognizer("G3.g", G3str, "G3Parser", null, false); boolean expecting = true; // should be ok assertEquals(expecting, ok); } @Test public void testHeadersPropogatedCorrectlyToImportedGrammars() throws Exception { String slave = "parser grammar S;\n" + "a : B {System.out.print(\"S.a\");} ;\n"; mkdir(tmpdir); writeFile(tmpdir, "S.g", slave); String master = "grammar M;\n" + "import S;\n" + "@header{package mypackage;}\n" + "@lexer::header{package mypackage;}\n" + "s : a ;\n" + "B : 'b' ;" + // defines B from inherited token space "WS : (' '|'\\n') {skip();} ;\n" ; boolean ok = antlr("M.g", "M.g", master, debug); boolean expecting = true; // should be ok assertEquals(expecting, ok); } }
gpl-2.0
Jianchu/checker-framework
framework/tests/framework/UnimportedExtends2.java
107
class UnimportedExtends2 { //:: error: cannot find symbol class Inner extends UnimportedClass {} }
gpl-2.0
fengshao0907/disconf
disconf-client/src/main/java/com/baidu/disconf/client/core/processor/impl/DisconfItemCoreProcessorImpl.java
5926
package com.baidu.disconf.client.core.processor.impl; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baidu.disconf.client.common.model.DisConfCommonModel; import com.baidu.disconf.client.common.model.DisconfCenterItem; import com.baidu.disconf.client.config.DisClientConfig; import com.baidu.disconf.client.core.processor.DisconfCoreProcessor; import com.baidu.disconf.client.fetcher.FetcherMgr; import com.baidu.disconf.client.store.DisconfStoreProcessor; import com.baidu.disconf.client.store.DisconfStoreProcessorFactory; import com.baidu.disconf.client.store.processor.model.DisconfValue; import com.baidu.disconf.client.watch.WatchMgr; import com.baidu.disconf.core.common.constants.DisConfigTypeEnum; /** * 配置项处理器实现 * * @author liaoqiqi * @version 2014-8-4 */ public class DisconfItemCoreProcessorImpl implements DisconfCoreProcessor { protected static final Logger LOGGER = LoggerFactory.getLogger(DisconfItemCoreProcessorImpl.class); // 监控器 private WatchMgr watchMgr = null; // 抓取器 private FetcherMgr fetcherMgr = null; // 仓库算子 private DisconfStoreProcessor disconfStoreProcessor = DisconfStoreProcessorFactory.getDisconfStoreItemProcessor(); public DisconfItemCoreProcessorImpl(WatchMgr watchMgr, FetcherMgr fetcherMgr) { this.fetcherMgr = fetcherMgr; this.watchMgr = watchMgr; } /** * */ @Override public void processAllItems() { /** * 配置ITEM列表处理 */ for (String key : disconfStoreProcessor.getConfKeySet()) { processOneItem(key); } } @Override public void processOneItem(String key) { LOGGER.debug("==============\tstart to process disconf item: " + key + "\t============================="); DisconfCenterItem disconfCenterItem = (DisconfCenterItem) disconfStoreProcessor.getConfData(key); if (disconfCenterItem != null) { try { updateOneConfItem(key, disconfCenterItem); } catch (Exception e) { LOGGER.error(e.toString(), e); } } } /** * 更新 一个配置 */ private void updateOneConf(String keyName) throws Exception { DisconfCenterItem disconfCenterItem = (DisconfCenterItem) disconfStoreProcessor.getConfData(keyName); if (disconfCenterItem != null) { // 更新仓库 updateOneConfItem(keyName, disconfCenterItem); // 更新实例 inject2OneConf(keyName, disconfCenterItem); } } /** * 更新一个配置 */ private void updateOneConfItem(String keyName, DisconfCenterItem disconfCenterItem) throws Exception { if (disconfCenterItem == null) { throw new Exception("cannot find disconfCenterItem " + keyName); } String value = null; // // 开启disconf才需要远程下载, 否则就用默认值 // if (DisClientConfig.getInstance().ENABLE_DISCONF) { // // 下载配置 // try { String url = disconfCenterItem.getRemoteServerUrl(); value = fetcherMgr.getValueFromServer(url); if (value != null) { LOGGER.debug("value: " + value); } } catch (Exception e) { LOGGER.error("cannot use remote configuration: " + keyName, e); LOGGER.info("using local variable: " + keyName); } LOGGER.debug("download ok."); } // // 注入到仓库中 // disconfStoreProcessor.inject2Store(keyName, new DisconfValue(value, null)); LOGGER.debug("inject ok."); // // Watch // if (DisClientConfig.getInstance().ENABLE_DISCONF) { if (watchMgr != null) { DisConfCommonModel disConfCommonModel = disconfStoreProcessor.getCommonModel(keyName); watchMgr.watchPath(this, disConfCommonModel, keyName, DisConfigTypeEnum.ITEM, value); LOGGER.debug("watch ok."); } else { LOGGER.warn("cannot monitor {} because watch mgr is null", keyName); } } } /** * 更新消息: */ @Override public void updateOneConfAndCallback(String key) throws Exception { // 更新 配置 updateOneConf(key); // 回调 DisconfCoreProcessUtils.callOneConf(disconfStoreProcessor, key); } /** * 某个配置项:注入到实例中 */ private void inject2OneConf(String key, DisconfCenterItem disconfCenterItem) { if (disconfCenterItem == null) { return; } try { Object object = null; Field field = disconfCenterItem.getField(); // // 静态 // if (!Modifier.isStatic(field.getModifiers())) { object = DisconfCoreProcessUtils.getSpringBean(field.getDeclaringClass()); } disconfStoreProcessor.inject2Instance(object, key); } catch (Exception e) { LOGGER.warn(e.toString(), e); } } /** * */ @Override public void inject2Conf() { /** * 配置ITEM列表处理 */ for (String key : disconfStoreProcessor.getConfKeySet()) { LOGGER.debug("==============\tstart to inject value to disconf item instance: " + key + "\t============================="); DisconfCenterItem disconfCenterItem = (DisconfCenterItem) disconfStoreProcessor.getConfData(key); inject2OneConf(key, disconfCenterItem); } } }
gpl-2.0
md-5/jdk10
test/hotspot/jtreg/vmTestbase/nsk/jdi/ShortValue/compareTo/compareto001a.java
6823
/* * Copyright (c) 2002, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package nsk.jdi.ShortValue.compareTo; import nsk.share.*; import nsk.share.jpda.*; import nsk.share.jdi.*; /** * The debugged application of the test. */ public class compareto001a { //----------------------------------------------------- immutable common fields private static int exitStatus; private static ArgumentHandler argHandler; private static Log log; private static IOPipe pipe; //---------------------------------------------------------- immutable common methods static void display(String msg) { log.display("debuggee > " + msg); } static void complain(String msg) { log.complain("debuggee FAILURE > " + msg); } public static void receiveSignal(String signal) { String line = pipe.readln(); if ( !line.equals(signal) ) throw new Failure("UNEXPECTED debugger's signal " + line); display("debuger's <" + signal + "> signal received."); } //------------------------------------------------------ mutable common fields //------------------------------------------------------ test specific fields static compareto001aClassToCheck testedObj = new compareto001aClassToCheck(); static String[] testedFields = { "cmpObjNULL", "cmpObject", "cmpBoolMAX", "cmpBoolMIN", "cmpByteMAX", "cmpByte1", "cmpByte0", "cmpByte_1", "cmpByteMIN", "cmpCharMAX", "cmpCharMIN", "cmpDoubleMAX", "cmpDouble1", "cmpDouble0", "cmpDouble_1", "cmpDoubleMIN", "cmpFloatMAX", "cmpFloat1", "cmpFloat0", "cmpFloat_1", "cmpFloatMIN", "cmpIntMAX", "cmpInt1", "cmpInt0", "cmpInt_1", "cmpIntMIN", "cmpLongMAX", "cmpLong1", "cmpLong0", "cmpLong_1", "cmpLongMIN", "cmpShortMAX", "cmpShort1", "cmpShort0", "cmpShort_1", "cmpShortMIN" }; static Object cmpObjNULL = null; static Object cmpObject = new Object(); static boolean cmpBoolMAX = true; static boolean cmpBoolMIN = false; static byte cmpByteMAX = Byte.MAX_VALUE; static byte cmpByte1 = 1; static byte cmpByte0 = 0; static byte cmpByte_1 = -1; static byte cmpByteMIN = Byte.MIN_VALUE; static char cmpCharMAX = Character.MAX_VALUE; static char cmpCharMIN = Character.MIN_VALUE; static double cmpDoubleMAX= Double.MAX_VALUE; static double cmpDouble1 = 1; static double cmpDouble0 = 0; static double cmpDouble_1 = -1; static double cmpDoubleMIN= Double.MIN_VALUE; static float cmpFloatMAX = Float.MAX_VALUE; static float cmpFloat1 = 1; static float cmpFloat0 = 0; static float cmpFloat_1 = -1; static float cmpFloatMIN = Float.MIN_VALUE; static int cmpIntMAX = Integer.MAX_VALUE; static int cmpInt1 = 1; static int cmpInt0 = 0; static int cmpInt_1 = -1; static int cmpIntMIN = Integer.MIN_VALUE; static long cmpLongMAX = Long.MAX_VALUE; static long cmpLong1 = 1; static long cmpLong0 = 0; static long cmpLong_1 = -1; static long cmpLongMIN = Long.MIN_VALUE; static short cmpShortMAX = Short.MAX_VALUE; static short cmpShort1 = 1; static short cmpShort0 = 0; static short cmpShort_1 = -1; static short cmpShortMIN = Short.MIN_VALUE; //------------------------------------------------------ mutable common method public static void main (String argv[]) { exitStatus = Consts.TEST_FAILED; argHandler = new ArgumentHandler(argv); log = argHandler.createDebugeeLog(); pipe = argHandler.createDebugeeIOPipe(log); try { pipe.println(compareto001.SIGNAL_READY); // receiveSignal(compareto001.SIGNAL_GO); receiveSignal(compareto001.SIGNAL_QUIT); display("completed succesfully."); System.exit(Consts.TEST_PASSED + Consts.JCK_STATUS_BASE); } catch (Failure e) { log.complain(e.getMessage()); System.exit(Consts.TEST_FAILED + Consts.JCK_STATUS_BASE); } } //--------------------------------------------------------- test specific methods } //--------------------------------------------------------- test specific classes class compareto001aClassToCheck { public short shortMAX = Short.MAX_VALUE; public short short1 = 1; public short short0 = 0; public short short_1 = -1; public short shortMIN = Short.MIN_VALUE; }
gpl-2.0
cqjjjzr/jsocks-mirror
src/java/net/sourceforge/jsocks/test/UPSOCKS.java
1135
package net.sourceforge.jsocks.test; import net.sourceforge.jsocks.socks.*; import net.sourceforge.jsocks.socks.server.*; import java.net.Socket; /** Test file for UserPasswordAuthentictor */ public class UPSOCKS implements UserValidation{ String user, password; UPSOCKS(String user,String password){ this.user = user; this.password = password; } public boolean isUserValid(String user,String password,Socket s){ System.err.println("User:"+user+"\tPassword:"+password); System.err.println("Socket:"+s); return (user.equals(this.user) && password.equals(this.password)); } public static void main(String args[]){ String user, password; if(args.length == 2){ user = args[0]; password = args[1]; }else{ user = "user"; password = "password"; } UPSOCKS us = new UPSOCKS(user,password); UserPasswordAuthenticator auth = new UserPasswordAuthenticator(us); ProxyServer server = new ProxyServer(auth); server.start(1080); } }
lgpl-3.0
vickychijwani/udacity-p3-super-duo
football-scores/app/src/main/java/barqsoft/footballscores/MainActivity.java
2966
package barqsoft.footballscores; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends ActionBarActivity { public static int selected_match_id; public static int current_fragment = 2; public static String LOG_TAG = "MainActivity"; private final String save_tag = "Save Test"; private PagerFragment my_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(LOG_TAG, "Reached MainActivity onCreate"); if (savedInstanceState == null) { my_main = new PagerFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.container, my_main) .commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_about) { Intent start_about = new Intent(this,AboutActivity.class); startActivity(start_about); return true; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { Log.v(save_tag,"will save"); Log.v(save_tag,"fragment: "+String.valueOf(my_main.mPagerHandler.getCurrentItem())); Log.v(save_tag,"selected id: "+selected_match_id); outState.putInt("Pager_Current",my_main.mPagerHandler.getCurrentItem()); outState.putInt("Selected_match",selected_match_id); getSupportFragmentManager().putFragment(outState,"my_main",my_main); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { Log.v(save_tag,"will retrive"); Log.v(save_tag,"fragment: "+String.valueOf(savedInstanceState.getInt("Pager_Current"))); Log.v(save_tag,"selected id: "+savedInstanceState.getInt("Selected_match")); current_fragment = savedInstanceState.getInt("Pager_Current"); selected_match_id = savedInstanceState.getInt("Selected_match"); my_main = (PagerFragment) getSupportFragmentManager().getFragment(savedInstanceState,"my_main"); super.onRestoreInstanceState(savedInstanceState); } }
unlicense
liancheng/parquet-mr
parquet-hadoop/src/main/java/parquet/hadoop/codec/SnappyDecompressor.java
4725
/** * Copyright 2012 Twitter, 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 parquet.hadoop.codec; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.hadoop.io.compress.Decompressor; import org.xerial.snappy.Snappy; import parquet.Preconditions; public class SnappyDecompressor implements Decompressor { // Buffer for uncompressed output. This buffer grows as necessary. private ByteBuffer outputBuffer = ByteBuffer.allocateDirect(0); // Buffer for compressed input. This buffer grows as necessary. private ByteBuffer inputBuffer = ByteBuffer.allocateDirect(0); private boolean finished; /** * Fills specified buffer with uncompressed data. Returns actual number * of bytes of uncompressed data. A return value of 0 indicates that * {@link #needsInput()} should be called in order to determine if more * input data is required. * * @param buffer Buffer for the compressed data * @param off Start offset of the data * @param len Size of the buffer * @return The actual number of bytes of uncompressed data. * @throws IOException */ @Override public synchronized int decompress(byte[] buffer, int off, int len) throws IOException { SnappyUtil.validateBuffer(buffer, off, len); if (inputBuffer.position() == 0 && !outputBuffer.hasRemaining()) { return 0; } if (!outputBuffer.hasRemaining()) { inputBuffer.rewind(); Preconditions.checkArgument(inputBuffer.position() == 0, "Invalid position of 0."); Preconditions.checkArgument(outputBuffer.position() == 0, "Invalid position of 0."); // There is compressed input, decompress it now. int decompressedSize = Snappy.uncompressedLength(inputBuffer); if (decompressedSize > outputBuffer.capacity()) { outputBuffer = ByteBuffer.allocateDirect(decompressedSize); } // Reset the previous outputBuffer (i.e. set position to 0) outputBuffer.clear(); int size = Snappy.uncompress(inputBuffer, outputBuffer); outputBuffer.limit(size); // We've decompressed the entire input, reset the input now inputBuffer.clear(); inputBuffer.limit(0); finished = true; } // Return compressed output up to 'len' int numBytes = Math.min(len, outputBuffer.remaining()); outputBuffer.get(buffer, off, numBytes); return numBytes; } /** * Sets input data for decompression. * This should be called if and only if {@link #needsInput()} returns * <code>true</code> indicating that more input data is required. * (Both native and non-native versions of various Decompressors require * that the data passed in via <code>b[]</code> remain unmodified until * the caller is explicitly notified--via {@link #needsInput()}--that the * buffer may be safely modified. With this requirement, an extra * buffer-copy can be avoided.) * * @param buffer Input data * @param off Start offset * @param len Length */ @Override public synchronized void setInput(byte[] buffer, int off, int len) { SnappyUtil.validateBuffer(buffer, off, len); if (inputBuffer.capacity() - inputBuffer.position() < len) { ByteBuffer newBuffer = ByteBuffer.allocateDirect(inputBuffer.position() + len); inputBuffer.rewind(); newBuffer.put(inputBuffer); inputBuffer = newBuffer; } else { inputBuffer.limit(inputBuffer.position() + len); } inputBuffer.put(buffer, off, len); } @Override public void end() { // No-op } @Override public synchronized boolean finished() { return finished && !outputBuffer.hasRemaining(); } @Override public int getRemaining() { return 0; } @Override public synchronized boolean needsInput() { return !inputBuffer.hasRemaining() && !outputBuffer.hasRemaining(); } @Override public synchronized void reset() { finished = false; inputBuffer.rewind(); outputBuffer.rewind(); inputBuffer.limit(0); outputBuffer.limit(0); } @Override public boolean needsDictionary() { return false; } @Override public void setDictionary(byte[] b, int off, int len) { // No-op } }
apache-2.0
dawidmalina/pinpoint
profiler/src/test/java/com/navercorp/pinpoint/profiler/interceptor/bci/TestObjectNestedClass.java
1898
/** * Copyright 2014 NAVER Corp. * 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.navercorp.pinpoint.profiler.interceptor.bci; import java.util.concurrent.Callable; /** * @author jaehong.kim * */ public class TestObjectNestedClass { public void annonymousInnerClass() { new Callable<Object>() { @Override public Object call() throws Exception { return null; } }; new Runnable() { public void run() { } }; } public void annonymousInnerClass2() { new Callable<Object>() { @Override public Object call() throws Exception { return null; } }; new Runnable() { public void run() { } }; } public void instanceInnerClass() { new InstanceInner(); } class InstanceInner {} public void localInnerClass() { class LocalInner {} new LocalInner(); } public void localInnerClass2() { class LocalInner {} new LocalInner(); } public void staticNestedClass() { new StaticNested(); } static class StaticNested{} public void enclosingMethod(String s, int i) { class LocalInner {} new LocalInner(); } }
apache-2.0
jaadds/product-apim
sample-scenarios/backend/src/main/java/server/obj/Salary.java
1401
/* * Copyright (c) 2017, WSO2 Inc. (http://wso2.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 server.obj; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Salary") public class Salary { private long id; private long fixed; private long allowance; private String empId; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getFixed() { return fixed; } public void setFexed(long fixed) { this.fixed = fixed; } public long getAllowance() { return allowance; } public void setAllowance(long allowance) { this.allowance = allowance; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } }
apache-2.0
jwren/intellij-community
plugins/kotlin/idea/tests/testData/android/gutterIcon/R.java
567
package com.myapp; public final class R { public static final class drawable { public static final int test_icon=0x7f02005d; } public static final class mipmap { public static final int test_icon=0x7f04005d; } public static final class color { public static final int colorAccent=0x7f0a0013; public static final int colorPrimary=0x7f0a0014; public static final int colorPrimaryDark=0x7f0a0015; } public static final class layout { public static final int activity_kotlin=0x7f08005d; } }
apache-2.0
jittagornp/cpe4235
connect-database/src/main/java/com/blogspot/na5cent/connectdb/S5QueryPagination.java
1216
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.blogspot.na5cent.connectdb; import com.blogspot.na5cent.connectdb.model.Department; import com.blogspot.na5cent.connectdb.printer.GenericReflectPrinter; import com.blogspot.na5cent.connectdb.query.Page; import com.blogspot.na5cent.connectdb.query.Pagination; import com.blogspot.na5cent.connectdb.service.DepartmentService; /** * * @author anonymous */ public class S5QueryPagination { public static void main(String[] args) throws Exception { Pagination pagination = new Pagination(1, 5); Page<Department> page = DepartmentService.findAll(pagination); System.out.println("total elements = " + page.getTotalElements()); System.out.println("total pages = " + page.getTotalPages()); System.out.println("page size = " + page.getPageRequestSize()); System.out.println("current page = " + page.getCurrentPageNumber()); System.out.println("current page size = " + page.getCurrentPageSize()); GenericReflectPrinter.prints(page.getContents()); } }
apache-2.0